@stacksjs/stx 0.2.687 → 0.2.690

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 (82) hide show
  1. package/dist/{chunk-5m6ja6mx.js → chunk-063y8kcp.js} +1 -1
  2. package/dist/{chunk-agx8pbg4.js → chunk-1k7js5nz.js} +1 -1
  3. package/dist/{chunk-9m1agnnx.js → chunk-1pzshxft.js} +1 -1
  4. package/dist/chunk-2mf8shg5.js +2 -0
  5. package/dist/{chunk-dztv0p4y.js → chunk-35cvjgj2.js} +1 -1
  6. package/dist/{chunk-m62xkpek.js → chunk-43h27729.js} +3 -3
  7. package/dist/{chunk-fvxvd48v.js → chunk-4566drka.js} +1 -1
  8. package/dist/{chunk-pe9ry4mj.js → chunk-4f5bmy7h.js} +61 -61
  9. package/dist/{chunk-g3jg4mcw.js → chunk-4hbevevz.js} +1 -1
  10. package/dist/{chunk-nm7b8cmr.js → chunk-4mqq6896.js} +5 -5
  11. package/dist/chunk-5443hz48.js +2 -0
  12. package/dist/chunk-55eek6b1.js +2 -0
  13. package/dist/{chunk-cz0p258g.js → chunk-5gh02j5x.js} +1 -1
  14. package/dist/{chunk-b2cfg8d1.js → chunk-5m42k74p.js} +1 -1
  15. package/dist/{chunk-ff7pvv0p.js → chunk-5mcwf93c.js} +2 -2
  16. package/dist/chunk-5y61b94b.js +2 -0
  17. package/dist/{chunk-7z5sp09n.js → chunk-67mex2d1.js} +1 -1
  18. package/dist/{chunk-haq3cg76.js → chunk-8485q7dh.js} +1 -1
  19. package/dist/{chunk-e25r7baw.js → chunk-84vsb4v3.js} +1 -1
  20. package/dist/{chunk-ay9bwfbj.js → chunk-91ytsvhd.js} +1 -1
  21. package/dist/{chunk-3vjzezn1.js → chunk-a5agchz8.js} +1 -1
  22. package/dist/chunk-b6vwy6bd.js +2 -0
  23. package/dist/chunk-b8v19j69.js +2 -0
  24. package/dist/{chunk-t2twa7wy.js → chunk-bzxfbh2x.js} +1 -1
  25. package/dist/{chunk-bzzye361.js → chunk-c9fs966z.js} +1 -1
  26. package/dist/{chunk-68wa4bf0.js → chunk-cm8ad78x.js} +1 -1
  27. package/dist/{chunk-mpvekbzr.js → chunk-dsrgestd.js} +5 -5
  28. package/dist/{chunk-2s1c7g5r.js → chunk-e9fmqn0g.js} +1 -1
  29. package/dist/{chunk-y8f59j6z.js → chunk-ejafjap5.js} +1 -1
  30. package/dist/{chunk-xszbpnaa.js → chunk-fk2m3xdd.js} +1 -1
  31. package/dist/{chunk-r16cej66.js → chunk-g9c284gf.js} +1 -1
  32. package/dist/{chunk-jhr08gjs.js → chunk-h176dx1q.js} +2 -2
  33. package/dist/{chunk-3zcc0w5e.js → chunk-hqzhej1p.js} +2 -2
  34. package/dist/{chunk-bkk6xq8p.js → chunk-hy4gaf8g.js} +1 -1
  35. package/dist/{chunk-9s8471tv.js → chunk-j5127cxs.js} +1 -1
  36. package/dist/{chunk-rtfyx54t.js → chunk-jk0gba16.js} +2 -2
  37. package/dist/{chunk-qkr7epna.js → chunk-jkhc0q7g.js} +1 -1
  38. package/dist/{chunk-qy26afdn.js → chunk-jt9kxnva.js} +2 -2
  39. package/dist/{chunk-zff3cb1e.js → chunk-mwmmmbxj.js} +4 -4
  40. package/dist/{chunk-71sawjg8.js → chunk-n42421az.js} +2 -2
  41. package/dist/{chunk-95yt1gxa.js → chunk-nc85m4p9.js} +1 -1
  42. package/dist/{chunk-xzffh9aj.js → chunk-ngd9dsrd.js} +1 -1
  43. package/dist/chunk-nrw84rpj.js +2 -0
  44. package/dist/chunk-p7nkw2nr.js +2 -0
  45. package/dist/chunk-pj1we4mn.js +2 -0
  46. package/dist/{chunk-mf7r2gd0.js → chunk-ppc64he4.js} +1 -1
  47. package/dist/{chunk-52g5q984.js → chunk-psprkndv.js} +1 -1
  48. package/dist/{chunk-3svg41sb.js → chunk-q3xesyn0.js} +1 -1
  49. package/dist/{chunk-bm6yhhew.js → chunk-r86d03dv.js} +1 -1
  50. package/dist/{chunk-fbj9b0p6.js → chunk-s0226rfp.js} +4 -4
  51. package/dist/{chunk-hr3m2h4n.js → chunk-s0ntt1cn.js} +1 -1
  52. package/dist/{chunk-1b526cba.js → chunk-s0vs1n7n.js} +1 -1
  53. package/dist/{chunk-9h46mvew.js → chunk-sj6t3cj2.js} +1 -1
  54. package/dist/{chunk-pfc2h65d.js → chunk-smqgdmc4.js} +1 -1
  55. package/dist/{chunk-f178pm4d.js → chunk-tjwv101c.js} +1 -1
  56. package/dist/chunk-twk9kr73.js +2 -0
  57. package/dist/{chunk-z6enp6s3.js → chunk-v7xpafs9.js} +1 -1
  58. package/dist/{chunk-q0v0cs2j.js → chunk-vjt6c16n.js} +1 -1
  59. package/dist/{chunk-h1bnge85.js → chunk-vvezfjt1.js} +1 -1
  60. package/dist/chunk-ywydtzba.js +2 -0
  61. package/dist/{chunk-1zjn5p5c.js → chunk-yxp7jmnz.js} +1 -1
  62. package/dist/{chunk-trzanjcp.js → chunk-znhrftsf.js} +1 -1
  63. package/dist/cli.js +7 -7
  64. package/dist/craft-entry.js +1 -1
  65. package/dist/craft.js +1 -1
  66. package/dist/menubar.d.ts +1 -0
  67. package/dist/menubar.js +27 -5
  68. package/dist/pwa.js +1 -1
  69. package/dist/ssg.js +2 -2
  70. package/dist/utils.js +2 -2
  71. package/package.json +5 -5
  72. package/dist/chunk-5j1bb675.js +0 -2
  73. package/dist/chunk-5rn0k6kq.js +0 -2
  74. package/dist/chunk-aprvds2c.js +0 -2
  75. package/dist/chunk-gcy2prwj.js +0 -2
  76. package/dist/chunk-gpk0ew71.js +0 -2
  77. package/dist/chunk-jk16vj3c.js +0 -2
  78. package/dist/chunk-kz9xs9gn.js +0 -2
  79. package/dist/chunk-m5y0tgax.js +0 -2
  80. package/dist/chunk-mpgf9zbd.js +0 -2
  81. package/dist/chunk-qk34p70z.js +0 -2
  82. package/dist/chunk-yxg5na8z.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{se,ue,un,At,Pt,g,n,pe,d}from"./chunk-pe9ry4mj.js";import{gt,$e,oa,Lr,to,no,o}from"./chunk-nm7b8cmr.js";import{ie,fr,xe,D,bn}from"./chunk-r0ys9aqa.js";import{vt,tr,ns,rs,ss,wt,xt,St,kt,_t,Ct,Ye}from"./chunk-kypwg2ws.js";import{Jr,i,R}from"./chunk-jhr08gjs.js";import{ut,Ri,ke,O,Ai,Hs,Pr,Ve,Pi,_e}from"./chunk-rtfyx54t.js";import{Zn,Qn}from"./chunk-95yt1gxa.js";import{kn}from"./chunk-t2twa7wy.js";import{e,nn,Kn,h}from"./chunk-qy26afdn.js";import{Ke}from"./chunk-zff3cb1e.js";import{Te}from"./chunk-374nhgyf.js";import{q,he,ye}from"./chunk-fbj9b0p6.js";import{c}from"./chunk-xvs84gas.js";import{W}from"./chunk-078as147.js";async function Fn(t){try{let r=await Bun.file(t).text(),s=zn(r),p=Nn(r,t),a=Un(r,s),l=Wn(r,s);return{file:t,metrics:s,issues:p,suggestions:a,performance:l}}catch(r){throw Error(`Failed to analyze template ${t}: ${r instanceof Error?r.message:String(r)}`)}}function zn(t){let r=t.split(`
2
+ import{se,ue,un,At,Pt,g,n,pe,d}from"./chunk-4f5bmy7h.js";import{gt,$e,oa,Lr,to,no,o}from"./chunk-4mqq6896.js";import{ie,fr,xe,D,bn}from"./chunk-r0ys9aqa.js";import{vt,tr,ns,rs,ss,wt,xt,St,kt,_t,Ct,Ye}from"./chunk-kypwg2ws.js";import{Jr,i,R}from"./chunk-h176dx1q.js";import{ut,Ri,ke,O,Ai,Hs,Pr,Ve,Pi,_e}from"./chunk-jk0gba16.js";import{Zn,Qn}from"./chunk-nc85m4p9.js";import{kn}from"./chunk-bzxfbh2x.js";import{e,nn,Kn,h}from"./chunk-jt9kxnva.js";import{Ke}from"./chunk-mwmmmbxj.js";import{Te}from"./chunk-374nhgyf.js";import{q,he,ye}from"./chunk-s0226rfp.js";import{c}from"./chunk-xvs84gas.js";import{W}from"./chunk-078as147.js";async function Fn(t){try{let r=await Bun.file(t).text(),s=zn(r),p=Nn(r,t),a=Un(r,s),l=Wn(r,s);return{file:t,metrics:s,issues:p,suggestions:a,performance:l}}catch(r){throw Error(`Failed to analyze template ${t}: ${r instanceof Error?r.message:String(r)}`)}}function zn(t){let r=t.split(`
3
3
  `),s=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),a=(s?s[1]:"").split(`
4
4
  `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let f=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,m=f+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of r)if(/@(?:if|unless|foreach|for|while|section)\b/.test(T)&&!/@end/.test(T)&&!/@else/.test(T))C++,S=Math.max(S,C);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(T))C--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+m*0.1+b*0.3+(a>10?a*0.05:0)+v));return{lines:r.length,characters:t.length,directives:l,expressions:m,components:b,layouts:w,scriptLines:a,complexity:x}}function Nn(t,r){let s=[],p=Kt(t,"if","endif");if(p>0)s.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let a=Kt(t,"foreach","endforeach");if(a>0)s.push({type:"error",category:"syntax",message:`Found ${a} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)s.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(f>0)s.push({type:"warning",category:"security",message:`Found ${f} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)s.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
5
5
  `).filter((b)=>b.length>120);if(y.length>0)s.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let m=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(m>3)s.push({type:"info",category:"maintainability",message:`Found ${m} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return s}function Un(t,r){let s=[];if(r.complexity>7)s.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(r.complexity>5&&r.directives.total>8)s.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(r.lines>100&&r.components===0)s.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(r.expressions>20)s.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)s.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(r.directives.total===0&&r.expressions<5)s.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(r.scriptLines>50)s.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return s}function Wn(t,r){let s=1;if(s+=r.directives.conditionals*0.1,s+=r.directives.loops*0.5,s+=r.directives.includes*2,s+=r.expressions*0.05,s+=r.components*1,r.scriptLines>10)s+=r.scriptLines*0.1;let p;if(r.expressions===0&&r.directives.total===0)p="high";else if(r.expressions<5&&r.directives.total<3)p="medium";else p="low";let a=[];if(s>10)a.push("Consider optimizing template complexity");if(p==="low"&&r.directives.total>5)a.push("Reduce dynamic content for better caching");if(r.components===0&&r.lines>40)a.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(s*100)/100,complexityScore:r.complexity,cacheability:p,recommendations:a}}function Kt(t,r,s){let p=t.replace(/<!--[\s\S]*?-->/g,""),a=(p.match(new RegExp(`@${r}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length;return Math.abs(a-l)}async function yi(t=["**/*.stx"],r){let s=[],p=[];for(let l of t){let f=await Array.fromAsync(new Bun.Glob(l).scan({cwd:r||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...f.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let f=await Fn(l);s.push(f)}catch(f){console.warn(`Failed to analyze ${l}:`,f)}let a=Vn(s);return{results:s,summary:a}}function Vn(t){let r=t.length,s=t.reduce((m,b)=>m+b.metrics.lines,0),p=r>0?t.reduce((m,b)=>m+b.metrics.complexity,0)/r:0,a=t.reduce((m,b)=>m+b.issues.length,0),l={};t.forEach((m)=>{m.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let f=r>0?t.reduce((m,b)=>m+b.performance.estimatedRenderTime,0)/r:0,u=Math.max(1,Math.min(10,Math.round(10-f/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(a>r*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:r,totalLines:s,avgComplexity:Math.round(p*100)/100,totalIssues:a,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as qn,readFile as Xn,readdir as Gn,stat as Xt,writeFile as Jn}from"fs/promises";import Re from"path";function en(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var tn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Yn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((r)=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function jt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function er(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function nr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function rr(t){let r=[];async function s(p){let a=await Gn(p,{withFileTypes:!0});a.sort((l,f)=>l.name.localeCompare(f.name));for(let l of a){let f=Re.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await s(f)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))r.push(f)}}return await s(t),r}function or(t,r){let s=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!s)return{};let p=s[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(a){throw Error(`${r}: <script component> must contain JSON metadata (${a.message})`)}}function sr(t,r){let s={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let a of p){if(!/\bclient\b/i.test(a[1])||/\bcomponent\b|\bstx:component\b/i.test(a[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(a[2])}catch(y){throw Error(`${r}: failed to transpile <script client> (${y.message})`)}let f=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=f.exec(l)){let y=u[1];if(tn.has(y))throw Error(`${r}: client ${en(y)}`);let m=f.lastIndex,b=1,w="",S=!1,C=m;for(;C<l.length&&b>0;C++){let x=l[C];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${r}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";s[y]=`${v}${y}(${u[2]}) {${l.slice(m,C-1)}}`,f.lastIndex=C}}return s}function ir(t){let r=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(r?r[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Gt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((r)=>r[1].trim()).filter(Boolean).join(`
@@ -876,7 +876,7 @@ else {
876
876
  };
877
877
  })();
878
878
  </script>
879
- `}function Ne(t,r,s={}){let p=zr(r,s),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+p+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function yt(t){let r=t.toLowerCase();return r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".sass")||r.endsWith(".less")}function bt(t){let r=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>r.endsWith(p))}function Tt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((s)=>s.test(t))}var tt=null;function $t(t){if(!tt)tt=new on(t);return tt}function st(){if(tt)tt.stop(),tt=null}import Rt from"path";var nt={name:"bun-plugin-stx",async setup(t){let s={...await i(),...t.config?.stx},p=new Set,a=s.webComponents?.enabled?`./${Rt.relative(Rt.dirname(t.config?.outdir||"dist"),s.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(s.webComponents?.enabled)try{let f=await Jr(s,p);if(l.push(...f),s.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(s.cache&&s.cachePath){let x=await Zn(f,s);if(x){if(s.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let y=await xe(()=>Bun.file(f).text(),"",(x)=>{throw new fr(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new fr(`stx file is empty: ${f}`,f);let{scriptContent:m,templateContent:b,allScripts:w}=se.time("script-extraction",()=>{let x=y,T=ue(y);if(T)x=T.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],I="",A=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",j=E.match(/<script\b([^>]*)>/i),K=j?j[1]:"";if(/\bserver\b/i.test(K))I=_;else A.push(E)}let M=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:I,templateContent:M,allScripts:A}}),S={__filename:f,__dirname:Rt.dirname(f),__stx:{webComponentsPath:a,builtComponents:l}};await xe(()=>g(m,S,f),void 0,(x)=>{let T=new ie(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,m.substring(0,100));if(D.log(T,{filePath:f,scriptContent:m}),s.debug)throw T});let v=await se.timeAsync("directive-processing",async()=>await o(b,S,f,s,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-3vjzezn1.js"),T=x(w.join(`
879
+ `}function Ne(t,r,s={}){let p=zr(r,s),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+p+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function yt(t){let r=t.toLowerCase();return r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".sass")||r.endsWith(".less")}function bt(t){let r=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>r.endsWith(p))}function Tt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((s)=>s.test(t))}var tt=null;function $t(t){if(!tt)tt=new on(t);return tt}function st(){if(tt)tt.stop(),tt=null}import Rt from"path";var nt={name:"bun-plugin-stx",async setup(t){let s={...await i(),...t.config?.stx},p=new Set,a=s.webComponents?.enabled?`./${Rt.relative(Rt.dirname(t.config?.outdir||"dist"),s.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(s.webComponents?.enabled)try{let f=await Jr(s,p);if(l.push(...f),s.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(s.cache&&s.cachePath){let x=await Zn(f,s);if(x){if(s.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let y=await xe(()=>Bun.file(f).text(),"",(x)=>{throw new fr(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new fr(`stx file is empty: ${f}`,f);let{scriptContent:m,templateContent:b,allScripts:w}=se.time("script-extraction",()=>{let x=y,T=ue(y);if(T)x=T.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],I="",A=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",j=E.match(/<script\b([^>]*)>/i),K=j?j[1]:"";if(/\bserver\b/i.test(K))I=_;else A.push(E)}let M=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:I,templateContent:M,allScripts:A}}),S={__filename:f,__dirname:Rt.dirname(f),__stx:{webComponentsPath:a,builtComponents:l}};await xe(()=>g(m,S,f),void 0,(x)=>{let T=new ie(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,m.substring(0,100));if(D.log(T,{filePath:f,scriptContent:m}),s.debug)throw T});let v=await se.timeAsync("directive-processing",async()=>await o(b,S,f,s,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-a5agchz8.js"),T=x(w.join(`
880
880
  `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
881
881
  `+v.slice(k);else v+=`
882
882
  ${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await Qn(f,v,u,s),s.debug)console.log(`Cached template ${f} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new ie(`Plugin processing failed: ${String(u)}`,f);if(D.log(y,{filePath:f,buildConfig:t.config}),bn.logDetailedError(y,{filePath:f,plugin:"bun-plugin-stx"}),s.debug)console.error("stx Plugin Error:",y);let m=y,b=m.line||null,w=m.context||null;return{contents:s.debug||W()?`<!DOCTYPE html>
@@ -939,7 +939,7 @@ ${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await Q
939
939
  <h1>Something went wrong</h1>
940
940
  <p>An internal error occurred. Please try again later.</p>
941
941
  </body>
942
- </html>`,loader:"html"}}})}};async function Cr(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=ge.resolve(t);if(!Be.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,r);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=c(process.cwd(),"output");Be.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let m=null,b=async()=>{try{let _={name:"public-assets",setup(we){we.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},j=await Bun.build({entrypoints:[u],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!j.success)return console.error(`${e.red}Build failed:${e.reset}`,j.logs),!1;let K=j.outputs.find((we)=>we.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return m=await Bun.file(K.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await b())return!1;let S=ge.dirname(u);await nn(S);let C=s;try{if(C=await We(s),C!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let _=r.hmrPort||C+1;l=$t({wsPort:_,verbose:!1}),f=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-m5y0tgax.js"),j=await _();if(T=r.stxOptions?.serverApi??j.serverApi,j?.apiRouter)x=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){v=j.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Y}=await import("./chunk-9rv27cdd.js"),we=j.broadcasting;await K(we);let le=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Pe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Pe))try{let ne=await Y(Pe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:I}=await import("./chunk-9m1agnnx.js"),A=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),a)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${f}${e.reset}`);let M=Nr({port:C,async fetch(_){return kn(_,await(async()=>{let j=new URL(_.url);if([y,ge.dirname(u),ge.join(process.cwd(),"public")].some((ne)=>I(ge.join(ne,j.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(_);if(ne.status!==404)return ne}catch{}if(v[j.pathname])try{return await v[j.pathname](_)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await A(_);if(K)return K;if(j.pathname==="/")return(async()=>{let F=await h(m||"");if(a)F=Ne(F,f);if(r.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(r.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(y,j.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=ge.extname(Y).toLowerCase(),L="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let we=ge.dirname(u),le=ge.join(we,j.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=ge.extname(le).toLowerCase(),L="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Pe=ge.join(process.cwd(),"public",j.pathname);if(Be.existsSync(Pe)&&Be.statSync(Pe).isFile()){let ne=Bun.file(Pe),F=ge.extname(Pe).toLowerCase(),L="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
942
+ </html>`,loader:"html"}}})}};async function Cr(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=ge.resolve(t);if(!Be.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,r);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=c(process.cwd(),"output");Be.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let m=null,b=async()=>{try{let _={name:"public-assets",setup(we){we.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},j=await Bun.build({entrypoints:[u],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!j.success)return console.error(`${e.red}Build failed:${e.reset}`,j.logs),!1;let K=j.outputs.find((we)=>we.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return m=await Bun.file(K.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await b())return!1;let S=ge.dirname(u);await nn(S);let C=s;try{if(C=await We(s),C!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let _=r.hmrPort||C+1;l=$t({wsPort:_,verbose:!1}),f=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-twk9kr73.js"),j=await _();if(T=r.stxOptions?.serverApi??j.serverApi,j?.apiRouter)x=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){v=j.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Y}=await import("./chunk-9rv27cdd.js"),we=j.broadcasting;await K(we);let le=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Pe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Pe))try{let ne=await Y(Pe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:I}=await import("./chunk-1pzshxft.js"),A=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),a)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${f}${e.reset}`);let M=Nr({port:C,async fetch(_){return kn(_,await(async()=>{let j=new URL(_.url);if([y,ge.dirname(u),ge.join(process.cwd(),"public")].some((ne)=>I(ge.join(ne,j.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(_);if(ne.status!==404)return ne}catch{}if(v[j.pathname])try{return await v[j.pathname](_)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await A(_);if(K)return K;if(j.pathname==="/")return(async()=>{let F=await h(m||"");if(a)F=Ne(F,f);if(r.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(r.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(y,j.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=ge.extname(Y).toLowerCase(),L="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let we=ge.dirname(u),le=ge.join(we,j.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=ge.extname(le).toLowerCase(),L="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Pe=ge.join(process.cwd(),"public",j.pathname);if(Be.existsSync(Pe)&&Be.statSync(Pe).isFile()){let ne=Bun.file(Pe),F=ge.extname(Pe).toLowerCase(),L="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
943
943
  ${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
944
944
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
945
945
  ${e.bright}\u2192 ${e.cyan}http://localhost:${C}/${e.reset}`),console.log(`
@@ -1426,12 +1426,12 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
1426
1426
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1427
1427
  ${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
1428
1428
  ${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),C=Object.entries(f).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ee.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Ee.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",I=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${I}`)}),console.log(`
1429
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(p)Xe.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),Ke.clear(),pe(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function ln(t){try{return un(await Bun.file(t).text())}catch{return}}function zt(t){let r=Bun.file(t),s=te.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(s)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(r,{headers:{"Content-Type":p[s]||"application/octet-stream",...l}})}async function Tr(t=".",r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=te.resolve(t),{loadStxConfig:y}=await import("./chunk-m5y0tgax.js"),m=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-9m1agnnx.js"),S=r.stxOptions?.serverApi??m.serverApi,C=await b(u,S),v=m.root&&m.root!=="."?te.join(u,m.root):u,x=r.pagesDir||m.pagesDir||"pages",T=te.join(v,x);if(!me.existsSync(T)&&!m._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=q(v,{pagesDir:x,pagesDirs:m._layerPageDirs?[T,...m._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let I=m?._pluginPageDirs||[],A=[];for(let{dir:P,prefix:H}of I)if(me.existsSync(P)){let z=q(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of z){let X=H==="/"?Q.pattern:`${H}${Q.pattern==="/"?"":Q.pattern}`;A.push({route:{...Q,pattern:X},prefix:H})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${H}${e.reset}`)}let M=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await Ai(u,r.stxOptions?.shell),_){if(E=await Hs(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}wt(),await St(u);let j=xt();if(j.length>0)console.log(`${e.blue}Loaded ${e.bright}${j.length}${e.blue} middleware: ${e.dim}${j.join(", ")}${e.reset}`);let K={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-m5y0tgax.js"),H=await P(u);if(H?.apiRouter)Y=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){K=H.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(H?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-9rv27cdd.js"),X=H.broadcasting;await z(X);let Oe=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let Se=te.join(process.cwd(),"channels.ts");if(me.existsSync(Se))try{let N=await Q(Se);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let we=c(u,"output");me.mkdirSync(we,{recursive:!0});let le=new Map,Pe=new Set,ne=async(P)=>{let H=rs(T,P);if(!H)return null;try{let z=await Bun.build({entrypoints:[H],outdir:we,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!z.success)return null;let Q=z.outputs.find((X)=>X.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,L=async(P,H)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Oe,injectRouterScript:Se}=await import("./chunk-m5y0tgax.js"),{checkCache:N,cacheTemplate:J,readFileCached:V,templateCache:de}=await import("./chunk-qkr7epna.js"),G=await Oe(u),Ue=(ae)=>{if(!ae)return ae;if(te.isAbsolute(ae))return ae;return te.resolve(u,ae)},ce={...X,...G,...r.stxOptions,autoShell:!0};if(r.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(u,"cache");let B=!H&&!r.profile,re=ce.cache!==!1;if(re&&B){let ae=de.get(P.filePath);if(ae)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=ae.mtime){let He=!0;for(let Ce of ae.dependencies){if(!me.existsSync(Ce)){He=!1;break}if((await me.promises.stat(Ce)).mtime.getTime()>ae.mtime){He=!1;break}}if(He){let Ce=ae.output;if(E)Ce=Ve(Ce,{preserveHead:!0});let ot=F.get(P.filePath);return{route:P,content:Ce,status:ot?.status??await ln(P.filePath),headers:ot?.headers}}}}catch{}let Ie=await N(P.filePath,ce);if(Ie){let je=Ie;if(E)je=Ve(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await ln(P.filePath),headers:He?.headers}}}let Z=re?await V(P.filePath):await Bun.file(P.filePath).text(),oe=un(Z),{classifyAllScripts:fe}=await import("./chunk-m5y0tgax.js"),U=fe(Z),Le=U.server.map((ae)=>ae.content),De=Z;for(let ae of U.server)De=De.replace(ae.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:H??{},__stx_runtime_head:{}};for(let ae of Le)try{await Q(ae,ee,P.filePath)}catch(Ie){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Ae=new Set,be;if(r.profile){let ae=performance.now();be=await z(De,ee,P.filePath,ce,Ae);let Ie=performance.now()-ae,je=te.relative(u,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else be=await z(De,ee,P.filePath,ce,Ae);if(!E)be=await Se(be,{router:ce.router});{let{interpolateScriptExpressions:ae}=await import("./chunk-3vjzezn1.js");be=be.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ae(He,ee)}</script>`})}if(E)be=Ve(be,{preserveHead:!0});if(re&&B)await J(P.filePath,be,Ae,ce);let{extractStreamBoundaries:at}=await import("./chunk-qk34p70z.js"),Qe=at(ee),rt=ee.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ae=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(rt).map((Ce)=>({id:Ce,render:async()=>{let ot=typeof ae[Ce]==="function"?await ae[Ce]():void 0;return z(rt[Ce],{...ee,$boundary:ot},P.filePath,Ie,new Set)}})),He=new Set(je.map((Ce)=>Ce.id));Qe=[...(Qe||[]).filter((Ce)=>!He.has(Ce.id)),...je]}if(Qe&&Qe.length>0)Pe.add(P.pattern);else Qe=void 0;let Wt=At(ee),Vt=Pt(ee);if(B)F.set(P.filePath,{status:Wt,headers:Vt});return{route:P,content:be,status:Wt??oe,headers:Vt,boundaries:Qe}}catch(z){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,z),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),H=new Set(M.keys());le.clear(),M.clear();let z=r.prebuild===!1?k.filter((X)=>P.has(X.pattern)):k,Q=r.prebuild===!1?A.filter(({route:X})=>H.has(X.pattern)):A;for(let X=0;X<z.length;X+=Fe){let Oe=z.slice(X,X+Fe),Se=await Promise.all(Oe.map((N)=>L(N)));for(let N of Se)if(N)le.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Oe=Q.slice(X,X+Fe),Se=await Promise.all(Oe.map(({route:N})=>L(N)));for(let N of Se)if(N)M.set(N.route.pattern,N)}return le.size>0};if(console.log(`${e.blue}${r.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(r.prebuild===!1?k.length+A.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await nn(u);let Ge=s;try{if(Ge=await We(s),Ge!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Ge+1;l=$t({wsPort:P,verbose:!1}),f=l.start(P)}let Ot=(P,H)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(H).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Wr({port:Ge,hostname:r.hostname,async fetch(P){let H=new URL(P.url),z=r.stxOptions?.offline??m.offline;if(H.pathname===to&&z?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:no(z,Lr()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=m?.publicDir||"public",X=te.join(u,Q,H.pathname),Oe=te.join(u,H.pathname),Se=te.join(we,H.pathname);if([X,Oe,Se].some((B)=>w(B,u,S)))return new Response("Not Found",{status:404});let[N,J,V]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(Se).catch(()=>null)]);if(N?.isFile()&&!w(X,u,S))return zt(X);if(J?.isFile()&&!w(Oe,u,S))return zt(Oe);if(V?.isFile()&&!w(Se,u,S))return zt(Se);if(H.pathname.startsWith("/_stx/component/")){let B=decodeURIComponent(H.pathname.slice(16));if(B)try{let re=`<${B} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(u,"components",`${B}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(H.pathname==="/_stx/img"){let{handleImageRequest:B}=await import("./chunk-ykjzhfyf.js"),re=await B(P,{publicDir:te.join(u,Q),cacheDir:c(u,"cache","img")});if(re)return re}if(Y)try{let B=await Y.handleRequest(P);if(B.status!==404)return B}catch{}if(K[H.pathname])try{return await K[H.pathname](P)}catch(B){return new Response(JSON.stringify({error:B.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await C(P);if(de)return de;let G=tr(H.pathname,k);if(G){let B=le.get(G.route.pattern),re=Pe.has(G.route.pattern);if(!B||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(B=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(B){let Z=B.status??200,oe=B.headers??{},fe=(G.route.filePath?gt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let De=await ne(404);if(De){let ee=De;if(ee=await h(ee,u),a)ee=Ne(ee,f);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Le=kt(H.pathname,G.params,fe,H.search),De=_t(Le,null,P,{isServer:!0}),ee=await Ct(fe.middleware,De);if(ee.redirect){let Ae=ee.redirect.path,be=ee.redirect.options.redirectCode||302,at=new Headers(ee.responseHeaders);return at.set("Location",Ae),new Response(null,{status:be,headers:at})}if(ee.abort){let{statusCode:Ae,message:be}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Ae}</title></head><body><h1>Error ${Ae}</h1><p>${be}</p></body></html>`,{status:Ae,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Ae=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;B.content=B.content.replace("</head>",`${Ae}</head>`)}}let U=B.content;if(E&&Pi(P)){let Le=Ye(U),De=he(U),ee=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Ae=ee?Ri(ee[1].trim()):"";if(Object.keys(G.params).length>0)U=Ot(U,G.params);U=await h(U,u);let be=m?.router?.container||"main";return U=_e(U,be),new Response(U,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Ae&&{"X-STX-Title":encodeURIComponent(Ae)},[oa]:Lr(),...O(),"Cache-Control":ut}})}if(E)U=Pr(E,U);if(Object.keys(G.params).length>0)U=Ot(U,G.params);if(U=await h(U,u),a)U=Ne(U,f);if(r.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(r.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;if(B.boundaries&&B.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-qk34p70z.js");return De(Le(U,B.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:Z,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(A.length>0){let B=A.map((Z)=>Z.route),re=tr(H.pathname,B);if(re){let Z=M.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await L(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)M.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(E)oe=Pr(E,oe);if(Object.keys(re.params).length>0)oe=Ot(oe,re.params);if(oe=await h(oe,u),a)oe=Ne(oe,f);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of I)if(Z!=="/"&&H.pathname.startsWith(Z)){let oe=M.get(Z)||M.get(Z+"/");if(!oe){let fe=A.find(({route:U})=>U.pattern===Z||U.pattern===`${Z}/`);if(fe){let U=await L(fe.route);if(U)oe=U,M.set(fe.route.pattern,U)}}if(oe){let fe=oe.content;if(E)fe=Pr(E,fe);if(fe=await h(fe,u),a)fe=Ne(fe,f);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(vt(H.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let B=Ue.content;if(B=await h(B,u),a)B=Ne(B,f);if(r.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;return new Response(B,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let B=ce;if(B=await h(B,u),a)B=Ne(B,f);return new Response(B,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let H=await ne(500);if(H)return new Response(H,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1429
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(p)Xe.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),Ke.clear(),pe(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function ln(t){try{return un(await Bun.file(t).text())}catch{return}}function zt(t){let r=Bun.file(t),s=te.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(s)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(r,{headers:{"Content-Type":p[s]||"application/octet-stream",...l}})}async function Tr(t=".",r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=te.resolve(t),{loadStxConfig:y}=await import("./chunk-twk9kr73.js"),m=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-1pzshxft.js"),S=r.stxOptions?.serverApi??m.serverApi,C=await b(u,S),v=m.root&&m.root!=="."?te.join(u,m.root):u,x=r.pagesDir||m.pagesDir||"pages",T=te.join(v,x);if(!me.existsSync(T)&&!m._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=q(v,{pagesDir:x,pagesDirs:m._layerPageDirs?[T,...m._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let I=m?._pluginPageDirs||[],A=[];for(let{dir:P,prefix:H}of I)if(me.existsSync(P)){let z=q(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of z){let X=H==="/"?Q.pattern:`${H}${Q.pattern==="/"?"":Q.pattern}`;A.push({route:{...Q,pattern:X},prefix:H})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${H}${e.reset}`)}let M=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await Ai(u,r.stxOptions?.shell),_){if(E=await Hs(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}wt(),await St(u);let j=xt();if(j.length>0)console.log(`${e.blue}Loaded ${e.bright}${j.length}${e.blue} middleware: ${e.dim}${j.join(", ")}${e.reset}`);let K={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-twk9kr73.js"),H=await P(u);if(H?.apiRouter)Y=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){K=H.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(H?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-9rv27cdd.js"),X=H.broadcasting;await z(X);let Oe=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let Se=te.join(process.cwd(),"channels.ts");if(me.existsSync(Se))try{let N=await Q(Se);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let we=c(u,"output");me.mkdirSync(we,{recursive:!0});let le=new Map,Pe=new Set,ne=async(P)=>{let H=rs(T,P);if(!H)return null;try{let z=await Bun.build({entrypoints:[H],outdir:we,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!z.success)return null;let Q=z.outputs.find((X)=>X.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,L=async(P,H)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Oe,injectRouterScript:Se}=await import("./chunk-twk9kr73.js"),{checkCache:N,cacheTemplate:J,readFileCached:V,templateCache:de}=await import("./chunk-jkhc0q7g.js"),G=await Oe(u),Ue=(ae)=>{if(!ae)return ae;if(te.isAbsolute(ae))return ae;return te.resolve(u,ae)},ce={...X,...G,...r.stxOptions,autoShell:!0};if(r.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(u,"cache");let B=!H&&!r.profile,re=ce.cache!==!1;if(re&&B){let ae=de.get(P.filePath);if(ae)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=ae.mtime){let He=!0;for(let Ce of ae.dependencies){if(!me.existsSync(Ce)){He=!1;break}if((await me.promises.stat(Ce)).mtime.getTime()>ae.mtime){He=!1;break}}if(He){let Ce=ae.output;if(E)Ce=Ve(Ce,{preserveHead:!0});let ot=F.get(P.filePath);return{route:P,content:Ce,status:ot?.status??await ln(P.filePath),headers:ot?.headers}}}}catch{}let Ie=await N(P.filePath,ce);if(Ie){let je=Ie;if(E)je=Ve(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await ln(P.filePath),headers:He?.headers}}}let Z=re?await V(P.filePath):await Bun.file(P.filePath).text(),oe=un(Z),{classifyAllScripts:fe}=await import("./chunk-twk9kr73.js"),U=fe(Z),Le=U.server.map((ae)=>ae.content),De=Z;for(let ae of U.server)De=De.replace(ae.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:H??{},__stx_runtime_head:{}};for(let ae of Le)try{await Q(ae,ee,P.filePath)}catch(Ie){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Ae=new Set,be;if(r.profile){let ae=performance.now();be=await z(De,ee,P.filePath,ce,Ae);let Ie=performance.now()-ae,je=te.relative(u,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else be=await z(De,ee,P.filePath,ce,Ae);if(!E)be=await Se(be,{router:ce.router});{let{interpolateScriptExpressions:ae}=await import("./chunk-a5agchz8.js");be=be.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ae(He,ee)}</script>`})}if(E)be=Ve(be,{preserveHead:!0});if(re&&B)await J(P.filePath,be,Ae,ce);let{extractStreamBoundaries:at}=await import("./chunk-2mf8shg5.js"),Qe=at(ee),rt=ee.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ae=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(rt).map((Ce)=>({id:Ce,render:async()=>{let ot=typeof ae[Ce]==="function"?await ae[Ce]():void 0;return z(rt[Ce],{...ee,$boundary:ot},P.filePath,Ie,new Set)}})),He=new Set(je.map((Ce)=>Ce.id));Qe=[...(Qe||[]).filter((Ce)=>!He.has(Ce.id)),...je]}if(Qe&&Qe.length>0)Pe.add(P.pattern);else Qe=void 0;let Wt=At(ee),Vt=Pt(ee);if(B)F.set(P.filePath,{status:Wt,headers:Vt});return{route:P,content:be,status:Wt??oe,headers:Vt,boundaries:Qe}}catch(z){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,z),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),H=new Set(M.keys());le.clear(),M.clear();let z=r.prebuild===!1?k.filter((X)=>P.has(X.pattern)):k,Q=r.prebuild===!1?A.filter(({route:X})=>H.has(X.pattern)):A;for(let X=0;X<z.length;X+=Fe){let Oe=z.slice(X,X+Fe),Se=await Promise.all(Oe.map((N)=>L(N)));for(let N of Se)if(N)le.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Oe=Q.slice(X,X+Fe),Se=await Promise.all(Oe.map(({route:N})=>L(N)));for(let N of Se)if(N)M.set(N.route.pattern,N)}return le.size>0};if(console.log(`${e.blue}${r.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(r.prebuild===!1?k.length+A.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await nn(u);let Ge=s;try{if(Ge=await We(s),Ge!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Ge+1;l=$t({wsPort:P,verbose:!1}),f=l.start(P)}let Ot=(P,H)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(H).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Wr({port:Ge,hostname:r.hostname,async fetch(P){let H=new URL(P.url),z=r.stxOptions?.offline??m.offline;if(H.pathname===to&&z?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:no(z,Lr()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=m?.publicDir||"public",X=te.join(u,Q,H.pathname),Oe=te.join(u,H.pathname),Se=te.join(we,H.pathname);if([X,Oe,Se].some((B)=>w(B,u,S)))return new Response("Not Found",{status:404});let[N,J,V]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(Se).catch(()=>null)]);if(N?.isFile()&&!w(X,u,S))return zt(X);if(J?.isFile()&&!w(Oe,u,S))return zt(Oe);if(V?.isFile()&&!w(Se,u,S))return zt(Se);if(H.pathname.startsWith("/_stx/component/")){let B=decodeURIComponent(H.pathname.slice(16));if(B)try{let re=`<${B} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(u,"components",`${B}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(H.pathname==="/_stx/img"){let{handleImageRequest:B}=await import("./chunk-ykjzhfyf.js"),re=await B(P,{publicDir:te.join(u,Q),cacheDir:c(u,"cache","img")});if(re)return re}if(Y)try{let B=await Y.handleRequest(P);if(B.status!==404)return B}catch{}if(K[H.pathname])try{return await K[H.pathname](P)}catch(B){return new Response(JSON.stringify({error:B.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await C(P);if(de)return de;let G=tr(H.pathname,k);if(G){let B=le.get(G.route.pattern),re=Pe.has(G.route.pattern);if(!B||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(B=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(B){let Z=B.status??200,oe=B.headers??{},fe=(G.route.filePath?gt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let De=await ne(404);if(De){let ee=De;if(ee=await h(ee,u),a)ee=Ne(ee,f);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Le=kt(H.pathname,G.params,fe,H.search),De=_t(Le,null,P,{isServer:!0}),ee=await Ct(fe.middleware,De);if(ee.redirect){let Ae=ee.redirect.path,be=ee.redirect.options.redirectCode||302,at=new Headers(ee.responseHeaders);return at.set("Location",Ae),new Response(null,{status:be,headers:at})}if(ee.abort){let{statusCode:Ae,message:be}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Ae}</title></head><body><h1>Error ${Ae}</h1><p>${be}</p></body></html>`,{status:Ae,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Ae=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;B.content=B.content.replace("</head>",`${Ae}</head>`)}}let U=B.content;if(E&&Pi(P)){let Le=Ye(U),De=he(U),ee=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Ae=ee?Ri(ee[1].trim()):"";if(Object.keys(G.params).length>0)U=Ot(U,G.params);U=await h(U,u);let be=m?.router?.container||"main";return U=_e(U,be),new Response(U,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Ae&&{"X-STX-Title":encodeURIComponent(Ae)},[oa]:Lr(),...O(),"Cache-Control":ut}})}if(E)U=Pr(E,U);if(Object.keys(G.params).length>0)U=Ot(U,G.params);if(U=await h(U,u),a)U=Ne(U,f);if(r.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(r.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;if(B.boundaries&&B.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-2mf8shg5.js");return De(Le(U,B.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:Z,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(A.length>0){let B=A.map((Z)=>Z.route),re=tr(H.pathname,B);if(re){let Z=M.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await L(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)M.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(E)oe=Pr(E,oe);if(Object.keys(re.params).length>0)oe=Ot(oe,re.params);if(oe=await h(oe,u),a)oe=Ne(oe,f);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of I)if(Z!=="/"&&H.pathname.startsWith(Z)){let oe=M.get(Z)||M.get(Z+"/");if(!oe){let fe=A.find(({route:U})=>U.pattern===Z||U.pattern===`${Z}/`);if(fe){let U=await L(fe.route);if(U)oe=U,M.set(fe.route.pattern,U)}}if(oe){let fe=oe.content;if(E)fe=Pr(E,fe);if(fe=await h(fe,u),a)fe=Ne(fe,f);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(vt(H.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let B=Ue.content;if(B=await h(B,u),a)B=Ne(B,f);if(r.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;return new Response(B,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let B=ce;if(B=await h(B,u),a)B=Ne(B,f);return new Response(B,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let H=await ne(500);if(H)return new Response(H,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1430
1430
  ${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1431
1431
  ${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
1432
1432
  ${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),a)console.log(`${e.dim} HMR: ws://localhost:${f}${e.reset}`);console.log(`
1433
1433
  ${e.yellow}Routes:${e.reset}`);let Mt=[...ss(k,u)];for(let{route:P}of A)Mt.push(`${P.pattern}`);if(Mt.forEach((P,H)=>{let Q=H===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
1434
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.url.toString(),()=>{if(l)st();Dt.stop()}),r.native){let P,H=te.join(T,"index.stx");if(me.existsSync(H)){let Q=await Bun.file(H).text();P=ht(Q)}let z=m?.app?.window??{};await Ze(Ge,{title:m?.app?.head?.title||te.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(N)=>N.startsWith("public/")||N.startsWith("public\\"),H=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([u,...m._layerGraph?.layers.map((J)=>J.root)??[],...m._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of m._layerGraph?.layers??[])for(let V of Object.values(J.resources)){if(!me.existsSync(V))continue;let de=me.realpathSync(V);if(![...N].some((G)=>de===G||de.startsWith(`${G}${te.sep}`)))N.add(de)}for(let[J,V]of z)if(!N.has(J))V.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(V,de)=>{Oe(J,V,de).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Oe=(N,J,V)=>(X=X.catch(()=>{}).then(()=>Se(N,J,V)),X),Se=async(N,J,V)=>{if(!V||Tt(V))return;if(bt(V)){if(m._layerGraph){let de=await y(u);Object.assign(m,de),k.splice(0,k.length,...q(v,{pagesDir:x,pagesDirs:de._layerPageDirs?[T,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),a&&l)l.reload(V)}else if(H(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-qkr7epna.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(_&&V){if(te.resolve(N,V)===_||te.basename(_)===V){let G=await Hs(_,r.stxOptions||{});if(G)E=G}}if(await ze(),await Kn(u),a&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-qkr7epna.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(await ze(),a&&l)l.reload(V)}}else if(yt(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),a&&l)l.updateCss(V)}};Q(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(l)st();Dt.stop(),process.exit(0)})}return!0}import Nt from"fs";import it from"path";async function Vr(t){try{let s=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return[];let p=s[1],a=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,f;while((f=l.exec(p))!==null){let u=f[1],y=f[2]||f[3]||f[4];if(!y)continue;let m={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)m.type=b[1].trim();if(u.match(/@required/i))m.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)m.default=S[1].trim();let C=u.split(`
1434
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.url.toString(),()=>{if(l)st();Dt.stop()}),r.native){let P,H=te.join(T,"index.stx");if(me.existsSync(H)){let Q=await Bun.file(H).text();P=ht(Q)}let z=m?.app?.window??{};await Ze(Ge,{title:m?.app?.head?.title||te.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(N)=>N.startsWith("public/")||N.startsWith("public\\"),H=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([u,...m._layerGraph?.layers.map((J)=>J.root)??[],...m._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of m._layerGraph?.layers??[])for(let V of Object.values(J.resources)){if(!me.existsSync(V))continue;let de=me.realpathSync(V);if(![...N].some((G)=>de===G||de.startsWith(`${G}${te.sep}`)))N.add(de)}for(let[J,V]of z)if(!N.has(J))V.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(V,de)=>{Oe(J,V,de).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Oe=(N,J,V)=>(X=X.catch(()=>{}).then(()=>Se(N,J,V)),X),Se=async(N,J,V)=>{if(!V||Tt(V))return;if(bt(V)){if(m._layerGraph){let de=await y(u);Object.assign(m,de),k.splice(0,k.length,...q(v,{pagesDir:x,pagesDirs:de._layerPageDirs?[T,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),a&&l)l.reload(V)}else if(H(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-jkhc0q7g.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(_&&V){if(te.resolve(N,V)===_||te.basename(_)===V){let G=await Hs(_,r.stxOptions||{});if(G)E=G}}if(await ze(),await Kn(u),a&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-jkhc0q7g.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(await ze(),a&&l)l.reload(V)}}else if(yt(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),a&&l)l.updateCss(V)}};Q(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(l)st();Dt.stop(),process.exit(0)})}return!0}import Nt from"fs";import it from"path";async function Vr(t){try{let s=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return[];let p=s[1],a=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,f;while((f=l.exec(p))!==null){let u=f[1],y=f[2]||f[3]||f[4];if(!y)continue;let m={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)m.type=b[1].trim();if(u.match(/@required/i))m.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)m.default=S[1].trim();let C=u.split(`
1435
1435
  `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);m.description=C.join(" ").trim(),a.push(m)}if(a.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let m=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of m){let[w]=b.split(":").map((S)=>S.trim());if(w)a.push({name:w})}}}return a}catch(r){return console.error(`Error extracting props from ${t}:`,r),[]}}async function qr(t){try{let r=await Bun.file(t).text(),s=r.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||r.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(s)return s[1].split(`
1436
1436
  `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Kr(t,r=!1,s){let p=it.basename(t,".stx"),a=await Vr(t),l=await qr(t),f="";if(r&&s)f=`<${s}></${s}>`;else{let u=a.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
1437
1437
  `);f=`<${p}
@@ -1,2 +1,2 @@
1
1
  // @bun
2
- import{$l,Vr}from"./chunk-h1bnge85.js";import"./chunk-hx787tfa.js";import"./chunk-jgxzbthg.js";import{ur}from"./chunk-pe9ry4mj.js";import"./chunk-f178pm4d.js";import"./chunk-t6m5d64b.js";import{tt}from"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{tt as freeIdentifiers,Vr as processComponents,$l as processESImports,ur as rendersAsElement};
2
+ import{$l,Vr}from"./chunk-vvezfjt1.js";import"./chunk-hx787tfa.js";import"./chunk-jgxzbthg.js";import{ur}from"./chunk-4f5bmy7h.js";import"./chunk-tjwv101c.js";import"./chunk-t6m5d64b.js";import{tt}from"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{tt as freeIdentifiers,Vr as processComponents,$l as processESImports,ur as rendersAsElement};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{Vn,Te}from"./chunk-374nhgyf.js";import{L,b,ir,ds,k}from"./chunk-pe9ry4mj.js";import{i,R}from"./chunk-jhr08gjs.js";import{eo}from"./chunk-68wa4bf0.js";import{Qe}from"./chunk-yn9kvsk1.js";import{c}from"./chunk-xvs84gas.js";import{r,fe}from"./chunk-9tg4995v.js";import d from"path";import v from"fs";import{AsyncLocalStorage as gt}from"async_hooks";var ht=11;function X(t,e,n){return/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(d.basename(t))||eo(t,e,n)}var ot=2;function gl(t){let e=process.env.STX_BUNDLE_CACHE_DIR?.trim();return e?d.resolve(e):c(t,"bundle-cache")}function nt(t,e){let n=t;for(let o of xt(e))if(o!==d.sep)n=n.split(o).join("\x00root");return n}var st=new Map;function xt(t){let e=d.resolve(t),n=st.get(e);if(!n){let o=e;try{o=v.realpathSync(e)}catch{}n=[...new Set([e,o])].sort((u,m)=>m.length-u.length),st.set(e,n)}return n}function $t(t,e){try{let n=v.statSync(t),o=d.resolve(e),u=t.startsWith(`${o}${d.sep}`);return{path:u?d.relative(o,t):t,...u?{inRoot:!0}:{},mtimeMs:n.mtimeMs,size:n.size,hash:Bun.hash(v.readFileSync(t)).toString(36)}}catch{return null}}function at(t,e){return t.inRoot?d.join(d.resolve(e),t.path):t.path}function yt(t,e){for(let n of t){let o=at(n,e);try{let u=v.statSync(o);if(u.size!==n.size)return!1;if(u.mtimeMs!==n.mtimeMs&&Bun.hash(v.readFileSync(o)).toString(36)!==n.hash)return!1}catch{return!1}}return!0}var ct=new Map,bt=100;function ml(t=process.env){let e=Number(t.STX_BUNDLE_CACHE_LIMIT);return Number.isFinite(e)&&e>=1?Math.floor(e):2000}var G=new Map;async function wt(t){let e=G.get(t)??0;if(e>0&&e<bt){G.set(t,e+1);return}G.set(t,1);try{let n=(await v.promises.readdir(t)).filter((l)=>l.endsWith(".js")),o=ml();if(n.length<=o)return;let m=(await Promise.all(n.map(async(l)=>{try{return{name:l,at:(await v.promises.stat(d.join(t,l))).mtimeMs}}catch{return null}}))).filter((l)=>l!==null);m.sort((l,y)=>y.at-l.at);for(let l of m.slice(o)){let y=l.name.slice(0,-3);await v.promises.rm(d.join(t,`${y}.js`),{force:!0}),await v.promises.rm(d.join(t,`${y}.deps.json`),{force:!0})}O("pruned bundle cache to",o,"entries")}catch{}}function Ee(t){return ct.get(t)??[]}function q(t,e){if(t)ct.set(t,e)}function hl(t=process.env){return t.STX_DEBUG==="true"||t.STX_DEBUG==="1"}function O(...t){if(hl())console.log("[stx:bundler]",...t)}var Y=[];function ra(t,e,n){Y.push({filePath:t||"<inline>",message:e,details:n})}function Xt(){return Y.slice()}function Jt(){Y.length=0}var Z;function cp(t){Z=t}function sa(){if(Z)return Z;try{let t=R.strict;return typeof t==="object"&&t!==null?t.bundlerFallback??"warn":"warn"}catch{return"warn"}}var Q=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function Yt(t){let e=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,n;while((n=e.exec(t))!==null){let u=n[1];if(!Q.some((l)=>l.test(u)))return O("detected user import:",u),!0}let o=/^[ \t]*import[ \t]*['"]([^'"]+)['"]/gm;while((n=o.exec(t))!==null){let u=n[1];if(/\.css(?:\?.*)?$/.test(u))continue;if(!Q.some((l)=>l.test(u)))return O("detected side-effect import:",u),!0}return!1}var Hn="stx-module:",St=/\.(?:[cm]?[jt]sx?|json)$/i;function yl(t,e){return d.relative(t,e).split(d.sep).join("/")}function bl(t,e){if(e.size===0)return t;return t.replace(/^([ \t]*import(?:(?:\s+|(?=[{*]))[^;"']*?\s*from\s*|\s*))(["'])([^"']+)\2/gm,(n,o,u,m)=>{let l=e.get(m);return l&&!m.startsWith(Hn)?`${o}${u}${l}${u}`:n})}function vl(t,e){let n=0,o=(m)=>{let l=`__stxMod${n++}`,y=JSON.stringify(m);return e.push(`var ${l} = globalThis.__stxModules && globalThis.__stxModules[${y}];`,`if (${l} === undefined) throw new Error("[stx] module " + ${JSON.stringify(y)} + " is not registered on this page (#1957)");`),l},u=(m,l)=>{for(let y of m.split(",")){let F=y.trim();if(!F)continue;let B=F.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!B)continue;let j=B[1].startsWith('"')?JSON.parse(B[1]):B[1],p=B[2]??j;e.push(`var ${p} = ${l}[${JSON.stringify(j)}];`)}};return t=t.replace(/^[ \t]*import(?:\s+|(?=[{*]))([^;"']+?)\s*from\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(m,l,y)=>{let F=y.slice(Hn.length),B=o(F),j=l.trim(),p=j.match(/^([\w$]+)\s*(?:,\s*|$)/);if(p&&!j.startsWith("{")&&!j.startsWith("*"))e.push(`var ${p[1]} = ${B}.default;`),j=j.slice(p[0].length).trim();let s=j.match(/^\*\s*as\s+([\w$]+)$/);if(s)e.push(`var ${s[1]} = ${B};`);else if(j.startsWith("{"))u(j.replace(/^\{|\}$/g,""),B);return""}),t=t.replace(/^[ \t]*import\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(m,l)=>(o(l.slice(Hn.length)),"")),t}function rt(t){let e=[t,`${t}.ts`,`${t}.tsx`,`${t}.js`,`${t}.mjs`,`${t}.jsx`,d.join(t,"index.ts"),d.join(t,"index.tsx"),d.join(t,"index.js"),d.join(t,"index.mjs")];for(let n of e)try{if(v.existsSync(n)&&v.statSync(n,{throwIfNoEntry:!1})?.isFile())return n}catch{}return}var K=new gt;function Js(t,e){let n=new Bun.CryptoHasher("md5");for(let[o,u]of[...t].sort(([m],[l])=>m<l?-1:m>l?1:0))n.update(`${o}\x00${u}\x00`);return K.run({modules:t,key:n.digest("hex").slice(0,12)},e)}function Zt(){return K.getStore()?.key??""}function vt(t,e,n,o,u,m,l=new Map,y,F){let B=(p,s,a)=>{if(X(s,t,y))return null;if(!m||p!==n||!St.test(s))return null;try{if(!v.statSync(s,{throwIfNoEntry:!1})?.isFile())return null}catch{return null}u.add(s);let w=`${Hn}${yl(process.cwd(),s)}`;return l.set(a,w),{path:w,external:!0}},j=(p,s)=>{let a=p===n?e:d.dirname(p),w=d.resolve(a,s);return rt(w)??w};return{name:"stx-client-bundle",setup(p){if(p.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(s)=>({path:s.path,external:!0})),p.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(s)=>({path:s.path,external:!0})),p.onResolve({filter:/^\//},(s)=>{if(s.path===n)return{path:n};let a=rt(s.path);if(a){let w=B(s.importer,a,s.path);if(w)return w;if(a!==n)u.add(a);return{path:a}}return{path:s.path,external:!0}}),p.onResolve({filter:/^\.\.?\//},(s)=>{let a=j(s.importer,s.path),w=B(s.importer,a,s.path);if(w)return w;return u.add(a),{path:a}}),p.onResolve({filter:/^[@~]\//},(s)=>{let a=d.resolve(t,s.path.slice(2)),w=[a,`${a}.ts`,`${a}.tsx`,`${a}.js`,`${a}.mjs`,`${a}.jsx`,d.join(a,"index.ts"),d.join(a,"index.tsx"),d.join(a,"index.js"),d.join(a,"index.mjs")];for(let x of w)if(v.existsSync(x)&&v.statSync(x,{throwIfNoEntry:!1})?.isFile()){let A=B(s.importer,x,s.path);if(A)return A;return O(`resolved ${s.path[0]}/ import:`,s.path,"\u2192",x),u.add(x),{path:x}}return console.warn(`[stx:bundler] could not resolve ${s.path[0]}/ import:`,s.path),{path:a}}),m)p.onResolve({filter:/^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/},(s)=>{if(s.importer!==n)return;let a=`${Hn}npm:${s.path}`;return l.set(s.path,a),{path:a,external:!0}});p.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(s)=>{if(s.path===n)return{contents:o,loader:"ts"};if(X(s.path,t,y))throw Error(`Server-only API source cannot be imported by a client script: ${s.path}`);let a=d.extname(s.path).toLowerCase(),w=a===".json"?"json":a===".tsx"?"tsx":a===".jsx"?"jsx":a===".ts"||a===".mts"||a===".cts"?"ts":"js";if(s.path!==n)u.add(s.path);let x=F?.get(s.path);if(x!==void 0)return{contents:x,loader:"js"};return{contents:v.readFileSync(s.path,"utf8"),loader:w}})}}}var H=new Map,P=b(64),it=Symbol.for("stx.client-bundle-build-queue");function wl(t){let e=globalThis,o=(e[it]??Promise.resolve()).then(t,t);return e[it]=o.then(()=>{return},()=>{return}),o}async function Qt(t,e,n={}){let o=n.projectRoot||process.cwd(),u=(await i(o)).serverApi,m=n.minify??!1,l=n.externalizeUserModules??!0,y=n.expose?.length?[...new Set(n.expose)].sort():void 0,F=n.cacheDir||gl(o),B=K.getStore(),j=new Bun.CryptoHasher("md5");j.update(`${ht}\x00${Qe()}\x00${JSON.stringify(u??!1)}\x00${l?"registry":"inline"}\x00${y?y.join(","):"*"}\x00${m?"minified":"readable"}\x00${B?.key??""}\x00${nt(t,o)}\x00${nt(e,o)}`);let p=j.digest("hex").slice(0,12),s=d.join(F,`${p}.js`),a=P.get(s);if(a){if(ds(a.files)&&a.files.every((M)=>!X(M.path,o,u))){O("memo hit:",p);let M=a.files.map((C)=>C.path);return q(e,M),n.collectInputs?.push(...M),a.code}P.delete(s),O("memo invalidated by dep change:",p)}let w=d.join(F,`${p}.deps.json`),x=Bun.file(s);if(await x.exists()){let M=Bun.file(w),C=!1,D=null;if(await M.exists())try{let I=JSON.parse(await M.text());if(I.metadataVersion===ot&&Array.isArray(I.files)&&yt(I.files,o))D=ir(I.files.map((g)=>at(g,o))),C=D.length===I.files.length&&!D.some((g)=>X(g.path,o,u))}catch{C=!1}if(C){if(O("cache hit:",p),D)q(e,D.map((T)=>T.path)),n.collectInputs?.push(...D.map((T)=>T.path));let I=await x.text(),g=new Date;if(v.promises.utimes(s,g,g).catch(()=>{}),D)P.set(s,{code:I,files:D});return I}O("cache invalidated by dep change:",p)}let A=H.get(p);if(A){let M=await A;if(n.collectInputs)n.collectInputs.push(...(P.get(s)?.files??[]).map((C)=>C.path));return M}let V=wl(()=>jt(t,e,{projectRoot:o,minify:m,cacheDir:F,hash:p,cachePath:s,depsPath:w,collectInputs:n.collectInputs,externalizeUserModules:l,serverApi:u,expose:y,throwOnFailure:n.throwOnFailure,substitutes:B?.modules}));H.set(p,V);try{return await V}finally{H.delete(p)}}var Bt=0;function xl(t){return`${t}-${process.pid}-${++Bt}`}async function jt(t,e,n){let{projectRoot:o,minify:u,cacheDir:m,hash:l,cachePath:y,depsPath:F,externalizeUserModules:B}=n,j=c(o,"bundle-tmp"),p=xl(l),s=d.join(o,`.stx-client-${p}.ts`),a=d.join(j,"out",p);v.mkdirSync(a,{recursive:!0});let w=d.dirname(e),x=new Set,A=/^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,V=/^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm,M=r(t),{depths:C,balanced:D}=fe(M),I=(_)=>!D||C[_]===0,g;while((g=A.exec(M))!==null){if(g[1])continue;if(!I(g.index))continue;if(g[2])g[2].split(",").forEach((_)=>{let f=_t(_);if(f)x.add(f)});else if(g[3])x.add(g[3])}while((g=V.exec(M))!==null){if(g[1])continue;if(!I(g.index))continue;x.add(g[2])}let T=/^[ \t]*import[ \t]+(?!type\b)(?:(\w+)\s*(?:,\s*)?)?(?:\*\s+as\s+(\w+)|\{([^}]+)\})?\s+from\b/gm;while((g=T.exec(M))!==null){if(!I(g.index))continue;let _=/^\s*['"]([^'"]+)['"]/.exec(t.slice(g.index+g[0].length))?.[1];if(_&&Q.some((f)=>f.test(_)))continue;if(g[1])x.add(g[1]);if(g[2])x.add(g[2]);for(let f of(g[3]??"").split(",")){let S=f.trim();if(!S||/^type\s/.test(S))continue;let U=/\bas\s+(\w+)\s*$/.exec(S)?.[1]??/^\w+$/.exec(S)?.[0];if(U)x.add(U)}}for(let _ of M.matchAll(/\bexport\s*\{([^}]+)\}/g))for(let f of _[1].split(",")){let S=/\bas\s+(\w+)\s*$/.exec(f)?.[1]??/^\s*(\w+)\s*$/.exec(f)?.[1];if(S)x.delete(S)}let lt=x.size>0?`
2
+ import{Vn,Te}from"./chunk-374nhgyf.js";import{L,b,ir,ds,k}from"./chunk-4f5bmy7h.js";import{i,R}from"./chunk-h176dx1q.js";import{eo}from"./chunk-cm8ad78x.js";import{Qe}from"./chunk-yn9kvsk1.js";import{c}from"./chunk-xvs84gas.js";import{r,fe}from"./chunk-9tg4995v.js";import d from"path";import v from"fs";import{AsyncLocalStorage as gt}from"async_hooks";var ht=11;function X(t,e,n){return/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(d.basename(t))||eo(t,e,n)}var ot=2;function gl(t){let e=process.env.STX_BUNDLE_CACHE_DIR?.trim();return e?d.resolve(e):c(t,"bundle-cache")}function nt(t,e){let n=t;for(let o of xt(e))if(o!==d.sep)n=n.split(o).join("\x00root");return n}var st=new Map;function xt(t){let e=d.resolve(t),n=st.get(e);if(!n){let o=e;try{o=v.realpathSync(e)}catch{}n=[...new Set([e,o])].sort((u,m)=>m.length-u.length),st.set(e,n)}return n}function $t(t,e){try{let n=v.statSync(t),o=d.resolve(e),u=t.startsWith(`${o}${d.sep}`);return{path:u?d.relative(o,t):t,...u?{inRoot:!0}:{},mtimeMs:n.mtimeMs,size:n.size,hash:Bun.hash(v.readFileSync(t)).toString(36)}}catch{return null}}function at(t,e){return t.inRoot?d.join(d.resolve(e),t.path):t.path}function yt(t,e){for(let n of t){let o=at(n,e);try{let u=v.statSync(o);if(u.size!==n.size)return!1;if(u.mtimeMs!==n.mtimeMs&&Bun.hash(v.readFileSync(o)).toString(36)!==n.hash)return!1}catch{return!1}}return!0}var ct=new Map,bt=100;function ml(t=process.env){let e=Number(t.STX_BUNDLE_CACHE_LIMIT);return Number.isFinite(e)&&e>=1?Math.floor(e):2000}var G=new Map;async function wt(t){let e=G.get(t)??0;if(e>0&&e<bt){G.set(t,e+1);return}G.set(t,1);try{let n=(await v.promises.readdir(t)).filter((l)=>l.endsWith(".js")),o=ml();if(n.length<=o)return;let m=(await Promise.all(n.map(async(l)=>{try{return{name:l,at:(await v.promises.stat(d.join(t,l))).mtimeMs}}catch{return null}}))).filter((l)=>l!==null);m.sort((l,y)=>y.at-l.at);for(let l of m.slice(o)){let y=l.name.slice(0,-3);await v.promises.rm(d.join(t,`${y}.js`),{force:!0}),await v.promises.rm(d.join(t,`${y}.deps.json`),{force:!0})}O("pruned bundle cache to",o,"entries")}catch{}}function Ee(t){return ct.get(t)??[]}function q(t,e){if(t)ct.set(t,e)}function hl(t=process.env){return t.STX_DEBUG==="true"||t.STX_DEBUG==="1"}function O(...t){if(hl())console.log("[stx:bundler]",...t)}var Y=[];function ra(t,e,n){Y.push({filePath:t||"<inline>",message:e,details:n})}function Xt(){return Y.slice()}function Jt(){Y.length=0}var Z;function cp(t){Z=t}function sa(){if(Z)return Z;try{let t=R.strict;return typeof t==="object"&&t!==null?t.bundlerFallback??"warn":"warn"}catch{return"warn"}}var Q=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function Yt(t){let e=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,n;while((n=e.exec(t))!==null){let u=n[1];if(!Q.some((l)=>l.test(u)))return O("detected user import:",u),!0}let o=/^[ \t]*import[ \t]*['"]([^'"]+)['"]/gm;while((n=o.exec(t))!==null){let u=n[1];if(/\.css(?:\?.*)?$/.test(u))continue;if(!Q.some((l)=>l.test(u)))return O("detected side-effect import:",u),!0}return!1}var Hn="stx-module:",St=/\.(?:[cm]?[jt]sx?|json)$/i;function yl(t,e){return d.relative(t,e).split(d.sep).join("/")}function bl(t,e){if(e.size===0)return t;return t.replace(/^([ \t]*import(?:(?:\s+|(?=[{*]))[^;"']*?\s*from\s*|\s*))(["'])([^"']+)\2/gm,(n,o,u,m)=>{let l=e.get(m);return l&&!m.startsWith(Hn)?`${o}${u}${l}${u}`:n})}function vl(t,e){let n=0,o=(m)=>{let l=`__stxMod${n++}`,y=JSON.stringify(m);return e.push(`var ${l} = globalThis.__stxModules && globalThis.__stxModules[${y}];`,`if (${l} === undefined) throw new Error("[stx] module " + ${JSON.stringify(y)} + " is not registered on this page (#1957)");`),l},u=(m,l)=>{for(let y of m.split(",")){let F=y.trim();if(!F)continue;let B=F.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!B)continue;let j=B[1].startsWith('"')?JSON.parse(B[1]):B[1],p=B[2]??j;e.push(`var ${p} = ${l}[${JSON.stringify(j)}];`)}};return t=t.replace(/^[ \t]*import(?:\s+|(?=[{*]))([^;"']+?)\s*from\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(m,l,y)=>{let F=y.slice(Hn.length),B=o(F),j=l.trim(),p=j.match(/^([\w$]+)\s*(?:,\s*|$)/);if(p&&!j.startsWith("{")&&!j.startsWith("*"))e.push(`var ${p[1]} = ${B}.default;`),j=j.slice(p[0].length).trim();let s=j.match(/^\*\s*as\s+([\w$]+)$/);if(s)e.push(`var ${s[1]} = ${B};`);else if(j.startsWith("{"))u(j.replace(/^\{|\}$/g,""),B);return""}),t=t.replace(/^[ \t]*import\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(m,l)=>(o(l.slice(Hn.length)),"")),t}function rt(t){let e=[t,`${t}.ts`,`${t}.tsx`,`${t}.js`,`${t}.mjs`,`${t}.jsx`,d.join(t,"index.ts"),d.join(t,"index.tsx"),d.join(t,"index.js"),d.join(t,"index.mjs")];for(let n of e)try{if(v.existsSync(n)&&v.statSync(n,{throwIfNoEntry:!1})?.isFile())return n}catch{}return}var K=new gt;function Js(t,e){let n=new Bun.CryptoHasher("md5");for(let[o,u]of[...t].sort(([m],[l])=>m<l?-1:m>l?1:0))n.update(`${o}\x00${u}\x00`);return K.run({modules:t,key:n.digest("hex").slice(0,12)},e)}function Zt(){return K.getStore()?.key??""}function vt(t,e,n,o,u,m,l=new Map,y,F){let B=(p,s,a)=>{if(X(s,t,y))return null;if(!m||p!==n||!St.test(s))return null;try{if(!v.statSync(s,{throwIfNoEntry:!1})?.isFile())return null}catch{return null}u.add(s);let w=`${Hn}${yl(process.cwd(),s)}`;return l.set(a,w),{path:w,external:!0}},j=(p,s)=>{let a=p===n?e:d.dirname(p),w=d.resolve(a,s);return rt(w)??w};return{name:"stx-client-bundle",setup(p){if(p.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(s)=>({path:s.path,external:!0})),p.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(s)=>({path:s.path,external:!0})),p.onResolve({filter:/^\//},(s)=>{if(s.path===n)return{path:n};let a=rt(s.path);if(a){let w=B(s.importer,a,s.path);if(w)return w;if(a!==n)u.add(a);return{path:a}}return{path:s.path,external:!0}}),p.onResolve({filter:/^\.\.?\//},(s)=>{let a=j(s.importer,s.path),w=B(s.importer,a,s.path);if(w)return w;return u.add(a),{path:a}}),p.onResolve({filter:/^[@~]\//},(s)=>{let a=d.resolve(t,s.path.slice(2)),w=[a,`${a}.ts`,`${a}.tsx`,`${a}.js`,`${a}.mjs`,`${a}.jsx`,d.join(a,"index.ts"),d.join(a,"index.tsx"),d.join(a,"index.js"),d.join(a,"index.mjs")];for(let x of w)if(v.existsSync(x)&&v.statSync(x,{throwIfNoEntry:!1})?.isFile()){let A=B(s.importer,x,s.path);if(A)return A;return O(`resolved ${s.path[0]}/ import:`,s.path,"\u2192",x),u.add(x),{path:x}}return console.warn(`[stx:bundler] could not resolve ${s.path[0]}/ import:`,s.path),{path:a}}),m)p.onResolve({filter:/^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/},(s)=>{if(s.importer!==n)return;let a=`${Hn}npm:${s.path}`;return l.set(s.path,a),{path:a,external:!0}});p.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(s)=>{if(s.path===n)return{contents:o,loader:"ts"};if(X(s.path,t,y))throw Error(`Server-only API source cannot be imported by a client script: ${s.path}`);let a=d.extname(s.path).toLowerCase(),w=a===".json"?"json":a===".tsx"?"tsx":a===".jsx"?"jsx":a===".ts"||a===".mts"||a===".cts"?"ts":"js";if(s.path!==n)u.add(s.path);let x=F?.get(s.path);if(x!==void 0)return{contents:x,loader:"js"};return{contents:v.readFileSync(s.path,"utf8"),loader:w}})}}}var H=new Map,P=b(64),it=Symbol.for("stx.client-bundle-build-queue");function wl(t){let e=globalThis,o=(e[it]??Promise.resolve()).then(t,t);return e[it]=o.then(()=>{return},()=>{return}),o}async function Qt(t,e,n={}){let o=n.projectRoot||process.cwd(),u=(await i(o)).serverApi,m=n.minify??!1,l=n.externalizeUserModules??!0,y=n.expose?.length?[...new Set(n.expose)].sort():void 0,F=n.cacheDir||gl(o),B=K.getStore(),j=new Bun.CryptoHasher("md5");j.update(`${ht}\x00${Qe()}\x00${JSON.stringify(u??!1)}\x00${l?"registry":"inline"}\x00${y?y.join(","):"*"}\x00${m?"minified":"readable"}\x00${B?.key??""}\x00${nt(t,o)}\x00${nt(e,o)}`);let p=j.digest("hex").slice(0,12),s=d.join(F,`${p}.js`),a=P.get(s);if(a){if(ds(a.files)&&a.files.every((M)=>!X(M.path,o,u))){O("memo hit:",p);let M=a.files.map((C)=>C.path);return q(e,M),n.collectInputs?.push(...M),a.code}P.delete(s),O("memo invalidated by dep change:",p)}let w=d.join(F,`${p}.deps.json`),x=Bun.file(s);if(await x.exists()){let M=Bun.file(w),C=!1,D=null;if(await M.exists())try{let I=JSON.parse(await M.text());if(I.metadataVersion===ot&&Array.isArray(I.files)&&yt(I.files,o))D=ir(I.files.map((g)=>at(g,o))),C=D.length===I.files.length&&!D.some((g)=>X(g.path,o,u))}catch{C=!1}if(C){if(O("cache hit:",p),D)q(e,D.map((T)=>T.path)),n.collectInputs?.push(...D.map((T)=>T.path));let I=await x.text(),g=new Date;if(v.promises.utimes(s,g,g).catch(()=>{}),D)P.set(s,{code:I,files:D});return I}O("cache invalidated by dep change:",p)}let A=H.get(p);if(A){let M=await A;if(n.collectInputs)n.collectInputs.push(...(P.get(s)?.files??[]).map((C)=>C.path));return M}let V=wl(()=>jt(t,e,{projectRoot:o,minify:m,cacheDir:F,hash:p,cachePath:s,depsPath:w,collectInputs:n.collectInputs,externalizeUserModules:l,serverApi:u,expose:y,throwOnFailure:n.throwOnFailure,substitutes:B?.modules}));H.set(p,V);try{return await V}finally{H.delete(p)}}var Bt=0;function xl(t){return`${t}-${process.pid}-${++Bt}`}async function jt(t,e,n){let{projectRoot:o,minify:u,cacheDir:m,hash:l,cachePath:y,depsPath:F,externalizeUserModules:B}=n,j=c(o,"bundle-tmp"),p=xl(l),s=d.join(o,`.stx-client-${p}.ts`),a=d.join(j,"out",p);v.mkdirSync(a,{recursive:!0});let w=d.dirname(e),x=new Set,A=/^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,V=/^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm,M=r(t),{depths:C,balanced:D}=fe(M),I=(_)=>!D||C[_]===0,g;while((g=A.exec(M))!==null){if(g[1])continue;if(!I(g.index))continue;if(g[2])g[2].split(",").forEach((_)=>{let f=_t(_);if(f)x.add(f)});else if(g[3])x.add(g[3])}while((g=V.exec(M))!==null){if(g[1])continue;if(!I(g.index))continue;x.add(g[2])}let T=/^[ \t]*import[ \t]+(?!type\b)(?:(\w+)\s*(?:,\s*)?)?(?:\*\s+as\s+(\w+)|\{([^}]+)\})?\s+from\b/gm;while((g=T.exec(M))!==null){if(!I(g.index))continue;let _=/^\s*['"]([^'"]+)['"]/.exec(t.slice(g.index+g[0].length))?.[1];if(_&&Q.some((f)=>f.test(_)))continue;if(g[1])x.add(g[1]);if(g[2])x.add(g[2]);for(let f of(g[3]??"").split(",")){let S=f.trim();if(!S||/^type\s/.test(S))continue;let U=/\bas\s+(\w+)\s*$/.exec(S)?.[1]??/^\w+$/.exec(S)?.[0];if(U)x.add(U)}}for(let _ of M.matchAll(/\bexport\s*\{([^}]+)\}/g))for(let f of _[1].split(",")){let S=/\bas\s+(\w+)\s*$/.exec(f)?.[1]??/^\s*(\w+)\s*$/.exec(f)?.[1];if(S)x.delete(S)}let lt=x.size>0?`
3
3
  export { ${[...x].join(", ")} }`:"";O("bundling:",l,"from:",d.basename(e));let tt=new Set,et=new Map;try{let _=await Bun.build({entrypoints:[s],outdir:a,target:"browser",format:"esm",minify:u?{whitespace:!1,identifiers:!0,syntax:!0}:!1,plugins:[vt(o,w,s,t+lt,tt,B,et,n.serverApi,n.substitutes)],define:{"process.env.NODE_ENV":u?'"production"':'"development"',...k()},root:o});if(!_.success){let E=_.logs.filter((N)=>N.level==="error").map((N)=>N.message).join(", ")||`Unable to bundle ${d.basename(e)}`,z=Vn(_.logs,e||void 0);if(console.warn("[stx:bundler] build failed:",E),ra(e||"",E,z),n.throwOnFailure||sa()==="error")throw Error(E);return t}let f="";for(let h of _.outputs){f=await h.text();break}let S=[];for(let h of f.matchAll(/^\s*export\s*\{([^}]*)\}\s*;?\s*$/gm))for(let E of h[1].split(",")){let z=E.trim().match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(z){S.push([z[2],z[1]]);continue}let N=E.trim();if(/^[A-Za-z_$][\w$]*$/.test(N))S.push([N,N])}if(n.expose){let h=new Set(n.expose);for(let E=S.length-1;E>=0;E--)if(!h.has(S[E][0]))S.splice(E,1)}let U=[];f=vl(bl(f,et),U);let ut=f.match(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm)||[];if(f=f.replace(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm,"").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm,"").replace(/^\s*export\s+default\s+.*$/gm,"").trim(),u&&f)try{f=new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(f)}catch{}let J=`__stxBundle_${l}`,dt=new Set(L(t,!0).split(",").map((h)=>h.trim())),pt=S.map(([h,E])=>`get ${JSON.stringify(h)}() { return ${E} }${dt.has(h)?`, set ${JSON.stringify(h)}(__stxValue_${E}) { ${E} = __stxValue_${E} }`:""}`).join(", "),ft=S.map(([h])=>`var ${h} = undefined;`).join(`
4
4
  `),mt=S.map(([h])=>`${h} = ${J}[${JSON.stringify(h)}];`).join(`
5
5
  `);if(f=`${ut.join(`
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{i}from"./chunk-jhr08gjs.js";import{Ue,ne}from"./chunk-03xn8244.js";import{Zi}from"./chunk-ff7pvv0p.js";import{f}from"./chunk-b7e07ybq.js";import{existsSync as A,mkdirSync as x,copyFileSync as T,chmodSync as P,rmSync as ue}from"fs";import{join as c,basename as be,resolve as H}from"path";import{spawn as q}from"child_process";import{platform as ge}from"os";var ep=`
2
+ import{i}from"./chunk-h176dx1q.js";import{Ue,ne}from"./chunk-03xn8244.js";import{Zi}from"./chunk-5mcwf93c.js";import{f}from"./chunk-b7e07ybq.js";import{existsSync as A,mkdirSync as x,copyFileSync as T,chmodSync as P,rmSync as ue}from"fs";import{join as c,basename as be,resolve as H}from"path";import{spawn as q}from"child_process";import{platform as ge}from"os";var ep=`
3
3
  <script>
4
4
  (function() {
5
5
  'use strict';
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import"./chunk-r0ys9aqa.js";import"./chunk-gtktv6nn.js";import"./chunk-6beg47t4.js";import"./chunk-pe9ry4mj.js";import"./chunk-t6m5d64b.js";import"./chunk-f178pm4d.js";import"./chunk-tenbwcts.js";import"./chunk-hr3m2h4n.js";import{c}from"./chunk-xvs84gas.js";import u from"fs";import l from"path";async function d(e,t={}){let s=Date.now(),n={total:0,passed:0,failed:0,new:0,failures:[],duration:0},i=t.snapshotDir||c(e.root,"story","snapshots");await u.promises.mkdir(i,{recursive:!0});let r=e.storyFiles;if(t.filter&&t.filter.length>0)r=r.filter((a)=>t.filter.some((o)=>a.fileName.toLowerCase().includes(o.toLowerCase())));for(let a of r)await h(a,i,t,n);return n.duration=Date.now()-s,n}async function h(e,t,s,n){let i=e.story;if(!i)return;for(let r of i.variants){n.total++;let a=l.join(t,`${e.id}-${r.id}.snap`),o=g(r.source||""),f=await w(a);if(s.update||!f){let p={storyId:e.id,variantId:r.id,component:e.fileName,timestamp:Date.now(),hash:o};if(await u.promises.writeFile(a,JSON.stringify(p,null,2)),!f)n.new++;n.passed++}else try{let p=await u.promises.readFile(a,"utf-8"),m=JSON.parse(p);if(m.hash===o)n.passed++;else n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:"Snapshot mismatch",difference:y(m.hash,o)})}catch(p){n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:`Error reading snapshot: ${p}`})}}}async function x(e,t={}){return(await d(e,{...t,update:!0})).total}function g(e){let t=0;for(let s=0;s<e.length;s++){let n=e.charCodeAt(s);t=(t<<5)-t+n,t=t&t}return t.toString(16)}function y(e,t){if(e===t)return 0;let s=Math.abs(Number.parseInt(e,16)-Number.parseInt(t,16));return Math.min(s/1e6,1)}async function w(e){try{return await u.promises.access(e),!0}catch{return!1}}function F(e){let t=[];if(t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(" STX Story Visual Regression Tests"),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),e.failures.length>0){t.push(" \u274C Failures:"),t.push("");for(let s of e.failures){if(t.push(` \u2022 ${s.component} / ${s.variantId}`),t.push(` ${s.message}`),s.difference!==void 0)t.push(` Difference: ${(s.difference*100).toFixed(2)}%`);t.push("")}}if(t.push(" Summary:"),t.push(` Total: ${e.total}`),t.push(` Passed: ${e.passed} \u2713`),t.push(` Failed: ${e.failed} \u2717`),e.new>0)t.push(` New: ${e.new} \u26A1`);return t.push(` Time: ${e.duration}ms`),t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),t.join(`
2
+ import"./chunk-r0ys9aqa.js";import"./chunk-gtktv6nn.js";import"./chunk-6beg47t4.js";import"./chunk-4f5bmy7h.js";import"./chunk-t6m5d64b.js";import"./chunk-tjwv101c.js";import"./chunk-tenbwcts.js";import"./chunk-s0ntt1cn.js";import{c}from"./chunk-xvs84gas.js";import u from"fs";import l from"path";async function d(e,t={}){let s=Date.now(),n={total:0,passed:0,failed:0,new:0,failures:[],duration:0},i=t.snapshotDir||c(e.root,"story","snapshots");await u.promises.mkdir(i,{recursive:!0});let r=e.storyFiles;if(t.filter&&t.filter.length>0)r=r.filter((a)=>t.filter.some((o)=>a.fileName.toLowerCase().includes(o.toLowerCase())));for(let a of r)await h(a,i,t,n);return n.duration=Date.now()-s,n}async function h(e,t,s,n){let i=e.story;if(!i)return;for(let r of i.variants){n.total++;let a=l.join(t,`${e.id}-${r.id}.snap`),o=g(r.source||""),f=await w(a);if(s.update||!f){let p={storyId:e.id,variantId:r.id,component:e.fileName,timestamp:Date.now(),hash:o};if(await u.promises.writeFile(a,JSON.stringify(p,null,2)),!f)n.new++;n.passed++}else try{let p=await u.promises.readFile(a,"utf-8"),m=JSON.parse(p);if(m.hash===o)n.passed++;else n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:"Snapshot mismatch",difference:y(m.hash,o)})}catch(p){n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:`Error reading snapshot: ${p}`})}}}async function x(e,t={}){return(await d(e,{...t,update:!0})).total}function g(e){let t=0;for(let s=0;s<e.length;s++){let n=e.charCodeAt(s);t=(t<<5)-t+n,t=t&t}return t.toString(16)}function y(e,t){if(e===t)return 0;let s=Math.abs(Number.parseInt(e,16)-Number.parseInt(t,16));return Math.min(s/1e6,1)}async function w(e){try{return await u.promises.access(e),!0}catch{return!1}}function F(e){let t=[];if(t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(" STX Story Visual Regression Tests"),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),e.failures.length>0){t.push(" \u274C Failures:"),t.push("");for(let s of e.failures){if(t.push(` \u2022 ${s.component} / ${s.variantId}`),t.push(` ${s.message}`),s.difference!==void 0)t.push(` Difference: ${(s.difference*100).toFixed(2)}%`);t.push("")}}if(t.push(" Summary:"),t.push(` Total: ${e.total}`),t.push(` Passed: ${e.passed} \u2713`),t.push(` Failed: ${e.failed} \u2717`),e.new>0)t.push(` New: ${e.new} \u26A1`);return t.push(` Time: ${e.duration}ms`),t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),t.join(`
3
3
  `)}export{F as formatTestResults,d as runVisualTests,x as updateSnapshots};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{t,a}from"./chunk-r0ys9aqa.js";import{n,gn,m}from"./chunk-pe9ry4mj.js";import{Ze}from"./chunk-kypwg2ws.js";import{Qr,es}from"./chunk-ygb33q5w.js";import{ka,vo,Yr,Zr}from"./chunk-912r15hr.js";import{wa,xa}from"./chunk-hr3m2h4n.js";import{bt}from"./chunk-3hxd5td3.js";import{sn,Ra,sr,or}from"./chunk-xvs84gas.js";import{f}from"./chunk-b7e07ybq.js";import{Ps}from"./chunk-vxrhvrr9.js";import Q from"fs";import j from"path";import{loadConfigWithResult as Ht}from"bunfig";var B={duration:300,delay:0,ease:"ease",direction:"both"};function nt(e,r={}){let{duration:o,delay:l,ease:s,direction:c,custom:d}={...B,...r};if(e==="custom"&&d)return d;switch(e){case"fade":return`${c==="in"?"opacity: 0; animation: fadeIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":c==="out"?"opacity: 1; animation: fadeOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"opacity: 1; transition: opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
2
+ import{t,a}from"./chunk-r0ys9aqa.js";import{n,gn,m}from"./chunk-4f5bmy7h.js";import{Ze}from"./chunk-kypwg2ws.js";import{Qr,es}from"./chunk-ygb33q5w.js";import{ka,vo,Yr,Zr}from"./chunk-912r15hr.js";import{wa,xa}from"./chunk-s0ntt1cn.js";import{bt}from"./chunk-3hxd5td3.js";import{sn,Ra,sr,or}from"./chunk-xvs84gas.js";import{f}from"./chunk-b7e07ybq.js";import{Ps}from"./chunk-vxrhvrr9.js";import Q from"fs";import j from"path";import{loadConfigWithResult as Ht}from"bunfig";var B={duration:300,delay:0,ease:"ease",direction:"both"};function nt(e,r={}){let{duration:o,delay:l,ease:s,direction:c,custom:d}={...B,...r};if(e==="custom"&&d)return d;switch(e){case"fade":return`${c==="in"?"opacity: 0; animation: fadeIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":c==="out"?"opacity: 1; animation: fadeOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"opacity: 1; transition: opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
3
3
  @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
4
4
  @keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }`;case"slide":return`${c==="in"?"transform: translateY(20px); opacity: 0; animation: slideIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":c==="out"?"transform: translateY(0); opacity: 1; animation: slideOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: translateY(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
5
5
  @keyframes slideIn { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
@@ -1307,6 +1307,6 @@ ${y}
1307
1307
  customElements.define('${r}', ${d});
1308
1308
  `}async function Qe(e,r,o,l){if(r.length<1)return a("WebComponent","@webcomponent directive requires at least the tag name parameter",t.INVALID_DIRECTIVE_SYNTAX);let s=r[0].replace(/['"]/g,""),d=(o.__stx_options||{}).componentsDir||"components",p=q.isAbsolute(d)?[q.join(d,`${s}.stx`),q.join(q.dirname(l),`${s}.stx`)]:[q.join(q.dirname(l),d,`${s}.stx`),q.join(process.cwd(),d,`${s}.stx`),q.join(q.dirname(l),`${s}.stx`)],u=null;for(let h of p)if(await n(h)){u=await Bun.file(h).text();break}if(!u)return a("WebComponent",`Component file not found: ${s}.stx`,t.FILE_NOT_FOUND);let g=Ft(u,s);return`<script type="module">
1309
1309
  ${qt(g)}
1310
- </script>`}var N={enabled:!0,ssr:!1,partialsDir:"partials",componentsDir:"components",layoutsDir:"layouts",defaultLayout:"default",debug:!1,cache:!0,stateDir:sn,cachePath:".stx/cache",cacheVersion:"1.0.0",componentRenderCacheBytes:33554432,build:{pagesDir:"pages",outputDir:"dist",baseUrl:"/",sitemap:!0,minify:!0,cache:!0,cacheDir:".stx/ssg-cache",concurrency:10,generate404:!0,publicDir:"public",trailingSlash:!1,cleanOutput:!0},customDirectives:[{name:"markdown",handler:Ie,hasEndTag:!0,description:"Render markdown content to HTML"},{name:"webcomponent",handler:Qe,hasEndTag:!1,description:"Include a web component in the template"},wa,xa,Qr,es,De,ke,Ae,Pe,_e,Oe,Fe,$e,...Ps],middleware:[],i18n:{defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},webComponents:{enabled:!1,outputDir:"dist/web-components",components:[]},docs:{enabled:!1,outputDir:"docs",format:"markdown",components:!0,templates:!0,directives:!0},streaming:{enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},hydration:{enabled:!1,mode:"islands",clientEntry:"src/client.ts",autoMarkers:!0,preload:"lazy"},router:{enabled:!0,container:"main",linkSelector:"a[href]",viewTransitions:!0,scrollToTop:!0,scrollRestoration:!0,prefetch:!0,cache:!0,cacheTTL:300000,skipSelectors:'[data-no-router], [target="_blank"]',viewTransitionCSS:{oldRoot:"fade-out 0.15s ease-in",newRoot:"fade-in 0.2s ease-out",oldContent:"slide-out 0.2s ease-in",newContent:"slide-in 0.25s ease-out"}},a11y:{enabled:!0,addSrOnlyStyles:!0,level:"AA",autoFix:!1,ignoreChecks:[]},seo:{enabled:!0,socialPreview:!0,defaultConfig:{title:"stx Project",description:"A website built with stx templating engine"}},animation:{enabled:!0,defaultDuration:300,defaultEase:"ease",respectMotionPreferences:!0,staggerDelay:50},markdown:{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0,additionalThemes:["light-plus","one-dark-pro","dracula","monokai","solarized-light","nord","github-dark"]}},loops:{maxWhileIterations:1000,useAltLoopVariable:!1},story:{enabled:!0,outDir:".stx/dist/story",storyMatch:["**/*.story.stx"],storyIgnored:["**/node_modules/**","**/dist/**","**/.stx/**"],port:6006},pwa:{enabled:!1,manifest:{name:"stx App",shortName:"stx",description:"A Progressive Web App built with stx",startUrl:"/",display:"standalone",orientation:"any",themeColor:"#000000",backgroundColor:"#ffffff",scope:"/"},icons:{src:"public/icon.png",sizes:[72,96,128,144,152,192,384,512],generateWebP:!0,generateAppleIcons:!0,outputDir:"pwa-icons",purpose:["any","maskable"]},routes:[{pattern:"/",strategy:"network-first"},{pattern:"/static/*",strategy:"cache-first",maxAgeSeconds:2592000},{pattern:"/api/*",strategy:"network-only"},{pattern:"*.js",strategy:"stale-while-revalidate"},{pattern:"*.css",strategy:"stale-while-revalidate"},{pattern:"*.png",strategy:"cache-first"},{pattern:"*.jpg",strategy:"cache-first"},{pattern:"*.webp",strategy:"cache-first"},{pattern:"*.svg",strategy:"cache-first"}],offline:{enabled:!0,fallbackTitle:"You are offline",fallbackMessage:"Please check your internet connection and try again.",precacheAssets:[]},serviceWorker:{fileName:"sw.js",cacheVersion:"1.0.0",skipWaiting:!0,clientsClaim:!0,navigationPreload:!1,excludeRoutes:["/api/auth/*"],cacheFileTypes:["html","css","js","png","jpg","jpeg","webp","svg","woff","woff2"],useWorkbox:!1},autoInject:!0,push:{enabled:!1,defaultOptions:{vibrate:[100,50,100],requireInteraction:!1}},backgroundSync:{enabled:!1,queueName:"stx-sync-queue",maxRetentionMinutes:1440,maxRetries:3,minInterval:1000,forms:[],endpoints:[]},shareTarget:{enabled:!1,action:"/share-target",method:"POST",enctype:"multipart/form-data",params:{title:"title",text:"text",url:"url"}},fileHandlers:{enabled:!1},protocolHandlers:[],cacheStorage:{maxSize:100,maxEntries:500,maxAge:30,purgeStrategy:"lru"},updates:{enabled:!0,promptUser:!0,autoReload:!1,message:"A new version is available. Reload to update?"},precache:{enabled:!0,includeHtml:!0,includeJs:!0,includeCss:!0,includeImages:!0,includeFonts:!0,include:[],exclude:["*.map","*.LICENSE.txt"],maxFileSizeKB:500}},media:{enabled:!0,image:{enabled:!0,defaultWidths:[320,480,640,768,1024,1280,1536,1920],defaultFormats:["avif","webp","jpeg"],defaultQuality:80,placeholderStrategy:"thumbhash",lazyByDefault:!0,enableDpr:!0,defaultDpr:[1,2,3],tsImages:{enabled:!0,outputDir:"dist/images",baseUrl:"/images",formatQuality:{jpeg:{quality:85,mozjpeg:!0,progressive:!0},png:{compressionLevel:9,palette:!1},webp:{quality:82,effort:5,smartSubsample:!0},avif:{quality:75,effort:4,lossless:!1}},breakpoints:[320,480,640,768,1024,1280,1536,1920],batchOptions:{concurrency:4,optimizationPreset:"web"}}},video:{enabled:!0,lazyByDefault:!0,defaultControls:!0,tsVideos:{enabled:!0,outputDir:"dist/videos",baseUrl:"/videos",defaultQuality:"high",streaming:{enabled:!0,format:"hls",segmentDuration:6,defaultQualities:[{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}]},thumbnails:{enabled:!0,count:10,format:"webp",width:320},transcoding:{defaultCodec:"h264",defaultAudioCodec:"aac",speedPreset:"medium"}}},upload:{enabled:!0,maxSize:10485760,allowedTypes:["image/*","video/*","audio/*","application/pdf"],maxConcurrent:3},protected:{enabled:!0,expirationSeconds:3600,batchSize:10},cache:{enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:500}},broadcasting:{enabled:!1,driver:"bun",host:"0.0.0.0",port:6001,scheme:"ws",verbose:!1}};function Ut(e,r,o){let l=r||"pages";if(e)return{root:e,pagesDir:l};let s=o||process.cwd(),c=j.join(s,"resources","views"),d=j.join(s,"resources","layouts");if(Q.existsSync(c)&&Q.existsSync(d))return{root:"resources",pagesDir:"views"};let p=j.join(s,"resources","views","pages");if(Q.existsSync(p))return{root:"resources/views",pagesDir:l};return{root:".",pagesDir:l}}var et=new Set,ue=["partialsDir","componentsDir","layoutsDir"],Se=new WeakMap;function Bt(e,r){let o=r.replace(/[\\/]+$/,"");if(!o||o===".")return!0;let l=e.replace(/\\/g,"/"),s=o.replace(/\\/g,"/");return l===s||l.startsWith(`${s}/`)}function Nl(e,r){let o=!e.root,l=Ut(e.root,e.pagesDir,r);if(e.root=l.root,e.pagesDir=l.pagesDir,o&&l.root!=="."){let s=`${r}::${l.root}`;if(!et.has(s))et.add(s),console.warn(`[stx] No "root" in config \u2014 inferred "${l.root}" from the project layout. Template directories are resolved under it; set root explicitly to pin this.`)}if(!Se.has(e)){let s={};for(let c of ue){let d=e[c];if(typeof d==="string"&&d)s[c]=d}Se.set(e,s)}if(e.root&&e.root!=="."){let s=e.root;for(let c of ue){let d=e[c];if(typeof d!=="string"||!d)continue;if(j.isAbsolute(d)||Bt(d,s))continue;e[c]=j.join(s,d)}}for(let s of ue){let c=e[s];if(typeof c!=="string"||!c||j.isAbsolute(c))continue;e[s]=j.resolve(r,c)}return e}function Jt(e,r){let o=Se.get(e);for(let l of ue){let s=e[l];if(typeof s!=="string"||!s)continue;let c=j.isAbsolute(s)?s:j.join(r,s);if(Q.existsSync(c))continue;let d=o?.[l]??s,p=e.root,u=!!p&&p!==".";console.warn(`[stx] ${String(l)} resolves to "${c}", which does not exist. Configured as "${d}"`+(u?`, resolved under root "${p}".`:"."))}}function Kt(e){if(e.customDirectives)e.customDirectives=[...e.customDirectives];if(e.middleware)e.middleware=[...e.middleware];if(e.apiRoutes)e.apiRoutes={...e.apiRoutes}}function Gt(e){if(Ra(e.stateDir),e.stateDir=sr(),e.cachePath=or(e.cachePath),e.build)e.build.cacheDir=or(e.build.cacheDir);if(e.media?.cache)e.media.cache.directory=or(e.media.cache.directory);if(e.story)e.story.outDir=or(e.story.outDir)}var K=null,Y=new Map,de=new Map,se=null;async function yo(e,r=Ht){try{return await r(e)}catch(o){if(o instanceof Error&&o.name==="ConfigNotFoundError")return{config:e.defaultConfig};throw o}}async function i(e){let r=e?j.resolve(e):process.cwd(),o=de.get(r);if(o&&o.signature!==Yr(o.graph)){let c=Y.get(r);if(Y.delete(r),de.delete(r),!e)K=null,se=null;let{clearComponentCache:d}=await import("./chunk-1zjn5p5c.js"),{partialsCache:p}=await import("./chunk-xzffh9aj.js");if(d(),p.clear(),c&&o.configSignature===Zr(o.graph)){let u=c.then(async(g)=>{let y={...o.graph};await vo(y,r),de.set(r,{graph:y,signature:Yr(y),configSignature:Zr(y)});let h={...g,_layerGraph:y};if(!e)K=h;return h});return Y.set(r,u),u}}if(!e){if(K)return K;if(se)return se}let l=Y.get(r);if(l)return l;let s=(async()=>{let c=[".ts",".js",".mjs",".cjs",".json"],d=c.some((v)=>Q.existsSync(j.join(r,`stx.config${v}`))),p=c.some((v)=>Q.existsSync(j.join(r,"config",`ui${v}`))),u;if(d&&p){let v=await yo({name:"ui",cwd:j.join(r,"config"),defaultConfig:N,errorPolicy:"throw",verbose:!1});u=(await yo({name:"stx",alias:"ui",cwd:r,defaultConfig:v.config,errorPolicy:"throw",verbose:!1})).config}else u=(await yo({name:"stx",alias:"ui",cwd:r,defaultConfig:N,errorPolicy:"throw",verbose:!1})).config;if(u.extends!==void 0||o){let v=await ka(r,N);u=v.config,de.set(r,{graph:v.graph,signature:Yr(v.graph),configSignature:Zr(v.graph)})}if(u.runtimeConfig){let{resolveRuntimeConfig:v}=await import("./chunk-wvz7rp5p.js");v(u.runtimeConfig,{});let{generateRuntimeConfigTypes:b}=await import("./chunk-b2cfg8d1.js");await b(r,u.runtimeConfig)}Kt(u),Gt(u),Nl(u,r),Jt(u,r);let g=[],y=new Set((u.plugins??[]).map((v)=>typeof v==="string"?v:v[0]));for(let v of u.componentPackages??["@stacksjs/components"]){let b=`${v}/stx-plugin`;if(y.has(b)||y.has(v))continue;try{f.resolve(b,{paths:[r]}),g.push(b)}catch{}}let h=[...u.plugins??[],...g];if(h.length>0){let{pluginManager:v}=await import("./chunk-vqv5w6gs.js"),b=[],x=[];for(let P of h){let S=typeof P==="string"?P:P[0],A=typeof P==="string"?{}:P[1]||{};try{let k,E;try{let w=f.resolve(S,{paths:[r]});k=await import(w),E=j.dirname(w)}catch{let w=j.resolve(r,S);k=await import(w),E=j.dirname(w)}let I=k.default||k;if(!v.has(I.name))await v.register(I,u);if(I.components){let w=Array.isArray(I.components)?I.components:[I.components];for(let C of w)b.push(j.resolve(E,C))}if(I.pages){let w=j.resolve(E,I.pages),C=A.path||"/";x.push({dir:w,prefix:C})}if(I.setup){let w={addDirective:(C)=>{u.customDirectives=u.customDirectives||[],u.customDirectives.push(C)},addRoute:(C,D)=>{u.apiRoutes=u.apiRoutes||{},u.apiRoutes[C]=D},addMiddleware:(C)=>{u.middleware=u.middleware||[],u.middleware.push(C)},pluginDir:E,config:u};await I.setup(A,w)}process.stderr.write(`[stx] Plugin loaded: ${I.name||S}
1310
+ </script>`}var N={enabled:!0,ssr:!1,partialsDir:"partials",componentsDir:"components",layoutsDir:"layouts",defaultLayout:"default",debug:!1,cache:!0,stateDir:sn,cachePath:".stx/cache",cacheVersion:"1.0.0",componentRenderCacheBytes:33554432,build:{pagesDir:"pages",outputDir:"dist",baseUrl:"/",sitemap:!0,minify:!0,cache:!0,cacheDir:".stx/ssg-cache",concurrency:10,generate404:!0,publicDir:"public",trailingSlash:!1,cleanOutput:!0},customDirectives:[{name:"markdown",handler:Ie,hasEndTag:!0,description:"Render markdown content to HTML"},{name:"webcomponent",handler:Qe,hasEndTag:!1,description:"Include a web component in the template"},wa,xa,Qr,es,De,ke,Ae,Pe,_e,Oe,Fe,$e,...Ps],middleware:[],i18n:{defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},webComponents:{enabled:!1,outputDir:"dist/web-components",components:[]},docs:{enabled:!1,outputDir:"docs",format:"markdown",components:!0,templates:!0,directives:!0},streaming:{enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},hydration:{enabled:!1,mode:"islands",clientEntry:"src/client.ts",autoMarkers:!0,preload:"lazy"},router:{enabled:!0,container:"main",linkSelector:"a[href]",viewTransitions:!0,scrollToTop:!0,scrollRestoration:!0,prefetch:!0,cache:!0,cacheTTL:300000,skipSelectors:'[data-no-router], [target="_blank"]',viewTransitionCSS:{oldRoot:"fade-out 0.15s ease-in",newRoot:"fade-in 0.2s ease-out",oldContent:"slide-out 0.2s ease-in",newContent:"slide-in 0.25s ease-out"}},a11y:{enabled:!0,addSrOnlyStyles:!0,level:"AA",autoFix:!1,ignoreChecks:[]},seo:{enabled:!0,socialPreview:!0,defaultConfig:{title:"stx Project",description:"A website built with stx templating engine"}},animation:{enabled:!0,defaultDuration:300,defaultEase:"ease",respectMotionPreferences:!0,staggerDelay:50},markdown:{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0,additionalThemes:["light-plus","one-dark-pro","dracula","monokai","solarized-light","nord","github-dark"]}},loops:{maxWhileIterations:1000,useAltLoopVariable:!1},story:{enabled:!0,outDir:".stx/dist/story",storyMatch:["**/*.story.stx"],storyIgnored:["**/node_modules/**","**/dist/**","**/.stx/**"],port:6006},pwa:{enabled:!1,manifest:{name:"stx App",shortName:"stx",description:"A Progressive Web App built with stx",startUrl:"/",display:"standalone",orientation:"any",themeColor:"#000000",backgroundColor:"#ffffff",scope:"/"},icons:{src:"public/icon.png",sizes:[72,96,128,144,152,192,384,512],generateWebP:!0,generateAppleIcons:!0,outputDir:"pwa-icons",purpose:["any","maskable"]},routes:[{pattern:"/",strategy:"network-first"},{pattern:"/static/*",strategy:"cache-first",maxAgeSeconds:2592000},{pattern:"/api/*",strategy:"network-only"},{pattern:"*.js",strategy:"stale-while-revalidate"},{pattern:"*.css",strategy:"stale-while-revalidate"},{pattern:"*.png",strategy:"cache-first"},{pattern:"*.jpg",strategy:"cache-first"},{pattern:"*.webp",strategy:"cache-first"},{pattern:"*.svg",strategy:"cache-first"}],offline:{enabled:!0,fallbackTitle:"You are offline",fallbackMessage:"Please check your internet connection and try again.",precacheAssets:[]},serviceWorker:{fileName:"sw.js",cacheVersion:"1.0.0",skipWaiting:!0,clientsClaim:!0,navigationPreload:!1,excludeRoutes:["/api/auth/*"],cacheFileTypes:["html","css","js","png","jpg","jpeg","webp","svg","woff","woff2"],useWorkbox:!1},autoInject:!0,push:{enabled:!1,defaultOptions:{vibrate:[100,50,100],requireInteraction:!1}},backgroundSync:{enabled:!1,queueName:"stx-sync-queue",maxRetentionMinutes:1440,maxRetries:3,minInterval:1000,forms:[],endpoints:[]},shareTarget:{enabled:!1,action:"/share-target",method:"POST",enctype:"multipart/form-data",params:{title:"title",text:"text",url:"url"}},fileHandlers:{enabled:!1},protocolHandlers:[],cacheStorage:{maxSize:100,maxEntries:500,maxAge:30,purgeStrategy:"lru"},updates:{enabled:!0,promptUser:!0,autoReload:!1,message:"A new version is available. Reload to update?"},precache:{enabled:!0,includeHtml:!0,includeJs:!0,includeCss:!0,includeImages:!0,includeFonts:!0,include:[],exclude:["*.map","*.LICENSE.txt"],maxFileSizeKB:500}},media:{enabled:!0,image:{enabled:!0,defaultWidths:[320,480,640,768,1024,1280,1536,1920],defaultFormats:["avif","webp","jpeg"],defaultQuality:80,placeholderStrategy:"thumbhash",lazyByDefault:!0,enableDpr:!0,defaultDpr:[1,2,3],tsImages:{enabled:!0,outputDir:"dist/images",baseUrl:"/images",formatQuality:{jpeg:{quality:85,mozjpeg:!0,progressive:!0},png:{compressionLevel:9,palette:!1},webp:{quality:82,effort:5,smartSubsample:!0},avif:{quality:75,effort:4,lossless:!1}},breakpoints:[320,480,640,768,1024,1280,1536,1920],batchOptions:{concurrency:4,optimizationPreset:"web"}}},video:{enabled:!0,lazyByDefault:!0,defaultControls:!0,tsVideos:{enabled:!0,outputDir:"dist/videos",baseUrl:"/videos",defaultQuality:"high",streaming:{enabled:!0,format:"hls",segmentDuration:6,defaultQualities:[{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}]},thumbnails:{enabled:!0,count:10,format:"webp",width:320},transcoding:{defaultCodec:"h264",defaultAudioCodec:"aac",speedPreset:"medium"}}},upload:{enabled:!0,maxSize:10485760,allowedTypes:["image/*","video/*","audio/*","application/pdf"],maxConcurrent:3},protected:{enabled:!0,expirationSeconds:3600,batchSize:10},cache:{enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:500}},broadcasting:{enabled:!1,driver:"bun",host:"0.0.0.0",port:6001,scheme:"ws",verbose:!1}};function Ut(e,r,o){let l=r||"pages";if(e)return{root:e,pagesDir:l};let s=o||process.cwd(),c=j.join(s,"resources","views"),d=j.join(s,"resources","layouts");if(Q.existsSync(c)&&Q.existsSync(d))return{root:"resources",pagesDir:"views"};let p=j.join(s,"resources","views","pages");if(Q.existsSync(p))return{root:"resources/views",pagesDir:l};return{root:".",pagesDir:l}}var et=new Set,ue=["partialsDir","componentsDir","layoutsDir"],Se=new WeakMap;function Bt(e,r){let o=r.replace(/[\\/]+$/,"");if(!o||o===".")return!0;let l=e.replace(/\\/g,"/"),s=o.replace(/\\/g,"/");return l===s||l.startsWith(`${s}/`)}function Nl(e,r){let o=!e.root,l=Ut(e.root,e.pagesDir,r);if(e.root=l.root,e.pagesDir=l.pagesDir,o&&l.root!=="."){let s=`${r}::${l.root}`;if(!et.has(s))et.add(s),console.warn(`[stx] No "root" in config \u2014 inferred "${l.root}" from the project layout. Template directories are resolved under it; set root explicitly to pin this.`)}if(!Se.has(e)){let s={};for(let c of ue){let d=e[c];if(typeof d==="string"&&d)s[c]=d}Se.set(e,s)}if(e.root&&e.root!=="."){let s=e.root;for(let c of ue){let d=e[c];if(typeof d!=="string"||!d)continue;if(j.isAbsolute(d)||Bt(d,s))continue;e[c]=j.join(s,d)}}for(let s of ue){let c=e[s];if(typeof c!=="string"||!c||j.isAbsolute(c))continue;e[s]=j.resolve(r,c)}return e}function Jt(e,r){let o=Se.get(e);for(let l of ue){let s=e[l];if(typeof s!=="string"||!s)continue;let c=j.isAbsolute(s)?s:j.join(r,s);if(Q.existsSync(c))continue;let d=o?.[l]??s,p=e.root,u=!!p&&p!==".";console.warn(`[stx] ${String(l)} resolves to "${c}", which does not exist. Configured as "${d}"`+(u?`, resolved under root "${p}".`:"."))}}function Kt(e){if(e.customDirectives)e.customDirectives=[...e.customDirectives];if(e.middleware)e.middleware=[...e.middleware];if(e.apiRoutes)e.apiRoutes={...e.apiRoutes}}function Gt(e){if(Ra(e.stateDir),e.stateDir=sr(),e.cachePath=or(e.cachePath),e.build)e.build.cacheDir=or(e.build.cacheDir);if(e.media?.cache)e.media.cache.directory=or(e.media.cache.directory);if(e.story)e.story.outDir=or(e.story.outDir)}var K=null,Y=new Map,de=new Map,se=null;async function yo(e,r=Ht){try{return await r(e)}catch(o){if(o instanceof Error&&o.name==="ConfigNotFoundError")return{config:e.defaultConfig};throw o}}async function i(e){let r=e?j.resolve(e):process.cwd(),o=de.get(r);if(o&&o.signature!==Yr(o.graph)){let c=Y.get(r);if(Y.delete(r),de.delete(r),!e)K=null,se=null;let{clearComponentCache:d}=await import("./chunk-yxp7jmnz.js"),{partialsCache:p}=await import("./chunk-ngd9dsrd.js");if(d(),p.clear(),c&&o.configSignature===Zr(o.graph)){let u=c.then(async(g)=>{let y={...o.graph};await vo(y,r),de.set(r,{graph:y,signature:Yr(y),configSignature:Zr(y)});let h={...g,_layerGraph:y};if(!e)K=h;return h});return Y.set(r,u),u}}if(!e){if(K)return K;if(se)return se}let l=Y.get(r);if(l)return l;let s=(async()=>{let c=[".ts",".js",".mjs",".cjs",".json"],d=c.some((v)=>Q.existsSync(j.join(r,`stx.config${v}`))),p=c.some((v)=>Q.existsSync(j.join(r,"config",`ui${v}`))),u;if(d&&p){let v=await yo({name:"ui",cwd:j.join(r,"config"),defaultConfig:N,errorPolicy:"throw",verbose:!1});u=(await yo({name:"stx",alias:"ui",cwd:r,defaultConfig:v.config,errorPolicy:"throw",verbose:!1})).config}else u=(await yo({name:"stx",alias:"ui",cwd:r,defaultConfig:N,errorPolicy:"throw",verbose:!1})).config;if(u.extends!==void 0||o){let v=await ka(r,N);u=v.config,de.set(r,{graph:v.graph,signature:Yr(v.graph),configSignature:Zr(v.graph)})}if(u.runtimeConfig){let{resolveRuntimeConfig:v}=await import("./chunk-wvz7rp5p.js");v(u.runtimeConfig,{});let{generateRuntimeConfigTypes:b}=await import("./chunk-5m42k74p.js");await b(r,u.runtimeConfig)}Kt(u),Gt(u),Nl(u,r),Jt(u,r);let g=[],y=new Set((u.plugins??[]).map((v)=>typeof v==="string"?v:v[0]));for(let v of u.componentPackages??["@stacksjs/components"]){let b=`${v}/stx-plugin`;if(y.has(b)||y.has(v))continue;try{f.resolve(b,{paths:[r]}),g.push(b)}catch{}}let h=[...u.plugins??[],...g];if(h.length>0){let{pluginManager:v}=await import("./chunk-vqv5w6gs.js"),b=[],x=[];for(let P of h){let S=typeof P==="string"?P:P[0],A=typeof P==="string"?{}:P[1]||{};try{let k,E;try{let w=f.resolve(S,{paths:[r]});k=await import(w),E=j.dirname(w)}catch{let w=j.resolve(r,S);k=await import(w),E=j.dirname(w)}let I=k.default||k;if(!v.has(I.name))await v.register(I,u);if(I.components){let w=Array.isArray(I.components)?I.components:[I.components];for(let C of w)b.push(j.resolve(E,C))}if(I.pages){let w=j.resolve(E,I.pages),C=A.path||"/";x.push({dir:w,prefix:C})}if(I.setup){let w={addDirective:(C)=>{u.customDirectives=u.customDirectives||[],u.customDirectives.push(C)},addRoute:(C,D)=>{u.apiRoutes=u.apiRoutes||{},u.apiRoutes[C]=D},addMiddleware:(C)=>{u.middleware=u.middleware||[],u.middleware.push(C)},pluginDir:E,config:u};await I.setup(A,w)}process.stderr.write(`[stx] Plugin loaded: ${I.name||S}
1311
1311
  `)}catch(k){console.warn(`[stx] Failed to load plugin ${S}:`,k.message)}}u._pluginComponentDirs=b,u._pluginPageDirs=x}return u})();if(Y.set(r,s),s.catch(()=>{if(Y.get(r)===s)Y.delete(r)}),!e)se=s,s.then((c)=>{K=c}).catch(()=>{});return s}var R=new Proxy(N,{get(e,r){if(K&&r in K)return K[r];if(!se)i().catch((o)=>{console.warn("[stx] Failed to load config file:",o?.message||o)});return e[r]}});function Ep(e){return e}function Tp(e){let r=[],o=[];if(e.partialsDir!==void 0&&typeof e.partialsDir!=="string")r.push({path:"partialsDir",message:"partialsDir must be a string",severity:"error"});if(e.componentsDir!==void 0&&typeof e.componentsDir!=="string")r.push({path:"componentsDir",message:"componentsDir must be a string",severity:"error"});if(e.cache!==void 0&&typeof e.cache!=="boolean")r.push({path:"cache",message:"cache must be a boolean",severity:"error"});if(e.debug!==void 0&&typeof e.debug!=="boolean")r.push({path:"debug",message:"debug must be a boolean",severity:"error"});if(e.streaming){if(e.streaming.bufferSize!==void 0){if(typeof e.streaming.bufferSize!=="number"||e.streaming.bufferSize<=0)r.push({path:"streaming.bufferSize",message:"streaming.bufferSize must be a positive number",severity:"error"})}if(e.streaming.timeout!==void 0){if(typeof e.streaming.timeout!=="number"||e.streaming.timeout<=0)r.push({path:"streaming.timeout",message:"streaming.timeout must be a positive number",severity:"error"})}if(e.streaming.strategy!==void 0){let l=["auto","manual","sections"];if(!l.includes(e.streaming.strategy))r.push({path:"streaming.strategy",message:`streaming.strategy must be one of: ${l.join(", ")}`,severity:"error"})}}if(e.i18n){if(e.i18n.format!==void 0){let l=["json","yaml","yml","js"];if(!l.includes(e.i18n.format))r.push({path:"i18n.format",message:`i18n.format must be one of: ${l.join(", ")}`,severity:"error"})}}if(e.animation){if(e.animation.defaultDuration!==void 0){if(typeof e.animation.defaultDuration!=="number"||e.animation.defaultDuration<0)r.push({path:"animation.defaultDuration",message:"animation.defaultDuration must be a non-negative number",severity:"error"})}if(e.animation.staggerDelay!==void 0){if(typeof e.animation.staggerDelay!=="number"||e.animation.staggerDelay<0)r.push({path:"animation.staggerDelay",message:"animation.staggerDelay must be a non-negative number",severity:"error"})}}if(e.a11y){if(e.a11y.level!==void 0){let l=["AA","AAA"];if(!l.includes(e.a11y.level))r.push({path:"a11y.level",message:`a11y.level must be one of: ${l.join(", ")}`,severity:"error"})}}if(e.hydration){if(e.hydration.mode!==void 0){let l=["progressive","islands"];if(!l.includes(e.hydration.mode))r.push({path:"hydration.mode",message:`hydration.mode must be one of: ${l.join(", ")}`,severity:"error"})}if(e.hydration.preload!==void 0){let l=["none","eager","lazy"];if(!l.includes(e.hydration.preload))r.push({path:"hydration.preload",message:`hydration.preload must be one of: ${l.join(", ")}`,severity:"error"})}}if(e.customDirectives)if(!Array.isArray(e.customDirectives))r.push({path:"customDirectives",message:"customDirectives must be an array",severity:"error"});else e.customDirectives.forEach((l,s)=>{if(!l.name||typeof l.name!=="string")r.push({path:`customDirectives[${s}].name`,message:"Custom directive must have a name string",severity:"error"});if(!l.handler||typeof l.handler!=="function")r.push({path:`customDirectives[${s}].handler`,message:"Custom directive must have a handler function",severity:"error"})});if(e.middleware)if(!Array.isArray(e.middleware))r.push({path:"middleware",message:"middleware must be an array",severity:"error"});else e.middleware.forEach((l,s)=>{if(!l.name||typeof l.name!=="string")r.push({path:`middleware[${s}].name`,message:"Middleware must have a name string",severity:"error"});if(!l.handler||typeof l.handler!=="function")r.push({path:`middleware[${s}].handler`,message:"Middleware must have a handler function",severity:"error"});if(!l.timing||!["before","after"].includes(l.timing))r.push({path:`middleware[${s}].timing`,message:'Middleware timing must be "before" or "after"',severity:"error"})});if(e.debug===!0&&e.cache===!0)o.push({path:"debug+cache",message:"Debug mode with caching enabled may show stale content during development",severity:"warning"});if(e.seo?.enabled===!0&&!e.seo?.defaultConfig?.title)o.push({path:"seo.defaultConfig.title",message:"SEO is enabled but no default title is set",severity:"warning"});if(e.pwa){if(e.pwa.enabled===!0&&!e.pwa.manifest?.name)r.push({path:"pwa.manifest.name",message:"PWA manifest name is required when PWA is enabled",severity:"error"});if(e.pwa.manifest?.display!==void 0){let l=["fullscreen","standalone","minimal-ui","browser"];if(!l.includes(e.pwa.manifest.display))r.push({path:"pwa.manifest.display",message:`PWA display must be one of: ${l.join(", ")}`,severity:"error"})}if(e.pwa.manifest?.orientation!==void 0){let l=["portrait","landscape","any","portrait-primary","portrait-secondary","landscape-primary","landscape-secondary"];if(!l.includes(e.pwa.manifest.orientation))r.push({path:"pwa.manifest.orientation",message:`PWA orientation must be one of: ${l.join(", ")}`,severity:"error"})}if(e.pwa.routes){let l=["cache-first","network-first","stale-while-revalidate","network-only","cache-only"];e.pwa.routes.forEach((s,c)=>{if(!s.pattern||typeof s.pattern!=="string")r.push({path:`pwa.routes[${c}].pattern`,message:"PWA route must have a pattern string",severity:"error"});if(!l.includes(s.strategy))r.push({path:`pwa.routes[${c}].strategy`,message:`PWA route strategy must be one of: ${l.join(", ")}`,severity:"error"});if(s.maxAgeSeconds!==void 0&&(typeof s.maxAgeSeconds!=="number"||s.maxAgeSeconds<0))r.push({path:`pwa.routes[${c}].maxAgeSeconds`,message:"PWA route maxAgeSeconds must be a non-negative number",severity:"error"});if(s.maxEntries!==void 0&&(typeof s.maxEntries!=="number"||s.maxEntries<1))r.push({path:`pwa.routes[${c}].maxEntries`,message:"PWA route maxEntries must be a positive number",severity:"error"})})}if(e.pwa.icons?.sizes){if(!Array.isArray(e.pwa.icons.sizes))r.push({path:"pwa.icons.sizes",message:"PWA icon sizes must be an array of numbers",severity:"error"});else if(e.pwa.icons.sizes.filter((s)=>typeof s!=="number"||s<16||s>1024).length>0)r.push({path:"pwa.icons.sizes",message:"PWA icon sizes must be numbers between 16 and 1024",severity:"error"})}if(e.pwa.icons?.purpose){let l=["any","maskable","monochrome"];if(e.pwa.icons.purpose.filter((c)=>!l.includes(c)).length>0)r.push({path:"pwa.icons.purpose",message:`PWA icon purpose must be one of: ${l.join(", ")}`,severity:"error"})}if(e.pwa.enabled===!0&&!e.pwa.icons?.src)o.push({path:"pwa.icons.src",message:"PWA is enabled but no icon source specified. Provide a 512x512 PNG for best results.",severity:"warning"});if(e.pwa.enabled===!0&&!e.pwa.manifest?.themeColor)o.push({path:"pwa.manifest.themeColor",message:"PWA theme color not set, defaulting to black",severity:"warning"})}return{valid:r.length===0,errors:r,warnings:o}}
1312
1312
  export{ga,ma,er,Je,ha,Jr,N,Nl,yo,i,R,Ep,Tp};
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{it,at,ct}from"./chunk-tp4eqfxq.js";import"./chunk-gtktv6nn.js";import"./chunk-6beg47t4.js";import{g}from"./chunk-pe9ry4mj.js";import"./chunk-r0ys9aqa.js";import"./chunk-t6m5d64b.js";import"./chunk-f178pm4d.js";import{Ft,Is,zt,pi,ot,fi,Os,Ht,mi,Vt}from"./chunk-vxnf3xab.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()=>{fi("Config file changed, restarting...");try{await e.onChange()}catch(p){ot(`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 st=".stx/story/analytics.json",dt=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,st),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:dt,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:pt(),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),u=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:u}}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 pt(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var lt=".stx/story/bookmarks.json",mt=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:mt,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:ut(),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 ut(){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{it,at,ct}from"./chunk-tp4eqfxq.js";import"./chunk-gtktv6nn.js";import"./chunk-6beg47t4.js";import{g}from"./chunk-4f5bmy7h.js";import"./chunk-r0ys9aqa.js";import"./chunk-t6m5d64b.js";import"./chunk-tjwv101c.js";import{Ft,Is,zt,pi,ot,fi,Os,Ht,mi,Vt}from"./chunk-vxnf3xab.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()=>{fi("Config file changed, restarting...");try{await e.onChange()}catch(p){ot(`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 st=".stx/story/analytics.json",dt=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,st),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:dt,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:pt(),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),u=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:u}}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 pt(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var lt=".stx/story/bookmarks.json",mt=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:mt,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:ut(),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 ut(){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,7 +556,7 @@ window.__stxPerformance = {
556
556
 
557
557
  window.clearPerformanceMetrics = () => window.__stxPerformance.clear();
558
558
  </script>
559
- `}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),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:ht(),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,yt),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 ht(){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-kz9xs9gn.js"),p={},u=h(n);if(u)try{await g(u,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 vt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await g(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 vt(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 bt(t,a.source,c);return b(t,e.path,{props:c})}async function bt(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-kz9xs9gn.js"),c={...r},n=h(e);if(n)try{await g(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 ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),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:ht(),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,yt),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 ht(){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-5443hz48.js"),p={},u=h(n);if(u)try{await g(u,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 vt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await g(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 vt(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 bt(t,a.source,c);return b(t,e.path,{props:c})}async function bt(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-5443hz48.js"),c={...r},n=h(e);if(n)try{await g(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
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 Ht(t);at(t,r);let s=Vt(t.config,r);ct(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 xt(t,f,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return wt(t,f,e.port)},websocket:{open(i){d.open(i)},close(i){d.close(i)},message(i,l){d.message(i,l)}}}),u=`http://${o}:${e.port}`,y=mi(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let m=await Ht(t);at(t,m);let f=Vt(t.config,m);if(ct(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=u;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:u,close:async()=>{y(),p.stop()}}}async function xt(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],u=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,u,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((u)=>u.id===n),p=c.getComponentAnalytics(n,d?.fileName||n);return Response.json(p)}return new Response("Not found",{status:404})}function wt(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"}">
@@ -1,3 +1,3 @@
1
1
  // @bun
2
- import{F,Ie}from"./chunk-pe9ry4mj.js";var o=/\b(?:state|derived|effect|batch|ref|reactive|computed|watch|watchEffect)\s*(?:<[^>]*>)?\s*\(/;function u(t,e,r){let i={fullTag:r,content:e,attrs:t};if(/\bserver\b/.test(t))return{...i,type:"server"};if(/\bdata-stx-scoped\b/.test(t))return{...i,type:"client"};if(o.test(e))return{...i,type:"signals"};if(/\bclient\b/.test(t)||/\btype\s*=\s*["']module["']/.test(t)||/\bsrc\s*=/.test(t))return{...i,type:"client"};return{...i,type:"server"}}var S=/^<script\b([^>]*)>([\s\S]*)<\/script\s*>$/i;function Gt(t){let e=[],r=[],i=[],c=0;while(c<t.length){let s=t.indexOf("<",c);if(s===-1)break;let p=Ie(t,s);if(p>s){c=p;continue}let a=F(t,s);if(a>s){let f=t.slice(s,a),l=S.exec(f);if(l){let n=u(l[1],l[2],f);switch(n.type){case"signals":e.push(n);break;case"client":r.push(n);break;case"server":i.push(n);break}}c=a;continue}c=s+(t.startsWith("<!--",s)?4:1)}return{signals:e,client:r,server:i}}
2
+ import{F,Ie}from"./chunk-4f5bmy7h.js";var o=/\b(?:state|derived|effect|batch|ref|reactive|computed|watch|watchEffect)\s*(?:<[^>]*>)?\s*\(/;function u(t,e,r){let i={fullTag:r,content:e,attrs:t};if(/\bserver\b/.test(t))return{...i,type:"server"};if(/\bdata-stx-scoped\b/.test(t))return{...i,type:"client"};if(o.test(e))return{...i,type:"signals"};if(/\bclient\b/.test(t)||/\btype\s*=\s*["']module["']/.test(t)||/\bsrc\s*=/.test(t))return{...i,type:"client"};return{...i,type:"server"}}var S=/^<script\b([^>]*)>([\s\S]*)<\/script\s*>$/i;function Gt(t){let e=[],r=[],i=[],c=0;while(c<t.length){let s=t.indexOf("<",c);if(s===-1)break;let p=Ie(t,s);if(p>s){c=p;continue}let a=F(t,s);if(a>s){let f=t.slice(s,a),l=S.exec(f);if(l){let n=u(l[1],l[2],f);switch(n.type){case"signals":e.push(n);break;case"client":r.push(n);break;case"server":i.push(n);break}}c=a;continue}c=s+(t.startsWith("<!--",s)?4:1)}return{signals:e,client:r,server:i}}
3
3
  export{Gt};
@@ -1,4 +1,4 @@
1
1
  // @bun
2
- import{x}from"./chunk-pe9ry4mj.js";import{ce}from"./chunk-bz3zn6f7.js";function g(e,t){let r={};for(let n of e)r[n]=ce(t(n));return new Proxy({},{get:(n,a)=>r[a]?.(),set:(n,a,o)=>{if(r[a])r[a].set(o);else r[a]=ce(o);return!0},has:(n,a)=>(a in r),deleteProperty:(n,a)=>(delete r[a],!0),ownKeys:()=>Reflect.ownKeys(r),getOwnPropertyDescriptor:(n,a)=>(a in r)?{enumerable:!0,configurable:!0,writable:!0,value:r[a]()}:void 0})}function v(e,t){let r={};for(let n of t)r[n]=e[n];return r}function Fi(e,t){let r=Object.keys(e),n=g(r,(i)=>t?.[i]??e[i].getDefaultValue()),a=g(r,()=>[]),o=g(r,()=>!1),c=g(r,()=>!1),f=g(r,()=>!1),s=ce(!1);async function u(i){f[i]=!0;let d=await e[i].validate(n[i],n);return a[i]=d,f[i]=!1,d.length===0}async function l(){s.set(!0);let i=await Promise.all(r.map(u));return s.set(!1),i.every(Boolean)}function m(){for(let i of r)n[i]=t?.[i]??e[i].getDefaultValue(),a[i]=[],o[i]=!1,c[i]=!1}function h(i){for(let d of r)if(d in i)n[d]=i[d],c[d]=!0}function b(i,d){n[i]=d,c[i]=!0}function y(i,d=!0){if(o[i]=d,d)u(i)}function p(i){return{value:n[i],errors:a[i],touched:o[i],dirty:c[i],valid:a[i].length===0,validating:f[i]}}function V(i){return async(d)=>{d?.preventDefault?.();for(let w of r)o[w]=!0;if(await l())await i(v(n,r))}}return{values:n,errors:a,touched:o,dirty:c,get isValid(){return r.every((i)=>a[i].length===0)},get isValidating(){return s()||r.some((i)=>f[i])},get isDirty(){return r.some((i)=>c[i])},validate:l,validateField:u,reset:m,setValues:h,setFieldValue:b,setFieldTouched:y,getFieldState:p,handleSubmit:V}}var il=Fi;class On{rules=[];defaultValue="";addRule(e){let t=new On;return t.rules=[...this.rules,e],t.defaultValue=this.defaultValue,t}required(e="This field is required"){return this.addRule({name:"required",message:e,validate:(t)=>{if(t===null||t===void 0)return e;if(typeof t==="string"&&t.trim()==="")return e;if(Array.isArray(t)&&t.length===0)return e;return!0}})}email(e="Please enter a valid email"){return this.addRule({name:"email",message:e,validate:(t)=>{if(!t)return!0;return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(t))||e}})}url(e="Please enter a valid URL"){return this.addRule({name:"url",message:e,validate:(t)=>{if(!t)return!0;try{return new URL(String(t)),!0}catch{return e}}})}min(e,t){let r=t||`Must be at least ${e} characters`;return this.addRule({name:"min",message:r,validate:(n)=>{if(!n)return!0;return String(n).length>=e||r}})}max(e,t){let r=t||`Must be no more than ${e} characters`;return this.addRule({name:"max",message:r,validate:(n)=>{if(!n)return!0;return String(n).length<=e||r}})}length(e,t,r){let n=r||`Must be between ${e} and ${t} characters`;return this.addRule({name:"length",message:n,validate:(a)=>{if(!a)return!0;let o=String(a).length;return o>=e&&o<=t||n}})}pattern(e,t="Invalid format"){return this.addRule({name:"pattern",message:t,validate:(r)=>{if(!r)return!0;return e.test(String(r))||t}})}hasUppercase(e="Must contain an uppercase letter"){return this.pattern(/[A-Z]/,e)}hasLowercase(e="Must contain a lowercase letter"){return this.pattern(/[a-z]/,e)}hasNumber(e="Must contain a number"){return this.pattern(/\d/,e)}hasSpecial(e="Must contain a special character"){return this.pattern(/[!@#$%^&*(),.?":{}|<>]/,e)}alphanumeric(e="Only letters and numbers allowed"){return this.pattern(/^[a-zA-Z0-9]+$/,e)}startsWithLetter(e="Must start with a letter"){return this.pattern(/^[a-zA-Z]/,e)}noSpaces(e="Spaces are not allowed"){return this.addRule({name:"noSpaces",message:e,validate:(t)=>{if(!t)return!0;return!String(t).includes(" ")||e}})}number(e="Must be a number"){let t=this.addRule({name:"number",message:e,validate:(r)=>{if(!r&&r!==0)return!0;return!Number.isNaN(Number(r))||e}});return t.defaultValue=0,t}integer(e="Must be a whole number"){return this.addRule({name:"integer",message:e,validate:(t)=>{if(!t&&t!==0)return!0;return Number.isInteger(Number(t))||e}})}positive(e="Must be a positive number"){return this.addRule({name:"positive",message:e,validate:(t)=>{if(!t&&t!==0)return!0;return Number(t)>0||e}})}negative(e="Must be a negative number"){return this.addRule({name:"negative",message:e,validate:(t)=>{if(!t&&t!==0)return!0;return Number(t)<0||e}})}minValue(e,t){let r=t||`Must be at least ${e}`;return this.addRule({name:"minValue",message:r,validate:(n)=>{if(!n&&n!==0)return!0;return Number(n)>=e||r}})}maxValue(e,t){let r=t||`Must be no more than ${e}`;return this.addRule({name:"maxValue",message:r,validate:(n)=>{if(!n&&n!==0)return!0;return Number(n)<=e||r}})}between(e,t,r){let n=r||`Must be between ${e} and ${t}`;return this.addRule({name:"between",message:n,validate:(a)=>{if(!a&&a!==0)return!0;let o=Number(a);return o>=e&&o<=t||n}})}matches(e,t){let r=t||`Must match ${e}`;return this.addRule({name:"matches",message:r,validate:(n,a)=>{if(!a)return!0;return n===a[e]||r}})}oneOf(e,t){let r=t||`Must be one of: ${e.join(", ")}`;return this.addRule({name:"oneOf",message:r,validate:(n)=>{if(!n)return!0;return e.includes(n)||r}})}notOneOf(e,t){let r=t||`Cannot be one of: ${e.join(", ")}`;return this.addRule({name:"notOneOf",message:r,validate:(n)=>{if(!n)return!0;return!e.includes(n)||r}})}date(e="Must be a valid date"){return this.addRule({name:"date",message:e,validate:(t)=>{if(!t)return!0;let r=new Date(String(t));return!Number.isNaN(r.getTime())||e}})}before(e,t){let r=new Date(e),n=t||`Must be before ${r.toLocaleDateString()}`;return this.addRule({name:"before",message:n,validate:(a)=>{if(!a)return!0;return new Date(String(a))<r||n}})}after(e,t){let r=new Date(e),n=t||`Must be after ${r.toLocaleDateString()}`;return this.addRule({name:"after",message:n,validate:(a)=>{if(!a)return!0;return new Date(String(a))>r||n}})}custom(e,t="Invalid value"){return this.addRule({name:"custom",message:t,validate:e})}async(e,t="Invalid value"){return this.addRule({name:"async",message:t,async:!0,validate:e})}when(e,t){let r=new On;r.rules=[...this.rules],r.defaultValue=this.defaultValue;for(let n of t.getRules())r.rules.push({...n,validate:(a,o)=>{if(!e(a,o||{}))return!0;return n.validate(a,o)}});return r}getRules(){return this.rules}getDefaultValue(){return this.defaultValue}default(e){let t=new On;return t.rules=[...this.rules],t.defaultValue=e,t}async validate(e,t){let r=[];for(let n of this.rules){let a=await n.validate(e,t);if(a!==!0)r.push(a)}return r}validateSync(e,t){let r=[];for(let n of this.rules){if(n.async)continue;let a=n.validate(e,t);if(a!==!0)r.push(a)}return r}}var id=new On;function al(e,t,r){let n=/@error\s*\(\s*([^)]+)\s*\)([\s\S]*?)@enderror/g;return e.replace(n,(a,o,c)=>{try{let f=o.trim().split("."),s=t;for(let l of f)if(s&&typeof s==="object"&&l in s)s=s[l];else return"";let u=s;if(!u||!Array.isArray(u)||u.length===0)return"";return u.map((l)=>x(c,{...t,message:l},r)).join(`
2
+ import{x}from"./chunk-4f5bmy7h.js";import{ce}from"./chunk-bz3zn6f7.js";function g(e,t){let r={};for(let n of e)r[n]=ce(t(n));return new Proxy({},{get:(n,a)=>r[a]?.(),set:(n,a,o)=>{if(r[a])r[a].set(o);else r[a]=ce(o);return!0},has:(n,a)=>(a in r),deleteProperty:(n,a)=>(delete r[a],!0),ownKeys:()=>Reflect.ownKeys(r),getOwnPropertyDescriptor:(n,a)=>(a in r)?{enumerable:!0,configurable:!0,writable:!0,value:r[a]()}:void 0})}function v(e,t){let r={};for(let n of t)r[n]=e[n];return r}function Fi(e,t){let r=Object.keys(e),n=g(r,(i)=>t?.[i]??e[i].getDefaultValue()),a=g(r,()=>[]),o=g(r,()=>!1),c=g(r,()=>!1),f=g(r,()=>!1),s=ce(!1);async function u(i){f[i]=!0;let d=await e[i].validate(n[i],n);return a[i]=d,f[i]=!1,d.length===0}async function l(){s.set(!0);let i=await Promise.all(r.map(u));return s.set(!1),i.every(Boolean)}function m(){for(let i of r)n[i]=t?.[i]??e[i].getDefaultValue(),a[i]=[],o[i]=!1,c[i]=!1}function h(i){for(let d of r)if(d in i)n[d]=i[d],c[d]=!0}function b(i,d){n[i]=d,c[i]=!0}function y(i,d=!0){if(o[i]=d,d)u(i)}function p(i){return{value:n[i],errors:a[i],touched:o[i],dirty:c[i],valid:a[i].length===0,validating:f[i]}}function V(i){return async(d)=>{d?.preventDefault?.();for(let w of r)o[w]=!0;if(await l())await i(v(n,r))}}return{values:n,errors:a,touched:o,dirty:c,get isValid(){return r.every((i)=>a[i].length===0)},get isValidating(){return s()||r.some((i)=>f[i])},get isDirty(){return r.some((i)=>c[i])},validate:l,validateField:u,reset:m,setValues:h,setFieldValue:b,setFieldTouched:y,getFieldState:p,handleSubmit:V}}var il=Fi;class On{rules=[];defaultValue="";addRule(e){let t=new On;return t.rules=[...this.rules,e],t.defaultValue=this.defaultValue,t}required(e="This field is required"){return this.addRule({name:"required",message:e,validate:(t)=>{if(t===null||t===void 0)return e;if(typeof t==="string"&&t.trim()==="")return e;if(Array.isArray(t)&&t.length===0)return e;return!0}})}email(e="Please enter a valid email"){return this.addRule({name:"email",message:e,validate:(t)=>{if(!t)return!0;return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(t))||e}})}url(e="Please enter a valid URL"){return this.addRule({name:"url",message:e,validate:(t)=>{if(!t)return!0;try{return new URL(String(t)),!0}catch{return e}}})}min(e,t){let r=t||`Must be at least ${e} characters`;return this.addRule({name:"min",message:r,validate:(n)=>{if(!n)return!0;return String(n).length>=e||r}})}max(e,t){let r=t||`Must be no more than ${e} characters`;return this.addRule({name:"max",message:r,validate:(n)=>{if(!n)return!0;return String(n).length<=e||r}})}length(e,t,r){let n=r||`Must be between ${e} and ${t} characters`;return this.addRule({name:"length",message:n,validate:(a)=>{if(!a)return!0;let o=String(a).length;return o>=e&&o<=t||n}})}pattern(e,t="Invalid format"){return this.addRule({name:"pattern",message:t,validate:(r)=>{if(!r)return!0;return e.test(String(r))||t}})}hasUppercase(e="Must contain an uppercase letter"){return this.pattern(/[A-Z]/,e)}hasLowercase(e="Must contain a lowercase letter"){return this.pattern(/[a-z]/,e)}hasNumber(e="Must contain a number"){return this.pattern(/\d/,e)}hasSpecial(e="Must contain a special character"){return this.pattern(/[!@#$%^&*(),.?":{}|<>]/,e)}alphanumeric(e="Only letters and numbers allowed"){return this.pattern(/^[a-zA-Z0-9]+$/,e)}startsWithLetter(e="Must start with a letter"){return this.pattern(/^[a-zA-Z]/,e)}noSpaces(e="Spaces are not allowed"){return this.addRule({name:"noSpaces",message:e,validate:(t)=>{if(!t)return!0;return!String(t).includes(" ")||e}})}number(e="Must be a number"){let t=this.addRule({name:"number",message:e,validate:(r)=>{if(!r&&r!==0)return!0;return!Number.isNaN(Number(r))||e}});return t.defaultValue=0,t}integer(e="Must be a whole number"){return this.addRule({name:"integer",message:e,validate:(t)=>{if(!t&&t!==0)return!0;return Number.isInteger(Number(t))||e}})}positive(e="Must be a positive number"){return this.addRule({name:"positive",message:e,validate:(t)=>{if(!t&&t!==0)return!0;return Number(t)>0||e}})}negative(e="Must be a negative number"){return this.addRule({name:"negative",message:e,validate:(t)=>{if(!t&&t!==0)return!0;return Number(t)<0||e}})}minValue(e,t){let r=t||`Must be at least ${e}`;return this.addRule({name:"minValue",message:r,validate:(n)=>{if(!n&&n!==0)return!0;return Number(n)>=e||r}})}maxValue(e,t){let r=t||`Must be no more than ${e}`;return this.addRule({name:"maxValue",message:r,validate:(n)=>{if(!n&&n!==0)return!0;return Number(n)<=e||r}})}between(e,t,r){let n=r||`Must be between ${e} and ${t}`;return this.addRule({name:"between",message:n,validate:(a)=>{if(!a&&a!==0)return!0;let o=Number(a);return o>=e&&o<=t||n}})}matches(e,t){let r=t||`Must match ${e}`;return this.addRule({name:"matches",message:r,validate:(n,a)=>{if(!a)return!0;return n===a[e]||r}})}oneOf(e,t){let r=t||`Must be one of: ${e.join(", ")}`;return this.addRule({name:"oneOf",message:r,validate:(n)=>{if(!n)return!0;return e.includes(n)||r}})}notOneOf(e,t){let r=t||`Cannot be one of: ${e.join(", ")}`;return this.addRule({name:"notOneOf",message:r,validate:(n)=>{if(!n)return!0;return!e.includes(n)||r}})}date(e="Must be a valid date"){return this.addRule({name:"date",message:e,validate:(t)=>{if(!t)return!0;let r=new Date(String(t));return!Number.isNaN(r.getTime())||e}})}before(e,t){let r=new Date(e),n=t||`Must be before ${r.toLocaleDateString()}`;return this.addRule({name:"before",message:n,validate:(a)=>{if(!a)return!0;return new Date(String(a))<r||n}})}after(e,t){let r=new Date(e),n=t||`Must be after ${r.toLocaleDateString()}`;return this.addRule({name:"after",message:n,validate:(a)=>{if(!a)return!0;return new Date(String(a))>r||n}})}custom(e,t="Invalid value"){return this.addRule({name:"custom",message:t,validate:e})}async(e,t="Invalid value"){return this.addRule({name:"async",message:t,async:!0,validate:e})}when(e,t){let r=new On;r.rules=[...this.rules],r.defaultValue=this.defaultValue;for(let n of t.getRules())r.rules.push({...n,validate:(a,o)=>{if(!e(a,o||{}))return!0;return n.validate(a,o)}});return r}getRules(){return this.rules}getDefaultValue(){return this.defaultValue}default(e){let t=new On;return t.rules=[...this.rules],t.defaultValue=e,t}async validate(e,t){let r=[];for(let n of this.rules){let a=await n.validate(e,t);if(a!==!0)r.push(a)}return r}validateSync(e,t){let r=[];for(let n of this.rules){if(n.async)continue;let a=n.validate(e,t);if(a!==!0)r.push(a)}return r}}var id=new On;function al(e,t,r){let n=/@error\s*\(\s*([^)]+)\s*\)([\s\S]*?)@enderror/g;return e.replace(n,(a,o,c)=>{try{let f=o.trim().split("."),s=t;for(let l of f)if(s&&typeof s==="object"&&l in s)s=s[l];else return"";let u=s;if(!u||!Array.isArray(u)||u.length===0)return"";return u.map((l)=>x(c,{...t,message:l},r)).join(`
3
3
  `)}catch{return""}})}function cl(e,t,r){let n=/@errors\s*\(\s*([^)]+)\s*\)([\s\S]*?)@enderrors/g;return e.replace(n,(a,o,c)=>{try{let f=o.trim().split("."),s=t;for(let l of f)if(s&&typeof s==="object"&&l in s)s=s[l];else return"";let u=s;if(!u||!Array.isArray(u)||u.length===0)return"";return u.map((l)=>x(c,{...t,message:l},r)).join(`
4
4
  `)}catch{return""}})}function ll(e,t,r){let n=/@hasErrors\s*\(\s*([^)]+)\s*\)([\s\S]*?)@endhasErrors/g;return e.replace(n,(a,o,c)=>{try{let f=o.trim().split("."),s=t;for(let l of f)if(s&&typeof s==="object"&&l in s)s=s[l];else return"";let u=s;if(!u||!Array.isArray(u)||u.length===0)return"";return c}catch{return""}})}function ad(e,t,r){let n=e;return n=al(n,t,r),n=cl(n,t,r),n=ll(n,t,r),n}export{Fi,il,On,id,al,cl,ll,ad};