@stacksjs/stx 0.2.855 → 0.2.857

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 (154) hide show
  1. package/dist/{chunk-6w3gv9d6.js → chunk-03t7tk2k.js} +1 -1
  2. package/dist/{chunk-jn6mdfrs.js → chunk-08a7j82a.js} +1 -1
  3. package/dist/{chunk-5ppe8d51.js → chunk-08vwk3x7.js} +1 -1
  4. package/dist/{chunk-0dmpc70r.js → chunk-0d3z8hwz.js} +14 -14
  5. package/dist/{chunk-k0arm18k.js → chunk-0hrkpb2h.js} +1 -1
  6. package/dist/{chunk-yzvp90yk.js → chunk-0veh8bcn.js} +2 -2
  7. package/dist/{chunk-4cd94cd5.js → chunk-1277d5we.js} +4 -4
  8. package/dist/{chunk-279n7sde.js → chunk-16p1vkn6.js} +3 -3
  9. package/dist/{chunk-zqb294v2.js → chunk-1772ax8e.js} +1 -1
  10. package/dist/chunk-1ffkbwdz.js +2 -0
  11. package/dist/{chunk-xfb7fdeq.js → chunk-1kmzj10y.js} +10 -10
  12. package/dist/{chunk-w032x0zm.js → chunk-1nankvf6.js} +2 -2
  13. package/dist/chunk-1qbagang.js +2 -0
  14. package/dist/{chunk-7tteg9bn.js → chunk-1qvtme01.js} +1 -1
  15. package/dist/{chunk-gn1dmfdv.js → chunk-1xx55d2p.js} +1 -1
  16. package/dist/{chunk-q0ycypnt.js → chunk-1ywqsmy2.js} +1 -1
  17. package/dist/{chunk-9n3584wt.js → chunk-23mccy5y.js} +1 -1
  18. package/dist/{chunk-2j2qzv8g.js → chunk-27zp4q77.js} +2 -2
  19. package/dist/chunk-2a471sw1.js +3 -0
  20. package/dist/{chunk-33ph9zb2.js → chunk-2cy33z00.js} +2 -2
  21. package/dist/chunk-2jrf9m4w.js +2 -0
  22. package/dist/chunk-3jgrrjvx.js +2 -0
  23. package/dist/{chunk-q0jmc3m4.js → chunk-3wabhzf4.js} +8 -8
  24. package/dist/{chunk-68pvvd7v.js → chunk-3zjyhhg4.js} +3 -3
  25. package/dist/{chunk-gxqtbbz0.js → chunk-41md2f3q.js} +3 -3
  26. package/dist/{chunk-ngnvyqk3.js → chunk-432c35hs.js} +2 -2
  27. package/dist/{chunk-a2fngjfx.js → chunk-4h9kkkh7.js} +1 -1
  28. package/dist/{chunk-h1f3dpvq.js → chunk-4tzsze9z.js} +2 -2
  29. package/dist/chunk-655m8g98.js +2 -0
  30. package/dist/chunk-68kspmq4.js +2 -0
  31. package/dist/{chunk-e8zpzt9s.js → chunk-6tpcm12w.js} +1 -1
  32. package/dist/chunk-6x0jm4bv.js +2 -0
  33. package/dist/{chunk-w835crjw.js → chunk-6zj9wsy3.js} +1 -1
  34. package/dist/{chunk-0vg0j7xa.js → chunk-827rt3ew.js} +1 -1
  35. package/dist/{chunk-fzkyk5j4.js → chunk-8hymdzv2.js} +4 -4
  36. package/dist/chunk-8j8fth4b.js +2 -0
  37. package/dist/{chunk-enxnw50k.js → chunk-8ta5b0eb.js} +1 -1
  38. package/dist/{chunk-pwem4sed.js → chunk-914wcp1a.js} +3 -3
  39. package/dist/{chunk-f858fazq.js → chunk-93cgpqva.js} +1 -1
  40. package/dist/{chunk-car6nhfe.js → chunk-9n8t7v78.js} +2 -2
  41. package/dist/chunk-9wf5fx4s.js +2 -0
  42. package/dist/chunk-a4v8z93r.js +2 -0
  43. package/dist/{chunk-463zkecq.js → chunk-a53jtd74.js} +1 -1
  44. package/dist/{chunk-krtkxnz6.js → chunk-admnvsmx.js} +2 -2
  45. package/dist/chunk-b16g785w.js +2 -0
  46. package/dist/{chunk-ctb1bj28.js → chunk-bg574nvy.js} +3 -3
  47. package/dist/{chunk-fbpqkrvb.js → chunk-bq6jy4yk.js} +3 -3
  48. package/dist/{chunk-hgy98n76.js → chunk-cama7kaq.js} +3 -3
  49. package/dist/chunk-ccdp6g5z.js +2 -0
  50. package/dist/chunk-chr56bhk.js +2 -0
  51. package/dist/{chunk-v8p8t3t4.js → chunk-cskmp5p1.js} +1 -1
  52. package/dist/{chunk-77kanny8.js → chunk-cvrkr3re.js} +9 -9
  53. package/dist/{chunk-9r999ees.js → chunk-dhpd4mx7.js} +2 -2
  54. package/dist/{chunk-9hvfmqs1.js → chunk-dnrgcjds.js} +8 -8
  55. package/dist/chunk-dtxg2a6m.js +2 -0
  56. package/dist/{chunk-wzv7k91a.js → chunk-e8we717q.js} +2 -2
  57. package/dist/{chunk-zswtgwxg.js → chunk-eefdz43s.js} +1 -1
  58. package/dist/chunk-ent64fyq.js +2 -0
  59. package/dist/chunk-erfspa7v.js +2 -0
  60. package/dist/chunk-f0kveh4g.js +2 -0
  61. package/dist/{chunk-anva219c.js → chunk-f1vvhbmw.js} +2 -2
  62. package/dist/chunk-f1z6y2ts.js +2 -0
  63. package/dist/chunk-f3msj6jf.js +2 -0
  64. package/dist/chunk-fk7wk568.js +2 -0
  65. package/dist/{chunk-mv48q1p4.js → chunk-fp24ecp8.js} +65 -65
  66. package/dist/{chunk-9z7fnv33.js → chunk-fyp1v087.js} +1 -1
  67. package/dist/{chunk-1qybwj8k.js → chunk-g0h1gxew.js} +11 -11
  68. package/dist/{chunk-kez50h8a.js → chunk-gggethdc.js} +1 -1
  69. package/dist/{chunk-7kc9xwht.js → chunk-gqrypyk7.js} +2 -2
  70. package/dist/chunk-gr19kv83.js +2 -0
  71. package/dist/{chunk-ynd2nfvs.js → chunk-hfng042r.js} +26 -26
  72. package/dist/chunk-hj1yn8w5.js +2 -0
  73. package/dist/{chunk-7hp50cpd.js → chunk-htwn1f36.js} +6 -6
  74. package/dist/chunk-hzrcnxzg.js +2 -0
  75. package/dist/{chunk-vw73gsxx.js → chunk-j2s8j7ff.js} +3 -3
  76. package/dist/chunk-jed9n2hz.js +2 -0
  77. package/dist/{chunk-xn2gyhes.js → chunk-jefafv6s.js} +4 -4
  78. package/dist/chunk-jhm1228j.js +4 -0
  79. package/dist/chunk-js7nmw8v.js +2 -0
  80. package/dist/chunk-k0ert6e7.js +3 -0
  81. package/dist/{chunk-2rxr5cj6.js → chunk-mfwfaggj.js} +9 -9
  82. package/dist/{chunk-hpwtjb4a.js → chunk-mzes9ds7.js} +2 -2
  83. package/dist/chunk-n68sanmz.js +2 -0
  84. package/dist/{chunk-cy60hmv2.js → chunk-npzzbdn1.js} +1 -1
  85. package/dist/chunk-nstcwcpj.js +2 -0
  86. package/dist/{chunk-ybq56wam.js → chunk-pb09xy77.js} +2 -2
  87. package/dist/chunk-q87hkwfg.js +3 -0
  88. package/dist/chunk-qe6631me.js +2 -0
  89. package/dist/{chunk-ma4ftg5p.js → chunk-qvydfw8g.js} +4 -4
  90. package/dist/{chunk-pesgcwrj.js → chunk-qw0ctwnc.js} +3 -3
  91. package/dist/chunk-rrf78ezg.js +2 -0
  92. package/dist/{chunk-4dfz7cdr.js → chunk-sb7zn84j.js} +5 -5
  93. package/dist/{chunk-f9thwm8c.js → chunk-sftyb8k4.js} +8 -8
  94. package/dist/{chunk-zme05d1n.js → chunk-sgnkbgx1.js} +1 -1
  95. package/dist/chunk-shy2hkvj.js +2 -0
  96. package/dist/{chunk-v4bqmzj9.js → chunk-sny8rqe8.js} +2 -2
  97. package/dist/{chunk-csgfws3j.js → chunk-v1eycdhj.js} +2 -2
  98. package/dist/{chunk-eegs2at0.js → chunk-vmrvkbw6.js} +1 -1
  99. package/dist/chunk-vr5h5jpw.js +2 -0
  100. package/dist/{chunk-11y3106w.js → chunk-wdh20fxz.js} +1 -1
  101. package/dist/chunk-wg7xzens.js +2 -0
  102. package/dist/{chunk-te82sjhy.js → chunk-xejhmsfw.js} +7 -7
  103. package/dist/{chunk-4wrddn8m.js → chunk-xfymp197.js} +9 -9
  104. package/dist/{chunk-qxk9grjm.js → chunk-xqr2ec9k.js} +1 -1
  105. package/dist/{chunk-fba71th7.js → chunk-xw12cd90.js} +7 -7
  106. package/dist/{chunk-gsn5vvw4.js → chunk-y5agvhgg.js} +1 -1
  107. package/dist/chunk-zd2c84ct.js +2 -0
  108. package/dist/{chunk-yscys65t.js → chunk-zrsc45wv.js} +1 -1
  109. package/dist/{chunk-mhjxx64x.js → chunk-zx5bt056.js} +24 -24
  110. package/dist/cli.js +17 -17
  111. package/dist/component-client-factories.js +6 -5
  112. package/dist/craft-entry.js +1 -1
  113. package/dist/craft.js +1 -1
  114. package/dist/pwa.js +3 -3
  115. package/dist/ssg.js +8 -8
  116. package/dist/utils.js +3 -2
  117. package/package.json +5 -5
  118. package/dist/chunk-161ksm7f.js +0 -2
  119. package/dist/chunk-1p968nww.js +0 -2
  120. package/dist/chunk-2y20dvab.js +0 -2
  121. package/dist/chunk-33yeb861.js +0 -2
  122. package/dist/chunk-3pm6d9zj.js +0 -2
  123. package/dist/chunk-3wt0nh3p.js +0 -2
  124. package/dist/chunk-5dykcrnv.js +0 -2
  125. package/dist/chunk-5xcxc9f8.js +0 -2
  126. package/dist/chunk-6bm19d4k.js +0 -2
  127. package/dist/chunk-81z64a84.js +0 -2
  128. package/dist/chunk-8gsd2n0j.js +0 -2
  129. package/dist/chunk-8kqqxqyp.js +0 -2
  130. package/dist/chunk-8qe34jb8.js +0 -3
  131. package/dist/chunk-bk0arddt.js +0 -2
  132. package/dist/chunk-c557w9e6.js +0 -2
  133. package/dist/chunk-cfmjtyzm.js +0 -2
  134. package/dist/chunk-ck9zengd.js +0 -2
  135. package/dist/chunk-cwt26rvt.js +0 -3
  136. package/dist/chunk-dbag44ta.js +0 -2
  137. package/dist/chunk-dfcnaaym.js +0 -2
  138. package/dist/chunk-ehp792dy.js +0 -3
  139. package/dist/chunk-ggthncvg.js +0 -2
  140. package/dist/chunk-hfcagm39.js +0 -2
  141. package/dist/chunk-hfe2byfx.js +0 -2
  142. package/dist/chunk-hmys6w75.js +0 -2
  143. package/dist/chunk-hqtj4ngq.js +0 -2
  144. package/dist/chunk-j3s5y2k5.js +0 -2
  145. package/dist/chunk-ns5epsng.js +0 -2
  146. package/dist/chunk-p91288ce.js +0 -2
  147. package/dist/chunk-pw6n7a9k.js +0 -2
  148. package/dist/chunk-qccpfn5x.js +0 -2
  149. package/dist/chunk-vbsr76qe.js +0 -2
  150. package/dist/chunk-vgaqznwt.js +0 -2
  151. package/dist/chunk-w165qe5q.js +0 -2
  152. package/dist/chunk-wz54wsm7.js +0 -2
  153. package/dist/chunk-x4077p94.js +0 -2
  154. package/dist/chunk-z0qfspzg.js +0 -4
