@stacksjs/stx 0.2.446 → 0.2.448

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 (141) hide show
  1. package/dist/{chunk-qa7j3j71.js → chunk-0tchj3ct.js} +4 -4
  2. package/dist/{chunk-7676qzab.js → chunk-0xztxj98.js} +3 -3
  3. package/dist/{chunk-5mxr3acg.js → chunk-13raxes0.js} +1 -1
  4. package/dist/{chunk-hkx8pggg.js → chunk-19h1j59a.js} +1 -1
  5. package/dist/chunk-21ypr4t0.js +2 -0
  6. package/dist/{chunk-1g91pegz.js → chunk-237psdsd.js} +1 -1
  7. package/dist/{chunk-mx9wp3va.js → chunk-26wmppja.js} +1 -1
  8. package/dist/chunk-2tpvt1c5.js +2 -0
  9. package/dist/chunk-4gjc61wn.js +2 -0
  10. package/dist/{chunk-9ad04ksh.js → chunk-4yyzje7d.js} +1 -1
  11. package/dist/{chunk-f85dyf2f.js → chunk-538h1sfc.js} +2 -2
  12. package/dist/{chunk-vxgtq00t.js → chunk-56rk985x.js} +3 -3
  13. package/dist/{chunk-1qnyn82e.js → chunk-5cyme1g0.js} +2 -2
  14. package/dist/chunk-5ftzrjpd.js +2 -0
  15. package/dist/{chunk-vyw0csez.js → chunk-5vgdbqbz.js} +3 -3
  16. package/dist/{chunk-56hvemdx.js → chunk-5xj1df83.js} +17 -17
  17. package/dist/{chunk-b5emjcf1.js → chunk-7417f610.js} +2 -2
  18. package/dist/chunk-78wsn958.js +2 -0
  19. package/dist/chunk-7aspn183.js +2 -0
  20. package/dist/{chunk-gvefw19e.js → chunk-7vdsd9rn.js} +1 -1
  21. package/dist/{chunk-r3f9jcf7.js → chunk-849wf19d.js} +3 -3
  22. package/dist/{chunk-j0nyamyf.js → chunk-8ah8npj3.js} +1 -1
  23. package/dist/chunk-8bzc2v6z.js +2 -0
  24. package/dist/{chunk-8nsmx2w4.js → chunk-8fj8sm1a.js} +2 -2
  25. package/dist/chunk-8gk34047.js +2 -0
  26. package/dist/{chunk-dvja1k84.js → chunk-8nsfkr5n.js} +1 -1
  27. package/dist/chunk-8y4wrp43.js +2 -0
  28. package/dist/{chunk-cm875f73.js → chunk-90562q79.js} +2 -2
  29. package/dist/{chunk-bbnyq3gm.js → chunk-9ndzk9r4.js} +2 -2
  30. package/dist/{chunk-97tb2m44.js → chunk-9xf7yk65.js} +2 -2
  31. package/dist/{chunk-224x6rsx.js → chunk-a5695s8k.js} +1 -1
  32. package/dist/{chunk-2xnwsavq.js → chunk-afhkvj3k.js} +2 -2
  33. package/dist/{chunk-m4q2e418.js → chunk-b1q5sh7x.js} +2 -2
  34. package/dist/{chunk-w9ebf2rb.js → chunk-bderms43.js} +1 -1
  35. package/dist/{chunk-gmzaknjp.js → chunk-bqc07550.js} +1 -1
  36. package/dist/chunk-brtvd5bs.js +2 -0
  37. package/dist/{chunk-cmctzee2.js → chunk-bxhzs857.js} +2 -2
  38. package/dist/{chunk-fbhgabf2.js → chunk-cs3507d0.js} +1 -1
  39. package/dist/chunk-cwc3p6p7.js +2 -0
  40. package/dist/chunk-d3yrvve4.js +2 -0
  41. package/dist/chunk-dk3zazaw.js +2 -0
  42. package/dist/{chunk-ye27ept1.js → chunk-e593pr1r.js} +1 -1
  43. package/dist/chunk-e8y69gg0.js +2 -0
  44. package/dist/chunk-es85mgdw.js +2 -0
  45. package/dist/chunk-fhpfe2s3.js +2 -0
  46. package/dist/chunk-fmc9fj4a.js +2 -0
  47. package/dist/chunk-fn863yek.js +2 -0
  48. package/dist/{chunk-ean2kjmg.js → chunk-fp6v2dq5.js} +4 -4
  49. package/dist/{chunk-egaknprm.js → chunk-frv8bhmz.js} +82 -82
  50. package/dist/{chunk-rvbcnahe.js → chunk-g2afpsw0.js} +2 -2
  51. package/dist/{chunk-dn9thd0h.js → chunk-g3h7j2n7.js} +2 -2
  52. package/dist/chunk-g4hv6v3e.js +2 -0
  53. package/dist/{chunk-aa7w63xc.js → chunk-g8k5rsqq.js} +32 -32
  54. package/dist/{chunk-4mppjen3.js → chunk-get6k573.js} +1 -1
  55. package/dist/{chunk-7v163hb5.js → chunk-gm7ewgf4.js} +1 -1
  56. package/dist/{chunk-csjm1z0c.js → chunk-h3gdfbmf.js} +1 -1
  57. package/dist/chunk-hdat2brj.js +2 -0
  58. package/dist/{chunk-81zfdd95.js → chunk-hhjff2r8.js} +3 -3
  59. package/dist/{chunk-j3gcjbnm.js → chunk-hz6a476h.js} +1 -1
  60. package/dist/chunk-j19s8n7w.js +2 -0
  61. package/dist/chunk-j1h2z4wh.js +2 -0
  62. package/dist/chunk-j3se49h7.js +2 -0
  63. package/dist/{chunk-xq4jdzje.js → chunk-jn8tj4kn.js} +3 -3
  64. package/dist/chunk-kwsw9tc4.js +2 -0
  65. package/dist/{chunk-xgwempyb.js → chunk-m5298269.js} +2 -2
  66. package/dist/{chunk-41fbr3m6.js → chunk-mmp7x8f0.js} +1 -1
  67. package/dist/chunk-mtctv02d.js +2 -0
  68. package/dist/{chunk-4rpfmh9w.js → chunk-n5w8nwec.js} +1 -1
  69. package/dist/{chunk-b3e0hcw0.js → chunk-n7n9zxmh.js} +100 -100
  70. package/dist/chunk-nkzn1hqq.js +2 -0
  71. package/dist/{chunk-06qhvtsv.js → chunk-ns7e951g.js} +1 -1
  72. package/dist/{chunk-ca24g1fa.js → chunk-p7m673vn.js} +4 -4
  73. package/dist/chunk-p9shre7t.js +2 -0
  74. package/dist/chunk-pgnr089q.js +2 -0
  75. package/dist/{chunk-0xntpjmp.js → chunk-pkpmyr0x.js} +2 -2
  76. package/dist/{chunk-ybk279xj.js → chunk-qmfwhvcr.js} +4 -4
  77. package/dist/{chunk-sgxjqqvd.js → chunk-qmp7j5h4.js} +1 -1
  78. package/dist/chunk-rp69az5a.js +2 -0
  79. package/dist/{chunk-h7ny0py8.js → chunk-s6e8mmk1.js} +1 -1
  80. package/dist/chunk-sfvyfvbm.js +2 -0
  81. package/dist/{chunk-9tbevvm3.js → chunk-t01a2dfe.js} +12 -12
  82. package/dist/chunk-t6d5zq7d.js +2 -0
  83. package/dist/{chunk-mcgpeyy8.js → chunk-tehvry9a.js} +4 -4
  84. package/dist/{chunk-t9tg1syw.js → chunk-vbzeeeax.js} +8 -8
  85. package/dist/{chunk-3yws0k28.js → chunk-vnq2c0tg.js} +5 -5
  86. package/dist/{chunk-ak7eyyka.js → chunk-w8ek4fe8.js} +2 -2
  87. package/dist/chunk-wf09xg7j.js +2 -0
  88. package/dist/{chunk-bh432b7n.js → chunk-x4ztj64h.js} +2 -2
  89. package/dist/{chunk-b7x7099z.js → chunk-y6zm894z.js} +5 -5
  90. package/dist/{chunk-9f0srtmg.js → chunk-yfd0e7dr.js} +1 -1
  91. package/dist/{chunk-39726w03.js → chunk-yn3w9g2z.js} +4 -4
  92. package/dist/chunk-ytq686vx.js +2 -0
  93. package/dist/{chunk-5zpt78j4.js → chunk-yx37nrgr.js} +4 -4
  94. package/dist/{chunk-3wdarmh7.js → chunk-z4b0kr1z.js} +4 -4
  95. package/dist/{chunk-12mzd0gf.js → chunk-z72wwstp.js} +3 -3
  96. package/dist/chunk-zj80vrv6.js +2 -0
  97. package/dist/{chunk-cs15xqf0.js → chunk-zqzv5jy2.js} +4 -4
  98. package/dist/cli.js +12 -12
  99. package/dist/craft-entry.js +2 -2
  100. package/dist/craft.js +2 -2
  101. package/dist/native/bridge/protocol.d.ts +1 -0
  102. package/dist/native/bridge/protocol.js +15 -0
  103. package/dist/native/runtime/shared-screen.js +1 -0
  104. package/dist/pwa.js +3 -3
  105. package/dist/ssg.js +16 -16
  106. package/dist/utils.js +24 -9
  107. package/package.json +2 -2
  108. package/dist/chunk-0e6da0m4.js +0 -2
  109. package/dist/chunk-2b66v3yx.js +0 -2
  110. package/dist/chunk-4awtqfv7.js +0 -2
  111. package/dist/chunk-4ct5vj9n.js +0 -2
  112. package/dist/chunk-66czf70n.js +0 -2
  113. package/dist/chunk-7cdrpkzz.js +0 -2
  114. package/dist/chunk-7kyr2atb.js +0 -2
  115. package/dist/chunk-8bsy7r0w.js +0 -2
  116. package/dist/chunk-93wp5h7v.js +0 -2
  117. package/dist/chunk-a14zkmbp.js +0 -2
  118. package/dist/chunk-a8hjvjb8.js +0 -2
  119. package/dist/chunk-e1n2t5tk.js +0 -2
  120. package/dist/chunk-frys2748.js +0 -2
  121. package/dist/chunk-gy7t9wd0.js +0 -2
  122. package/dist/chunk-h15q5qan.js +0 -2
  123. package/dist/chunk-hvawaf7a.js +0 -2
  124. package/dist/chunk-k2k6engs.js +0 -2
  125. package/dist/chunk-kp7r61aj.js +0 -2
  126. package/dist/chunk-kr2phxhf.js +0 -2
  127. package/dist/chunk-m2k2b81v.js +0 -2
  128. package/dist/chunk-p2b0r3qn.js +0 -2
  129. package/dist/chunk-p46gy056.js +0 -2
  130. package/dist/chunk-p5hrdsk9.js +0 -2
  131. package/dist/chunk-qy8wb31b.js +0 -2
  132. package/dist/chunk-qzyfjyna.js +0 -2
  133. package/dist/chunk-rwdkh7c0.js +0 -2
  134. package/dist/chunk-sjgg6r0a.js +0 -2
  135. package/dist/chunk-tq441vbg.js +0 -2
  136. package/dist/chunk-vn09wm09.js +0 -2
  137. package/dist/chunk-xex4nkgq.js +0 -2
  138. package/dist/chunk-xr03p49w.js +0 -2
  139. package/dist/chunk-y8kz05mn.js +0 -2
  140. package/dist/chunk-ycmc1zpt.js +0 -2
  141. package/dist/chunk-ymvdbs80.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{K,un,te,_,Et}from"./chunk-56hvemdx.js";import{Ze,gn,ir,or,ar,Qe,et,tt,nt,rt,st,xe}from"./chunk-b5emjcf1.js";import{U,h,Zt,Qt,e,vt,en,f,je,xt,Be,Fe,Z,M,ae,q,d,ye,Zi,us,n,r,ee,qn,i,T,ce}from"./chunk-b3e0hcw0.js";import{_e,ni,ne,C,ri,vr,kn,ge,si,re}from"./chunk-3wdarmh7.js";import{At}from"./chunk-4mppjen3.js";import{De}from"./chunk-3yws0k28.js";import{a}from"./chunk-cm875f73.js";import{D}from"./chunk-yqsza22w.js";function zs(t,o){let s=[],p=`${o}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(p)){let m=l.slice(p.length);if(m)s.push(m);continue}if(l===o){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))s.push(m),c++}}return s}var{serve:rr}=globalThis.Bun;import Bt from"fs";import pt from"path";function bt(){return`
2
+ import{K,un,te,_,Et}from"./chunk-5xj1df83.js";import{Ze,gn,or,ir,ar,Qe,et,tt,nt,rt,st,xe}from"./chunk-7417f610.js";import{U,h,Zt,Qt,e,vt,en,f,je,xt,Be,Fe,Z,M,ae,q,d,ye,Qo,us,n,r,ee,qn,o,T,ce}from"./chunk-n7n9zxmh.js";import{_e,no,ne,C,ro,vr,kn,ge,so,re}from"./chunk-z4b0kr1z.js";import{At}from"./chunk-get6k573.js";import{De}from"./chunk-vnq2c0tg.js";import{a}from"./chunk-90562q79.js";import{D}from"./chunk-yqsza22w.js";function zs(t,s){let i=[],p=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(p)){let m=l.slice(p.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}var{serve:rr}=globalThis.Bun;import Bt from"fs";import pt from"path";function bt(){return`
3
3
  /* Theme selector for code blocks */
4
4
  .theme-selector {
5
5
  margin: 1rem 0;
@@ -74,17 +74,17 @@ else {
74
74
  document.addEventListener('DOMContentLoaded', changeTheme);`}function kt(t){if(Object.keys(t).length===0)return"";return`
75
75
  <div class="frontmatter">
76
76
  <h3>Frontmatter</h3>
77
- ${Object.entries(t).map(([o,s])=>`
77
+ ${Object.entries(t).map(([s,i])=>`
78
78
  <div class="frontmatter-item">
79
- <span class="frontmatter-label">${o}:</span>
80
- <span>${Array.isArray(s)?s.join(", "):String(s)}</span>
79
+ <span class="frontmatter-label">${s}:</span>
80
+ <span>${Array.isArray(i)?i.join(", "):String(i)}</span>
81
81
  </div>`).join("")}
82
- </div>`}import Gt from"net";async function Gn(t){return new Promise((o)=>{let s=Gt.createServer();s.once("error",()=>o(!1)),s.once("listening",()=>{s.close(()=>o(!0))}),s.listen(t,"0.0.0.0")})}async function Jn(t){return new Promise((o)=>{let s=Gt.createServer();s.once("error",()=>o(!1)),s.once("listening",()=>{s.close(()=>o(!0))}),s.listen(t,"::")})}async function Yn(t){if(!await Gn(t))return!1;return await Jn(t)}async function Ye(t,o=20){t=Number(t);for(let s=0;s<o;s++){let p=t+s;if(await Yn(p))return p}throw Error(`Could not find an available port between ${t} and ${t+o-1}`)}var Qn={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Zn(){try{let t=await import("./chunk-74j18qk0.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function dt(t,o={}){let s={...Qn,...o},p=await Zn();if(!p)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await p.openDevWindow(t,{title:s.title,width:s.width,height:s.height,darkMode:s.darkMode,hotReload:s.hotReload,titlebarHidden:s.titlebarHidden,nativeSidebar:s.nativeSidebar,sidebarWidth:s.sidebarWidth,sidebarConfig:s.sidebarConfig});if(c&&s.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function Tt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
82
+ </div>`}import Gt from"net";async function Gn(t){return new Promise((s)=>{let i=Gt.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"0.0.0.0")})}async function Jn(t){return new Promise((s)=>{let i=Gt.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"::")})}async function Yn(t){if(!await Gn(t))return!1;return await Jn(t)}async function Ye(t,s=20){t=Number(t);for(let i=0;i<s;i++){let p=t+i;if(await Yn(p))return p}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Qn={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Zn(){try{let t=await import("./chunk-74j18qk0.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function dt(t,s={}){let i={...Qn,...s},p=await Zn();if(!p)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await p.openDevWindow(t,{title:i.title,width:i.width,height:i.height,darkMode:i.darkMode,hotReload:i.hotReload,titlebarHidden:i.titlebarHidden,nativeSidebar:i.nativeSidebar,sidebarWidth:i.sidebarWidth,sidebarConfig:i.sidebarConfig});if(c&&i.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function Tt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
83
83
  ${l}
84
84
  return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
85
- `,y=Function(m)();if(y)return y}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let s=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(s)try{return JSON.parse(s[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let c=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function Ht(){console.log(`
86
- 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 er(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`),Ht()}function tr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function ot(t,o,s){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ht();let p="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(s?.onQuit)s.onQuit();o(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
87
- `)){let l=p.trim().toLowerCase();p="",nr(l,t,o,s)}})}function nr(t,o,s,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else tr(o);break;case"c":if(p?.onClear)p.onClear();else console.clear(),er(o);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),s(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ht();break;default:break}}async function Ft(t,o={}){let s=o.port||3000,p=o.watch!==!1,c=pt.resolve(t);if(!Bt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await ce(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),E=o.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,v=E?.defaultTheme||"github-dark",x=["github-dark"],R=E?.additionalThemes||[],B=[...new Set([...x,...R])].map((L)=>`<option value="${L}"${L===v?" selected":""}>${L}</option>`).join(`
85
+ `,y=Function(m)();if(y)return y}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let i=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(i)try{return JSON.parse(i[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let c=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function Ht(){console.log(`
86
+ 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 er(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`),Ht()}function tr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function ot(t,s,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ht();let p="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
87
+ `)){let l=p.trim().toLowerCase();p="",nr(l,t,s,i)}})}function nr(t,s,i,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else tr(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),er(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ht();break;default:break}}async function Ft(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=pt.resolve(t);if(!Bt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await ce(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),E=s.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,v=E?.defaultTheme||"github-dark",x=["github-dark"],R=E?.additionalThemes||[],B=[...new Set([...x,...R])].map((L)=>`<option value="${L}"${L===v?" selected":""}>${L}</option>`).join(`
88
88
  `);return l=`
89
89
  <!DOCTYPE html>
90
90
  <html lang="en">
@@ -247,12 +247,12 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
247
247
  </script>
248
248
  </body>
249
249
  </html>
250
- `,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await m())return!1;let y=s;try{if(y=await Ye(s),y!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let g=rr({port:y,fetch(w){if(new URL(w.url).pathname==="/")return new Response(l,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
250
+ `,!0}catch(w){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,w),!1}};if(!await m())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let g=rr({port:y,fetch(w){if(new URL(w.url).pathname==="/")return new Response(l,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
251
251
  ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
252
252
  ${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(`
253
253
  ${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
254
254
  ${e.yellow}Routes:${e.reset}`);let b=pt.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${b}${e.reset}`),console.log(`
255
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(g.url.toString(),()=>{if(p)Bt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),o.native)await dt(y,{title:pt.basename(c,".md")});if(p){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Bt.watch(w,{recursive:!0},async(E,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function sr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:zi}=globalThis.Bun;import Ne from"fs";import Se from"path";class Jt{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 o=t??this.options.wsPort,s=20;for(let p=0;p<s;p++)try{if(this.server=Bun.serve({port:o,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let u=JSON.parse(m);if(u.type==="console"&&Array.isArray(u.args)){let y=u.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${b}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${o}`);return o}catch(c){if(c?.code==="EADDRINUSE"){o++;continue}throw c}throw Error(`Could not find an available port after ${s} 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 o=JSON.stringify(t),s=0;for(let p of this.clients)try{if(p.readyState===1)p.send(o),s++}catch{this.clients.delete(p)}if(this.options.verbose&&s>0)console.log(`[HMR] Broadcast ${t.type} to ${s} 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,o){this.broadcast({type:"css-update",path:t,content:o,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 cr(t,o={}){let{showOverlay:s=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=o;return`
255
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(g.url.toString(),()=>{if(p)Bt.watch(pt.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await dt(y,{title:pt.basename(c,".md")});if(p){let w=pt.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Bt.watch(w,{recursive:!0},async(E,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function sr(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ni}=globalThis.Bun;import Ne from"fs";import Se from"path";class Jt{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let p=0;p<i;p++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let u=JSON.parse(m);if(u.type==="console"&&Array.isArray(u.args)){let y=u.args.join(" "),b={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[u.level]??"\x1B[36m";console.log(`${b}[browser]${u.level!=="log"?` ${u.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),i++}catch{this.clients.delete(p)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function cr(t,s={}){let{showOverlay:i=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
256
256
  <script>
257
257
  (function() {
258
258
  // stx Hot Reload Client
@@ -264,7 +264,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(g.u
264
264
  var overlay = null;
265
265
  var wasConnected = false; // Track if we ever connected successfully
266
266
 
267
- ${s?`
267
+ ${i?`
268
268
  // Create connection status overlay
269
269
  function createOverlay() {
270
270
  overlay = document.createElement('div');
@@ -451,13 +451,13 @@ else {
451
451
  };
452
452
  })();
453
453
  </script>
454
- `}function Xe(t,o,s={}){let p=cr(o,s),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function $t(t){let o=t.toLowerCase();return o.endsWith(".css")||o.endsWith(".scss")||o.endsWith(".sass")||o.endsWith(".less")}function Ct(t){let o=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>o.endsWith(p))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((s)=>s.test(t))}var ut=null;function Pt(t){if(!ut)ut=new Jt(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import _t from"path";async function lr(t){try{let o=await Bun.file(t).text(),s=dr(o),p=ur(o,t),c=mr(o,s),l=hr(o,s);return{file:t,metrics:s,issues:p,suggestions:c,performance:l}}catch(o){throw Error(`Failed to analyze template ${t}: ${o instanceof Error?o.message:String(o)}`)}}function dr(t){let o=t.split(`
455
- `),s=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(s?s[1]:"").split(`
456
- `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,E=0;for(let R of o)if(/@(?:if|unless|foreach|for|while|section)\b/.test(R)&&!/@end/.test(R)&&!/@else/.test(R))E++,S=Math.max(S,E);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(R))E--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+b*0.3+(c>10?c*0.05:0)+v));return{lines:o.length,characters:t.length,directives:l,expressions:g,components:b,layouts:w,scriptLines:c,complexity:x}}function ur(t,o){let s=[],p=tn(t,"if","endif");if(p>0)s.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=tn(t,"foreach","endforeach");if(c>0)s.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)s.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)s.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)s.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
457
- `).filter((b)=>b.length>120);if(y.length>0)s.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)s.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return s}function mr(t,o){let s=[];if(o.complexity>7)s.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(o.complexity>5&&o.directives.total>8)s.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(o.lines>100&&o.components===0)s.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(o.expressions>20)s.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)s.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(o.directives.total===0&&o.expressions<5)s.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(o.scriptLines>50)s.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return s}function hr(t,o){let s=1;if(s+=o.directives.conditionals*0.1,s+=o.directives.loops*0.5,s+=o.directives.includes*2,s+=o.expressions*0.05,s+=o.components*1,o.scriptLines>10)s+=o.scriptLines*0.1;let p;if(o.expressions===0&&o.directives.total===0)p="high";else if(o.expressions<5&&o.directives.total<3)p="medium";else p="low";let c=[];if(s>10)c.push("Consider optimizing template complexity");if(p==="low"&&o.directives.total>5)c.push("Reduce dynamic content for better caching");if(o.components===0&&o.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(s*100)/100,complexityScore:o.complexity,cacheability:p,recommendations:c}}function tn(t,o,s){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${o}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Hs(t=["**/*.stx"],o){let s=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:o||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await lr(l);s.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=yr(s);return{results:s,summary:c}}function yr(t){let o=t.length,s=t.reduce((g,b)=>g+b.metrics.lines,0),p=o>0?t.reduce((g,b)=>g+b.metrics.complexity,0)/o:0,c=t.reduce((g,b)=>g+b.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let m=o>0?t.reduce((g,b)=>g+b.performance.estimatedRenderTime,0)/o:0,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(c>o*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:o,totalLines:s,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as br,readFile as xr,readdir as wr,stat as nn,writeFile as Sr}from"fs/promises";import Ee from"path";function ln(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 dn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function kr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((o)=>o.charAt(0).toUpperCase()+o.slice(1)).join("")}function Ut(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Tr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function $r(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function Cr(t){let o=[];async function s(p){let c=await wr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Ee.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await s(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))o.push(m)}}return await s(t),o}function Rr(t,o){let s=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!s)return{};let p=s[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${o}: <script component> must contain JSON metadata (${c.message})`)}}function Er(t,o){let s={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(y){throw Error(`${o}: failed to transpile <script client> (${y.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=m.exec(l)){let y=u[1];if(dn.has(y))throw Error(`${o}: client ${ln(y)}`);let g=m.lastIndex,b=1,w="",S=!1,E=g;for(;E<l.length&&b>0;E++){let x=l[E];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${o}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";s[y]=`${v}${y}(${u[2]}) {${l.slice(g,E-1)}}`,m.lastIndex=E}}return s}function Pr(t){let o=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(o?o[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function rn(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((o)=>o[1].trim()).filter(Boolean).join(`
454
+ `}function Xe(t,s,i={}){let p=cr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+p+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function $t(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Ct(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>s.endsWith(p))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var ut=null;function Pt(t){if(!ut)ut=new Jt(t);return ut}function ht(){if(ut)ut.stop(),ut=null}import _t from"path";async function lr(t){try{let s=await Bun.file(t).text(),i=dr(s),p=ur(s,t),c=mr(s,i),l=hr(s,i);return{file:t,metrics:i,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function dr(t){let s=t.split(`
455
+ `),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(i?i[1]:"").split(`
456
+ `).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,E=0;for(let R of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(R)&&!/@end/.test(R)&&!/@else/.test(R))E++,S=Math.max(S,E);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(R))E--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+b*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:b,layouts:w,scriptLines:c,complexity:x}}function ur(t,s){let i=[],p=tn(t,"if","endif");if(p>0)i.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=tn(t,"foreach","endforeach");if(c>0)i.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)i.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)i.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
457
+ `).filter((b)=>b.length>120);if(y.length>0)i.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function mr(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function hr(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let p;if(s.expressions===0&&s.directives.total===0)p="high";else if(s.expressions<5&&s.directives.total<3)p="medium";else p="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(p==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function tn(t,s,i){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Hs(t=["**/*.stx"],s){let i=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await lr(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=yr(i);return{results:i,summary:c}}function yr(t){let s=t.length,i=t.reduce((g,b)=>g+b.metrics.lines,0),p=s>0?t.reduce((g,b)=>g+b.metrics.complexity,0)/s:0,c=t.reduce((g,b)=>g+b.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let m=s>0?t.reduce((g,b)=>g+b.performance.estimatedRenderTime,0)/s:0,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as br,readFile as xr,readdir as wr,stat as nn,writeFile as Sr}from"fs/promises";import Ee from"path";function ln(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 dn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function kr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Ut(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Tr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function $r(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function Cr(t){let s=[];async function i(p){let c=await wr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Ee.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function Rr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let p=i[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function Er(t,s){let i={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(y){throw Error(`${s}: failed to transpile <script client> (${y.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=m.exec(l)){let y=u[1];if(dn.has(y))throw Error(`${s}: client ${ln(y)}`);let g=m.lastIndex,b=1,w="",S=!1,E=g;for(;E<l.length&&b>0;E++){let x=l[E];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${s}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";i[y]=`${v}${y}(${u[2]}) {${l.slice(g,E-1)}}`,m.lastIndex=E}}return i}function Pr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function rn(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
458
458
 
459
- `)}function Or(t){if(!t)return null;let o=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(o))return"string";if(/^number$/.test(o))return"number";if(/^boolean$/.test(o))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(o))return"string";return"object"}function Ar(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 Dr(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 Mr(t){let o=[],s=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(y)=>{if(p[y]!=="(")return null;let g=0,b="";for(let w=y;w<p.length;w++){let S=p[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(y+1,w),end:w+1}}}return null},u=(y)=>{if(y==="")return;let g=0,b=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=b.exec(y)){if(w.index>g)o.push(`out += ${JSON.stringify(y.slice(g,w.index))};`);o.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<y.length)o.push(`out += ${JSON.stringify(y.slice(g))};`)};while(l=c.exec(p)){u(p.slice(s,l.index)),s=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(s):null;if(g)s=g.end,c.lastIndex=g.end;let b=g?.expression;switch(l[1]){case"if":o.push(`if (${b}) {`);break;case"elseif":o.push(`} else if (${b}) {`);break;case"else":o.push("} else {");break;case"endif":case"endforeach":o.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((b||"").trim());if(!w){o.push(`out += ${JSON.stringify(l[0]+(g?`(${b})`:""))};`);break}let[,S,E,v]=w;o.push(E?`for (const [${E}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(s)),o.join(`
460
- `)}function Ot(t,o,s,p){if(t[o]!==s)return-1;let c=0,l=null;for(let m=o;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===s)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function zt(t,o,s){let p=s?"([{<":"([{",c=s?")]}>":")]}",l=[],m=0,u=null,y="";for(let g=0;g<t.length;g++){let b=t[g];if(u){if(y+=b,b==="\\"){y+=t[++g]??"";continue}if(b===u)u=null;continue}if(b==="'"||b==='"'||b==="`"){u=b,y+=b;continue}if(p.includes(b))m++;else if(c.includes(b))m--;if(m===0&&o.includes(b)){l.push(y),y="";continue}y+=b}return l.push(y),l.map((g)=>g.trim()).filter(Boolean)}function _r(t){let o=0,s=null;for(let p=0;p<t.length;p++){let c=t[p];if(s){if(c==="\\"){p++;continue}if(c===s)s=null;continue}if(c==="'"||c==='"'||c==="`"){s=c;continue}if("([{".includes(c))o++;else if(")]}".includes(c))o--;if(o!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function on(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 Lr(t){let o=/\bdefineProps\b/.exec(t);if(!o)return null;let s=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=s.exec(t);k&&k.index<o.index;k=s.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),y=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=Ot(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(y(),t[u]!=="=")return null;u++,y();let b=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(b);if(b)u+=b[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let E="";if(y(),t[u]==="<"){let k=Ot(t,u,"<",">");if(k===-1)return null;E=t.slice(u+1,k-1).trim(),u=k}if(y(),t[u]!=="(")return null;let v=Ot(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(y(),t[u]===",")u++,y();if(t[u]==="{"){let k=Ot(t,u,"{","}");if(k===-1)return null;for(let[B,L]of Nt(t.slice(u,k)))l[B]=L;u=k}if(y(),t[u]===",")u++,y();if(t[u]===")")u++}if(t[u]===";")u++;let R=/^[A-Za-z_$][\w$]*$/.test(E)?E:void 0;if(E.startsWith("{"))for(let k of zt(E.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let B=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(B)c[B[1]]=B[2].trim()}if(x.startsWith("{"))for(let[k,B]of Nt(x)){if(m.push(k),!B.startsWith("{")){let L=on(B);if(L)c[k]=L;continue}for(let[L,j]of Nt(B))if(L==="default")l[k]=j;else if(L==="type"){let P=on(j);if(P)c[k]=P}}else if(x.startsWith("["))for(let k of zt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of zt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let B=_r(k),j=(B===-1?k:k.slice(0,B)).split(":")[0].trim().replace(/^\.\.\./,"");if(!j)continue;if(m.push(j),B!==-1)l[j]=k.slice(B+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:R}}function Nt(t){let o=t.trim().replace(/^\{/,"").replace(/\}$/,""),s=[],p=0;while(p<o.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(o);if(!l)break;p=c.lastIndex;let m=0,u="",y=p;while(p<o.length){let b=o[p];if(u){if(b==="\\")p++;else if(b===u)u=""}else if(b==="'"||b==='"'||b==="`")u=b;else if(b==="{"||b==="["||b==="(")m++;else if(b==="}"||b==="]"||b===")")m--;else if(b===","&&m===0)break;p++}let g=o.slice(y,p).trim();if(g)s.push([l[1],g]);p++}return s}function Ir(t,o,s){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],y={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(E,v,x,R)=>{let k=Ee.resolve(Ee.dirname(o),x),B=Ee.relative(s,k);return`${v}${B.startsWith(".")?B:`./${B}`}${R}`})),""});let b=Lr(l);if(b)u.push(...b.propNames),Object.assign(y,b.defaults),Object.assign(g,b.declared),l=l.replace(b.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let E=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),E.push(v[1]);w[S[1]]=E}if(b&&b.propNames.length===0&&b.typeName){for(let S of w[b.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:y,declared:g}}function jr(t){let o=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let y=c.toLowerCase();o.add(y);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${u}"${g?` data-stx-mod-${y}="${g}"`:""}`}),eventTypes:[...o].sort()}}function Hr(t){let o=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=o.length;return o.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:o}}function Br(t){let o=new Set;for(let s of t.matchAll(/<slot\b([^>]*)>/gi))o.add(s[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...o].map((s)=>({name:s}))}function Fr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((o)=>o[1]))].sort().map((o)=>({name:o}))}function sn(t,o){if(!o||!new Set(["string","number","boolean","object","array"]).has(o.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...o,reflect:o.reflect??o.attribute!==!1}}async function zr(t,o,s){let p=Ee.isAbsolute(o.file)?o.file:Ee.resolve(t,o.file),c=await xr(p,"utf8"),l=Rr(c,p),m=Ee.basename(p,".stx"),u=o.name||l.name||kr(m),y=`${Ut(s.prefix||"stx")}-${Ut(m)}`,g=o.tag||l.tag||y;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!Tr(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let b=o.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(b).map(([L,j])=>[L,sn(L,j)])),S=jr(Pr(c)),E=Hr(S.template),v=Ir(c,p,Ee.resolve(s.outputDir)),x=Mr(E.template);for(let L of v.propNames){if(w[L])continue;let j=v.defaults[L];w[L]=sn(L,{type:Or(v.declared[L])??Ar(j),...j===void 0?{}:{default:Dr(j)}})}let R=l.methods||{},k=o.methods||{},B=Er(c,p);return{file:Ee.relative(t,p),sourcePath:p,name:u,tag:g,description:o.description||l.description||"",template:E.template,styles:rn(c),shadowMode:$r(o.shadowDOM??l.shadowDOM??s.shadowDOM),progressive:o.progressive??l.progressive??s.progressive??!0,properties:w,events:o.events||l.events||{},methods:{...R,...k,...B},eventTypes:S.eventTypes,bindings:E.bindings,slots:Br(E.template),cssProperties:Fr(rn(c)),scope:v,render:x}}function Nr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),o=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
459
+ `)}function Or(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function Ar(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 Dr(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 Mr(t){let s=[],i=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(y)=>{if(p[y]!=="(")return null;let g=0,b="";for(let w=y;w<p.length;w++){let S=p[w];if(b!==""){if(S==="\\")w++;else if(S===b)b="";continue}if(S==="'"||S==='"'||S==="`"){b=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(y+1,w),end:w+1}}}return null},u=(y)=>{if(y==="")return;let g=0,b=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=b.exec(y)){if(w.index>g)s.push(`out += ${JSON.stringify(y.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<y.length)s.push(`out += ${JSON.stringify(y.slice(g))};`)};while(l=c.exec(p)){u(p.slice(i,l.index)),i=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(i):null;if(g)i=g.end,c.lastIndex=g.end;let b=g?.expression;switch(l[1]){case"if":s.push(`if (${b}) {`);break;case"elseif":s.push(`} else if (${b}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((b||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${b})`:""))};`);break}let[,S,E,v]=w;s.push(E?`for (const [${E}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(i)),s.join(`
460
+ `)}function Ot(t,s,i,p){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===i)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function zt(t,s,i){let p=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,u=null,y="";for(let g=0;g<t.length;g++){let b=t[g];if(u){if(y+=b,b==="\\"){y+=t[++g]??"";continue}if(b===u)u=null;continue}if(b==="'"||b==='"'||b==="`"){u=b,y+=b;continue}if(p.includes(b))m++;else if(c.includes(b))m--;if(m===0&&s.includes(b)){l.push(y),y="";continue}y+=b}return l.push(y),l.map((g)=>g.trim()).filter(Boolean)}function _r(t){let s=0,i=null;for(let p=0;p<t.length;p++){let c=t[p];if(i){if(c==="\\"){p++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function on(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 Lr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),y=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=Ot(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(y(),t[u]!=="=")return null;u++,y();let b=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(b);if(b)u+=b[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let E="";if(y(),t[u]==="<"){let k=Ot(t,u,"<",">");if(k===-1)return null;E=t.slice(u+1,k-1).trim(),u=k}if(y(),t[u]!=="(")return null;let v=Ot(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(y(),t[u]===",")u++,y();if(t[u]==="{"){let k=Ot(t,u,"{","}");if(k===-1)return null;for(let[B,L]of Nt(t.slice(u,k)))l[B]=L;u=k}if(y(),t[u]===",")u++,y();if(t[u]===")")u++}if(t[u]===";")u++;let R=/^[A-Za-z_$][\w$]*$/.test(E)?E:void 0;if(E.startsWith("{"))for(let k of zt(E.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let B=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(B)c[B[1]]=B[2].trim()}if(x.startsWith("{"))for(let[k,B]of Nt(x)){if(m.push(k),!B.startsWith("{")){let L=on(B);if(L)c[k]=L;continue}for(let[L,j]of Nt(B))if(L==="default")l[k]=j;else if(L==="type"){let P=on(j);if(P)c[k]=P}}else if(x.startsWith("["))for(let k of zt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of zt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let B=_r(k),j=(B===-1?k:k.slice(0,B)).split(":")[0].trim().replace(/^\.\.\./,"");if(!j)continue;if(m.push(j),B!==-1)l[j]=k.slice(B+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:R}}function Nt(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],p=0;while(p<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(s);if(!l)break;p=c.lastIndex;let m=0,u="",y=p;while(p<s.length){let b=s[p];if(u){if(b==="\\")p++;else if(b===u)u=""}else if(b==="'"||b==='"'||b==="`")u=b;else if(b==="{"||b==="["||b==="(")m++;else if(b==="}"||b==="]"||b===")")m--;else if(b===","&&m===0)break;p++}let g=s.slice(y,p).trim();if(g)i.push([l[1],g]);p++}return i}function Ir(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],y={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(E,v,x,R)=>{let k=Ee.resolve(Ee.dirname(s),x),B=Ee.relative(i,k);return`${v}${B.startsWith(".")?B:`./${B}`}${R}`})),""});let b=Lr(l);if(b)u.push(...b.propNames),Object.assign(y,b.defaults),Object.assign(g,b.declared),l=l.replace(b.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let E=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),E.push(v[1]);w[S[1]]=E}if(b&&b.propNames.length===0&&b.typeName){for(let S of w[b.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:y,declared:g}}function jr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let y=c.toLowerCase();s.add(y);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${u}"${g?` data-stx-mod-${y}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Hr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Br(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function Fr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function sn(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function zr(t,s,i){let p=Ee.isAbsolute(s.file)?s.file:Ee.resolve(t,s.file),c=await xr(p,"utf8"),l=Rr(c,p),m=Ee.basename(p,".stx"),u=s.name||l.name||kr(m),y=`${Ut(i.prefix||"stx")}-${Ut(m)}`,g=s.tag||l.tag||y;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!Tr(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let b=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(b).map(([L,j])=>[L,sn(L,j)])),S=jr(Pr(c)),E=Hr(S.template),v=Ir(c,p,Ee.resolve(i.outputDir)),x=Mr(E.template);for(let L of v.propNames){if(w[L])continue;let j=v.defaults[L];w[L]=sn(L,{type:Or(v.declared[L])??Ar(j),...j===void 0?{}:{default:Dr(j)}})}let R=l.methods||{},k=s.methods||{},B=Er(c,p);return{file:Ee.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:E.template,styles:rn(c),shadowMode:$r(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...R,...k,...B},eventTypes:S.eventTypes,bindings:E.bindings,slots:Br(E.template),cssProperties:Fr(rn(c)),scope:v,render:x}}function Nr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
461
461
 
462
462
  const escapeHTML = (value) => String(value ?? '')
463
463
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -664,7 +664,7 @@ export class StxElement extends HTMLElementBase {
664
664
  ? this.render(RENDER_HELPERS)
665
665
  : definition.template
666
666
  .replace(new RegExp(${t}, 'g'), (_match, expression) => String(valueAt(this, expression) ?? ''))
667
- .replace(new RegExp(${o}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
667
+ .replace(new RegExp(${s}, 'g'), (_match, expression) => escapeHTML(valueAt(this, expression)));
668
668
  if (definition.shadowMode && definition.styles) html = '<style>' + definition.styles + '</style>' + html;
669
669
  root.innerHTML = html;
670
670
  this._applyBindings();
@@ -755,7 +755,7 @@ export function defineComponent(Component, definition) {
755
755
  }
756
756
  return Component;
757
757
  }
758
- `}function Ur(t){let o=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),s=Object.entries(t.methods).map(([u,y])=>{if(dn.has(u))throw Error(`${t.sourcePath}: ${ln(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
758
+ `}function Ur(t){let s=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),i=Object.entries(t.methods).map(([u,y])=>{if(dn.has(u))throw Error(`${t.sourcePath}: ${ln(u)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${u}($event) {
759
759
  ${y}
760
760
  }`}).join(`
761
761
 
@@ -775,17 +775,17 @@ ${p.imports.length?`${p.imports.join(`
775
775
  `:""}
776
776
  /** ${t.description||`${t.name} web component generated from ${t.file}.`} */
777
777
  export class ${t.name} extends StxElement {
778
- ${s}${m}
778
+ ${i}${m}
779
779
  }
780
780
 
781
- defineComponent(${t.name}, ${o});
781
+ defineComponent(${t.name}, ${s});
782
782
  export default ${t.name};
783
- `}function Dt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Wr(t){let o=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${Dt(m)}`).join(`
784
- `),s=Object.entries(t.properties).map(([l,m])=>` ${l}: ${Dt(m)}`).join(`
783
+ `}function Dt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Wr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${Dt(m)}`).join(`
784
+ `),i=Object.entries(t.properties).map(([l,m])=>` ${l}: ${Dt(m)}`).join(`
785
785
  `),p=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
786
786
  `),c=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
787
787
  `);return`export interface ${t.name}Props {
788
- ${o}
788
+ ${s}
789
789
  }
790
790
 
791
791
  export interface ${t.name}EventMap {
@@ -793,7 +793,7 @@ ${p}
793
793
  }
794
794
 
795
795
  export declare class ${t.name} extends HTMLElement {
796
- ${s}
796
+ ${i}
797
797
  ${c}
798
798
  readonly updateComplete: Promise<void>
799
799
  requestUpdate(): Promise<void>
@@ -810,9 +810,9 @@ export default ${t.name}
810
810
  `}function Vr(t){return`declare global {
811
811
  namespace JSX {
812
812
  interface IntrinsicElements {
813
- ${t.map((s)=>{let p=Object.entries(s.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${Dt(m)}`).join(`
814
- `),c=Object.keys(s.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${s.events[l].detailType||"unknown"}>) => void`).join(`
815
- `);return` ${JSON.stringify(s.tag)}: {
813
+ ${t.map((i)=>{let p=Object.entries(i.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${Dt(m)}`).join(`
814
+ `),c=Object.keys(i.events).map((l)=>` ${`on${l.split(/[-:]/).map((u)=>u.charAt(0).toUpperCase()+u.slice(1)).join("")}`}?: (event: CustomEvent<${i.events[l].detailType||"unknown"}>) => void`).join(`
815
+ `);return` ${JSON.stringify(i.tag)}: {
816
816
  ${p}
817
817
  ${c}
818
818
  children?: unknown
@@ -826,9 +826,9 @@ ${c}
826
826
  }
827
827
 
828
828
  export {}
829
- `}function qr(t){return{schemaVersion:"1.0.0",modules:t.map((o)=>({kind:"javascript-module",path:`./${o.tag}.js`,declarations:[{kind:"class",name:o.name,description:o.description||void 0,customElement:!0,tagName:o.tag,members:Object.entries(o.properties).map(([s,p])=>({kind:"field",name:s,description:p.description,type:{text:Dt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||Ut(s),reflects:p.reflect})),events:Object.entries(o.events).map(([s,p])=>({name:s,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:o.slots,cssProperties:o.cssProperties}],exports:[{kind:"js",name:o.name,declaration:{name:o.name,module:`./${o.tag}.js`}}]}))}}function an(t){if(!t.styles)return"";let o=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(o))return o;return`@scope (${t.tag}) {
830
- ${o}
831
- }`}function cn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Kr(t){let o=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
829
+ `}function qr(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([i,p])=>({kind:"field",name:i,description:p.description,type:{text:Dt(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||Ut(i),reflects:p.reflect})),events:Object.entries(s.events).map(([i,p])=>({name:i,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function an(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
830
+ ${s}
831
+ }`}function cn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Kr(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
832
832
  `);return`const definitions = ${JSON.stringify(c,null,2)};
833
833
  const escapeHTML = (value) => String(value ?? '')
834
834
  .replaceAll('&', '&amp;').replaceAll('<', '&lt;').replaceAll('>', '&gt;')
@@ -841,8 +841,8 @@ export function renderComponent(tag, props = {}, slots = {}) {
841
841
  const values = Object.fromEntries(Object.entries(definition.properties).map(([name, property]) => [name, property.default]));
842
842
  Object.assign(values, props);
843
843
  let template = definition.template
844
- .replace(new RegExp(${o}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
845
- .replace(new RegExp(${s}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
844
+ .replace(new RegExp(${s}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
845
+ .replace(new RegExp(${i}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
846
846
  .replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
847
847
  const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
848
848
  if (property.attribute === false || !(name in props)) return [];
@@ -862,7 +862,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
862
862
  }
863
863
 
864
864
  ${l}
865
- `}async function Vs(t){let o=Ee.resolve(t.inputDir),s=Ee.resolve(t.outputDir);if(!(await nn(o).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${o}`);let c=t.components?.length?t.components:(await Cr(o)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${o}`);let l=await Promise.all(c.map((x)=>zr(o,x,t)));l.sort((x,R)=>x.tag.localeCompare(R.tag));let m=l.filter((x,R)=>l.findIndex((k)=>k.tag===x.tag)!==R);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let u=l.filter((x,R)=>l.findIndex((k)=>k.name===x.name)!==R);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await br(s,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ee.join(s,x);return await Sr(k,R.endsWith(`
865
+ `}async function Vs(t){let s=Ee.resolve(t.inputDir),i=Ee.resolve(t.outputDir);if(!(await nn(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await Cr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>zr(s,x,t)));l.sort((x,R)=>x.tag.localeCompare(R.tag));let m=l.filter((x,R)=>l.findIndex((k)=>k.tag===x.tag)!==R);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let u=l.filter((x,R)=>l.findIndex((k)=>k.name===x.name)!==R);if(u.length)throw Error(`Duplicate component class name: ${u[0].name}`);await br(i,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ee.join(i,x);return await Sr(k,R.endsWith(`
866
866
  `)?R:`${R}
867
867
  `,"utf8"),y.push(k),k};await g("runtime.js",Nr());for(let x of l){if(await g(`${x.tag}.js`,Ur(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Wr(x));if(t.css!==!1&&x.styles){let R=x.shadowMode?x.styles:an(x);await g(`${x.tag}.css`,t.minify?cn(R):R)}}let b=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
868
868
  `);if(await g("index.js",b),await g("ssr.js",Kr(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
@@ -872,17 +872,17 @@ export declare function renderComponent(tag: string, props?: Record<string, unkn
872
872
  ${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
873
873
  `)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(qr(l),null,2));let S;if(t.css!==!1){let x=l.filter((R)=>!R.shadowMode&&R.styles).map(an).join(`
874
874
 
875
- `);if(x)S=await g("bundle.css",t.minify?cn(x):x)}let E;if(t.bundle!==!1){E=Ee.join(s,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(s,"index.js")],outdir:s,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(R){let k=R instanceof AggregateError?R.errors:[R],B=k.map((L)=>String(L).trim()).filter(Boolean).join(`
875
+ `);if(x)S=await g("bundle.css",t.minify?cn(x):x)}let E;if(t.bundle!==!1){E=Ee.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(R){let k=R instanceof AggregateError?R.errors:[R],B=k.map((L)=>String(L).trim()).filter(Boolean).join(`
876
876
  `);throw AggregateError(k,`Failed to bundle component library${B?`
877
877
  ${B}`:""}`)}if(!x.success){let R=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
878
878
  `);throw AggregateError(x.logs,`Failed to bundle component library${R?`
879
- ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await Promise.all(y.map(async(x)=>(await nn(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ee.join(s,`${x.tag}.js`)})),files:y,manifest:w,bundle:E,cssBundle:S,totalBytes:v.reduce((x,R)=>x+R,0)}}import Wt from"fs";import yt from"path";async function Xr(t){try{let s=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return[];let p=s[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(p))!==null){let u=m[1],y=m[2]||m[3]||m[4];if(!y)continue;let g={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)g.type=b[1].trim();if(u.match(/@required/i))g.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let E=u.split(`
880
- `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=E.join(" ").trim(),c.push(g)}if(c.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let g=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of g){let[w]=b.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(o){return console.error(`Error extracting props from ${t}:`,o),[]}}async function Gr(t){try{let o=await Bun.file(t).text(),s=o.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||o.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(s)return s[1].split(`
881
- `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Jr(t,o=!1,s){let p=yt.basename(t,".stx"),c=await Xr(t),l=await Gr(t),m="";if(o&&s)m=`<${s}></${s}>`;else{let u=c.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
879
+ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await Promise.all(y.map(async(x)=>(await nn(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ee.join(i,`${x.tag}.js`)})),files:y,manifest:w,bundle:E,cssBundle:S,totalBytes:v.reduce((x,R)=>x+R,0)}}import Wt from"fs";import yt from"path";async function Xr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let p=i[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(p))!==null){let u=m[1],y=m[2]||m[3]||m[4];if(!y)continue;let g={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)g.type=b[1].trim();if(u.match(/@required/i))g.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let E=u.split(`
880
+ `).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=E.join(" ").trim(),c.push(g)}if(c.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let g=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of g){let[w]=b.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(s){return console.error(`Error extracting props from ${t}:`,s),[]}}async function Gr(t){try{let s=await Bun.file(t).text(),i=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(i)return i[1].split(`
881
+ `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Jr(t,s=!1,i){let p=yt.basename(t,".stx"),c=await Xr(t),l=await Gr(t),m="";if(s&&i)m=`<${i}></${i}>`;else{let u=c.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
882
882
  `);m=`<${p}
883
883
  ${u}
884
- />`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:o,tag:s}}async function pn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let o=await Wt.promises.readdir(t,{withFileTypes:!0}),s=[];for(let p of o){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await pn(c);s.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))s.push(c)}return s}catch(o){return console.error(`Error finding component files in ${t}:`,o),[]}}async function Yr(t,o){try{if(!await r(t))return[];let s=await pn(t),p=[],c=new Map;if(o?.components?.length)for(let l of o.components)c.set(l.file,l);for(let l of s){let m=c.get(l),u=!!m,y=m?.tag,g=await Jr(l,u,y);p.push(g)}return p}catch(s){return console.error("Error generating component docs:",s),[]}}async function Qr(t){try{if(!await r(t))return[];let o=await Wt.promises.readdir(t,{withFileTypes:!0}),s=[];for(let p of o){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let c=yt.join(t,p.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=u?u[1].split(`
885
- `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,b=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=b.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let E=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=E.exec(l))!==null)v.add(S[1]);s.push({name:m,path:c,description:y,components:[...w],directives:[...v]})}return s}catch(o){return console.error("Error generating template docs:",o),[]}}async function Zr(t=[]){try{let o=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
884
+ />`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function pn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await pn(c);i.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function Yr(t,s){try{if(!await r(t))return[];let i=await pn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),u=!!m,y=m?.tag,g=await Jr(l,u,y);p.push(g)}return p}catch(i){return console.error("Error generating component docs:",i),[]}}async function Qr(t){try{if(!await r(t))return[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),i=[];for(let p of s){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let c=yt.join(t,p.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),u=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=u?u[1].split(`
885
+ `).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,b=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=b.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let E=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=E.exec(l))!==null)v.add(S[1]);i.push({name:m,path:c,description:y,components:[...w],directives:[...v]})}return i}catch(s){return console.error("Error generating template docs:",s),[]}}async function Zr(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
886
886
  <p>Welcome, {{ user.name }}!</p>
887
887
  @endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
888
888
  <p>Welcome back!</p>
@@ -902,7 +902,7 @@ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await
902
902
  <p>Page {{ page }}</p>
903
903
  @endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
904
904
  {{ This will be displayed as-is }}
905
- @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let s of t)o.push({name:s.name,description:s.description||"",hasEndTag:s.hasEndTag||!1,example:""});return o}catch(o){return console.error("Error generating directive docs:",o),[]}}function eo(t=[],o=[],s=[],p){let c=`# stx Documentation
905
+ @endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let i of t)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function eo(t=[],s=[],i=[],p){let c=`# stx Documentation
906
906
 
907
907
  `;if(p)c+=`${p}
908
908
 
@@ -922,9 +922,9 @@ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await
922
922
  `;c+=`
923
923
  `}if(l.example)c+=`#### Example
924
924
 
925
- `,c+="```html\n",c+=l.example,c+="\n```\n\n"}}if(o.length>0){c+=`## Templates
925
+ `,c+="```html\n",c+=l.example,c+="\n```\n\n"}}if(s.length>0){c+=`## Templates
926
926
 
927
- `;for(let l of o){if(c+=`### ${l.name}
927
+ `;for(let l of s){if(c+=`### ${l.name}
928
928
 
929
929
  `,l.description)c+=`${l.description}
930
930
 
@@ -932,19 +932,19 @@ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await
932
932
 
933
933
  `;if(l.directives&&l.directives.length>0)c+=`**Directives Used:** ${l.directives.join(", ")}
934
934
 
935
- `}}if(s.length>0){c+=`## Directives
935
+ `}}if(i.length>0){c+=`## Directives
936
936
 
937
937
  `,c+=`| Directive | Description | Has End Tag |
938
938
  `,c+=`| --------- | ----------- | ----------- |
939
- `;for(let l of s)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
939
+ `;for(let l of i)c+=`| @${l.name} | ${l.description||"-"} | ${l.hasEndTag?"Yes":"No"} |
940
940
  `;c+=`
941
- `;for(let l of s)if(l.example)c+=`### @${l.name}
941
+ `;for(let l of i)if(l.example)c+=`### @${l.name}
942
942
 
943
943
  `,c+=`${l.description||""}
944
944
 
945
945
  `,c+=`#### Example
946
946
 
947
- `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function to(t=[],o=[],s=[],p){let c=`<!DOCTYPE html>
947
+ `,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function to(t=[],s=[],i=[],p){let c=`<!DOCTYPE html>
948
948
  <html lang="en">
949
949
  <head>
950
950
  <meta charset="UTF-8">
@@ -1003,7 +1003,7 @@ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await
1003
1003
  <td>${m.required?"Yes":"No"}</td>
1004
1004
  <td>${m.default||"-"}</td>
1005
1005
  <td>${m.description||"-"}</td>
1006
- </tr>`;c+="</tbody></table>"}if(l.example)c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(o.length>0){c+="<h2>Templates</h2>";for(let l of o){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)c+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)c+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(s.length>0){c+="<h2>Directives</h2>",c+=`<table>
1006
+ </tr>`;c+="</tbody></table>"}if(l.example)c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}}if(s.length>0){c+="<h2>Templates</h2>";for(let l of s){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.components&&l.components.length>0)c+=`<p><strong>Components Used:</strong> ${l.components.join(", ")}</p>`;if(l.directives&&l.directives.length>0)c+=`<p><strong>Directives Used:</strong> ${l.directives.join(", ")}</p>`}}if(i.length>0){c+="<h2>Directives</h2>",c+=`<table>
1007
1007
  <thead>
1008
1008
  <tr>
1009
1009
  <th>Directive</th>
@@ -1011,44 +1011,44 @@ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await
1011
1011
  <th>Has End Tag</th>
1012
1012
  </tr>
1013
1013
  </thead>
1014
- <tbody>`;for(let l of s)c+=`<tr>
1014
+ <tbody>`;for(let l of i)c+=`<tr>
1015
1015
  <td>@${l.name}</td>
1016
1016
  <td>${l.description||"-"}</td>
1017
1017
  <td>${l.hasEndTag?"Yes":"No"}</td>
1018
- </tr>`;c+="</tbody></table>";for(let l of s)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return c+="</body></html>",c}function no(t=[],o=[],s=[],p){return JSON.stringify({components:t,templates:o,directives:s,extraContent:p||""},null,2)}async function ro(t){try{let{componentsDir:o,templatesDir:s,webComponentsConfig:p,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Wt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),o)console.log(`Components directory: ${o}`);if(s)console.log(`Templates directory: ${s}`);console.log(`Output directory: ${m}`);let u=[];if(l.components!==!1&&o)console.log("Generating component documentation..."),u=await Yr(o,p),console.log(`Found ${u.length} components`);let y=[];if(l.templates!==!1&&s)console.log("Generating template documentation..."),y=await Qr(s),console.log(`Found ${y.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await Zr(c),console.log(`Found ${g.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",E="";switch(b){case"markdown":S=eo(u,y,g,w),E="md";break;case"html":S=to(u,y,g,w),E="html";break;case"json":S=no(u,y,g,w),E="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=yt.join(m,`stx-docs.${E}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(o){return console.error("Error generating documentation:",o),!1}}async function Us(t){let o={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},s=t.componentsDir||T.componentsDir,p=t.templatesDir||".";return ro({componentsDir:s,templatesDir:p,webComponentsConfig:T.webComponents,customDirectives:T.customDirectives,config:o})}var mn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function pr(t,o={}){let s={...mn,...o};if(t.trim()==="")return`
1019
- `;let p=t;if(s.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=io(p,s),p=po(p,s),p=ao(p,s),s.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
1018
+ </tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}</code></pre>`}return c+="</body></html>",c}function oo(t=[],s=[],i=[],p){return JSON.stringify({components:t,templates:s,directives:i,extraContent:p||""},null,2)}async function io(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:p,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Wt.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let u=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),u=await Yr(s,p),console.log(`Found ${u.length} components`);let y=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),y=await Qr(i),console.log(`Found ${y.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await Zr(c),console.log(`Found ${g.length} directives`);let b=l.format||"markdown",w=l.extraContent,S="",E="";switch(b){case"markdown":S=eo(u,y,g,w),E="md";break;case"html":S=to(u,y,g,w),E="html";break;case"json":S=oo(u,y,g,w),E="json";break;default:throw Error(`Unsupported documentation format: ${b}`)}let v=yt.join(m,`stx-docs.${E}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function Us(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},i=t.componentsDir||T.componentsDir,p=t.templatesDir||".";return io({componentsDir:i,templatesDir:p,webComponentsConfig:T.webComponents,customDirectives:T.customDirectives,config:s})}var mn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function pr(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
1019
+ `;let p=t;if(i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=lo(p,i),p=mo(p,i),p=po(p,i),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
1020
1020
  `).replace(/\r/g,`
1021
1021
  `),!p.endsWith(`
1022
1022
  `))p+=`
1023
- `;return p}function Ws(t,o={}){let s={...mn,...o};if(t.trim()==="")return`
1023
+ `;return p}function Ws(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
1024
1024
  `;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,u,y)=>{let g=u.split(`
1025
1025
  `),b=g.filter((x)=>x.trim().length>0);if(b.length===0)return c;let w=Math.min(...b.map((x)=>{let R=x.match(/^( *)/);return R?R[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
1026
- `),v=pr(S,s).trimEnd().split(`
1026
+ `),v=pr(S,i).trimEnd().split(`
1027
1027
  `).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
1028
1028
  `);return`${l}\`\`\`${m}
1029
1029
  ${v}
1030
- ${l}\`\`\``}),s.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
1030
+ ${l}\`\`\``}),i.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
1031
1031
  `).replace(/\r/g,`
1032
1032
  `),!p.endsWith(`
1033
1033
  `))p+=`
1034
- `;return p}function so(t){let o=t,s=[],p="__PROTECTED_BLOCK_";return o=o.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=s.length;return s.push(c),`${p}${l}__`}),o=o.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1034
+ `;return p}function co(t){let s=t,i=[],p="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=i.length;return i.push(c),`${p}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1035
1035
  $1
1036
- `),o=o.replace(/(@end\w+)/g,`
1036
+ `),s=s.replace(/(@end\w+)/g,`
1037
1037
  $1
1038
- `),o=o.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1038
+ `),s=s.replace(/(@(?:else|elseif|empty)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
1039
1039
  $1
1040
- `),o=o.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
1040
+ `),s=s.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
1041
1041
  $1
1042
- `),o=o.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,u)=>{let y=u.substring(m+c.length,Math.min(u.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&y.match(new RegExp(`^</${g}>`)))return c;return`
1043
- ${c}`}),o=o.replace(/(>)(<\/)/g,(c,l,m,u,y)=>{let g=y.substring(Math.max(0,u-50),u),w=y.substring(u+c.length,Math.min(y.length,u+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
1044
- ${m}`}),o=o.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let y=u.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],b=new RegExp(`<${g}[^>]*>$`);if(g&&y.match(b))return c;return`${c}
1045
- `}),o=o.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>s[Number.parseInt(l,10)]),o=o.replace(/\n{2,}/g,`
1046
- `),o=o.split(`
1042
+ `),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,u)=>{let y=u.substring(m+c.length,Math.min(u.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&y.match(new RegExp(`^</${g}>`)))return c;return`
1043
+ ${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,u,y)=>{let g=y.substring(Math.max(0,u-50),u),w=y.substring(u+c.length,Math.min(y.length,u+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
1044
+ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let y=u.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],b=new RegExp(`<${g}[^>]*>$`);if(g&&y.match(b))return c;return`${c}
1045
+ `}),s=s.replace(new RegExp(`${p}(\\d+)__`,"g"),(c,l)=>i[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
1046
+ `),s=s.split(`
1047
1047
  `).map((c)=>c.trim()).join(`
1048
- `),o=o.replace(/^\n+/,"").replace(/\n+$/,""),o}function io(t,o){let p=so(t).split(`
1049
- `),c=[],l=0,m=!1,u=o.useTabs?"\t":" ".repeat(o.indentSize);for(let y=0;y<p.length;y++){let g=p[y],b=g.trim();if(b===""){c.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let E=b===">";if(fn(b)&&!b.startsWith("<")&&!b.startsWith("@")){c.push(u.repeat(l)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),R=b.startsWith("@")&&lo(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),B=b.startsWith("<!--"),L=b.startsWith("</"),j=b.startsWith("<")&&!L&&!B&&!k,P=b.includes("/>")||co(b),I=fn(b);if(L||v)l=Math.max(0,l-1);let F=x?Math.max(0,l-1):l;if(E)c.push(g);else c.push(u.repeat(F)+b);if(j&&!P&&!I&&!E||R)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1050
- `)}function ao(t,o){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(s,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(s,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),o.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(s,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(s,p)=>`{!! ${p.trim()} !!}`);return t}function co(t){let o=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let s=t.match(/<(\w+)/);if(s){let p=s[1];return o.includes(p.toLowerCase())}return!1}function fn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function lo(t){let o=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let s of o)if(t.startsWith(`@${s}`))return!t.includes(`@end${s}`);return!1}function po(t,o){if(!o.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(s,p,c)=>{if(!c.trim())return s;if(c.includes("<")||c.includes(`
1051
- `)||c.includes("@"))return s;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.sort((g,b)=>{if(g.name==="id")return-1;if(b.name==="id")return 1;if(g.name==="class")return-1;if(b.name==="class")return 1;return g.name.localeCompare(b.name)});let y=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import hn from"fs";import Vt from"path";async function qs(t="index.stx",o={}){try{let s=o.force||!1,p=Vt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!s)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(p);if(!hn.existsSync(c))hn.mkdirSync(c,{recursive:!0});let l;if(o.template){let m=Vt.resolve(process.cwd(),o.template);if(!await Bun.file(m).exists())throw Error(`Template file ${o.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${o.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${o.template}`)}else if(o.preset)l=xn(o.preset),console.warn(`Using '${o.preset}' preset template`);else l=xn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(s){return console.error(`Error creating file: ${s instanceof Error?s.message:String(s)}`),!1}}function xn(t){switch(t){case"basic":return vn();case"component":return uo();case"layout":return fo();case"blog":return mo();case"api":return go();case"app":return ho();default:return vn()}}function vn(){return`<script>
1048
+ `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function lo(t,s){let p=co(t).split(`
1049
+ `),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let y=0;y<p.length;y++){let g=p[y],b=g.trim();if(b===""){c.push("");continue}let w=b.match(/<script\b/i),S=b.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let E=b===">";if(fn(b)&&!b.startsWith("<")&&!b.startsWith("@")){c.push(u.repeat(l)+b);continue}let v=b.startsWith("@end"),x=b.startsWith("@else")||b.startsWith("@elseif"),R=b.startsWith("@")&&fo(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),B=b.startsWith("<!--"),L=b.startsWith("</"),j=b.startsWith("<")&&!L&&!B&&!k,P=b.includes("/>")||uo(b),I=fn(b);if(L||v)l=Math.max(0,l-1);let F=x?Math.max(0,l-1):l;if(E)c.push(g);else c.push(u.repeat(F)+b);if(j&&!P&&!I&&!E||R)l++;if(w)m=!0;if(S)m=!1}return c.join(`
1050
+ `)}function po(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,p)=>`{!! ${p.trim()} !!}`);return t}function uo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let p=i[1];return s.includes(p.toLowerCase())}return!1}function fn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function fo(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function mo(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,p,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
1051
+ `)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.sort((g,b)=>{if(g.name==="id")return-1;if(b.name==="id")return 1;if(g.name==="class")return-1;if(b.name==="class")return 1;return g.name.localeCompare(b.name)});let y=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import hn from"fs";import Vt from"path";async function qs(t="index.stx",s={}){try{let i=s.force||!1,p=Vt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(p);if(!hn.existsSync(c))hn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=Vt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=xn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=xn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function xn(t){switch(t){case"basic":return vn();case"component":return go();case"layout":return ho();case"blog":return yo();case"api":return bo();case"app":return xo();default:return vn()}}function vn(){return`<script>
1052
1052
  const title = "My stx Page"
1053
1053
  const description = "A page built with stx"
1054
1054
  const features = [
@@ -1073,7 +1073,7 @@ const features = [
1073
1073
  </div>
1074
1074
  @endforeach
1075
1075
  </main>
1076
- @endsection`}function uo(){return`{{-- Component: Card --}}
1076
+ @endsection`}function go(){return`{{-- Component: Card --}}
1077
1077
  {{-- Props: title, variant, collapsible --}}
1078
1078
  {{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
1079
1079
  <script>
@@ -1118,7 +1118,7 @@ const features = [
1118
1118
  .card.collapsed .card__toggle { transform: rotate(-90deg); }
1119
1119
  .card__body { padding: 1rem; }
1120
1120
  .card.collapsed .card__body { display: none; }
1121
- </style>`}function fo(){return`<!DOCTYPE html>
1121
+ </style>`}function ho(){return`<!DOCTYPE html>
1122
1122
  <html lang="en">
1123
1123
  <head>
1124
1124
  <meta charset="UTF-8">
@@ -1169,7 +1169,7 @@ const features = [
1169
1169
 
1170
1170
  @yield('scripts')
1171
1171
  </body>
1172
- </html>`}function mo(){return`<script>
1172
+ </html>`}function yo(){return`<script>
1173
1173
  // Article metadata
1174
1174
  const title = "My Blog Post"
1175
1175
  const author = "Your Name"
@@ -1214,7 +1214,7 @@ const features = [
1214
1214
  <p>Wrap up your thoughts here.</p>
1215
1215
  </div>
1216
1216
  </article>
1217
- @endsection`}function go(){return`<script>
1217
+ @endsection`}function bo(){return`<script>
1218
1218
  // API endpoint configuration
1219
1219
  const endpoint = "/api/data"
1220
1220
  const method = "GET"
@@ -1249,7 +1249,7 @@ const features = [
1249
1249
  }
1250
1250
  @else
1251
1251
  {{ JSON.stringify(data, null, 2) }}
1252
- @endif`}function ho(){return`<!DOCTYPE html>
1252
+ @endif`}function xo(){return`<!DOCTYPE html>
1253
1253
  <html lang="en">
1254
1254
  <head>
1255
1255
  <meta charset="UTF-8">
@@ -1474,7 +1474,7 @@ const features = [
1474
1474
  })();
1475
1475
  </script>
1476
1476
  </body>
1477
- </html>`}var Ks="f9c3713";function Do(t){return t}function Oo(t){return t}var Sn=`
1477
+ </html>`}var Ks="f9c3713";function Di(t){return t}function Oi(t){return t}var Sn=`
1478
1478
  <script data-stx-helpers>
1479
1479
  (function() {
1480
1480
  'use strict'
@@ -1785,11 +1785,11 @@ else {
1785
1785
 
1786
1786
  })()
1787
1787
  </script>
1788
- `;import Me from"fs";import Te from"path";function An(t){try{return Me.statSync(t).mtimeMs}catch{return null}}function Mt(t,o){let s=Math.max(0,Math.round((o-t)/1000));if(s<60)return`${s}s ago`;if(s<3600)return`${Math.round(s/60)}m ago`;return`${Math.round(s/3600)}h ago`}function Pi(t,o){try{return globalThis.Bun?.resolveSync(t,o)??null}catch{return null}}function Dn(t,o="stx"){let s=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(s,"pantry","@stacksjs",o);if(Me.existsSync(c))return c;let l=Te.dirname(s);if(l===s)break;s=l}return null}var Mn=["@stacksjs/stx","bun-plugin-stx"];function Oi(t){try{let o=Me.readFileSync(Te.join(t,"package.json"),"utf8"),s=JSON.parse(o)?.version;return typeof s==="string"?s:null}catch{return null}}function Ai(t,o=6){let s=Te.resolve(t),p=[],c=new Set;function l(u,y){if(y>o)return;let g;try{g=Me.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of Mn){let S=Te.join(u,w),E=Oi(S);if(E!==null)p.push({name:w,version:E,dir:Te.relative(s,S)||S,nested:y>0})}let b;try{b=Me.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of b){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=Te.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let R=Te.join(S,x.name,"node_modules");if(Me.existsSync(R))l(R,y+1)}continue}let E=Te.join(S,"node_modules");if(Me.existsSync(E))l(E,y+1)}}let m=Te.join(s,"node_modules");if(Me.existsSync(m))l(m,0);return p}function Di(t){let o=[];for(let s of Mn){let p=t.filter((m)=>m.name===s);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){o.push({name:`${s} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}o.push({name:`${s} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${s}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${s}/package.json' -exec grep -H '"version"' {} +`})}return o}async function fr(t={}){let o=t.cwd?Te.resolve(t.cwd):process.cwd(),s=t.resolve??Pi,p=Date.now(),c=[],l=s("@stacksjs/stx",o);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=s("bun-plugin-stx",o);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let y of Di(Ai(o)))c.push(y);let u=Dn(o,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=Te.join(u,"src/signals.ts"),g=[Te.join(u,"dist/index.js"),Te.join(u,"dist/signals.js")].find((v)=>Me.existsSync(v))||null,b=An(y),w=g?An(g):null;if(b==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<b){let v=Math.round((b-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Mt(w,p)}) is OLDER than src/signals.ts (${Mt(b,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Mt(b,p)}, dist ${Mt(w,p)})`});let S=Te.join(o,"node_modules/@stacksjs/stx"),E=null;try{E=Me.lstatSync(S)}catch{E=null}if(!E)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(E.isSymbolicLink()){let v=null;try{v=Me.realpathSync(S)}catch{}let x=(()=>{try{return Me.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(y){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:c,ok:!c.some((y)=>y.status==="error")}}function gr(t){let o={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},s=["stx runtime resolution:"];for(let p of t.checks)if(s.push(` ${o[p.status]} ${p.name}: ${p.detail}`),p.fix)s.push(` \u2192 ${p.fix}`);return s.push(""),s.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),s.join(`
1789
- `)}var ft={name:"bun-plugin-stx",async setup(t){let s={...await i(),...t.config?.stx},p=new Set,c=s.webComponents?.enabled?`./${_t.relative(_t.dirname(t.config?.outdir||"dist"),s.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(s.webComponents?.enabled)try{let m=await qn(s,p);if(l.push(...m),s.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(s.cache&&s.cachePath){let x=await Zt(m,s);if(x){if(s.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let y=await te(()=>Bun.file(m).text(),"",(x)=>{throw new un(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new un(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:b,allScripts:w}=U.time("script-extraction",()=>{let x=y,R=Z(y);if(R)x=R.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],B="",L=[];for(let P of k){let I=P.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=P.match(/<script\b([^>]*)>/i),G=F?F[1]:"";if(/\bserver\b/i.test(G))B=I;else L.push(P)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:B,templateContent:j,allScripts:L}}),S={__filename:m,__dirname:_t.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>d(g,S,m),void 0,(x)=>{let R=new K(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(_.log(R,{filePath:m,scriptContent:g}),s.debug)throw R});let v=await U.timeAsync("directive-processing",async()=>await n(b,S,m,s,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-fbhgabf2.js"),R=x(w.join(`
1788
+ `;import Me from"fs";import Te from"path";function An(t){try{return Me.statSync(t).mtimeMs}catch{return null}}function Mt(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Ei(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Dn(t,s="stx"){let i=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(i,"pantry","@stacksjs",s);if(Me.existsSync(c))return c;let l=Te.dirname(i);if(l===i)break;i=l}return null}var Mn=["@stacksjs/stx","bun-plugin-stx"];function Pi(t){try{let s=Me.readFileSync(Te.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Ai(t,s=6){let i=Te.resolve(t),p=[],c=new Set;function l(u,y){if(y>s)return;let g;try{g=Me.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of Mn){let S=Te.join(u,w),E=Pi(S);if(E!==null)p.push({name:w,version:E,dir:Te.relative(i,S)||S,nested:y>0})}let b;try{b=Me.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of b){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=Te.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let R=Te.join(S,x.name,"node_modules");if(Me.existsSync(R))l(R,y+1)}continue}let E=Te.join(S,"node_modules");if(Me.existsSync(E))l(E,y+1)}}let m=Te.join(i,"node_modules");if(Me.existsSync(m))l(m,0);return p}function Mi(t){let s=[];for(let i of Mn){let p=t.filter((m)=>m.name===i);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function fr(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),i=t.resolve??Ei,p=Date.now(),c=[],l=i("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let y of Mi(Ai(s)))c.push(y);let u=Dn(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=Te.join(u,"src/signals.ts"),g=[Te.join(u,"dist/index.js"),Te.join(u,"dist/signals.js")].find((v)=>Me.existsSync(v))||null,b=An(y),w=g?An(g):null;if(b==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<b){let v=Math.round((b-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Mt(w,p)}) is OLDER than src/signals.ts (${Mt(b,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Mt(b,p)}, dist ${Mt(w,p)})`});let S=Te.join(s,"node_modules/@stacksjs/stx"),E=null;try{E=Me.lstatSync(S)}catch{E=null}if(!E)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(E.isSymbolicLink()){let v=null;try{v=Me.realpathSync(S)}catch{}let x=(()=>{try{return Me.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(y){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:c,ok:!c.some((y)=>y.status==="error")}}function gr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let p of t.checks)if(i.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)i.push(` \u2192 ${p.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
1789
+ `)}var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},p=new Set,c=i.webComponents?.enabled?`./${_t.relative(_t.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await qn(i,p);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(i.cache&&i.cachePath){let x=await Zt(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let y=await te(()=>Bun.file(m).text(),"",(x)=>{throw new un(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new un(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:b,allScripts:w}=U.time("script-extraction",()=>{let x=y,R=Z(y);if(R)x=R.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],B="",L=[];for(let P of k){let I=P.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=P.match(/<script\b([^>]*)>/i),G=F?F[1]:"";if(/\bserver\b/i.test(G))B=I;else L.push(P)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:B,templateContent:j,allScripts:L}}),S={__filename:m,__dirname:_t.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>d(g,S,m),void 0,(x)=>{let R=new K(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(_.log(R,{filePath:m,scriptContent:g}),i.debug)throw R});let v=await U.timeAsync("directive-processing",async()=>await n(b,S,m,i,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-cs3507d0.js"),R=x(w.join(`
1790
1790
  `),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+R+`
1791
1791
  `+v.slice(k);else v+=`
1792
- ${R}`}if(v=await q(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await Qt(m,v,u,s),s.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new K(`Plugin processing failed: ${String(u)}`,m);if(_.log(y,{filePath:m,buildConfig:t.config}),Et.logDetailedError(y,{filePath:m,plugin:"bun-plugin-stx"}),s.debug)console.error("stx Plugin Error:",y);let g=y,b=g.line||null,w=g.context||null;return{contents:s.debug||D()?`<!DOCTYPE html>
1792
+ ${R}`}if(v=await q(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await Qt(m,v,u,i),i.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new K(`Plugin processing failed: ${String(u)}`,m);if(_.log(y,{filePath:m,buildConfig:t.config}),Et.logDetailedError(y,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",y);let g=y,b=g.line||null,w=g.context||null;return{contents:i.debug||D()?`<!DOCTYPE html>
1793
1793
  <html lang="en">
1794
1794
  <head>
1795
1795
  <meta charset="UTF-8">
@@ -1849,12 +1849,12 @@ ${R}`}if(v=await q(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await Qt
1849
1849
  <h1>Something went wrong</h1>
1850
1850
  <p>An internal error occurred. Please try again later.</p>
1851
1851
  </body>
1852
- </html>`,loader:"html"}}})}};async function yn(t,o={}){let s=o.port||3000,p=o.watch!==!1,c=o.hotReload!==!1&&p,l=null,m=o.hmrPort||s+1,u=Se.resolve(t);if(!Ne.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,o);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=a(process.cwd(),"output");Ne.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,b=async()=>{try{let I={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},F=await Bun.build({entrypoints:[u],outdir:y,plugins:[I,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...o.stxOptions});if(!F.success)return console.error(`${e.red}Build failed:${e.reset}`,F.logs),!1;let G=F.outputs.find(($e)=>$e.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(I){return console.error(`${e.red}Error building stx file:${e.reset}`,I),!1}};if(!await b())return!1;let S=Se.dirname(u);await vt(S);let E=s;try{if(E=await Ye(s),E!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${E} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let I=o.hmrPort||E+1;l=Pt({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,R;try{let{loadStxConfig:I}=await import("./chunk-gy7t9wd0.js"),F=await I();if(R=o.stxOptions?.serverApi??F.serverApi,F?.apiRouter)x=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){v=F.apiRoutes;let G=Object.keys(v).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:oe}=await import("./chunk-06qhvtsv.js"),$e=F.broadcasting;await G($e);let he=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Oe=Se.join(process.cwd(),"channels.ts");if(Ne.existsSync(Oe))try{let le=await oe(Oe);console.log(`${e.blue}Loaded ${e.bright}${le} broadcast channel${le!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(le){console.warn(`${e.yellow}Failed to load channels.ts: ${le.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:B}=await import("./chunk-93wp5h7v.js"),L=await k(process.cwd(),R);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${E}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let j=zi({port:E,async fetch(I){return At(I,await(async()=>{let F=new URL(I.url);if([y,Se.dirname(u),Se.join(process.cwd(),"public")].some((le)=>B(Se.join(le,F.pathname),process.cwd(),R)))return new Response("Not Found",{status:404});if(x)try{let le=await x.handleRequest(I);if(le.status!==404)return le}catch{}if(v[F.pathname])try{return await v[F.pathname](I)}catch(le){return new Response(JSON.stringify({error:le.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await L(I);if(G)return G;if(F.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Xe(W,m);if(o.native)if(W.includes("<head>"))W=W.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(o.titlebarHidden)if(W.includes("<head>"))W=W.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let oe=Se.join(y,F.pathname);if(Ne.existsSync(oe)&&Ne.statSync(oe).isFile()){let le=Bun.file(oe),W=Se.extname(oe).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}let $e=Se.dirname(u),he=Se.join($e,F.pathname);if(Ne.existsSync(he)&&Ne.statSync(he).isFile()){let le=Bun.file(he),W=Se.extname(he).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}let Oe=Se.join(process.cwd(),"public",F.pathname);if(Ne.existsSync(Oe)&&Ne.statSync(Oe).isFile()){let le=Bun.file(Oe),W=Se.extname(Oe).toLowerCase(),H="application/octet-stream";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}return new Response("Not Found",{status:404})})())},error(I){return new Response(`<pre>${I}
1852
+ </html>`,loader:"html"}}})}};async function yn(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=Se.resolve(t);if(!Ne.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=a(process.cwd(),"output");Ne.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,b=async()=>{try{let I={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},F=await Bun.build({entrypoints:[u],outdir:y,plugins:[I,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!F.success)return console.error(`${e.red}Build failed:${e.reset}`,F.logs),!1;let G=F.outputs.find(($e)=>$e.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(I){return console.error(`${e.red}Error building stx file:${e.reset}`,I),!1}};if(!await b())return!1;let S=Se.dirname(u);await vt(S);let E=i;try{if(E=await Ye(i),E!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${E} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let I=s.hmrPort||E+1;l=Pt({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,R;try{let{loadStxConfig:I}=await import("./chunk-4gjc61wn.js"),F=await I();if(R=s.stxOptions?.serverApi??F.serverApi,F?.apiRouter)x=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){v=F.apiRoutes;let G=Object.keys(v).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:oe}=await import("./chunk-ns7e951g.js"),$e=F.broadcasting;await G($e);let he=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Oe=Se.join(process.cwd(),"channels.ts");if(Ne.existsSync(Oe))try{let le=await oe(Oe);console.log(`${e.blue}Loaded ${e.bright}${le} broadcast channel${le!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(le){console.warn(`${e.yellow}Failed to load channels.ts: ${le.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:B}=await import("./chunk-d3yrvve4.js"),L=await k(process.cwd(),R);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${E}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let j=Ni({port:E,async fetch(I){return At(I,await(async()=>{let F=new URL(I.url);if([y,Se.dirname(u),Se.join(process.cwd(),"public")].some((le)=>B(Se.join(le,F.pathname),process.cwd(),R)))return new Response("Not Found",{status:404});if(x)try{let le=await x.handleRequest(I);if(le.status!==404)return le}catch{}if(v[F.pathname])try{return await v[F.pathname](I)}catch(le){return new Response(JSON.stringify({error:le.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await L(I);if(G)return G;if(F.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Xe(W,m);if(s.native)if(W.includes("<head>"))W=W.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(s.titlebarHidden)if(W.includes("<head>"))W=W.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let oe=Se.join(y,F.pathname);if(Ne.existsSync(oe)&&Ne.statSync(oe).isFile()){let le=Bun.file(oe),W=Se.extname(oe).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}let $e=Se.dirname(u),he=Se.join($e,F.pathname);if(Ne.existsSync(he)&&Ne.statSync(he).isFile()){let le=Bun.file(he),W=Se.extname(he).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}let Oe=Se.join(process.cwd(),"public",F.pathname);if(Ne.existsSync(Oe)&&Ne.statSync(Oe).isFile()){let le=Bun.file(Oe),W=Se.extname(Oe).toLowerCase(),H="application/octet-stream";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":H}})}return new Response("Not Found",{status:404})})())},error(I){return new Response(`<pre>${I}
1853
1853
  ${I.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
1854
1854
  ${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(`
1855
1855
  ${e.bright}\u2192 ${e.cyan}http://localhost:${E}/${e.reset}`),console.log(`
1856
1856
  ${e.yellow}Routes:${e.reset}`);let P=Se.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${P}${e.reset}`),console.log(`
1857
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(j.url.toString(),()=>{if(p)Ne.watch(Se.dirname(u),{recursive:!0}).close();j.stop()}),o.native){let I=await Bun.file(u).text(),F=Tt(I);await dt(E,{title:Se.basename(u,".stx"),titlebarHidden:o.titlebarHidden===!0,nativeSidebar:!!F,sidebarConfig:F})}if(p){let I=Se.dirname(u);console.log(`${e.blue}Watching ${e.bright}${I}${e.reset} for changes...`);let F=Ne.watch(I,{recursive:!0},async(G,oe)=>{if(!oe||Rt(oe))return;if(Ct(oe)){console.log(`${e.yellow}File ${e.bright}${oe}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee();let $e=await b();if(await en(S),c&&l)if($e)l.reload(oe);else l.error("Build failed - check console for details")}else if($t(oe)){if(console.log(`${e.cyan}CSS ${e.bright}${oe}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(oe)}});process.on("SIGINT",()=>{if(F.close(),l)ht();j.stop(),process.exit(0)})}return!0}var{serve:Ni}=globalThis.Bun;import it from"fs";import Pe from"path";function Vn(t){if(t.length===0)return"";if(t.length===1)return t[0];let o=t.map((p)=>p.split(Pe.sep)),s=[];for(let p=0;p<o[0].length;p++){let c=o[0][p];if(o.every((l)=>l[p]===c))s.push(c);else break}return s.join(Pe.sep)}async function bn(t,o={}){let s=o.port||3000,p=o.watch!==!1;for(let v of t){let x=Pe.resolve(v);if(!it.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");it.mkdirSync(c,{recursive:!0});let l=Vn(t.map((v)=>Pe.dirname(Pe.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],y=async()=>{try{for(let v of t){let x=Pe.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:B}=await ce(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),L=o.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,j=L?.defaultTheme||"github-dark",P=["github-dark"],I=L?.additionalThemes||[],G=[...new Set([...P,...I])].map((Oe)=>`<option value="${Oe}"${Oe===j?" selected":""}>${Oe}</option>`).join(`
1857
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(j.url.toString(),()=>{if(p)Ne.watch(Se.dirname(u),{recursive:!0}).close();j.stop()}),s.native){let I=await Bun.file(u).text(),F=Tt(I);await dt(E,{title:Se.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!F,sidebarConfig:F})}if(p){let I=Se.dirname(u);console.log(`${e.blue}Watching ${e.bright}${I}${e.reset} for changes...`);let F=Ne.watch(I,{recursive:!0},async(G,oe)=>{if(!oe||Rt(oe))return;if(Ct(oe)){console.log(`${e.yellow}File ${e.bright}${oe}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee();let $e=await b();if(await en(S),c&&l)if($e)l.reload(oe);else l.error("Build failed - check console for details")}else if($t(oe)){if(console.log(`${e.cyan}CSS ${e.bright}${oe}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(oe)}});process.on("SIGINT",()=>{if(F.close(),l)ht();j.stop(),process.exit(0)})}return!0}var{serve:Ui}=globalThis.Bun;import it from"fs";import Pe from"path";function Vn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Pe.sep)),i=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))i.push(c);else break}return i.join(Pe.sep)}async function bn(t,s={}){let i=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Pe.resolve(v);if(!it.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");it.mkdirSync(c,{recursive:!0});let l=Vn(t.map((v)=>Pe.dirname(Pe.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],y=async()=>{try{for(let v of t){let x=Pe.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:B}=await ce(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:T.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),L=s.markdown?.syntaxHighlighting||T.markdown?.syntaxHighlighting,j=L?.defaultTheme||"github-dark",P=["github-dark"],I=L?.additionalThemes||[],G=[...new Set([...P,...I])].map((Oe)=>`<option value="${Oe}"${Oe===j?" selected":""}>${Oe}</option>`).join(`
1858
1858
  `),oe=`
1859
1859
  <!DOCTYPE html>
1860
1860
  <html lang="en">
@@ -2017,17 +2017,17 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(j.u
2017
2017
  </script>
2018
2018
  </body>
2019
2019
  </html>
2020
- `,he=`/${Pe.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:oe,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(P){P.onResolve({filter:/^\/(images|fonts|assets|public)\//},(I)=>({path:I.path,external:!0}))}},B;try{let P=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ft],define:{"process.env.NODE_ENV":'"development"'},...o.stxOptions});if(!P.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,De(P.logs,x));continue}let I=P.outputs.find((F)=>F.path.endsWith(".html"));if(!I){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}B=await Bun.file(I.path).text()}catch(P){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
2021
- ${De(P,x)}`);continue}let j=`/${Pe.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:P,params:I}=ir(j,{page:!0});u.push({pattern:P,paramNames:I,filePath:x,routeTemplate:j,fileType:"stx"}),m[j]={filePath:x,content:B,fileType:"stx"}}else m[j||"/"]={filePath:x,content:B,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,De(v)),!1}};if(!await y())return!1;let b=s;try{if(b=await Ye(s),b!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${b} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${b}/${e.reset}...`);let w=Ni({port:b,async fetch(v){let x=new URL(v.url),R=Pe.join(process.cwd(),"public",x.pathname);if(it.existsSync(R)&&it.statSync(R).isFile()){let L=Bun.file(R),j=Pe.extname(R).toLowerCase(),P="application/octet-stream";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),F=await L.text(),G=I.transformSync(F);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":P="text/html";break;case".css":P="text/css";break;case".js":P="text/javascript";break;case".json":P="application/json";break;case".png":P="image/png";break;case".jpg":case".jpeg":P="image/jpeg";break;case".gif":P="image/gif";break;case".svg":P="image/svg+xml";break;case".ico":P="image/x-icon";break;case".woff":P="font/woff";break;case".woff2":P="font/woff2";break;case".ttf":P="font/ttf";break;case".otf":P="font/otf";break;case".eot":P="application/vnd.ms-fontobject";break}return new Response(L,{headers:{"Content-Type":P}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let L of u){let j=x.pathname.match(L.pattern);if(j){let P=m[L.routeTemplate];if(P){let I={};for(let oe=0;oe<L.paramNames.length;oe++)I[L.paramNames[oe]]=decodeURIComponent(j[oe+1]);let F=P.content,G=`<script>window.__routeParams = ${JSON.stringify(I)};</script>`;if(F.includes("</head>"))F=F.replace("</head>",`${G}
2020
+ `,he=`/${Pe.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:oe,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(P){P.onResolve({filter:/^\/(images|fonts|assets|public)\//},(I)=>({path:I.path,external:!0}))}},B;try{let P=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ft],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!P.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,De(P.logs,x));continue}let I=P.outputs.find((F)=>F.path.endsWith(".html"));if(!I){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}B=await Bun.file(I.path).text()}catch(P){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
2021
+ ${De(P,x)}`);continue}let j=`/${Pe.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:P,params:I}=or(j,{page:!0});u.push({pattern:P,paramNames:I,filePath:x,routeTemplate:j,fileType:"stx"}),m[j]={filePath:x,content:B,fileType:"stx"}}else m[j||"/"]={filePath:x,content:B,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,De(v)),!1}};if(!await y())return!1;let b=i;try{if(b=await Ye(i),b!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${b} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${b}/${e.reset}...`);let w=Ui({port:b,async fetch(v){let x=new URL(v.url),R=Pe.join(process.cwd(),"public",x.pathname);if(it.existsSync(R)&&it.statSync(R).isFile()){let L=Bun.file(R),j=Pe.extname(R).toLowerCase(),P="application/octet-stream";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),F=await L.text(),G=I.transformSync(F);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":P="text/html";break;case".css":P="text/css";break;case".js":P="text/javascript";break;case".json":P="application/json";break;case".png":P="image/png";break;case".jpg":case".jpeg":P="image/jpeg";break;case".gif":P="image/gif";break;case".svg":P="image/svg+xml";break;case".ico":P="image/x-icon";break;case".woff":P="font/woff";break;case".woff2":P="font/woff2";break;case".ttf":P="font/ttf";break;case".otf":P="font/otf";break;case".eot":P="application/vnd.ms-fontobject";break}return new Response(L,{headers:{"Content-Type":P}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let L of u){let j=x.pathname.match(L.pattern);if(j){let P=m[L.routeTemplate];if(P){let I={};for(let oe=0;oe<L.paramNames.length;oe++)I[L.paramNames[oe]]=decodeURIComponent(j[oe+1]);let F=P.content,G=`<script>window.__routeParams = ${JSON.stringify(I)};</script>`;if(F.includes("</head>"))F=F.replace("</head>",`${G}
2022
2022
  </head>`);else F=G+F;k={...P,content:F}}break}}if(k)return f(k.content).then((L)=>{if(L.includes("</head>"))L=L.replace("</head>",`${Sn}
2023
2023
  </head>`);return new Response(L,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let B=Pe.join(c,x.pathname);if(it.existsSync(B)&&it.statSync(B).isFile()){let L=Bun.file(B),j=Pe.extname(B).toLowerCase(),P="text/plain";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),F=await L.text(),G=I.transformSync(F);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":P="text/html";break;case".css":P="text/css";break;case".js":P="text/javascript";break;case".json":P="application/json";break;case".png":P="image/png";break;case".jpg":case".jpeg":P="image/jpeg";break;case".gif":P="image/gif";break;case".svg":P="image/svg+xml";break;case".ico":P="image/x-icon";break;case".woff":P="font/woff";break;case".woff2":P="font/woff2";break;case".ttf":P="font/ttf";break;case".otf":P="font/otf";break;case".eot":P="application/vnd.ms-fontobject";break}return new Response(L,{headers:{"Content-Type":P}})}if(x.pathname!=="/"&&m["/"]){let L=ne(v);return f(m["/"].content).then((j)=>{if(L){let P=j.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(P){let I=j.match(/<title[^>]*>([\s\S]*?)<\/title>/i),F=I?I[1]:"",G=`<!DOCTYPE html><html><head><title>${Wn(F)}</title></head><body><main>${P[1]}</main></body></html>`;return new Response(G,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...C(),"Cache-Control":_e,Pragma:"no-cache",Expires:"0"}})}}return new Response(j,{headers:{"Content-Type":"text/html",...C(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
2024
2024
  ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
2025
2025
  ${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(`
2026
2026
  ${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
2027
2027
  ${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),E=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Pe.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");E.push({route:x,filePath:Pe.relative(process.cwd(),v.filePath),fileType:"stx"})}if(E.sort((v,x)=>v.route.localeCompare(x.route)),E.forEach((v,x)=>{let k=x===E.length-1?"\u2514\u2500 ":"\u251C\u2500 ",B=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${B}`)}),console.log(`
2028
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(w.url.toString(),()=>{if(p)it.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=it.watch(l,{recursive:!0},async(x,R)=>{if(!R)return;if(R.endsWith(".stx")||R.endsWith(".js")||R.endsWith(".ts")||R.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${R}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Wn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Ui}=globalThis.Bun;import ve from"fs";import ie from"path";async function Kn(t){try{return xt(await Bun.file(t).text())}catch{return}}function qt(t){let o=Bun.file(t),s=ie.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(s)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(o,{headers:{"Content-Type":p[s]||"application/octet-stream",...l}})}async function wn(t=".",o={}){let s=o.port||3000,p=o.watch!==!1,c=o.hotReload!==!1&&p,l=null,m=o.hmrPort||s+1,u=ie.resolve(t),{loadStxConfig:y}=await import("./chunk-gy7t9wd0.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-93wp5h7v.js"),S=o.stxOptions?.serverApi??g.serverApi,E=await b(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=o.pagesDir||g.pagesDir||"pages",R=ie.join(v,x);if(!ve.existsSync(R)&&!g._layerPageDirs?.some((O)=>ve.existsSync(O)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${R}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=M(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[R,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${R}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let B=g?._pluginPageDirs||[],L=[];for(let{dir:O,prefix:z}of B)if(ve.existsSync(O)){let N=M(ie.dirname(O),{pagesDir:ie.basename(O)});for(let V of N){let we=z==="/"?V.pattern:`${z}${V.pattern==="/"?"":V.pattern}`;L.push({route:{...V,pattern:we},prefix:z})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${z}${e.reset}`)}let j=new Map,P=null,I=null;if(o.stxOptions?.shell!==!1){if(I=await ri(u,o.stxOptions?.shell),I){if(P=await vr(I,o.stxOptions||{}),P)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(u,I)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Qe(),await tt(u);let F=et();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let G={},oe=null;try{let{loadStxConfig:O}=await import("./chunk-gy7t9wd0.js"),z=await O(u);if(z?.apiRouter)oe=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){G=z.apiRoutes;let N=Object.keys(G).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:V}=await import("./chunk-06qhvtsv.js"),we=z.broadcasting;await N(we);let We=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let se=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${se} broadcast channel${se!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(se){console.warn(`${e.yellow}Failed to load channels.ts: ${se.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let $e=a(u,"output");ve.mkdirSync($e,{recursive:!0});let he=new Map,Oe=new Set,le=async(O)=>{let z=or(R,O);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...o.stxOptions});if(!N.success)return null;let V=N.outputs.find((we)=>we.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,H=async(O,z)=>{try{let{processDirectives:N,extractVariables:V,defaultConfig:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-gy7t9wd0.js"),{checkCache:se,cacheTemplate:Q,readFileCached:X,templateCache:J}=await import("./chunk-h15q5qan.js"),ke=await We(u),Je=(de)=>{if(!de)return de;if(ie.isAbsolute(de))return de;return ie.resolve(u,de)},A={...we,...ke,...o.stxOptions,autoShell:!0};if(o.debugDirectives)A.debug=!0;A.partialsDir=Je(A.partialsDir),A.componentsDir=Je(A.componentsDir),A.layoutsDir=Je(A.layoutsDir),A.storesDir=Je(A.storesDir||"stores"),A.cachePath=Je(A.cachePath)??a(u,"cache");let be=!z&&!o.profile,pe=A.cache!==!1;if(pe&&be){let de=J.get(O.filePath);if(de)try{if((await ve.promises.stat(O.filePath)).mtime.getTime()<=de.mtime){let ze=!0;for(let Re of de.dependencies){if(!ve.existsSync(Re)){ze=!1;break}if((await ve.promises.stat(Re)).mtime.getTime()>de.mtime){ze=!1;break}}if(ze){let Re=de.output;if(P)Re=ge(Re,{preserveHead:!0});let gt=W.get(O.filePath);return{route:O,content:Re,status:gt?.status??await Kn(O.filePath),headers:gt?.headers}}}}catch{}let Ie=await se(O.filePath,A);if(Ie){let He=Ie;if(P)He=ge(He,{preserveHead:!0});let ze=W.get(O.filePath);return{route:O,content:He,status:ze?.status??await Kn(O.filePath),headers:ze?.headers}}}let me=pe?await X(O.filePath):await Bun.file(O.filePath).text(),Ce=xt(me),{classifyAllScripts:Y}=await import("./chunk-gy7t9wd0.js"),Le=Y(me),Ve=Le.server.map((de)=>de.content),ue=me;for(let de of Le.server)ue=ue.replace(de.fullTag,"");let fe={__filename:O.filePath,__dirname:ie.dirname(O.filePath),__stx_options:A,params:z??{},__stx_runtime_head:{}};for(let de of Ve)try{await V(de,fe,O.filePath)}catch(Ie){if(o.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let Ke=new Set,Ae;if(o.profile){let de=performance.now();Ae=await N(ue,fe,O.filePath,A,Ke);let Ie=performance.now()-de,He=ie.relative(u,O.filePath)||O.filePath;console.log(`[stx:profile] ${He} \u2192 ${Ie.toFixed(2)}ms`)}else Ae=await N(ue,fe,O.filePath,A,Ke);if(!P)Ae=await Ge(Ae,{router:A.router});{let{interpolateScriptExpressions:de}=await import("./chunk-fbhgabf2.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,He,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return Ie;return`<script${He}>${de(ze,fe)}</script>`})}if(P)Ae=ge(Ae,{preserveHead:!0});if(pe&&be)await Q(O.filePath,Ae,Ke,A);let{extractStreamBoundaries:Xn}=await import("./chunk-p2b0r3qn.js"),lt=Xn(fe),mt=fe.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let de=fe.streamBoundaries||{},Ie={...A,autoShell:!1},He=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof de[Re]==="function"?await de[Re]():void 0;return N(mt[Re],{...fe,$boundary:gt},O.filePath,Ie,new Set)}})),ze=new Set(He.map((Re)=>Re.id));lt=[...(lt||[]).filter((Re)=>!ze.has(Re.id)),...He]}if(lt&&lt.length>0)Oe.add(O.pattern);else lt=void 0;let Kt=Be(fe),Xt=Fe(fe);if(be)W.set(O.filePath,{status:Kt,headers:Xt});return{route:O,content:Ae,status:Kt??Ce,headers:Xt,boundaries:lt}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},Ue=8,qe=async()=>{he.clear(),j.clear();for(let O=0;O<k.length;O+=Ue){let z=k.slice(O,O+Ue),N=await Promise.all(z.map((V)=>H(V)));for(let V of N)if(V)he.set(V.route.pattern,V)}for(let O=0;O<L.length;O+=Ue){let z=L.slice(O,O+Ue),N=await Promise.all(z.map(({route:V})=>H(V)));for(let V of N)if(V)j.set(V.route.pattern,V)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await vt(u);let at=s;try{if(at=await Ye(s),at!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${at} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let O=o.hmrPort||at+1;l=Pt({wsPort:O,verbose:!1}),m=l.start(O)}let Lt=(O,z)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).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(O.includes("</head>"))return O.replace("</head>",`${V}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+O};console.log(`${e.blue}Starting server...${e.reset}`);let It=Ui({port:at,async fetch(O){let z=new URL(O.url),N=g?.publicDir||"public",V=ie.join(u,N,z.pathname),we=ie.join(u,z.pathname),We=ie.join($e,z.pathname);if([V,we,We].some((A)=>w(A,u,S)))return new Response("Not Found",{status:404});let[Ge,se,Q]=await Promise.all([ve.promises.stat(V).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return qt(V);if(se?.isFile()&&!w(we,u,S))return qt(we);if(Q?.isFile()&&!w(We,u,S))return qt(We);if(z.pathname.startsWith("/_stx/component/")){let A=decodeURIComponent(z.pathname.slice(16));if(A)try{let be=`<${A} />`,pe={...buildConfig,autoShell:!1},me=await processDirectives(be,{},ie.join(u,"components",`${A}.stx`),pe,new Set);return new Response(me,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:A}=await import("./chunk-kr2phxhf.js"),be=await A(O,{publicDir:ie.join(u,N),cacheDir:a(u,"cache","img")});if(be)return be}if(oe)try{let A=await oe.handleRequest(O);if(A.status!==404)return A}catch{}if(G[z.pathname])try{return await G[z.pathname](O)}catch(A){return new Response(JSON.stringify({error:A.message}),{status:500,headers:{"Content-Type":"application/json"}})}let X=await E(O);if(X)return X;let J=gn(z.pathname,k);if(J){let A=he.get(J.route.pattern),be=Oe.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||be){let pe=await H(J.route,J.params);if(pe)A=pe}if(A){let pe=A.status??200,me=A.headers??{},Ce=(J.route.filePath?je(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:J.params})){let Ve=await le(404);if(Ve){let ue=Ve;if(ue=await f(ue,u),c)ue=Xe(ue,m);return new Response(ue,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Le=nt(z.pathname,J.params,Ce,z.search),Ve=rt(Le,null,O,{isServer:!0}),ue=await st(Ce.middleware,Ve);if(ue.redirect){let fe=ue.redirect.path,Ke=ue.redirect.options.redirectCode||302,Ae=new Headers(ue.responseHeaders);return Ae.set("Location",fe),new Response(null,{status:Ke,headers:Ae})}if(ue.abort){let{statusCode:fe,message:Ke}=ue.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${fe}</title></head><body><h1>Error ${fe}</h1><p>${Ke}</p></body></html>`,{status:fe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ue.state).length>0){let fe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ue.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;A.content=A.content.replace("</head>",`${fe}</head>`)}}let Y=A.content;if(P&&si(O)){let Le=xe(Y),Ve=ae(Y),ue=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=ue?ni(ue[1].trim()):"";if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);Y=await f(Y,u);let Ke=g?.router?.container||"main";return Y=re(Y,Ke),new Response(Y,{status:pe,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...fe&&{"X-STX-Title":encodeURIComponent(fe)},[Zi]:us(),...C(),"Cache-Control":_e}})}if(P)Y=kn(P,Y);if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);if(Y=await f(Y,u),c)Y=Xe(Y,m);if(o.native)if(Y.includes("<head>"))Y=Y.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 Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(o.titlebarHidden)if(Y.includes("<head>"))Y=Y.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 Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(A.boundaries&&A.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-p2b0r3qn.js");return Ve(Le(Y,A.boundaries,{timeoutMs:30000}),{status:pe,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:pe,headers:{"Content-Type":"text/html",...C(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...me}})}}if(L.length>0){let A=L.map((pe)=>pe.route),be=gn(z.pathname,A);if(be){let pe=j.get(be.route.pattern);if(pe){let me=pe.content;if(P)me=kn(P,me);if(Object.keys(be.params).length>0)me=Lt(me,be.params);if(me=await f(me,u),c)me=Xe(me,m);return new Response(me,{status:pe.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:pe}of B)if(pe!=="/"&&z.pathname.startsWith(pe)){let me=j.get(pe)||j.get(pe+"/");if(me){let Ce=me.content;if(P)Ce=kn(P,Ce);if(Ce=await f(Ce,u),c)Ce=Xe(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ze(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.get("/");if(ke){let A=ke.content;if(A=await f(A,u),c)A=Xe(A,m);if(o.native)if(A.includes("<head>"))A=A.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 A="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+A;return new Response(A,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await le(404);if(Je){let A=Je;if(A=await f(A,u),c)A=Xe(A,m);return new Response(A,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let z=await le(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
2028
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(w.url.toString(),()=>{if(p)it.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=it.watch(l,{recursive:!0},async(x,R)=>{if(!R)return;if(R.endsWith(".stx")||R.endsWith(".js")||R.endsWith(".ts")||R.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${R}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Wn(t){return String(t??"").replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;")}var{serve:Wi}=globalThis.Bun;import ve from"fs";import ie from"path";async function Kn(t){try{return xt(await Bun.file(t).text())}catch{return}}function qt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function wn(t=".",s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=ie.resolve(t),{loadStxConfig:y}=await import("./chunk-4gjc61wn.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-d3yrvve4.js"),S=s.stxOptions?.serverApi??g.serverApi,E=await b(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",R=ie.join(v,x);if(!ve.existsSync(R)&&!g._layerPageDirs?.some((O)=>ve.existsSync(O)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${R}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=M(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[R,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${R}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let B=g?._pluginPageDirs||[],L=[];for(let{dir:O,prefix:z}of B)if(ve.existsSync(O)){let N=M(ie.dirname(O),{pagesDir:ie.basename(O)});for(let V of N){let we=z==="/"?V.pattern:`${z}${V.pattern==="/"?"":V.pattern}`;L.push({route:{...V,pattern:we},prefix:z})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${z}${e.reset}`)}let j=new Map,P=null,I=null;if(s.stxOptions?.shell!==!1){if(I=await ro(u,s.stxOptions?.shell),I){if(P=await vr(I,s.stxOptions||{}),P)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(u,I)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Qe(),await tt(u);let F=et();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let G={},oe=null;try{let{loadStxConfig:O}=await import("./chunk-4gjc61wn.js"),z=await O(u);if(z?.apiRouter)oe=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){G=z.apiRoutes;let N=Object.keys(G).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:V}=await import("./chunk-ns7e951g.js"),we=z.broadcasting;await N(we);let We=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let se=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${se} broadcast channel${se!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(se){console.warn(`${e.yellow}Failed to load channels.ts: ${se.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let $e=a(u,"output");ve.mkdirSync($e,{recursive:!0});let he=new Map,Oe=new Set,le=async(O)=>{let z=ir(R,O);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!N.success)return null;let V=N.outputs.find((we)=>we.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,H=async(O,z)=>{try{let{processDirectives:N,extractVariables:V,defaultConfig:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-4gjc61wn.js"),{checkCache:se,cacheTemplate:Q,readFileCached:X,templateCache:J}=await import("./chunk-j1h2z4wh.js"),ke=await We(u),Je=(de)=>{if(!de)return de;if(ie.isAbsolute(de))return de;return ie.resolve(u,de)},A={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)A.debug=!0;A.partialsDir=Je(A.partialsDir),A.componentsDir=Je(A.componentsDir),A.layoutsDir=Je(A.layoutsDir),A.storesDir=Je(A.storesDir||"stores"),A.cachePath=Je(A.cachePath)??a(u,"cache");let be=!z&&!s.profile,pe=A.cache!==!1;if(pe&&be){let de=J.get(O.filePath);if(de)try{if((await ve.promises.stat(O.filePath)).mtime.getTime()<=de.mtime){let ze=!0;for(let Re of de.dependencies){if(!ve.existsSync(Re)){ze=!1;break}if((await ve.promises.stat(Re)).mtime.getTime()>de.mtime){ze=!1;break}}if(ze){let Re=de.output;if(P)Re=ge(Re,{preserveHead:!0});let gt=W.get(O.filePath);return{route:O,content:Re,status:gt?.status??await Kn(O.filePath),headers:gt?.headers}}}}catch{}let Ie=await se(O.filePath,A);if(Ie){let He=Ie;if(P)He=ge(He,{preserveHead:!0});let ze=W.get(O.filePath);return{route:O,content:He,status:ze?.status??await Kn(O.filePath),headers:ze?.headers}}}let me=pe?await X(O.filePath):await Bun.file(O.filePath).text(),Ce=xt(me),{classifyAllScripts:Y}=await import("./chunk-4gjc61wn.js"),Le=Y(me),Ve=Le.server.map((de)=>de.content),ue=me;for(let de of Le.server)ue=ue.replace(de.fullTag,"");let fe={__filename:O.filePath,__dirname:ie.dirname(O.filePath),__stx_options:A,params:z??{},__stx_runtime_head:{}};for(let de of Ve)try{await V(de,fe,O.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let Ke=new Set,Ae;if(s.profile){let de=performance.now();Ae=await N(ue,fe,O.filePath,A,Ke);let Ie=performance.now()-de,He=ie.relative(u,O.filePath)||O.filePath;console.log(`[stx:profile] ${He} \u2192 ${Ie.toFixed(2)}ms`)}else Ae=await N(ue,fe,O.filePath,A,Ke);if(!P)Ae=await Ge(Ae,{router:A.router});{let{interpolateScriptExpressions:de}=await import("./chunk-cs3507d0.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,He,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return Ie;return`<script${He}>${de(ze,fe)}</script>`})}if(P)Ae=ge(Ae,{preserveHead:!0});if(pe&&be)await Q(O.filePath,Ae,Ke,A);let{extractStreamBoundaries:Xn}=await import("./chunk-2tpvt1c5.js"),lt=Xn(fe),mt=fe.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let de=fe.streamBoundaries||{},Ie={...A,autoShell:!1},He=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof de[Re]==="function"?await de[Re]():void 0;return N(mt[Re],{...fe,$boundary:gt},O.filePath,Ie,new Set)}})),ze=new Set(He.map((Re)=>Re.id));lt=[...(lt||[]).filter((Re)=>!ze.has(Re.id)),...He]}if(lt&&lt.length>0)Oe.add(O.pattern);else lt=void 0;let Kt=Be(fe),Xt=Fe(fe);if(be)W.set(O.filePath,{status:Kt,headers:Xt});return{route:O,content:Ae,status:Kt??Ce,headers:Xt,boundaries:lt}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},Ue=8,qe=async()=>{he.clear(),j.clear();for(let O=0;O<k.length;O+=Ue){let z=k.slice(O,O+Ue),N=await Promise.all(z.map((V)=>H(V)));for(let V of N)if(V)he.set(V.route.pattern,V)}for(let O=0;O<L.length;O+=Ue){let z=L.slice(O,O+Ue),N=await Promise.all(z.map(({route:V})=>H(V)));for(let V of N)if(V)j.set(V.route.pattern,V)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await vt(u);let at=i;try{if(at=await Ye(i),at!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${at} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let O=s.hmrPort||at+1;l=Pt({wsPort:O,verbose:!1}),m=l.start(O)}let Lt=(O,z)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).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(O.includes("</head>"))return O.replace("</head>",`${V}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+O};console.log(`${e.blue}Starting server...${e.reset}`);let It=Wi({port:at,async fetch(O){let z=new URL(O.url),N=g?.publicDir||"public",V=ie.join(u,N,z.pathname),we=ie.join(u,z.pathname),We=ie.join($e,z.pathname);if([V,we,We].some((A)=>w(A,u,S)))return new Response("Not Found",{status:404});let[Ge,se,Q]=await Promise.all([ve.promises.stat(V).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return qt(V);if(se?.isFile()&&!w(we,u,S))return qt(we);if(Q?.isFile()&&!w(We,u,S))return qt(We);if(z.pathname.startsWith("/_stx/component/")){let A=decodeURIComponent(z.pathname.slice(16));if(A)try{let be=`<${A} />`,pe={...buildConfig,autoShell:!1},me=await processDirectives(be,{},ie.join(u,"components",`${A}.stx`),pe,new Set);return new Response(me,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:A}=await import("./chunk-zj80vrv6.js"),be=await A(O,{publicDir:ie.join(u,N),cacheDir:a(u,"cache","img")});if(be)return be}if(oe)try{let A=await oe.handleRequest(O);if(A.status!==404)return A}catch{}if(G[z.pathname])try{return await G[z.pathname](O)}catch(A){return new Response(JSON.stringify({error:A.message}),{status:500,headers:{"Content-Type":"application/json"}})}let X=await E(O);if(X)return X;let J=gn(z.pathname,k);if(J){let A=he.get(J.route.pattern),be=Oe.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||be){let pe=await H(J.route,J.params);if(pe)A=pe}if(A){let pe=A.status??200,me=A.headers??{},Ce=(J.route.filePath?je(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:J.params})){let Ve=await le(404);if(Ve){let ue=Ve;if(ue=await f(ue,u),c)ue=Xe(ue,m);return new Response(ue,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Le=nt(z.pathname,J.params,Ce,z.search),Ve=rt(Le,null,O,{isServer:!0}),ue=await st(Ce.middleware,Ve);if(ue.redirect){let fe=ue.redirect.path,Ke=ue.redirect.options.redirectCode||302,Ae=new Headers(ue.responseHeaders);return Ae.set("Location",fe),new Response(null,{status:Ke,headers:Ae})}if(ue.abort){let{statusCode:fe,message:Ke}=ue.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${fe}</title></head><body><h1>Error ${fe}</h1><p>${Ke}</p></body></html>`,{status:fe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ue.state).length>0){let fe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ue.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;A.content=A.content.replace("</head>",`${fe}</head>`)}}let Y=A.content;if(P&&so(O)){let Le=xe(Y),Ve=ae(Y),ue=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=ue?no(ue[1].trim()):"";if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);Y=await f(Y,u);let Ke=g?.router?.container||"main";return Y=re(Y,Ke),new Response(Y,{status:pe,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...fe&&{"X-STX-Title":encodeURIComponent(fe)},[Qo]:us(),...C(),"Cache-Control":_e}})}if(P)Y=kn(P,Y);if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);if(Y=await f(Y,u),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.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 Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.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 Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(A.boundaries&&A.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-2tpvt1c5.js");return Ve(Le(Y,A.boundaries,{timeoutMs:30000}),{status:pe,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:pe,headers:{"Content-Type":"text/html",...C(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...me}})}}if(L.length>0){let A=L.map((pe)=>pe.route),be=gn(z.pathname,A);if(be){let pe=j.get(be.route.pattern);if(pe){let me=pe.content;if(P)me=kn(P,me);if(Object.keys(be.params).length>0)me=Lt(me,be.params);if(me=await f(me,u),c)me=Xe(me,m);return new Response(me,{status:pe.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:pe}of B)if(pe!=="/"&&z.pathname.startsWith(pe)){let me=j.get(pe)||j.get(pe+"/");if(me){let Ce=me.content;if(P)Ce=kn(P,Ce);if(Ce=await f(Ce,u),c)Ce=Xe(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ze(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.get("/");if(ke){let A=ke.content;if(A=await f(A,u),c)A=Xe(A,m);if(s.native)if(A.includes("<head>"))A=A.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 A="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+A;return new Response(A,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await le(404);if(Je){let A=Je;if(A=await f(A,u),c)A=Xe(A,m);return new Response(A,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let z=await le(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
2029
2029
  ${O.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
2030
2030
  ${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(`
2031
2031
  ${e.bright}\u2192 ${e.cyan}http://localhost:${at}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
2032
2032
  ${e.yellow}Routes:${e.reset}`);let jt=[...ar(k,u)];for(let{route:O}of L)jt.push(`${O.pattern}`);if(jt.forEach((O,z)=>{let V=z===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${O}`)}),console.log(`
2033
- Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(It.url.toString(),()=>{if(l)ht();It.stop()}),o.native){let O,z=ie.join(R,"index.stx");if(ve.existsSync(z)){let V=await Bun.file(z).text();O=Tt(V)}let N=g?.app?.window??{};await dt(at,{title:g?.app?.head?.title||ie.basename(u)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??o.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(se)=>se.startsWith("public/")||se.startsWith("public\\"),z=(se)=>{let Q=se.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},N=new Map,V=()=>{let se=new Set([u,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let X of Object.values(Q.resources)){if(!ve.existsSync(X))continue;let J=ve.realpathSync(X);if(![...se].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))se.add(J)}for(let[Q,X]of N)if(!se.has(Q))X.close(),N.delete(Q);for(let Q of se)if(!N.has(Q)&&ve.existsSync(Q))N.set(Q,ve.watch(Q,{recursive:!0},(X,J)=>{We(Q,X,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},we=Promise.resolve(),We=(se,Q,X)=>(we=we.catch(()=>{}).then(()=>Ge(se,Q,X)),we),Ge=async(se,Q,X)=>{if(!X||Rt(X))return;if(Ct(X)){if(g._layerGraph){let J=await y(u);Object.assign(g,J),k.splice(0,k.length,...M(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[R,...J._layerPageDirs.slice(1)]:void 0})),V()}if(O(X)){if(console.log(`${e.cyan}${X} changed${e.reset}`),c&&l)l.reload(X)}else if(z(X)){console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-h15q5qan.js");J(ie.resolve(se,X)),ke.delete(ie.resolve(se,X))}catch{}if(I&&X){if(ie.resolve(se,X)===I||ie.basename(I)===X){let ke=await vr(I,o.stxOptions||{});if(ke)P=ke}}if(await qe(),await en(u),c&&l)l.reload(X)}else{console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-h15q5qan.js");J(ie.resolve(se,X)),ke.delete(ie.resolve(se,X))}catch{}if(await qe(),c&&l)l.reload(X)}}else if($t(X)){if(console.log(`${e.cyan}CSS ${X} changed${e.reset}`),c&&l)l.updateCss(X)}};V(),process.on("SIGINT",()=>{for(let se of N.values())se.close();if(l)ht();It.stop(),process.exit(0)})}return!0}export{zs,Hs,Vs,Us,pr,Ws,qs,Ks,Do,Oo,fr,gr,yn,bn,wn};
2033
+ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let O,z=ie.join(R,"index.stx");if(ve.existsSync(z)){let V=await Bun.file(z).text();O=Tt(V)}let N=g?.app?.window??{};await dt(at,{title:g?.app?.head?.title||ie.basename(u)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(se)=>se.startsWith("public/")||se.startsWith("public\\"),z=(se)=>{let Q=se.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},N=new Map,V=()=>{let se=new Set([u,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let X of Object.values(Q.resources)){if(!ve.existsSync(X))continue;let J=ve.realpathSync(X);if(![...se].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))se.add(J)}for(let[Q,X]of N)if(!se.has(Q))X.close(),N.delete(Q);for(let Q of se)if(!N.has(Q)&&ve.existsSync(Q))N.set(Q,ve.watch(Q,{recursive:!0},(X,J)=>{We(Q,X,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},we=Promise.resolve(),We=(se,Q,X)=>(we=we.catch(()=>{}).then(()=>Ge(se,Q,X)),we),Ge=async(se,Q,X)=>{if(!X||Rt(X))return;if(Ct(X)){if(g._layerGraph){let J=await y(u);Object.assign(g,J),k.splice(0,k.length,...M(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[R,...J._layerPageDirs.slice(1)]:void 0})),V()}if(O(X)){if(console.log(`${e.cyan}${X} changed${e.reset}`),c&&l)l.reload(X)}else if(z(X)){console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-j1h2z4wh.js");J(ie.resolve(se,X)),ke.delete(ie.resolve(se,X))}catch{}if(I&&X){if(ie.resolve(se,X)===I||ie.basename(I)===X){let ke=await vr(I,s.stxOptions||{});if(ke)P=ke}}if(await qe(),await en(u),c&&l)l.reload(X)}else{console.log(`${e.yellow}${X} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-j1h2z4wh.js");J(ie.resolve(se,X)),ke.delete(ie.resolve(se,X))}catch{}if(await qe(),c&&l)l.reload(X)}}else if($t(X)){if(console.log(`${e.cyan}CSS ${X} changed${e.reset}`),c&&l)l.updateCss(X)}};V(),process.on("SIGINT",()=>{for(let se of N.values())se.close();if(l)ht();It.stop(),process.exit(0)})}return!0}export{zs,Hs,Vs,Us,pr,Ws,qs,Ks,Di,Oi,fr,gr,yn,bn,wn};