@@ -1,11 +1,11 @@
1
1
  // @bun
2
- import{pe,yn,Mt,Dt,g,s,ge,p}from"./chunk-mv48q1p4.js";import{wt,Ae,uc,ls,jo,Bo,i}from"./chunk-ynd2nfvs.js";import{ce,ee,Ar,_e,z,En}from"./chunk-0dmpc70r.js";import{_t,hr,Ps,Is,Os,Ct,Et,Tt,$t,Rt,At,tt}from"./chunk-9r999ees.js";import{Cs,a,O}from"./chunk-1qybwj8k.js";import{mt,Jt,Ee,j,ga,wo,Jr,qe,ma,Ke,Te}from"./chunk-fba71th7.js";import{fr,gr}from"./chunk-k0arm18k.js";import{e,dn,cr,b}from"./chunk-9hvfmqs1.js";import{Ye}from"./chunk-xfb7fdeq.js";import{Re}from"./chunk-hpwtjb4a.js";import{In}from"./chunk-9n3584wt.js";import{X,we,ve}from"./chunk-7hp50cpd.js";import{c}from"./chunk-ehp792dy.js";import{G}from"./chunk-ym5qgw03.js";async function zn(t){try{let n=await Bun.file(t).text(),r=Nn(n),d=Un(n,t),o=Wn(n,r),l=Vn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Nn(t){let n=t.split(`
2
+ import{fe,yn,Dt,Lt,g,s,me,p}from"./chunk-fp24ecp8.js";import{vt,Pe,uc,ls,jo,Bo,i}from"./chunk-hfng042r.js";import{le,ee,Ar,Ce,z,En}from"./chunk-0d3z8hwz.js";import{Ct,hr,Ps,Is,Os,Et,Tt,$t,Rt,At,Pt,nt}from"./chunk-dhpd4mx7.js";import{Cs,a,O}from"./chunk-g0h1gxew.js";import{ht,Yt,Te,j,ga,wo,Jr,Ke,ma,Ge,$e}from"./chunk-xw12cd90.js";import{fr,gr}from"./chunk-0hrkpb2h.js";import{e,pn,cr,b}from"./chunk-dnrgcjds.js";import{Ze}from"./chunk-1kmzj10y.js";import{Ae}from"./chunk-mzes9ds7.js";import{In}from"./chunk-23mccy5y.js";import{X,ve,xe}from"./chunk-htwn1f36.js";import{c}from"./chunk-k0ert6e7.js";import{G}from"./chunk-ym5qgw03.js";async function zn(t){try{let n=await Bun.file(t).text(),r=Nn(n),d=Un(n,t),o=Wn(n,r),l=Vn(n,r);return{file:t,metrics:r,issues:d,suggestions:o,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Nn(t){let n=t.split(`
3
3
  `),r=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),o=(r?r[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 u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,m=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+m,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,y=Math.min(10,Math.ceil(l.total*0.5+h*0.1+x*0.3+(o>10?o*0.05:0)+w));return{lines:n.length,characters:t.length,directives:l,expressions:h,components:x,layouts:v,scriptLines:o,complexity:y}}function Un(t,n){let r=[],d=Xt(t,"if","endif");if(d>0)r.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=Xt(t,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} 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)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)r.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${x.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let m=t.split(`
5
- `).filter((x)=>x.length>120);if(m.length>0)r.push({type:"info",category:"maintainability",message:`Found ${m.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Wn(t,n){let r=[];if(n.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function Vn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:o}}function Xt(t,n,r){let d=t.replace(/<!--[\s\S]*?-->/g,""),o=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-l)}async function ta(t=["**/*.stx"],n){let r=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await zn(l);r.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let o=qn(r);return{results:r,summary:o}}function qn(t){let n=t.length,r=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,o=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),m=[];if(d>6)m.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)m.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)m.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(d*100)/100,totalIssues:o,issuesByCategory:l,performanceScore:f,recommendations:m}}import{mkdir as Kn,readFile as Xn,readdir as Gn,stat as Gt,writeFile as Jn}from"fs/promises";import ke from"path";function nn(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 rn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Yn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.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 Qn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function Zn(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function er(t){let n=[];async function r(d){let o=await Gn(d,{withFileTypes:!0});o.sort((l,u)=>l.name.localeCompare(u.name));for(let l of o){let u=ke.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await r(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await r(t),n}function tr(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let d=r[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function nr(t,n){let r={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of d){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(m){throw Error(`${n}: failed to transpile <script client> (${m.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let m=f[1];if(rn.has(m))throw Error(`${n}: client ${nn(m)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let y=l[T];if(S){S=!1;continue}if(v){if(y==="\\")S=!0;else if(y===v)v="";continue}if(y==='"'||y==="'"||y==="`")v=y;else if(y==="{")x++;else if(y==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${m}"`);let w=f[0].includes("async")?"async ":"";r[m]=`${w}${m}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return r}function rr(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Yt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
5
+ `).filter((x)=>x.length>120);if(m.length>0)r.push({type:"info",category:"maintainability",message:`Found ${m.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)r.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Wn(t,n){let r=[];if(n.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function Vn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:o}}function Xt(t,n,r){let d=t.replace(/<!--[\s\S]*?-->/g,""),o=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-l)}async function ta(t=["**/*.stx"],n){let r=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await zn(l);r.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let o=qn(r);return{results:r,summary:o}}function qn(t){let n=t.length,r=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,o=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),m=[];if(d>6)m.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)m.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)m.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(d*100)/100,totalIssues:o,issuesByCategory:l,performanceScore:f,recommendations:m}}import{mkdir as Kn,readFile as Xn,readdir as Gn,stat as Gt,writeFile as Jn}from"fs/promises";import ke from"path";function nn(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 rn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Yn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.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 Qn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function Zn(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function er(t){let n=[];async function r(d){let o=await Gn(d,{withFileTypes:!0});o.sort((l,u)=>l.name.localeCompare(u.name));for(let l of o){let u=ke.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await r(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await r(t),n}function tr(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let d=r[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function nr(t,n){let r={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of d){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(m){throw Error(`${n}: failed to transpile <script client> (${m.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let m=f[1];if(rn.has(m))throw Error(`${n}: client ${nn(m)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let y=l[T];if(S){S=!1;continue}if(v){if(y==="\\")S=!0;else if(y===v)v="";continue}if(y==='"'||y==="'"||y==="`")v=y;else if(y==="{")x++;else if(y==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${m}"`);let w=f[0].includes("async")?"async ":"";r[m]=`${w}${m}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return r}function rr(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
6
6
 
7
7
  `)}function or(t){if(!t)return null;let n=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(n))return"string";if(/^number$/.test(n))return"number";if(/^boolean$/.test(n))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(n))return"string";return"object"}function sr(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function ir(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function ar(t){let n=[],r=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),o=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,u=(m)=>{if(d[m]!=="(")return null;let h=0,x="";for(let v=m;v<d.length;v++){let S=d[v];if(x!==""){if(S==="\\")v++;else if(S===x)x="";continue}if(S==="'"||S==='"'||S==="`"){x=S;continue}if(S==="(")h++;else if(S===")"){if(h--,h===0)return{expression:d.slice(m+1,v),end:v+1}}}return null},f=(m)=>{if(m==="")return;let h=0,x=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,v;while(v=x.exec(m)){if(v.index>h)n.push(`out += ${JSON.stringify(m.slice(h,v.index))};`);n.push(v[1]!==void 0?`out += __raw(${v[1]});`:`out += __escape(${v[2]});`),h=v.index+v[0].length}if(h<m.length)n.push(`out += ${JSON.stringify(m.slice(h))};`)};while(l=o.exec(d)){f(d.slice(r,l.index)),r=l.index+l[0].length;let h=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?u(r):null;if(h)r=h.end,o.lastIndex=h.end;let x=h?.expression;switch(l[1]){case"if":n.push(`if (${x}) {`);break;case"elseif":n.push(`} else if (${x}) {`);break;case"else":n.push("} else {");break;case"endif":case"endforeach":n.push("}");break;case"foreach":{let v=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((x||"").trim());if(!v){n.push(`out += ${JSON.stringify(l[0]+(h?`(${x})`:""))};`);break}let[,S,T,w]=v;n.push(T?`for (const [${T}, ${w}] of __entries(${S})) {`:`for (const ${w} of __values(${S})) {`);break}}}return f(d.slice(r)),n.join(`
8
- `)}function lt(t,n,r,d){if(t[n]!==r)return-1;let o=0,l=null;for(let u=n;u<t.length;u++){let f=t[u];if(l){if(f==="\\"){u++;continue}if(f===l)l=null;continue}if(f==="'"||f==='"'||f==="`"){l=f;continue}if(f===r)o++;else if(f===d){if(d===">"&&t[u-1]==="=")continue;if(o--,o===0)return u+1}}return-1}function Lt(t,n,r){let d=r?"([{<":"([{",o=r?")]}>":")]}",l=[],u=0,f=null,m="";for(let h=0;h<t.length;h++){let x=t[h];if(f){if(m+=x,x==="\\"){m+=t[++h]??"";continue}if(x===f)f=null;continue}if(x==="'"||x==='"'||x==="`"){f=x,m+=x;continue}if(d.includes(x))u++;else if(o.includes(x))u--;if(u===0&&n.includes(x)){l.push(m),m="";continue}m+=x}return l.push(m),l.map((h)=>h.trim()).filter(Boolean)}function lr(t){let n=0,r=null;for(let d=0;d<t.length;d++){let o=t[d];if(r){if(o==="\\"){d++;continue}if(o===r)r=null;continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if("([{".includes(o))n++;else if(")]}".includes(o))n--;if(n!==0||o!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Qt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function dr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let r=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let E=r.exec(t);E&&E.index<n.index;E=r.exec(t))d=E.index+E[0].indexOf(E[1]);if(d===-1)return null;let o={},l={},u=[],f={},m=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(m<t.length&&/\s/.test(t[m]))m++},x;if(t[m]==="{"){let E=lt(t,m,"{","}");if(E===-1)return null;x=t.slice(m,E),m=E}else{let E=/^[A-Za-z_$][\w$]*/.exec(t.slice(m));if(!E)return null;x=E[0],m+=E[0].length}if(h(),t[m]!=="=")return null;m++,h();let v=/^withDefaults\s*\(\s*/.exec(t.slice(m)),S=Boolean(v);if(v)m+=v[0].length;let T=/^defineProps\b/.exec(t.slice(m));if(!T)return null;m+=T[0].length;let w="";if(h(),t[m]==="<"){let E=lt(t,m,"<",">");if(E===-1)return null;w=t.slice(m+1,E-1).trim(),m=E}if(h(),t[m]!=="(")return null;let y=lt(t,m,"(",")");if(y===-1)return null;let k=t.slice(m+1,y-1).trim();if(m=y,S){if(h(),t[m]===",")m++,h();if(t[m]==="{"){let E=lt(t,m,"{","}");if(E===-1)return null;for(let[R,A]of It(t.slice(m,E)))l[R]=A;m=E}if(h(),t[m]===",")m++,h();if(t[m]===")")m++}if(t[m]===";")m++;let M=/^[A-Za-z_$][\w$]*$/.test(w)?w:void 0;if(w.startsWith("{"))for(let E of Lt(w.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let R=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(E);if(R)o[R[1]]=R[2].trim()}if(k.startsWith("{"))for(let[E,R]of It(k)){if(u.push(E),!R.startsWith("{")){let A=Qt(R);if(A)o[E]=A;continue}for(let[A,C]of It(R))if(A==="default")l[E]=C;else if(A==="type"){let D=Qt(C);if(D)o[E]=D}}else if(k.startsWith("["))for(let E of Lt(k.slice(1,-1),",",!1))u.push(E.replace(/^['"`]/,"").replace(/['"`]$/,""));if(x.startsWith("{")){u.length=0;for(let E of Lt(x.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let R=lr(E),A=R===-1?E:E.slice(0,R),C=A.split(":")[0].trim().replace(/^\.\.\./,"");if(!C)continue;if(u.push(C),f[C]=A.trim(),R!==-1)l[C]=E.slice(R+1).trim()}}else if(u.length===0)u.push(...Object.keys(o));return{text:t.slice(d,m),propNames:u,propBindings:f,defaults:l,declared:o,typeName:M}}function It(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),r=[],d=0;while(d<n.length){let o=/\s*([A-Za-z_$][\w$]*)\s*:/y;o.lastIndex=d;let l=o.exec(n);if(!l)break;d=o.lastIndex;let u=0,f="",m=d;while(d<n.length){let x=n[d];if(f){if(x==="\\")d++;else if(x===f)f=""}else if(x==="'"||x==='"'||x==="`")f=x;else if(x==="{"||x==="["||x==="(")u++;else if(x==="}"||x==="]"||x===")")u--;else if(x===","&&u===0)break;d++}let h=n.slice(m,d).trim();if(h)r.push([l[1],h]);d++}return r}function pr(t,n,r){let o=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((T)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(T[1]));if(!o)return{imports:[],body:"",propNames:[],propBindings:{},defaults:{},declared:{}};let l=o[2],u=[],f=[],m={},h={},x={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(T)=>{if(/from\s*['"]stx['"]/.test(T))return"";return u.push(T.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(w,y,k,M)=>{let E=ke.resolve(ke.dirname(n),k),R=ke.relative(r,E);return`${y}${R.startsWith(".")?R:`./${R}`}${M}`})),""});let v=dr(l);if(v)f.push(...v.propNames),Object.assign(m,v.propBindings),Object.assign(h,v.defaults),Object.assign(x,v.declared),l=l.replace(v.text,"");let S={};for(let T of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let w=[];for(let y of T[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))x[y[1]]=y[2].trim(),w.push(y[1]);S[T[1]]=w}if(v&&v.propNames.length===0&&v.typeName){for(let T of S[v.typeName]??[])if(!f.includes(T))f.push(T)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:l.trim(),propNames:f,propBindings:m,defaults:h,declared:x}}function ur(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,o,l,u,f)=>{let m=o.toLowerCase();n.add(m);let h=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${m}="${f}"${h?` data-stx-mod-${m}="${h}"`:""}`}),eventTypes:[...n].sort()}}function mr(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,o,l,u)=>{let f=n.length;return n.push({id:f,name:o,expression:u}),` data-stx-bind-${f}=""`}),bindings:n}}function yr(t){let n=new Set;for(let r of t.matchAll(/<slot\b([^>]*)>/gi))n.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((r)=>({name:r}))}function br(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function Zt(t,n){if(!n||!new Set(["string","number","boolean","object","array"]).has(n.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...n,reflect:n.reflect??n.attribute!==!1}}async function xr(t,n,r){let d=ke.isAbsolute(n.file)?n.file:ke.resolve(t,n.file),o=await Xn(d,"utf8"),l=tr(o,d),u=ke.basename(d,".stx"),f=n.name||l.name||Yn(u),m=`${jt(r.prefix||"stx")}-${jt(u)}`,h=n.tag||l.tag||m;if(!f||!/^[A-Za-z_$][\w$]*$/.test(f))throw Error(`${d}: invalid component class name "${f}"`);if(!Qn(h))throw Error(`${d}: invalid custom-element tag "${h}"; tags must be lowercase and contain a hyphen`);let x=n.properties||l.properties||l.props||{},v=Object.fromEntries(Object.entries(x).map(([R,A])=>[R,Zt(R,A)])),S=ur(rr(o)),T=mr(S.template),w=pr(o,d,ke.resolve(r.outputDir)),y=ar(T.template);for(let R of w.propNames){if(v[R])continue;let A=w.defaults[R];v[R]=Zt(R,{type:or(w.declared[R])??sr(A),...A===void 0?{}:{default:ir(A)}})}let k=l.methods||{},M=n.methods||{},E=nr(o,d);return{file:ke.relative(t,d),sourcePath:d,name:f,tag:h,description:n.description||l.description||"",template:T.template,styles:Yt(o),shadowMode:Zn(n.shadowDOM??l.shadowDOM??r.shadowDOM),progressive:n.progressive??l.progressive??r.progressive??!0,properties:v,events:n.events||l.events||{},methods:{...k,...M,...E},eventTypes:S.eventTypes,bindings:T.bindings,slots:yr(T.template),cssProperties:br(Yt(o)),scope:w,render:y}}function vr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),n=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
8
+ `)}function lt(t,n,r,d){if(t[n]!==r)return-1;let o=0,l=null;for(let u=n;u<t.length;u++){let f=t[u];if(l){if(f==="\\"){u++;continue}if(f===l)l=null;continue}if(f==="'"||f==='"'||f==="`"){l=f;continue}if(f===r)o++;else if(f===d){if(d===">"&&t[u-1]==="=")continue;if(o--,o===0)return u+1}}return-1}function _t(t,n,r){let d=r?"([{<":"([{",o=r?")]}>":")]}",l=[],u=0,f=null,m="";for(let h=0;h<t.length;h++){let x=t[h];if(f){if(m+=x,x==="\\"){m+=t[++h]??"";continue}if(x===f)f=null;continue}if(x==="'"||x==='"'||x==="`"){f=x,m+=x;continue}if(d.includes(x))u++;else if(o.includes(x))u--;if(u===0&&n.includes(x)){l.push(m),m="";continue}m+=x}return l.push(m),l.map((h)=>h.trim()).filter(Boolean)}function lr(t){let n=0,r=null;for(let d=0;d<t.length;d++){let o=t[d];if(r){if(o==="\\"){d++;continue}if(o===r)r=null;continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if("([{".includes(o))n++;else if(")]}".includes(o))n--;if(n!==0||o!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Qt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function dr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let r=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let E=r.exec(t);E&&E.index<n.index;E=r.exec(t))d=E.index+E[0].indexOf(E[1]);if(d===-1)return null;let o={},l={},u=[],f={},m=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(m<t.length&&/\s/.test(t[m]))m++},x;if(t[m]==="{"){let E=lt(t,m,"{","}");if(E===-1)return null;x=t.slice(m,E),m=E}else{let E=/^[A-Za-z_$][\w$]*/.exec(t.slice(m));if(!E)return null;x=E[0],m+=E[0].length}if(h(),t[m]!=="=")return null;m++,h();let v=/^withDefaults\s*\(\s*/.exec(t.slice(m)),S=Boolean(v);if(v)m+=v[0].length;let T=/^defineProps\b/.exec(t.slice(m));if(!T)return null;m+=T[0].length;let w="";if(h(),t[m]==="<"){let E=lt(t,m,"<",">");if(E===-1)return null;w=t.slice(m+1,E-1).trim(),m=E}if(h(),t[m]!=="(")return null;let y=lt(t,m,"(",")");if(y===-1)return null;let k=t.slice(m+1,y-1).trim();if(m=y,S){if(h(),t[m]===",")m++,h();if(t[m]==="{"){let E=lt(t,m,"{","}");if(E===-1)return null;for(let[R,A]of It(t.slice(m,E)))l[R]=A;m=E}if(h(),t[m]===",")m++,h();if(t[m]===")")m++}if(t[m]===";")m++;let M=/^[A-Za-z_$][\w$]*$/.test(w)?w:void 0;if(w.startsWith("{"))for(let E of _t(w.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let R=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(E);if(R)o[R[1]]=R[2].trim()}if(k.startsWith("{"))for(let[E,R]of It(k)){if(u.push(E),!R.startsWith("{")){let A=Qt(R);if(A)o[E]=A;continue}for(let[A,C]of It(R))if(A==="default")l[E]=C;else if(A==="type"){let D=Qt(C);if(D)o[E]=D}}else if(k.startsWith("["))for(let E of _t(k.slice(1,-1),",",!1))u.push(E.replace(/^['"`]/,"").replace(/['"`]$/,""));if(x.startsWith("{")){u.length=0;for(let E of _t(x.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let R=lr(E),A=R===-1?E:E.slice(0,R),C=A.split(":")[0].trim().replace(/^\.\.\./,"");if(!C)continue;if(u.push(C),f[C]=A.trim(),R!==-1)l[C]=E.slice(R+1).trim()}}else if(u.length===0)u.push(...Object.keys(o));return{text:t.slice(d,m),propNames:u,propBindings:f,defaults:l,declared:o,typeName:M}}function It(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),r=[],d=0;while(d<n.length){let o=/\s*([A-Za-z_$][\w$]*)\s*:/y;o.lastIndex=d;let l=o.exec(n);if(!l)break;d=o.lastIndex;let u=0,f="",m=d;while(d<n.length){let x=n[d];if(f){if(x==="\\")d++;else if(x===f)f=""}else if(x==="'"||x==='"'||x==="`")f=x;else if(x==="{"||x==="["||x==="(")u++;else if(x==="}"||x==="]"||x===")")u--;else if(x===","&&u===0)break;d++}let h=n.slice(m,d).trim();if(h)r.push([l[1],h]);d++}return r}function pr(t,n,r){let o=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((T)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(T[1]));if(!o)return{imports:[],body:"",propNames:[],propBindings:{},defaults:{},declared:{}};let l=o[2],u=[],f=[],m={},h={},x={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(T)=>{if(/from\s*['"]stx['"]/.test(T))return"";return u.push(T.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(w,y,k,M)=>{let E=ke.resolve(ke.dirname(n),k),R=ke.relative(r,E);return`${y}${R.startsWith(".")?R:`./${R}`}${M}`})),""});let v=dr(l);if(v)f.push(...v.propNames),Object.assign(m,v.propBindings),Object.assign(h,v.defaults),Object.assign(x,v.declared),l=l.replace(v.text,"");let S={};for(let T of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let w=[];for(let y of T[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))x[y[1]]=y[2].trim(),w.push(y[1]);S[T[1]]=w}if(v&&v.propNames.length===0&&v.typeName){for(let T of S[v.typeName]??[])if(!f.includes(T))f.push(T)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:l.trim(),propNames:f,propBindings:m,defaults:h,declared:x}}function ur(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,o,l,u,f)=>{let m=o.toLowerCase();n.add(m);let h=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${m}="${f}"${h?` data-stx-mod-${m}="${h}"`:""}`}),eventTypes:[...n].sort()}}function mr(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,o,l,u)=>{let f=n.length;return n.push({id:f,name:o,expression:u}),` data-stx-bind-${f}=""`}),bindings:n}}function yr(t){let n=new Set;for(let r of t.matchAll(/<slot\b([^>]*)>/gi))n.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((r)=>({name:r}))}function br(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function Zt(t,n){if(!n||!new Set(["string","number","boolean","object","array"]).has(n.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...n,reflect:n.reflect??n.attribute!==!1}}async function xr(t,n,r){let d=ke.isAbsolute(n.file)?n.file:ke.resolve(t,n.file),o=await Xn(d,"utf8"),l=tr(o,d),u=ke.basename(d,".stx"),f=n.name||l.name||Yn(u),m=`${jt(r.prefix||"stx")}-${jt(u)}`,h=n.tag||l.tag||m;if(!f||!/^[A-Za-z_$][\w$]*$/.test(f))throw Error(`${d}: invalid component class name "${f}"`);if(!Qn(h))throw Error(`${d}: invalid custom-element tag "${h}"; tags must be lowercase and contain a hyphen`);let x=n.properties||l.properties||l.props||{},v=Object.fromEntries(Object.entries(x).map(([R,A])=>[R,Zt(R,A)])),S=ur(rr(o)),T=mr(S.template),w=pr(o,d,ke.resolve(r.outputDir)),y=ar(T.template);for(let R of w.propNames){if(v[R])continue;let A=w.defaults[R];v[R]=Zt(R,{type:or(w.declared[R])??sr(A),...A===void 0?{}:{default:ir(A)}})}let k=l.methods||{},M=n.methods||{},E=nr(o,d);return{file:ke.relative(t,d),sourcePath:d,name:f,tag:h,description:n.description||l.description||"",template:T.template,styles:Jt(o),shadowMode:Zn(n.shadowDOM??l.shadowDOM??r.shadowDOM),progressive:n.progressive??l.progressive??r.progressive??!0,properties:v,events:n.events||l.events||{},methods:{...k,...M,...E},eventTypes:S.eventTypes,bindings:T.bindings,slots:yr(T.template),cssProperties:br(Jt(o)),scope:w,render:y}}function vr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),n=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
9
9
 
10
10
  const escapeHTML = (value) => String(value ?? '')
11
11
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -515,12 +515,12 @@ else {
515
515
  <span class="frontmatter-label">${n}:</span>
516
516
  <span>${Array.isArray(r)?r.join(", "):String(r)}</span>
517
517
  </div>`).join("")}
518
- </div>`}async function Cr(t){let{default:n}=await import("net");return new Promise((r)=>{let d=n.createServer();d.once("error",()=>r(!1)),d.once("listening",()=>{d.close(()=>r(!0))}),d.listen(t,"0.0.0.0")})}async function Rr(t){let{default:n}=await import("net");return new Promise((r)=>{let d=n.createServer();d.once("error",()=>r(!1)),d.once("listening",()=>{d.close(()=>r(!0))}),d.listen(t,"::")})}async function Er(t){if(!await Cr(t))return!1;return await Rr(t)}async function We(t,n=20){t=Number(t);for(let r=0;r<n;r++){let d=t+r;if(await Er(d))return d}throw Error(`Could not find an available port between ${t} and ${t+n-1}`)}var Pr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Or(){try{let t=await import("./chunk-gsn5vvw4.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,n={}){let r={...Pr,...n},d=await Or();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let o=await d.openDevWindow(t,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,o),!1}}function gt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let o=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(o){let l=o[1];try{let u=`
518
+ </div>`}async function Cr(t){let{default:n}=await import("net");return new Promise((r)=>{let d=n.createServer();d.once("error",()=>r(!1)),d.once("listening",()=>{d.close(()=>r(!0))}),d.listen(t,"0.0.0.0")})}async function Rr(t){let{default:n}=await import("net");return new Promise((r)=>{let d=n.createServer();d.once("error",()=>r(!1)),d.once("listening",()=>{d.close(()=>r(!0))}),d.listen(t,"::")})}async function Er(t){if(!await Cr(t))return!1;return await Rr(t)}async function We(t,n=20){t=Number(t);for(let r=0;r<n;r++){let d=t+r;if(await Er(d))return d}throw Error(`Could not find an available port between ${t} and ${t+n-1}`)}var Pr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Or(){try{let t=await import("./chunk-y5agvhgg.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Qe(t,n={}){let r={...Pr,...n},d=await Or();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let o=await d.openDevWindow(t,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,o),!1}}function mt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let o=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(o){let l=o[1];try{let u=`
519
519
  ${l}
520
520
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
521
521
  `,m=Function(u)();if(m)return m}catch(u){console.warn("Invalid sidebarConfig:",u)}}return{sections:[]}}let r=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(r)try{return JSON.parse(r[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let o=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(o)return Function(`return ${o[1]}`)()}catch(o){console.warn("Invalid native-sidebar script configuration:",o)}return}function Bt(){console.log(`
522
522
  Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function Dr(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),Bt()}function Mr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ve(t,n,r){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Bt();let d="";process.stdin.on("data",(o)=>{if(o==="\x03"){if(r?.onQuit)r.onQuit();n(),process.exit(0)}if(d+=o,d.endsWith("\r")||d.endsWith(`
523
- `)){let l=d.trim().toLowerCase();d="",_r(l,t,n,r)}})}function _r(t,n,r,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else Mr(n);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Dr(n);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),r(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else Bt();break;default:break}}async function zt(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=et.resolve(t);if(!Ft.existsSync(o))return console.error(`${e.red}Error: File not found: ${e.bright}${o}${e.reset}`),!1;if(!o.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${o}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,u=async()=>{try{let{content:v,data:S}=await Ae(o,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:O.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),T=n.markdown?.syntaxHighlighting||O.markdown?.syntaxHighlighting,w=T?.defaultTheme||"github-dark",y=["github-dark"],k=T?.additionalThemes||[],E=[...new Set([...y,...k])].map((R)=>`<option value="${R}"${R===w?" selected":""}>${R}</option>`).join(`
523
+ `)){let l=d.trim().toLowerCase();d="",_r(l,t,n,r)}})}function _r(t,n,r,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else Mr(n);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Dr(n);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),r(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else Bt();break;default:break}}async function zt(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=et.resolve(t);if(!Ft.existsSync(o))return console.error(`${e.red}Error: File not found: ${e.bright}${o}${e.reset}`),!1;if(!o.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${o}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,u=async()=>{try{let{content:v,data:S}=await Pe(o,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:O.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),T=n.markdown?.syntaxHighlighting||O.markdown?.syntaxHighlighting,w=T?.defaultTheme||"github-dark",y=["github-dark"],k=T?.additionalThemes||[],E=[...new Set([...y,...k])].map((R)=>`<option value="${R}"${R===w?" selected":""}>${R}</option>`).join(`
524
524
  `);return l=`
525
525
  <!DOCTYPE html>
526
526
  <html lang="en">
@@ -688,7 +688,7 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
688
688
  ${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(`
689
689
  ${e.bright}\u2192 ${e.cyan}http://localhost:${m}/${e.reset}`),console.log(`
690
690
  ${e.yellow}Routes:${e.reset}`);let x=et.relative(process.cwd(),o);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${x}${e.reset}`),console.log(`
691
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(h.url.toString(),()=>{if(d)Ft.watch(et.dirname(o),{recursive:!0}).close();h.stop()}),n.native)await Ze(m,{title:et.basename(o,".md")});if(d){let v=et.dirname(o);console.log(`${e.blue}Watching ${e.bright}${v}${e.reset} for changes...`);let S=Ft.watch(v,{recursive:!0},async(T,w)=>{if(w&&w.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${w}${e.yellow} changed, reprocessing...${e.reset}`),await u()});process.on("SIGINT",()=>{S.close(),h.stop(),process.exit(0)})}return!0}function Ir(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Hr}=globalThis.Bun;import Be from"fs";import me from"path";class on{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let n=t??this.options.wsPort,r=20;for(let d=0;d<r;d++)try{if(this.server=Bun.serve({port:n,fetch(o,l){if(l.upgrade(o,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(o)=>{if(this.clients.add(o),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);o.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(o)=>{if(this.clients.delete(o),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(o,l)=>{let u=typeof l==="string"?l:l.toString();if(u==="ping")return;try{let f=JSON.parse(u);if(f.type==="console"&&Array.isArray(f.args)){let m=f.args.join(" "),x={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[f.level]??"\x1B[36m";console.log(`${x}[browser]${f.level!=="log"?` ${f.level}`:""}\x1B[0m ${m}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${n}`);return n}catch(o){if(o?.code==="EADDRINUSE"){n++;continue}throw o}throw Error(`Could not find an available port after ${r} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let n=JSON.stringify(t),r=0;for(let d of this.clients)try{if(d.readyState===1)d.send(n),r++}catch{this.clients.delete(d)}if(this.options.verbose&&r>0)console.log(`[HMR] Broadcast ${t.type} to ${r} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,n){this.broadcast({type:"css-update",path:t,content:n,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function jr(t,n={}){let{showOverlay:r=!0,reconnectInterval:d=1000,maxReconnectAttempts:o=10}=n;return`
691
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(h.url.toString(),()=>{if(d)Ft.watch(et.dirname(o),{recursive:!0}).close();h.stop()}),n.native)await Qe(m,{title:et.basename(o,".md")});if(d){let v=et.dirname(o);console.log(`${e.blue}Watching ${e.bright}${v}${e.reset} for changes...`);let S=Ft.watch(v,{recursive:!0},async(T,w)=>{if(w&&w.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${w}${e.yellow} changed, reprocessing...${e.reset}`),await u()});process.on("SIGINT",()=>{S.close(),h.stop(),process.exit(0)})}return!0}function Ir(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Hr}=globalThis.Bun;import Be from"fs";import ge from"path";class on{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let n=t??this.options.wsPort,r=20;for(let d=0;d<r;d++)try{if(this.server=Bun.serve({port:n,fetch(o,l){if(l.upgrade(o,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(o)=>{if(this.clients.add(o),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);o.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(o)=>{if(this.clients.delete(o),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(o,l)=>{let u=typeof l==="string"?l:l.toString();if(u==="ping")return;try{let f=JSON.parse(u);if(f.type==="console"&&Array.isArray(f.args)){let m=f.args.join(" "),x={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[f.level]??"\x1B[36m";console.log(`${x}[browser]${f.level!=="log"?` ${f.level}`:""}\x1B[0m ${m}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${n}`);return n}catch(o){if(o?.code==="EADDRINUSE"){n++;continue}throw o}throw Error(`Could not find an available port after ${r} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let n=JSON.stringify(t),r=0;for(let d of this.clients)try{if(d.readyState===1)d.send(n),r++}catch{this.clients.delete(d)}if(this.options.verbose&&r>0)console.log(`[HMR] Broadcast ${t.type} to ${r} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,n){this.broadcast({type:"css-update",path:t,content:n,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function jr(t,n={}){let{showOverlay:r=!0,reconnectInterval:d=1000,maxReconnectAttempts:o=10}=n;return`
692
692
  <script>
693
693
  (function() {
694
694
  // stx Hot Reload Client
@@ -887,10 +887,10 @@ else {
887
887
  };
888
888
  })();
889
889
  </script>
890
- `}function Ne(t,n,r={}){let d=jr(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function yt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function bt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var nt=null;function xt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import vt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${vt.relative(vt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await Cs(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let y=await fr(u,r);if(y){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:y,loader:"html"}}}let m=await _e(()=>Bun.file(u).text(),"",(y)=>{throw new Ar(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${y.message}`)});if(!m)throw new Ar(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=ce.time("script-extraction",()=>{let y=m,k=pe(m);if(k)y=k.content.trim();let M=m.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of M){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",L=C.match(/<script\b([^>]*)>/i),V=L?L[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=y.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:vt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await _e(()=>g(h,S,u),void 0,(y)=>{let k=new ee(`Script execution failed in ${u}: ${y.message}`,u,void 0,void 0,h.substring(0,100));if(z.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await ce.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:y}=await import("./chunk-6w3gv9d6.js"),k=y(v.join(`
890
+ `}function Ne(t,n,r={}){let d=jr(n,r),o=t.lastIndexOf("</body>");if(o!==-1)return t.slice(0,o)+d+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function gt(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function yt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function bt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var tt=null;function xt(t){if(!tt)tt=new on(t);return tt}function it(){if(tt)tt.stop(),tt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},d=new Set,o=r.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(r.webComponents?.enabled)try{let u=await Cs(r,d);if(l.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(r.cache&&r.cachePath){let y=await fr(u,r);if(y){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:y,loader:"html"}}}let m=await Ce(()=>Bun.file(u).text(),"",(y)=>{throw new Ar(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${y.message}`)});if(!m)throw new Ar(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=le.time("script-extraction",()=>{let y=m,k=fe(m);if(k)y=k.content.trim();let M=m.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of M){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",L=C.match(/<script\b([^>]*)>/i),V=L?L[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=y.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:o,builtComponents:l}};await Ce(()=>g(h,S,u),void 0,(y)=>{let k=new ee(`Script execution failed in ${u}: ${y.message}`,u,void 0,void 0,h.substring(0,100));if(z.log(k,{filePath:u,scriptContent:h}),r.debug)throw k});let w=await le.timeAsync("directive-processing",async()=>await i(x,S,u,r,f));if(v.length>0){let{interpolateScriptsInTemplate:y}=await import("./chunk-03t7tk2k.js"),k=y(v.join(`
891
891
  `),S),M=w.search(/<\/body>/i);if(M!==-1)w=w.slice(0,M)+k+`
892
892
  `+w.slice(M);else w+=`
893
- ${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await gr(u,w,f,r),r.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let m=f instanceof Error?f:new ee(`Plugin processing failed: ${String(f)}`,u);if(z.log(m,{filePath:u,buildConfig:t.config}),En.logDetailedError(m,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",m);let h=m,x=h.line||null,v=h.context||null;return{contents:r.debug||G()?`<!DOCTYPE html>
893
+ ${k}`}if(w=await xe(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await gr(u,w,f,r),r.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let m=f instanceof Error?f:new ee(`Plugin processing failed: ${String(f)}`,u);if(z.log(m,{filePath:u,buildConfig:t.config}),En.logDetailedError(m,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",m);let h=m,x=h.line||null,v=h.context||null;return{contents:r.debug||G()?`<!DOCTYPE html>
894
894
  <html lang="en">
895
895
  <head>
896
896
  <meta charset="UTF-8">
@@ -931,7 +931,7 @@ ${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await g
931
931
  <li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
932
932
  <li>Verify that all variables used in the template are properly defined</li>
933
933
  <li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
934
- <li>Run <code>stx debug ${p(vt.basename(u))}</code> for detailed analysis</li>
934
+ <li>Run <code>stx debug ${p(wt.basename(u))}</code> for detailed analysis</li>
935
935
  <li>Enable debug mode in your stx config for more detailed error messages</li>
936
936
  </ul>
937
937
  </div>
@@ -950,12 +950,12 @@ ${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await g
950
950
  <h1>Something went wrong</h1>
951
951
  <p>An internal error occurred. Please try again later.</p>
952
952
  </body>
953
- </html>`,loader:"html"}}})}};async function Ur(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=me.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return zt(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let m=c(process.cwd(),"output");Be.mkdirSync(m,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},L=await Bun.build({entrypoints:[f],outdir:m,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!L.success)return console.error(`${e.red}Build failed:${e.reset}`,L.logs),!1;let V=L.outputs.find((be)=>be.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=me.dirname(f);await dn(S);let T=r;try{if(T=await We(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let D=n.hmrPort||T+1;l=xt({wsPort:D,verbose:!1}),u=l.start(D)}let w={},y=null,k;try{let{loadStxConfig:D}=await import("./chunk-j3s5y2k5.js"),L=await D();if(k=n.stxOptions?.serverApi??L.serverApi,L?.apiRouter)y=L?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(L?.apiRoutes){w=L.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(L?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-dm10y06z.js"),be=L.broadcasting;await V(be);let le=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Ce=me.join(process.cwd(),"channels.ts");if(Be.existsSync(Ce))try{let re=await Y(Ce);console.log(`${e.blue}Loaded ${e.bright}${re} broadcast channel${re!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(re){console.warn(`${e.yellow}Failed to load channels.ts: ${re.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:M,isServerApiSource:E}=await import("./chunk-hfcagm39.js"),R=await M(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Hr({port:T,async fetch(D){return In(D,await(async()=>{let L=new URL(D.url);if([m,me.dirname(f),me.join(process.cwd(),"public")].some((re)=>E(me.join(re,L.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(y)try{let re=await y.handleRequest(D);if(re.status!==404)return re}catch{}if(w[L.pathname])try{return await w[L.pathname](D)}catch(re){return new Response(JSON.stringify({error:re.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(D);if(V)return V;if(L.pathname==="/")return(async()=>{let F=await b(h||"");if(o)F=Ne(F,u);if(n.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(n.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=me.join(m,L.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let re=Bun.file(Y),F=me.extname(Y).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await re.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":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(re,{headers:{"Content-Type":_}})}let be=me.dirname(f),le=me.join(be,L.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let re=Bun.file(le),F=me.extname(le).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await re.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":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(re,{headers:{"Content-Type":_}})}let Ce=me.join(process.cwd(),"public",L.pathname);if(Be.existsSync(Ce)&&Be.statSync(Ce).isFile()){let re=Bun.file(Ce),F=me.extname(Ce).toLowerCase(),_="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await re.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":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(re,{headers:{"Content-Type":_}})}return new Response("Not Found",{status:404})})())},error(D){return new Response(`<pre>${D}
953
+ </html>`,loader:"html"}}})}};async function Ur(t,n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return zt(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let m=c(process.cwd(),"output");Be.mkdirSync(m,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ce)=>({path:ce.path,external:!0}))}},L=await Bun.build({entrypoints:[f],outdir:m,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!L.success)return console.error(`${e.red}Build failed:${e.reset}`,L.logs),!1;let V=L.outputs.find((be)=>be.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=ge.dirname(f);await pn(S);let T=r;try{if(T=await We(r),T!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let D=n.hmrPort||T+1;l=xt({wsPort:D,verbose:!1}),u=l.start(D)}let w={},y=null,k;try{let{loadStxConfig:D}=await import("./chunk-dtxg2a6m.js"),L=await D();if(k=n.stxOptions?.serverApi??L.serverApi,L?.apiRouter)y=L?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(L?.apiRoutes){w=L.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(L?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-dm10y06z.js"),be=L.broadcasting;await V(be);let ce=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ce}/ws${e.reset}`);let Ee=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Ee))try{let re=await Y(Ee);console.log(`${e.blue}Loaded ${e.bright}${re} broadcast channel${re!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(re){console.warn(`${e.yellow}Failed to load channels.ts: ${re.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:M,isServerApiSource:E}=await import("./chunk-zd2c84ct.js"),R=await M(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Hr({port:T,async fetch(D){return In(D,await(async()=>{let L=new URL(D.url);if([m,ge.dirname(f),ge.join(process.cwd(),"public")].some((re)=>E(ge.join(re,L.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(y)try{let re=await y.handleRequest(D);if(re.status!==404)return re}catch{}if(w[L.pathname])try{return await w[L.pathname](D)}catch(re){return new Response(JSON.stringify({error:re.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(D);if(V)return V;if(L.pathname==="/")return(async()=>{let F=await b(h||"");if(o)F=Ne(F,u);if(n.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(n.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(m,L.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let re=Bun.file(Y),F=ge.extname(Y).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await re.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":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(re,{headers:{"Content-Type":_}})}let be=ge.dirname(f),ce=ge.join(be,L.pathname);if(Be.existsSync(ce)&&Be.statSync(ce).isFile()){let re=Bun.file(ce),F=ge.extname(ce).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await re.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":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(re,{headers:{"Content-Type":_}})}let Ee=ge.join(process.cwd(),"public",L.pathname);if(Be.existsSync(Ee)&&Be.statSync(Ee).isFile()){let re=Bun.file(Ee),F=ge.extname(Ee).toLowerCase(),_="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await re.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":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(re,{headers:{"Content-Type":_}})}return new Response("Not Found",{status:404})})())},error(D){return new Response(`<pre>${D}
954
954
  ${D.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
955
955
  ${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(`
956
956
  ${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
957
- ${e.yellow}Routes:${e.reset}`);let C=me.relative(process.cwd(),f);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${C}${e.reset}`),console.log(`
958
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(A.url.toString(),()=>{if(d)Be.watch(me.dirname(f),{recursive:!0}).close();A.stop()}),n.native){let D=await Bun.file(f).text(),L=gt(D);await Ze(T,{title:me.basename(f,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!L,sidebarConfig:L})}if(d){let D=me.dirname(f);console.log(`${e.blue}Watching ${e.bright}${D}${e.reset} for changes...`);let L=Be.watch(D,{recursive:!0},async(V,Y)=>{if(!Y||bt(Y))return;if(yt(Y)){console.log(`${e.yellow}File ${e.bright}${Y}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge();let be=await x();if(await cr(S),o&&l)if(be)l.reload(Y);else l.error("Build failed - check console for details")}else if(ht(Y)){if(console.log(`${e.cyan}CSS ${e.bright}${Y}${e.cyan} changed${e.reset}`),o&&l)l.updateCss(Y)}});process.on("SIGINT",()=>{if(L.close(),l)it();A.stop(),process.exit(0)})}return!0}var{serve:Br}=globalThis.Bun;import Xe from"fs";import $e from"path";var sn=`
957
+ ${e.yellow}Routes:${e.reset}`);let C=ge.relative(process.cwd(),f);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${C}${e.reset}`),console.log(`
958
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(A.url.toString(),()=>{if(d)Be.watch(ge.dirname(f),{recursive:!0}).close();A.stop()}),n.native){let D=await Bun.file(f).text(),L=mt(D);await Qe(T,{title:ge.basename(f,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!L,sidebarConfig:L})}if(d){let D=ge.dirname(f);console.log(`${e.blue}Watching ${e.bright}${D}${e.reset} for changes...`);let L=Be.watch(D,{recursive:!0},async(V,Y)=>{if(!Y||bt(Y))return;if(yt(Y)){console.log(`${e.yellow}File ${e.bright}${Y}${e.yellow} changed, rebuilding...${e.reset}`),Ze.clear(),me();let be=await x();if(await cr(S),o&&l)if(be)l.reload(Y);else l.error("Build failed - check console for details")}else if(gt(Y)){if(console.log(`${e.cyan}CSS ${e.bright}${Y}${e.cyan} changed${e.reset}`),o&&l)l.updateCss(Y)}});process.on("SIGINT",()=>{if(L.close(),l)it();A.stop(),process.exit(0)})}return!0}var{serve:Br}=globalThis.Bun;import qe from"fs";import Re from"path";var sn=`
959
959
  <script data-stx-helpers>
960
960
  (function() {
961
961
  'use strict'
@@ -1266,14 +1266,14 @@ else {
1266
1266
 
1267
1267
  })()
1268
1268
  </script>
1269
- `;function cn(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((d)=>d.split($e.sep)),r=[];for(let d=0;d<n[0].length;d++){let o=n[0][d];if(n.every((l)=>l[d]===o))r.push(o);else break}return r.join($e.sep)}async function Wr(t,n={}){let r=n.port||3000,d=n.watch!==!1;for(let w of t){let y=$e.resolve(w);if(!Xe.existsSync(y))return console.error(`${e.red}Error: File not found: ${e.bright}${y}${e.reset}`),!1;if(!y.endsWith(".stx")&&!y.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${y}${e.reset}. Only .stx and .md files are supported.`),!1}let o=c(process.cwd(),"output");Xe.mkdirSync(o,{recursive:!0});let l=cn(t.map((w)=>$e.dirname($e.resolve(w))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let u={},f=[],m=async()=>{try{for(let w of t){let y=$e.resolve(w);if(y.endsWith(".md"))try{let{content:M,data:E}=await Ae(y,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:O.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=n.markdown?.syntaxHighlighting||O.markdown?.syntaxHighlighting,A=R?.defaultTheme||"github-dark",C=["github-dark"],D=R?.additionalThemes||[],V=[...new Set([...C,...D])].map((Ce)=>`<option value="${Ce}"${Ce===A?" selected":""}>${Ce}</option>`).join(`
1269
+ `;function cn(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((d)=>d.split(Re.sep)),r=[];for(let d=0;d<n[0].length;d++){let o=n[0][d];if(n.every((l)=>l[d]===o))r.push(o);else break}return r.join(Re.sep)}async function Wr(t,n={}){let r=n.port||3000,d=n.watch!==!1;for(let w of t){let y=Re.resolve(w);if(!qe.existsSync(y))return console.error(`${e.red}Error: File not found: ${e.bright}${y}${e.reset}`),!1;if(!y.endsWith(".stx")&&!y.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${y}${e.reset}. Only .stx and .md files are supported.`),!1}let o=c(process.cwd(),"output");qe.mkdirSync(o,{recursive:!0});let l=cn(t.map((w)=>Re.dirname(Re.resolve(w))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let u={},f=[],m=async()=>{try{for(let w of t){let y=Re.resolve(w);if(y.endsWith(".md"))try{let{content:M,data:E}=await Pe(y,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:O.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=n.markdown?.syntaxHighlighting||O.markdown?.syntaxHighlighting,A=R?.defaultTheme||"github-dark",C=["github-dark"],D=R?.additionalThemes||[],V=[...new Set([...C,...D])].map((Ee)=>`<option value="${Ee}"${Ee===A?" selected":""}>${Ee}</option>`).join(`
1270
1270
  `),Y=`
1271
1271
  <!DOCTYPE html>
1272
1272
  <html lang="en">
1273
1273
  <head>
1274
1274
  <meta charset="UTF-8">
1275
1275
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1276
- <title>${an(E.title||$e.basename(y))}</title>
1276
+ <title>${an(E.title||Re.basename(y))}</title>
1277
1277
  <!-- Syntax highlighting styles -->
1278
1278
  <style id="syntax-theme">
1279
1279
  :root {
@@ -1429,25 +1429,25 @@ else {
1429
1429
  </script>
1430
1430
  </body>
1431
1431
  </html>
1432
- `,le=`/${$e.relative(l,y).replace(/\.md$/,"")}`;if(le.endsWith("/index"))le=le.slice(0,-6)||"/";u[le||"/"]={filePath:y,content:Y,fileType:"md"}}catch(M){console.error(`${e.red}Error processing Markdown file ${e.bright}${w}${e.reset}:`,M);continue}else{let M={name:"public-assets",setup(C){C.onResolve({filter:/^\/(images|fonts|assets|public)\//},(D)=>({path:D.path,external:!0}))}},E;try{let C=await Bun.build({entrypoints:[y],outdir:o,plugins:[M,rt],define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!C.success){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:`,Re(C.logs,y));continue}let D=C.outputs.find((L)=>L.path.endsWith(".html"));if(!D){console.error(`${e.red}No HTML output found for ${e.bright}${w}${e.reset}`);continue}E=await Bun.file(D.path).text()}catch(C){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:
1433
- ${Re(C,y)}`);continue}let A=`/${$e.relative(l,y).replace(/\.stx$/,"")}`;if(A.endsWith("/index"))A=A.slice(0,-6)||"/";if(A.includes("[")){let{regex:C,params:D}=Ps(A,{page:!0});f.push({pattern:C,paramNames:D,filePath:y,routeTemplate:A,fileType:"stx"}),u[A]={filePath:y,content:E,fileType:"stx"}}else u[A||"/"]={filePath:y,content:E,fileType:"stx"}}}if(Object.keys(u).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(w){return console.error(`${e.red}Error processing files:${e.reset}`,Re(w)),!1}};if(!await m())return!1;let x=r;try{if(x=await We(r),x!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${x} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${x}/${e.reset}...`);let v=Br({port:x,async fetch(w){let y=new URL(w.url),k=$e.join(process.cwd(),"public",y.pathname);if(Xe.existsSync(k)&&Xe.statSync(k).isFile()){let R=Bun.file(k),A=$e.extname(k).toLowerCase(),C="application/octet-stream";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}let M=u[y.pathname];if(!M&&!y.pathname.endsWith("/"))M=u[`${y.pathname}/`];if(!M)for(let R of f){let A=y.pathname.match(R.pattern);if(A){let C=u[R.routeTemplate];if(C){let D={};for(let Y=0;Y<R.paramNames.length;Y++)D[R.paramNames[Y]]=decodeURIComponent(A[Y+1]);let L=C.content,V=`<script>window.__routeParams = ${JSON.stringify(D)};</script>`;if(L.includes("</head>"))L=L.replace("</head>",`${V}
1432
+ `,ce=`/${Re.relative(l,y).replace(/\.md$/,"")}`;if(ce.endsWith("/index"))ce=ce.slice(0,-6)||"/";u[ce||"/"]={filePath:y,content:Y,fileType:"md"}}catch(M){console.error(`${e.red}Error processing Markdown file ${e.bright}${w}${e.reset}:`,M);continue}else{let M={name:"public-assets",setup(C){C.onResolve({filter:/^\/(images|fonts|assets|public)\//},(D)=>({path:D.path,external:!0}))}},E;try{let C=await Bun.build({entrypoints:[y],outdir:o,plugins:[M,rt],define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!C.success){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:`,Ae(C.logs,y));continue}let D=C.outputs.find((L)=>L.path.endsWith(".html"));if(!D){console.error(`${e.red}No HTML output found for ${e.bright}${w}${e.reset}`);continue}E=await Bun.file(D.path).text()}catch(C){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:
1433
+ ${Ae(C,y)}`);continue}let A=`/${Re.relative(l,y).replace(/\.stx$/,"")}`;if(A.endsWith("/index"))A=A.slice(0,-6)||"/";if(A.includes("[")){let{regex:C,params:D}=Ps(A,{page:!0});f.push({pattern:C,paramNames:D,filePath:y,routeTemplate:A,fileType:"stx"}),u[A]={filePath:y,content:E,fileType:"stx"}}else u[A||"/"]={filePath:y,content:E,fileType:"stx"}}}if(Object.keys(u).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(w){return console.error(`${e.red}Error processing files:${e.reset}`,Ae(w)),!1}};if(!await m())return!1;let x=r;try{if(x=await We(r),x!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${x} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${x}/${e.reset}...`);let v=Br({port:x,async fetch(w){let y=new URL(w.url),k=Re.join(process.cwd(),"public",y.pathname);if(qe.existsSync(k)&&qe.statSync(k).isFile()){let R=Bun.file(k),A=Re.extname(k).toLowerCase(),C="application/octet-stream";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}let M=u[y.pathname];if(!M&&!y.pathname.endsWith("/"))M=u[`${y.pathname}/`];if(!M)for(let R of f){let A=y.pathname.match(R.pattern);if(A){let C=u[R.routeTemplate];if(C){let D={};for(let Y=0;Y<R.paramNames.length;Y++)D[R.paramNames[Y]]=decodeURIComponent(A[Y+1]);let L=C.content,V=`<script>window.__routeParams = ${JSON.stringify(D)};</script>`;if(L.includes("</head>"))L=L.replace("</head>",`${V}
1434
1434
  </head>`);else L=V+L;M={...C,content:L}}break}}if(M)return b(M.content).then((R)=>{if(R.includes("</head>"))R=R.replace("</head>",`${sn}
1435
- </head>`);return new Response(R,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let E=$e.join(o,y.pathname);if(Xe.existsSync(E)&&Xe.statSync(E).isFile()){let R=Bun.file(E),A=$e.extname(E).toLowerCase(),C="text/plain";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}if(y.pathname!=="/"&&u["/"]){let R=Ee(w);return b(u["/"].content).then((A)=>{if(R){let C=A.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(C){let D=A.match(/<title[^>]*>([\s\S]*?)<\/title>/i),L=D?D[1]:"",V=`<!DOCTYPE html><html><head><title>${an(L)}</title></head><body><main>${C[1]}</main></body></html>`;return new Response(V,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...j(),"Cache-Control":mt,Pragma:"no-cache",Expires:"0"}})}}return new Response(A,{headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
1435
+ </head>`);return new Response(R,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let E=Re.join(o,y.pathname);if(qe.existsSync(E)&&qe.statSync(E).isFile()){let R=Bun.file(E),A=Re.extname(E).toLowerCase(),C="text/plain";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}if(y.pathname!=="/"&&u["/"]){let R=Te(w);return b(u["/"].content).then((A)=>{if(R){let C=A.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(C){let D=A.match(/<title[^>]*>([\s\S]*?)<\/title>/i),L=D?D[1]:"",V=`<!DOCTYPE html><html><head><title>${an(L)}</title></head><body><main>${C[1]}</main></body></html>`;return new Response(V,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...j(),"Cache-Control":ht,Pragma:"no-cache",Expires:"0"}})}}return new Response(A,{headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
1436
1436
  ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1437
1437
  ${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(`
1438
1438
  ${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
1439
- ${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[y])=>w.localeCompare(y)).map(([w,y])=>({route:w==="/"?"/":w,filePath:$e.relative(process.cwd(),y.filePath),fileType:y.fileType}));for(let w of f){let y=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:y,filePath:$e.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,y)=>w.route.localeCompare(y.route)),T.forEach((w,y)=>{let M=y===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${M}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
1440
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge(),await m()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Fr}=globalThis.Bun;import fe from"fs";import ne from"path";async function ln(t){try{return yn(await Bun.file(t).text())}catch{return}}function Nt(t){let n=Bun.file(t),r=ne.extname(t).toLowerCase(),d={".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(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function qr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ne.resolve(t),{loadStxConfig:m}=await import("./chunk-j3s5y2k5.js"),h=await m(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-hfcagm39.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?ne.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=ne.join(w,y);if(!fe.existsSync(k)&&!h._layerPageDirs?.some((P)=>fe.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${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 ${y}/index.stx for the homepage.${e.reset}`),!1;let M=X(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(fe.existsSync(P)){let N=X(ne.dirname(P),{pagesDir:ne.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await ga(f,n.stxOptions?.shell),D){if(C=await wo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${ne.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Ct(),await Tt(f);let L=Et();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-j3s5y2k5.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-dm10y06z.js"),q=I.broadcasting;await N(q);let Pe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Pe}/ws${e.reset}`);let xe=ne.join(process.cwd(),"channels.ts");if(fe.existsSync(xe))try{let U=await Q(xe);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");fe.mkdirSync(be,{recursive:!0});let le=new Map,Ce=new Set,re=async(P)=>{let I=Is(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Pe,injectRouterScript:xe}=await import("./chunk-j3s5y2k5.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-8gsd2n0j.js"),K=await Pe(f),Ue=(ie)=>{if(!ie)return ie;if(ne.isAbsolute(ie))return ie;return ne.resolve(f,ie)},ae={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ae.debug=!0;ae.partialsDir=Ue(ae.partialsDir),ae.componentsDir=Ue(ae.componentsDir),ae.layoutsDir=Ue(ae.layoutsDir),ae.storesDir=Ue(ae.storesDir||"stores"),ae.cachePath=Ue(ae.cachePath)??c(f,"cache");let H=!I&&!n.profile,oe=ae.cache!==!1;if(oe&&H){let ie=de.get(P.filePath);if(ie)try{if((await fe.promises.stat(P.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!fe.existsSync(Se)){He=!1;break}if((await fe.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=qe(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await ln(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ae);if(Ie){let je=Ie;if(C)je=qe(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=oe?await W(P.filePath):await Bun.file(P.filePath).text(),se=yn(Z),{classifyAllScripts:ue}=await import("./chunk-j3s5y2k5.js"),B=ue(Z),Le=B.server.map((ie)=>ie.content),De=Z;for(let ie of B.server)De=De.replace(ie.fullTag,"");let te={__filename:P.filePath,__dirname:ne.dirname(P.filePath),__stx_options:ae,params:I??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,te,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Oe=new Set,he;if(n.profile){let ie=performance.now();he=await N(De,te,P.filePath,ae,Oe);let Ie=performance.now()-ie,je=ne.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(De,te,P.filePath,ae,Oe);if(!C)he=await xe(he,{router:ae.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-6w3gv9d6.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,te)}</script>`})}if(C)he=qe(he,{preserveHead:!0});if(oe&&H)await J(P.filePath,he,Oe,ae);let{extractStreamBoundaries:ct}=await import("./chunk-ggthncvg.js"),Qe=ct(te),ot=te.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=te.streamBoundaries||{},Ie={...ae,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...te,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Ce.add(P.pattern);else Qe=void 0;let Vt=Mt(te),qt=Dt(te);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??se,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),I=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Pe=N.slice(q,q+Fe),xe=await Promise.all(Pe.map((U)=>_(U)));for(let U of xe)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Pe=Q.slice(q,q+Fe),xe=await Promise.all(Pe.map(({route:U})=>_(U)));for(let U of xe)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await dn(f);let Ge=r;try{if(Ge=await We(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Ge+1;l=xt({wsPort:P,verbose:!1}),u=l.start(P)}let kt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).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 Pt=Fr({port:Ge,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===jo&&N?.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:Bo(N,ls()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=ne.join(f,Q,I.pathname),Pe=ne.join(f,I.pathname),xe=ne.join(be,I.pathname);if([q,Pe,xe].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([fe.promises.stat(q).catch(()=>null),fe.promises.stat(Pe).catch(()=>null),fe.promises.stat(xe).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return Nt(q);if(J?.isFile()&&!v(Pe,f,S))return Nt(Pe);if(W?.isFile()&&!v(xe,f,S))return Nt(xe);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let oe=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(oe,{},ne.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(oe){return new Response(`<div class="stx-async-error">${oe.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-33yeb861.js"),oe=await H(P,{publicDir:ne.join(f,Q),cacheDir:c(f,"cache","img")});if(oe)return oe}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=hr(I.pathname,M);if(K){let H=le.get(K.route.pattern),oe=Ce.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||oe){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!oe)le.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},ue=(K.route.filePath?wt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:K.params})){let De=await re(404);if(De){let te=De;if(te=await b(te,f),o)te=Ne(te,u);return new Response(te,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=$t(I.pathname,K.params,ue,I.search),De=Rt(Le,null,P,{isServer:!0}),te=await At(ue.middleware,De);if(te.redirect){let Oe=te.redirect.path,he=te.redirect.options.redirectCode||302,ct=new Headers(te.responseHeaders);return ct.set("Location",Oe),new Response(null,{status:he,headers:ct})}if(te.abort){let{statusCode:Oe,message:he}=te.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Oe}</title></head><body><h1>Error ${Oe}</h1><p>${he}</p></body></html>`,{status:Oe,headers:{"Content-Type":"text/html"}})}if(Object.keys(te.state).length>0){let Oe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(te.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${Oe}</head>`)}}let B=H.content;if(C&&ma(P)&&Ke(B,h?.router?.container||"main")){let Le=tt(B),De=we(B),te=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Oe=te?Jt(te[1].trim()):"";if(Object.keys(K.params).length>0)B=kt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=Te(B,he,!0),new Response(B,{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",...Oe&&{"X-STX-Title":encodeURIComponent(Oe)},[uc]:ls(),...j(),"Cache-Control":mt}})}if(C)B=Jr(C,B);if(Object.keys(K.params).length>0)B=kt(B,K.params);if(B=await b(B,f),o)B=Ne(B,u);if(n.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;if(n.titlebarHidden)if(B.includes("<head>"))B=B.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 B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-ggthncvg.js");return De(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),oe=hr(I.pathname,H);if(oe){let Z=A.get(oe.route.pattern);if(!Z||oe.route.isDynamic){let se=await _(oe.route,oe.params);if(se){if(Z=se,!oe.route.isDynamic)A.set(oe.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=Jr(C,se);if(Object.keys(oe.params).length>0)se=kt(se,oe.params);if(se=await b(se,f),o)se=Ne(se,u);return new Response(se,{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 E)if(Z!=="/"&&I.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await _(ue.route);if(B)se=B,A.set(ue.route.pattern,B)}}if(se){let ue=se.content;if(C)ue=Jr(C,ue);if(ue=await b(ue,f),o)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(_t(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.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 H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ae=await re(404);if(ae){let H=ae;if(H=await b(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await re(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1439
+ ${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[y])=>w.localeCompare(y)).map(([w,y])=>({route:w==="/"?"/":w,filePath:Re.relative(process.cwd(),y.filePath),fileType:y.fileType}));for(let w of f){let y=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:y,filePath:Re.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,y)=>w.route.localeCompare(y.route)),T.forEach((w,y)=>{let M=y===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${M}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
1440
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)qe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=qe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ze.clear(),me(),await m()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Fr}=globalThis.Bun;import ue from"fs";import ne from"path";async function ln(t){try{return yn(await Bun.file(t).text())}catch{return}}function Nt(t){let n=Bun.file(t),r=ne.extname(t).toLowerCase(),d={".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(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function qr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ne.resolve(t),{loadStxConfig:m}=await import("./chunk-dtxg2a6m.js"),h=await m(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-zd2c84ct.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?ne.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=ne.join(w,y);if(!ue.existsSync(k)&&!h._layerPageDirs?.some((P)=>ue.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${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 ${y}/index.stx for the homepage.${e.reset}`),!1;let M=X(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(ue.existsSync(P)){let N=X(ne.dirname(P),{pagesDir:ne.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await ga(f,n.stxOptions?.shell),D){if(C=await wo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${ne.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Et(),await $t(f);let L=Tt();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-dtxg2a6m.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-dm10y06z.js"),q=I.broadcasting;await N(q);let Oe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let we=ne.join(process.cwd(),"channels.ts");if(ue.existsSync(we))try{let U=await Q(we);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");ue.mkdirSync(be,{recursive:!0});let ce=new Map,Ee=new Set,re=async(P)=>{let I=Is(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Oe,injectRouterScript:we}=await import("./chunk-dtxg2a6m.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-fk7wk568.js"),K=await Oe(f),Ue=(ie)=>{if(!ie)return ie;if(ne.isAbsolute(ie))return ie;return ne.resolve(f,ie)},ae={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ae.debug=!0;ae.partialsDir=Ue(ae.partialsDir),ae.componentsDir=Ue(ae.componentsDir),ae.layoutsDir=Ue(ae.layoutsDir),ae.storesDir=Ue(ae.storesDir||"stores"),ae.cachePath=Ue(ae.cachePath)??c(f,"cache");let H=!I&&!n.profile,oe=ae.cache!==!1;if(oe&&H){let ie=de.get(P.filePath);if(ie)try{if((await ue.promises.stat(P.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!ue.existsSync(Se)){He=!1;break}if((await ue.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=Ke(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await ln(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ae);if(Ie){let je=Ie;if(C)je=Ke(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=oe?await W(P.filePath):await Bun.file(P.filePath).text(),se=yn(Z),{classifyAllScripts:pe}=await import("./chunk-dtxg2a6m.js"),B=pe(Z),Le=B.server.map((ie)=>ie.content),Me=Z;for(let ie of B.server)Me=Me.replace(ie.fullTag,"");let te={__filename:P.filePath,__dirname:ne.dirname(P.filePath),__stx_options:ae,params:I??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,te,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,te,P.filePath,ae,De);let Ie=performance.now()-ie,je=ne.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,te,P.filePath,ae,De);if(!C)he=await we(he,{router:ae.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-03t7tk2k.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,te)}</script>`})}if(C)he=Ke(he,{preserveHead:!0});if(oe&&H)await J(P.filePath,he,De,ae);let{extractStreamBoundaries:ct}=await import("./chunk-js7nmw8v.js"),Ye=ct(te),ot=te.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=te.streamBoundaries||{},Ie={...ae,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...te,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Ye=[...(Ye||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Ye&&Ye.length>0)Ee.add(P.pattern);else Ye=void 0;let Vt=Dt(te),qt=Lt(te);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??se,headers:qt,boundaries:Ye}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(ce.keys()),I=new Set(A.keys());ce.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Oe=N.slice(q,q+Fe),we=await Promise.all(Oe.map((U)=>_(U)));for(let U of we)if(U)ce.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Oe=Q.slice(q,q+Fe),we=await Promise.all(Oe.map(({route:U})=>_(U)));for(let U of we)if(U)A.set(U.route.pattern,U)}return ce.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await pn(f);let Xe=r;try{if(Xe=await We(r),Xe!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Xe+1;l=xt({wsPort:P,verbose:!1}),u=l.start(P)}let kt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).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 Ot=Fr({port:Xe,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===jo&&N?.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:Bo(N,ls()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=ne.join(f,Q,I.pathname),Oe=ne.join(f,I.pathname),we=ne.join(be,I.pathname);if([q,Oe,we].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([ue.promises.stat(q).catch(()=>null),ue.promises.stat(Oe).catch(()=>null),ue.promises.stat(we).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return Nt(q);if(J?.isFile()&&!v(Oe,f,S))return Nt(Oe);if(W?.isFile()&&!v(we,f,S))return Nt(we);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let oe=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(oe,{},ne.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(oe){return new Response(`<div class="stx-async-error">${oe.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-nstcwcpj.js"),oe=await H(P,{publicDir:ne.join(f,Q),cacheDir:c(f,"cache","img")});if(oe)return oe}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=hr(I.pathname,M);if(K){let H=ce.get(K.route.pattern),oe=Ee.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||oe){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!oe)ce.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},pe=(K.route.filePath?vt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(pe.validate){if(!await pe.validate({params:K.params})){let Me=await re(404);if(Me){let te=Me;if(te=await b(te,f),o)te=Ne(te,u);return new Response(te,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(pe.middleware){let Le=Rt(I.pathname,K.params,pe,I.search),Me=At(Le,null,P,{isServer:!0}),te=await Pt(pe.middleware,Me);if(te.redirect){let De=te.redirect.path,he=te.redirect.options.redirectCode||302,ct=new Headers(te.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(te.abort){let{statusCode:De,message:he}=te.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(te.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(te.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let B=H.content;if(C&&ma(P)&&Ge(B,h?.router?.container||"main")){let Le=nt(B),Me=ve(B),te=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=te?Yt(te[1].trim()):"";if(Object.keys(K.params).length>0)B=kt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=$e(B,he,!0),new Response(B,{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":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[uc]:ls(),...j(),"Cache-Control":ht}})}if(C)B=Jr(C,B);if(Object.keys(K.params).length>0)B=kt(B,K.params);if(B=await b(B,f),o)B=Ne(B,u);if(n.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;if(n.titlebarHidden)if(B.includes("<head>"))B=B.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 B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-js7nmw8v.js");return Me(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),oe=hr(I.pathname,H);if(oe){let Z=A.get(oe.route.pattern);if(!Z||oe.route.isDynamic){let se=await _(oe.route,oe.params);if(se){if(Z=se,!oe.route.isDynamic)A.set(oe.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=Jr(C,se);if(Object.keys(oe.params).length>0)se=kt(se,oe.params);if(se=await b(se,f),o)se=Ne(se,u);return new Response(se,{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 E)if(Z!=="/"&&I.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let pe=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(pe){let B=await _(pe.route);if(B)se=B,A.set(pe.route.pattern,B)}}if(se){let pe=se.content;if(C)pe=Jr(C,pe);if(pe=await b(pe,f),o)pe=Ne(pe,u);return new Response(pe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ct(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=ce.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.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 H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ae=await re(404);if(ae){let H=ae;if(H=await b(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await re(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
1441
1441
  ${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
1442
1442
  ${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(`
1443
- ${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),o)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
1444
- ${e.yellow}Routes:${e.reset}`);let Ot=[...Os(M,f)];for(let{route:P}of R)Ot.push(`${P.pattern}`);if(Ot.forEach((P,I)=>{let Q=I===Ot.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
1445
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Pt.url.toString(),()=>{if(l)it();Pt.stop()}),n.native){let P,I=ne.join(k,"index.stx");if(fe.existsSync(I)){let Q=await Bun.file(I).text();P=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||ne.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),I=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>ne.dirname(J))??[]].filter((J)=>fe.existsSync(J)).map((J)=>fe.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!fe.existsSync(W))continue;let de=fe.realpathSync(W);if(![...U].some((K)=>de===K||de.startsWith(`${K}${ne.sep}`)))U.add(de)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&fe.existsSync(J))N.set(J,fe.watch(J,{recursive:!0},(W,de)=>{Pe(J,W,de).catch((K)=>console.error("[stx] Layer rebuild failed:",K))}))},q=Promise.resolve(),Pe=(U,J,W)=>(q=q.catch(()=>{}).then(()=>xe(U,J,W)),q),xe=async(U,J,W)=>{if(!W||bt(W))return;if(yt(W)){if(h._layerGraph){let de=await m(f);Object.assign(h,de),M.splice(0,M.length,...X(w,{pagesDir:y,pagesDirs:de._layerPageDirs?[k,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(I(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-8gsd2n0j.js");de(ne.resolve(U,W)),K.delete(ne.resolve(U,W))}catch{}if(D&&W){if(ne.resolve(U,W)===D||ne.basename(D)===W){let K=await wo(D,n.stxOptions||{});if(K)C=K}}if(await ze(),await cr(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-8gsd2n0j.js");de(ne.resolve(U,W)),K.delete(ne.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();Pt.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function zr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],m=u[2]||u[3]||u[4];if(!m)continue;let h={name:m},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
1443
+ ${e.bright}\u2192 ${e.cyan}http://localhost:${Xe}/${e.reset}`),o)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
1444
+ ${e.yellow}Routes:${e.reset}`);let Mt=[...Os(M,f)];for(let{route:P}of R)Mt.push(`${P.pattern}`);if(Mt.forEach((P,I)=>{let Q=I===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
1445
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.url.toString(),()=>{if(l)it();Ot.stop()}),n.native){let P,I=ne.join(k,"index.stx");if(ue.existsSync(I)){let Q=await Bun.file(I).text();P=mt(Q)}let N=h?.app?.window??{};await Qe(Xe,{title:h?.app?.head?.title||ne.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),I=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>ne.dirname(J))??[]].filter((J)=>ue.existsSync(J)).map((J)=>ue.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!ue.existsSync(W))continue;let de=ue.realpathSync(W);if(![...U].some((K)=>de===K||de.startsWith(`${K}${ne.sep}`)))U.add(de)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&ue.existsSync(J))N.set(J,ue.watch(J,{recursive:!0},(W,de)=>{Oe(J,W,de).catch((K)=>console.error("[stx] Layer rebuild failed:",K))}))},q=Promise.resolve(),Oe=(U,J,W)=>(q=q.catch(()=>{}).then(()=>we(U,J,W)),q),we=async(U,J,W)=>{if(!W||bt(W))return;if(yt(W)){if(h._layerGraph){let de=await m(f);Object.assign(h,de),M.splice(0,M.length,...X(w,{pagesDir:y,pagesDirs:de._layerPageDirs?[k,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),o&&l)l.reload(W)}else if(I(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ze.clear(),me();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-fk7wk568.js");de(ne.resolve(U,W)),K.delete(ne.resolve(U,W))}catch{}if(D&&W){if(ne.resolve(U,W)===D||ne.basename(D)===W){let K=await wo(D,n.stxOptions||{});if(K)C=K}}if(await ze(),await cr(f),o&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ze.clear(),me();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-fk7wk568.js");de(ne.resolve(U,W)),K.delete(ne.resolve(U,W))}catch{}if(await ze(),o&&l)l.reload(W)}}else if(gt(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),o&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();Ot.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function zr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let d=r[1],o=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],m=u[2]||u[3]||u[4];if(!m)continue;let h={name:m},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
1446
1446
  `).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),o.push(h)}if(o.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)o.push({name:v})}}}return o}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Nr(t){try{let n=await Bun.file(t).text(),r=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
1447
1447
  `).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Vr(t,n=!1,r){let d=at.basename(t,".stx"),o=await zr(t),l=await Nr(t),u="";if(n&&r)u=`<${r}></${r}>`;else{let f=o.map((m)=>{if(m.type==="boolean")return`:${m.name}="true"`;return`${m.name}="value"`}).join(`
1448
1448
  `);u=`<${d}
1449
1449
  ${f}
1450
- />`}return{name:d,path:t,description:l,props:o,example:u,isWebComponent:n,tag:r}}async function pn(t){try{if(!await s(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){let o=at.join(t,d.name);if(d.isDirectory()){let l=await pn(o);r.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))r.push(o)}return r}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Kr(t,n){try{if(!await s(t))return[];let r=await pn(t),d=[],o=new Map;if(n?.components?.length)for(let l of n.components)o.set(l.file,l);for(let l of r){let u=o.get(l),f=!!u,m=u?.tag,h=await Vr(l,f,m);d.push(h)}return d}catch(r){return console.error("Error generating component docs:",r),[]}}async function Xr(t){try{if(!await s(t))return[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let o=at.join(t,d.name),l=await Bun.file(o).text(),u=at.basename(o,".stx"),f=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),m=f?f[1].split(`
1450
+ />`}return{name:d,path:t,description:l,props:o,example:u,isWebComponent:n,tag:r}}async function dn(t){try{if(!await s(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){let o=at.join(t,d.name);if(d.isDirectory()){let l=await dn(o);r.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))r.push(o)}return r}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Kr(t,n){try{if(!await s(t))return[];let r=await dn(t),d=[],o=new Map;if(n?.components?.length)for(let l of n.components)o.set(l.file,l);for(let l of r){let u=o.get(l),f=!!u,m=u?.tag,h=await Vr(l,f,m);d.push(h)}return d}catch(r){return console.error("Error generating component docs:",r),[]}}async function Xr(t){try{if(!await s(t))return[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),r=[];for(let d of n){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let o=at.join(t,d.name),l=await Bun.file(o).text(),u=at.basename(o,".stx"),f=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),m=f?f[1].split(`
1451
1451
  `).map((y)=>y.trim().replace(/^\*\s*/,"")).join(" ").trim():"",h=/@component\(\s*['"]([^'"]+)['"]/g,x=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,v=new Set,S;while((S=h.exec(l))!==null)v.add(S[1]);while((S=x.exec(l))!==null)if(S[1]&&S[1]!=="slot")v.add(S[1]);let T=/@([a-z]+)(?:\s*\(|\s+|$)/g,w=new Set;while((S=T.exec(l))!==null)w.add(S[1]);r.push({name:u,path:o,description:m,components:[...v],directives:[...w]})}return r}catch(n){return console.error("Error generating template docs:",n),[]}}async function Gr(t=[]){try{let n=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
1452
1452
  <p>Welcome, {{ user.name }}!</p>
1453
1453
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
@@ -2040,5 +2040,5 @@ const features = [
2040
2040
  })();
2041
2041
  </script>
2042
2042
  </body>
2043
- </html>`}var ia="f9c3713";function Nl(t){return t}function Ml(t){return t}function ea(t,n){let r=[],d=`${n}=`;for(let o=0;o<t.length;o++){let l=t[o];if(l.startsWith(d)){let u=l.slice(d.length);if(u)r.push(u);continue}if(l===n){let u=t[o+1];if(u!==void 0&&!u.startsWith("-"))r.push(u),o++}}return r}import Me from"fs";import ye from"path";function $n(t){try{return Me.statSync(t).mtimeMs}catch{return null}}function St(t,n){let r=Math.max(0,Math.round((n-t)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function Ti(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function Cn(t,n="stx"){let r=ye.resolve(t);for(let d=0;d<10;d++){let o=ye.join(r,"pantry","@stacksjs",n);if(Me.existsSync(o))return o;let l=ye.dirname(r);if(l===r)break;r=l}return null}var Rn=["@stacksjs/stx","bun-plugin-stx"];function $i(t){try{let n=Me.readFileSync(ye.join(t,"package.json"),"utf8"),r=JSON.parse(n)?.version;return typeof r==="string"?r:null}catch{return null}}function Ci(t,n=6){let r=ye.resolve(t),d=[],o=new Set;function l(f,m){if(m>n)return;let h;try{h=Me.realpathSync(f)}catch{return}if(o.has(h))return;o.add(h);for(let v of Rn){let S=ye.join(f,v),T=$i(S);if(T!==null)d.push({name:v,version:T,dir:ye.relative(r,S)||S,nested:m>0})}let x;try{x=Me.readdirSync(f,{withFileTypes:!0})}catch{return}for(let v of x){if(!v.isDirectory()&&!v.isSymbolicLink())continue;if(v.name===".bin"||v.name===".cache")continue;let S=ye.join(f,v.name);if(v.name.startsWith("@")){let w;try{w=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let y of w){let k=ye.join(S,y.name,"node_modules");if(Me.existsSync(k))l(k,m+1)}continue}let T=ye.join(S,"node_modules");if(Me.existsSync(T))l(T,m+1)}}let u=ye.join(r,"node_modules");if(Me.existsSync(u))l(u,0);return d}function Ri(t){let n=[];for(let r of Rn){let d=t.filter((u)=>u.name===r);if(d.length<=1)continue;let o=[...new Set(d.map((u)=>u.version))],l=d.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(o.length===1){n.push({name:`${r} copies`,status:"info",detail:`${d.length} copies, all ${o[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${r} copies disagree`,status:"error",detail:`${o.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${r}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${r}/package.json' -exec grep -H '"version"' {} +`})}return n}async function po(t={}){let n=t.cwd?ye.resolve(t.cwd):process.cwd(),r=t.resolve??Ti,d=Date.now(),o=[],l=r("@stacksjs/stx",n);o.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let u=r("bun-plugin-stx",n);if(u)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let m of Ri(Ci(n)))o.push(m);let f=Cn(n,"stx");if(!f)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let m=ye.join(f,"src/signals.ts"),h=[ye.join(f,"dist/index.js"),ye.join(f,"dist/signals.js")].find((w)=>Me.existsSync(w))||null,x=$n(m),v=h?$n(h):null;if(x==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${f} but no src/signals.ts to compare`});else if(v==null)o.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${f} && bun build.ts`});else if(v<x){let w=Math.round((x-v)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${St(v,d)}) is OLDER than src/signals.ts (${St(x,d)}) by ${w}s \u2014 your edit isn't built`,fix:`cd ${f} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${St(x,d)}, dist ${St(v,d)})`});let S=ye.join(n,"node_modules/@stacksjs/stx"),T=null;try{T=Me.lstatSync(S)}catch{T=null}if(!T)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(T.isSymbolicLink()){let w=null;try{w=Me.realpathSync(S)}catch{}let y=(()=>{try{return Me.realpathSync(f)}catch{return f}})();o.push(w===y?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${w||"(dangling)"}, not pantry`})}else o.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(o.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let h=t.generateRuntime().length;o.push(h>1000?{name:"signals runtime",status:"ok",detail:`generated ${h.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${h} chars \u2014 suspiciously short`})}catch(m){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${m.message}`})}return{checks:o,ok:!o.some((m)=>m.status==="error")}}function fo(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let d of t.checks)if(r.push(` ${n[d.status]} ${d.name}: ${d.detail}`),d.fix)r.push(` \u2192 ${d.fix}`);return r.push(""),r.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
2043
+ </html>`}var ia="f9c3713";function Nl(t){return t}function Ml(t){return t}function ea(t,n){let r=[],d=`${n}=`;for(let o=0;o<t.length;o++){let l=t[o];if(l.startsWith(d)){let u=l.slice(d.length);if(u)r.push(u);continue}if(l===n){let u=t[o+1];if(u!==void 0&&!u.startsWith("-"))r.push(u),o++}}return r}import _e from"fs";import ye from"path";function $n(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function St(t,n){let r=Math.max(0,Math.round((n-t)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function Ti(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function Cn(t,n="stx"){let r=ye.resolve(t);for(let d=0;d<10;d++){let o=ye.join(r,"pantry","@stacksjs",n);if(_e.existsSync(o))return o;let l=ye.dirname(r);if(l===r)break;r=l}return null}var Rn=["@stacksjs/stx","bun-plugin-stx"];function $i(t){try{let n=_e.readFileSync(ye.join(t,"package.json"),"utf8"),r=JSON.parse(n)?.version;return typeof r==="string"?r:null}catch{return null}}function Ci(t,n=6){let r=ye.resolve(t),d=[],o=new Set;function l(f,m){if(m>n)return;let h;try{h=_e.realpathSync(f)}catch{return}if(o.has(h))return;o.add(h);for(let v of Rn){let S=ye.join(f,v),T=$i(S);if(T!==null)d.push({name:v,version:T,dir:ye.relative(r,S)||S,nested:m>0})}let x;try{x=_e.readdirSync(f,{withFileTypes:!0})}catch{return}for(let v of x){if(!v.isDirectory()&&!v.isSymbolicLink())continue;if(v.name===".bin"||v.name===".cache")continue;let S=ye.join(f,v.name);if(v.name.startsWith("@")){let w;try{w=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let y of w){let k=ye.join(S,y.name,"node_modules");if(_e.existsSync(k))l(k,m+1)}continue}let T=ye.join(S,"node_modules");if(_e.existsSync(T))l(T,m+1)}}let u=ye.join(r,"node_modules");if(_e.existsSync(u))l(u,0);return d}function Ri(t){let n=[];for(let r of Rn){let d=t.filter((u)=>u.name===r);if(d.length<=1)continue;let o=[...new Set(d.map((u)=>u.version))],l=d.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(o.length===1){n.push({name:`${r} copies`,status:"info",detail:`${d.length} copies, all ${o[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${r} copies disagree`,status:"error",detail:`${o.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${r}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${r}/package.json' -exec grep -H '"version"' {} +`})}return n}async function po(t={}){let n=t.cwd?ye.resolve(t.cwd):process.cwd(),r=t.resolve??Ti,d=Date.now(),o=[],l=r("@stacksjs/stx",n);o.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let u=r("bun-plugin-stx",n);if(u)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let m of Ri(Ci(n)))o.push(m);let f=Cn(n,"stx");if(!f)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let m=ye.join(f,"src/signals.ts"),h=[ye.join(f,"dist/index.js"),ye.join(f,"dist/signals.js")].find((w)=>_e.existsSync(w))||null,x=$n(m),v=h?$n(h):null;if(x==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${f} but no src/signals.ts to compare`});else if(v==null)o.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${f} && bun build.ts`});else if(v<x){let w=Math.round((x-v)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${St(v,d)}) is OLDER than src/signals.ts (${St(x,d)}) by ${w}s \u2014 your edit isn't built`,fix:`cd ${f} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${St(x,d)}, dist ${St(v,d)})`});let S=ye.join(n,"node_modules/@stacksjs/stx"),T=null;try{T=_e.lstatSync(S)}catch{T=null}if(!T)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(T.isSymbolicLink()){let w=null;try{w=_e.realpathSync(S)}catch{}let y=(()=>{try{return _e.realpathSync(f)}catch{return f}})();o.push(w===y?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${w||"(dangling)"}, not pantry`})}else o.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(o.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let h=t.generateRuntime().length;o.push(h>1000?{name:"signals runtime",status:"ok",detail:`generated ${h.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${h} chars \u2014 suspiciously short`})}catch(m){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${m.message}`})}return{checks:o,ok:!o.some((m)=>m.status==="error")}}function fo(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let d of t.checks)if(r.push(` ${n[d.status]} ${d.name}: ${d.detail}`),d.fix)r.push(` \u2192 ${d.fix}`);return r.push(""),r.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
2044
2044
  `)}export{ea,ta,na,ra,uo,sa,oa,ia,Nl,Ml,po,fo,Ur,Wr,qr};