@stacksjs/stx 0.2.428 → 0.2.429

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 (99) hide show
  1. package/dist/{chunk-qh7kx90q.js → chunk-0mvy3x76.js} +1 -1
  2. package/dist/{chunk-dyhb8ey9.js → chunk-122d4nek.js} +1 -1
  3. package/dist/chunk-1ryby13h.js +2 -0
  4. package/dist/{chunk-ckew8xkb.js → chunk-1vkzta7c.js} +1 -1
  5. package/dist/{chunk-m2xk6a2p.js → chunk-2btdk4fq.js} +1 -1
  6. package/dist/{chunk-v6hjn4xn.js → chunk-2s132hw3.js} +1 -1
  7. package/dist/chunk-386zrhbf.js +2 -0
  8. package/dist/chunk-3hn1vt2v.js +2 -0
  9. package/dist/{chunk-awg10gdf.js → chunk-4fhpbsaw.js} +1 -1
  10. package/dist/{chunk-t3wh1jbk.js → chunk-4wf68rht.js} +3 -3
  11. package/dist/{chunk-8a0r2j8f.js → chunk-4xemkkm8.js} +2 -2
  12. package/dist/{chunk-89b2r1q0.js → chunk-5f0r0g18.js} +2 -2
  13. package/dist/{chunk-pcfdd3jv.js → chunk-63b0yqx8.js} +1 -1
  14. package/dist/chunk-67r98kff.js +2 -0
  15. package/dist/{chunk-m9m03bcp.js → chunk-6wnwnckz.js} +1 -1
  16. package/dist/chunk-7j2m67xq.js +2 -0
  17. package/dist/chunk-82fvm2tx.js +2 -0
  18. package/dist/chunk-9wzrgmak.js +2 -0
  19. package/dist/{chunk-t1b2kzhn.js → chunk-avy3h8m6.js} +1 -1
  20. package/dist/{chunk-xdjevnv6.js → chunk-bcnd7806.js} +72 -72
  21. package/dist/{chunk-vfk725vm.js → chunk-bjnvymb7.js} +2 -2
  22. package/dist/{chunk-a8g6y9kw.js → chunk-c0ants8t.js} +4 -4
  23. package/dist/{chunk-wgas6fb9.js → chunk-ck0m8ecw.js} +1 -1
  24. package/dist/{chunk-9wbt987t.js → chunk-cp9egkx4.js} +1 -1
  25. package/dist/{chunk-5562x3jp.js → chunk-dfrsad24.js} +1 -1
  26. package/dist/{chunk-mg7jhx5v.js → chunk-djdf6agj.js} +1 -1
  27. package/dist/chunk-dxed2qq7.js +2 -0
  28. package/dist/{chunk-frvfpmes.js → chunk-ehsqp1p8.js} +2 -2
  29. package/dist/chunk-ek9h45fp.js +2 -0
  30. package/dist/{chunk-jbrdebzs.js → chunk-fb7bfyjz.js} +2 -2
  31. package/dist/{chunk-0yv4gk8g.js → chunk-gc37w44c.js} +1 -1
  32. package/dist/{chunk-xs68rj51.js → chunk-gqy7arys.js} +2 -2
  33. package/dist/{chunk-n5gwwjch.js → chunk-gxdmkk4n.js} +1 -1
  34. package/dist/{chunk-k3ths2yp.js → chunk-h94sthre.js} +41 -41
  35. package/dist/{chunk-thdbqsxq.js → chunk-hnx1jgfp.js} +1 -1
  36. package/dist/{chunk-rb0v8enr.js → chunk-jp602m75.js} +1 -1
  37. package/dist/{chunk-k1bm8hsv.js → chunk-jphk7zc5.js} +1 -1
  38. package/dist/{chunk-k7m5f5mx.js → chunk-k0v70ttf.js} +1 -1
  39. package/dist/{chunk-2x9jd5w0.js → chunk-ktedzx9e.js} +1 -1
  40. package/dist/chunk-m162mqbc.js +2 -0
  41. package/dist/{chunk-hvme6tw2.js → chunk-mgcykz7g.js} +1 -1
  42. package/dist/{chunk-5qmj2aq7.js → chunk-mgekvbpa.js} +3 -3
  43. package/dist/{chunk-48kgnqpk.js → chunk-mjgqhhap.js} +3 -3
  44. package/dist/chunk-mkzxhfae.js +2 -0
  45. package/dist/{chunk-mevm81je.js → chunk-nbkefgvz.js} +1 -1
  46. package/dist/{chunk-4ya53yrh.js → chunk-pfmkkgsa.js} +1 -1
  47. package/dist/{chunk-62chbqev.js → chunk-rnbgn7xn.js} +1 -1
  48. package/dist/{chunk-26gfsa9w.js → chunk-rnjkfhh0.js} +1 -1
  49. package/dist/{chunk-1p8hc1ve.js → chunk-rqfhknzj.js} +1 -1
  50. package/dist/chunk-rqqckzq0.js +2 -0
  51. package/dist/chunk-s9rv2v1p.js +2 -0
  52. package/dist/{chunk-60ment0t.js → chunk-sb0x0jmv.js} +3 -3
  53. package/dist/chunk-sjvy2y23.js +2 -0
  54. package/dist/chunk-sv780pxb.js +2 -0
  55. package/dist/chunk-tsh37jew.js +2 -0
  56. package/dist/chunk-v5mpp9qy.js +2 -0
  57. package/dist/{chunk-y5b468c3.js → chunk-v5y10md6.js} +1 -1
  58. package/dist/{chunk-pnrtj8xp.js → chunk-vfd9wmsf.js} +1 -1
  59. package/dist/{chunk-yaebdyfr.js → chunk-w3j0ppg4.js} +2 -2
  60. package/dist/chunk-w4gv0scs.js +2 -0
  61. package/dist/{chunk-prgv92bc.js → chunk-wfz1kycm.js} +1 -1
  62. package/dist/{chunk-s295vp9x.js → chunk-wr9ac0cv.js} +2 -2
  63. package/dist/chunk-x1rejs3z.js +2 -0
  64. package/dist/{chunk-6jgjmycb.js → chunk-x38d7mvy.js} +1 -1
  65. package/dist/{chunk-9v3zrsfy.js → chunk-xbx92967.js} +2 -2
  66. package/dist/{chunk-wdxct95c.js → chunk-xnf5eay1.js} +1 -1
  67. package/dist/{chunk-ptjqacjd.js → chunk-y438dzvn.js} +2 -2
  68. package/dist/chunk-yw4hccce.js +2 -0
  69. package/dist/{chunk-w1s1hhrg.js → chunk-zp1zsjwh.js} +1 -1
  70. package/dist/chunk-zzb53zgh.js +2 -0
  71. package/dist/cli.js +10 -10
  72. package/dist/craft-entry.js +2 -2
  73. package/dist/craft.js +2 -2
  74. package/dist/index.d.ts +1 -0
  75. package/dist/index.js +1 -0
  76. package/dist/pwa.js +1 -1
  77. package/dist/ssg.js +2 -2
  78. package/package.json +5 -5
  79. package/dist/chunk-0wwpej8f.js +0 -2
  80. package/dist/chunk-18c2va7t.js +0 -2
  81. package/dist/chunk-1ey2myy4.js +0 -2
  82. package/dist/chunk-5mfhk69g.js +0 -2
  83. package/dist/chunk-8ghw6h48.js +0 -2
  84. package/dist/chunk-9gmyvvry.js +0 -2
  85. package/dist/chunk-9j72har9.js +0 -2
  86. package/dist/chunk-cm1vzy7d.js +0 -2
  87. package/dist/chunk-cnmz9543.js +0 -2
  88. package/dist/chunk-e06jpx5x.js +0 -2
  89. package/dist/chunk-e90n9tzp.js +0 -2
  90. package/dist/chunk-gfpk07wd.js +0 -2
  91. package/dist/chunk-k8grzx71.js +0 -2
  92. package/dist/chunk-ncrcacdr.js +0 -2
  93. package/dist/chunk-nsta4z55.js +0 -2
  94. package/dist/chunk-phvxs54d.js +0 -2
  95. package/dist/chunk-r3sj53m1.js +0 -2
  96. package/dist/chunk-t8kadtva.js +0 -2
  97. package/dist/chunk-wr78aadr.js +0 -2
  98. package/dist/chunk-y9epxz9w.js +0 -2
  99. package/dist/chunk-zsc4qb0g.js +0 -2
@@ -1,5 +1,5 @@
1
1
  // @bun
2
- import{K,un,te,_,Et}from"./chunk-89b2r1q0.js";import{Ze,gn,sr,ir,or,Qe,et,tt,nt,rt,st,xe}from"./chunk-12pvnn1e.js";import{U,h,Zt,Qt,e,wt,en,f,je,xt,Be,Fe,Z,M,ae,q,d,ye,Yi,cs,n,r,ee,Wn,i,T,ce}from"./chunk-xdjevnv6.js";import{_e,ei,ne,C,ti,vr,kn,ge,ni,re}from"./chunk-5qmj2aq7.js";import{At}from"./chunk-n5gwwjch.js";import{De}from"./chunk-prgv92bc.js";import{a}from"./chunk-wtms9jhs.js";import{D}from"./chunk-yqsza22w.js";function Bs(t,s){let o=[],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)o.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))o.push(m),c++}}return o}var{serve:nr}=globalThis.Bun;import Bt from"fs";import pt from"path";function bt(){return`
2
+ import{K,un,te,_,Et}from"./chunk-5f0r0g18.js";import{Ze,gn,sr,ir,or,Qe,et,tt,nt,rt,st,xe}from"./chunk-12pvnn1e.js";import{U,h,Zt,Qt,e,vt,en,f,je,xt,Be,Fe,Z,M,ae,q,d,ye,Yi,cs,n,r,ee,Wn,i,T,ce}from"./chunk-bcnd7806.js";import{_e,ei,ne,C,ti,wr,kn,ge,ni,re}from"./chunk-mgekvbpa.js";import{At}from"./chunk-gxdmkk4n.js";import{De}from"./chunk-wfz1kycm.js";import{a}from"./chunk-wtms9jhs.js";import{D}from"./chunk-yqsza22w.js";function Bs(t,s){let o=[],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)o.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))o.push(m),c++}}return o}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;
@@ -49,7 +49,7 @@ import{K,un,te,_,Et}from"./chunk-89b2r1q0.js";import{Ze,gn,sr,ir,or,Qe,et,tt,nt,
49
49
 
50
50
  body.dark-mode a {
51
51
  color: #58a6ff;
52
- }`}function vt(t){return`
52
+ }`}function wt(t){return`
53
53
  <div class="theme-selector">
54
54
  Theme:
55
55
  <select id="themeSelector" onchange="changeTheme()">
@@ -79,19 +79,19 @@ else {
79
79
  <span class="frontmatter-label">${s}:</span>
80
80
  <span>${Array.isArray(o)?o.join(", "):String(o)}</span>
81
81
  </div>`).join("")}
82
- </div>`}import Gt from"net";async function Xn(t){return new Promise((s)=>{let o=Gt.createServer();o.once("error",()=>s(!1)),o.once("listening",()=>{o.close(()=>s(!0))}),o.listen(t,"0.0.0.0")})}async function Gn(t){return new Promise((s)=>{let o=Gt.createServer();o.once("error",()=>s(!1)),o.once("listening",()=>{o.close(()=>s(!0))}),o.listen(t,"::")})}async function Jn(t){if(!await Xn(t))return!1;return await Gn(t)}async function Ye(t,s=20){t=Number(t);for(let o=0;o<s;o++){let p=t+o;if(await Jn(p))return p}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Yn={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Qn(){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 o={...Yn,...s},p=await Qn();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:o.title,width:o.width,height:o.height,darkMode:o.darkMode,hotReload:o.hotReload,titlebarHidden:o.titlebarHidden,nativeSidebar:o.nativeSidebar,sidebarWidth:o.sidebarWidth,sidebarConfig:o.sidebarConfig});if(c&&o.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 o=Gt.createServer();o.once("error",()=>s(!1)),o.once("listening",()=>{o.close(()=>s(!0))}),o.listen(t,"0.0.0.0")})}async function Jn(t){return new Promise((s)=>{let o=Gt.createServer();o.once("error",()=>s(!1)),o.once("listening",()=>{o.close(()=>s(!0))}),o.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 o=0;o<s;o++){let p=t+o;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 o={...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:o.title,width:o.width,height:o.height,darkMode:o.darkMode,hotReload:o.hotReload,titlebarHidden:o.titlebarHidden,nativeSidebar:o.nativeSidebar,sidebarWidth:o.sidebarWidth,sidebarConfig:o.sidebarConfig});if(c&&o.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
85
  `,y=Function(m)();if(y)return y}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let o=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(o)try{return JSON.parse(o[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 Zn(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 er(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,o){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(o?.onQuit)o.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
87
- `)){let l=p.trim().toLowerCase();p="",tr(l,t,s,o)}})}function tr(t,s,o,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else er(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Zn(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),o(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ht();break;default:break}}async function Ft(t,s={}){let o=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(`
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,o){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(o?.onQuit)o.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
87
+ `)){let l=p.trim().toLowerCase();p="",nr(l,t,s,o)}})}function nr(t,s,o,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}`),o(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ht();break;default:break}}async function Ft(t,s={}){let o=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">
91
91
  <head>
92
92
  <meta charset="UTF-8">
93
93
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
94
- <title>${rr(S.title||pt.basename(c))}</title>
94
+ <title>${ar(S.title||pt.basename(c))}</title>
95
95
  <!-- Syntax highlighting styles -->
96
96
  <style id="syntax-theme">
97
97
  :root {
@@ -238,7 +238,7 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
238
238
  </head>
239
239
  <body>
240
240
  ${kt(S)}
241
- ${vt(B)}
241
+ ${wt(B)}
242
242
 
243
243
  ${w}
244
244
 
@@ -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=o;try{if(y=await Ye(o),y!==o)console.log(`${e.yellow}Port ${o} 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=nr({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=o;try{if(y=await Ye(o),y!==o)console.log(`${e.yellow}Port ${o} 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()}),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 rr(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 s=t??this.options.wsPort,o=20;for(let p=0;p<o;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 ${o} 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),o=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),o++}catch{this.clients.delete(p)}if(this.options.verbose&&o>0)console.log(`[HMR] Broadcast ${t.type} to ${o} 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 ar(t,s={}){let{showOverlay:o=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;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 ar(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 s=t??this.options.wsPort,o=20;for(let p=0;p<o;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 ${o} 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),o=0;for(let p of this.clients)try{if(p.readyState===1)p.send(s),o++}catch{this.clients.delete(p)}if(this.options.verbose&&o>0)console.log(`[HMR] Broadcast ${t.type} to ${o} 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:o=!0,reconnectInterval:p=1000,maxReconnectAttempts:c=10}=s;return`
256
256
  <script>
257
257
  (function() {
258
258
  // stx Hot Reload Client
@@ -451,13 +451,13 @@ else {
451
451
  };
452
452
  })();
453
453
  </script>
454
- `}function Xe(t,s,o={}){let p=ar(s,o),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((o)=>o.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(),o=ur(s),p=mr(s,t),c=gr(s,o),l=hr(s,o);return{file:t,metrics:o,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function ur(t){let s=t.split(`
454
+ `}function Xe(t,s,o={}){let p=cr(s,o),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((o)=>o.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(),o=ur(s),p=mr(s,t),c=gr(s,o),l=hr(s,o);return{file:t,metrics:o,issues:p,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function ur(t){let s=t.split(`
455
455
  `),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(o?o[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 mr(t,s){let o=[],p=Yt(t,"if","endif");if(p>0)o.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Yt(t,"foreach","endforeach");if(c>0)o.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)o.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)o.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)o.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)o.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)o.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function gr(t,s){let o=[];if(s.complexity>7)o.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)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)o.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)o.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)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function hr(t,s){let o=1;if(o+=s.directives.conditionals*0.1,o+=s.directives.loops*0.5,o+=s.directives.includes*2,o+=s.expressions*0.05,o+=s.components*1,s.scriptLines>10)o+=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(o>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(o*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function Yt(t,s,o){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Fs(t=["**/*.stx"],s){let o=[],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);o.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=yr(o);return{results:o,summary:c}}function yr(t){let s=t.length,o=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:o,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 tn,writeFile as Sr}from"fs/promises";import Ee from"path";function cn(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 ln=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 o(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 o(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await o(t),s}function Rr(t,s){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let p=o[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 o={},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(ln.has(y))throw Error(`${s}: client ${cn(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 ":"";o[y]=`${v}${y}(${u[2]}) {${l.slice(g,E-1)}}`,m.lastIndex=E}}return o}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 nn(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
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 mr(t,s){let o=[],p=tn(t,"if","endif");if(p>0)o.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)o.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)o.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)o.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)o.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)o.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)o.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function gr(t,s){let o=[];if(s.complexity>7)o.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)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)o.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)o.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)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function hr(t,s){let o=1;if(o+=s.directives.conditionals*0.1,o+=s.directives.loops*0.5,o+=s.directives.includes*2,o+=s.expressions*0.05,o+=s.components*1,s.scriptLines>10)o+=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(o>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(o*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function tn(t,s,o){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Fs(t=["**/*.stx"],s){let o=[],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);o.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=yr(o);return{results:o,summary:c}}function yr(t){let s=t.length,o=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:o,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as br,readFile as xr,readdir as vr,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 o(p){let c=await vr(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 o(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await o(t),s}function Rr(t,s){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let p=o[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 o={},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 ":"";o[y]=`${v}${y}(${u[2]}) {${l.slice(g,E-1)}}`,m.lastIndex=E}}return o}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 Ar(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 Or(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=[],o=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(o,l.index)),o=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(o):null;if(g)o=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(o)),s.join(`
460
- `)}function Ot(t,s,o,p){if(t[s]!==o)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===o)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function zt(t,s,o){let p=o?"([{<":"([{",c=o?")]}>":")]}",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,o=null;for(let p=0;p<t.length;p++){let c=t[p];if(o){if(c==="\\"){p++;continue}if(c===o)o=null;continue}if(c==="'"||c==='"'||c==="`"){o=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 rn(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 o=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=o.exec(t);k&&k.index<s.index;k=o.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=rn(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=rn(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(/\}$/,""),o=[],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)o.push([l[1],g]);p++}return o}function Ir(t,s,o){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(o,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 o of t.matchAll(/<slot\b([^>]*)>/gi))s.add(o[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((o)=>({name:o}))}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,o){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(o.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(o.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:Ar(v.declared[L])??Or(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:nn(c),shadowMode:$r(s.shadowDOM??l.shadowDOM??o.shadowDOM),progressive:s.progressive??l.progressive??o.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(nn(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 {};
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=[],o=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(o,l.index)),o=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(o):null;if(g)o=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(o)),s.join(`
460
+ `)}function Ot(t,s,o,p){if(t[s]!==o)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===o)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function zt(t,s,o){let p=o?"([{<":"([{",c=o?")]}>":")]}",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,o=null;for(let p=0;p<t.length;p++){let c=t[p];if(o){if(c==="\\"){p++;continue}if(c===o)o=null;continue}if(c==="'"||c==='"'||c==="`"){o=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 sn(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 o=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=o.exec(t);k&&k.index<s.index;k=o.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=sn(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=sn(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(/\}$/,""),o=[],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)o.push([l[1],g]);p++}return o}function Ir(t,s,o){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(o,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 o of t.matchAll(/<slot\b([^>]*)>/gi))s.add(o[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((o)=>({name:o}))}function Fr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function on(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,o){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(o.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,on(L,j)])),S=jr(Pr(c)),E=Hr(S.template),v=Ir(c,p,Ee.resolve(o.outputDir)),x=Mr(E.template);for(let L of v.propNames){if(w[L])continue;let j=v.defaults[L];w[L]=on(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??o.shadowDOM),progressive:s.progressive??l.progressive??o.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;')
@@ -755,7 +755,7 @@ export function defineComponent(Component, definition) {
755
755
  }
756
756
  return Component;
757
757
  }
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),o=Object.entries(t.methods).map(([u,y])=>{if(ln.has(u))throw Error(`${t.sourcePath}: ${cn(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),o=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
 
@@ -826,9 +826,9 @@ ${c}
826
826
  }
827
827
 
828
828
  export {}
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(([o,p])=>({kind:"field",name:o,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(o),reflects:p.reflect})),events:Object.entries(s.events).map(([o,p])=>({name:o,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 on(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}) {
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(([o,p])=>({kind:"field",name:o,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(o),reflects:p.reflect})),events:Object.entries(s.events).map(([o,p])=>({name:o,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
830
  ${s}
831
- }`}function an(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*!!\\}"),o=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(`
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*!!\\}"),o=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;')
@@ -862,26 +862,26 @@ export function renderComponent(tag, props = {}, slots = {}) {
862
862
  }
863
863
 
864
864
  ${l}
865
- `}async function zs(t){let s=Ee.resolve(t.inputDir),o=Ee.resolve(t.outputDir);if(!(await tn(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(o,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ee.join(o,x);return await Sr(k,R.endsWith(`
865
+ `}async function zs(t){let s=Ee.resolve(t.inputDir),o=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(o,{recursive:!0});let y=[],g=async(x,R)=>{let k=Ee.join(o,x);return await Sr(k,R.endsWith(`
866
866
  `)?R:`${R}
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:on(x);await g(`${x.tag}.css`,t.minify?an(R):R)}}let b=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
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(`
869
869
  `)),await g("custom-elements.d.ts",Vr(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
870
870
  `)}
871
871
  export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
872
872
  ${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
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(on).join(`
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?an(x):x)}let E;if(t.bundle!==!1){E=Ee.join(o,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(o,"index.js")],outdir:o,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(o,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(o,"index.js")],outdir:o,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 tn(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ee.join(o,`${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 o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let p=o[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(`
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(o,`${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 o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let p=o[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
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(),o=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
881
881
  `).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Jr(t,s=!1,o){let p=yt.basename(t,".stx"),c=await Xr(t),l=await Gr(t),m="";if(s&&o)m=`<${o}></${o}>`;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:s,tag:o}}async function dn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),o=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await dn(c);o.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))o.push(c)}return o}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function Yr(t,s){try{if(!await r(t))return[];let o=await dn(t),p=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of o){let m=c.get(l),u=!!m,y=m?.tag,g=await Jr(l,u,y);p.push(g)}return p}catch(o){return console.error("Error generating component docs:",o),[]}}async function Qr(t){try{if(!await r(t))return[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),o=[];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(`
884
+ />`}return{name:p,path:t,description:l,props:c,example:m,isWebComponent:s,tag:o}}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}),o=[];for(let p of s){let c=yt.join(t,p.name);if(p.isDirectory()){let l=await pn(c);o.push(...l)}else if(p.isFile()&&p.name.endsWith(".stx"))o.push(c)}return o}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function Yr(t,s){try{if(!await r(t))return[];let o=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 o){let m=c.get(l),u=!!m,y=m?.tag,g=await Jr(l,u,y);p.push(g)}return p}catch(o){return console.error("Error generating component docs:",o),[]}}async function Qr(t){try{if(!await r(t))return[];let s=await Wt.promises.readdir(t,{withFileTypes:!0}),o=[];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
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]);o.push({name:m,path:c,description:y,components:[...w],directives:[...v]})}return o}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)
@@ -1015,12 +1015,12 @@ ${R}`:""}`)}if(y.push(E),t.sourcemap==="external")y.push(`${E}.map`)}let v=await
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 o)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 ns(t=[],s=[],o=[],p){return JSON.stringify({components:t,templates:s,directives:o,extraContent:p||""},null,2)}async function rs(t){try{let{componentsDir:s,templatesDir:o,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(o)console.log(`Templates directory: ${o}`);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&&o)console.log("Generating template documentation..."),y=await Qr(o),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=es(u,y,g,w),E="md";break;case"html":S=ts(u,y,g,w),E="html";break;case"json":S=ns(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 Hs(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},o=t.componentsDir||T.componentsDir,p=t.templatesDir||".";return rs({componentsDir:o,templatesDir:p,webComponentsConfig:T.webComponents,customDirectives:T.customDirectives,config:s})}var fn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function dr(t,s={}){let o={...fn,...s};if(t.trim()==="")return`
1018
+ </tr>`;c+="</tbody></table>";for(let l of o)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 ns(t=[],s=[],o=[],p){return JSON.stringify({components:t,templates:s,directives:o,extraContent:p||""},null,2)}async function rs(t){try{let{componentsDir:s,templatesDir:o,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(o)console.log(`Templates directory: ${o}`);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&&o)console.log("Generating template documentation..."),y=await Qr(o),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=es(u,y,g,w),E="md";break;case"html":S=ts(u,y,g,w),E="html";break;case"json":S=ns(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 Hs(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},o=t.componentsDir||T.componentsDir,p=t.templatesDir||".";return rs({componentsDir:o,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 dr(t,s={}){let o={...mn,...s};if(t.trim()==="")return`
1019
1019
  `;let p=t;if(o.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=is(p,o),p=ps(p,o),p=as(p,o),o.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 Vs(t,s={}){let o={...fn,...s};if(t.trim()==="")return`
1023
+ `;return p}function Vs(t,s={}){let o={...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
1026
  `),v=dr(S,o).trimEnd().split(`
@@ -1046,9 +1046,9 @@ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let y=u.substring(Math.max
1046
1046
  `),s=s.split(`
1047
1047
  `).map((c)=>c.trim()).join(`
1048
1048
  `),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function is(t,s){let p=os(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(pn(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("@")&&ds(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),B=b.startsWith("<!--"),L=b.startsWith("</"),j=b.startsWith("<")&&!L&&!B&&!k,P=b.includes("/>")||ls(b),I=pn(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 as(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(o,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(o,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(o,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(o,p)=>`{!! ${p.trim()} !!}`);return t}function ls(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let o=t.match(/<(\w+)/);if(o){let p=o[1];return s.includes(p.toLowerCase())}return!1}function pn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function ds(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let o of s)if(t.startsWith(`@${o}`))return!t.includes(`@end${o}`);return!1}function ps(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(o,p,c)=>{if(!c.trim())return o;if(c.includes("<")||c.includes(`
1051
- `)||c.includes("@"))return o;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 mn from"fs";import Vt from"path";async function Us(t="index.stx",s={}){try{let o=s.force||!1,p=Vt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!o)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(p);if(!mn.existsSync(c))mn.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=hn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=hn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(o){return console.error(`Error creating file: ${o instanceof Error?o.message:String(o)}`),!1}}function hn(t){switch(t){case"basic":return xn();case"component":return us();case"layout":return fs();case"blog":return ms();case"api":return gs();case"app":return hs();default:return xn()}}function xn(){return`<script>
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("@")&&ds(b),k=b.startsWith("<!DOCTYPE")||b.startsWith("<!doctype"),B=b.startsWith("<!--"),L=b.startsWith("</"),j=b.startsWith("<")&&!L&&!B&&!k,P=b.includes("/>")||ls(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 as(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(o,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(o,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(o,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(o,p)=>`{!! ${p.trim()} !!}`);return t}function ls(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let o=t.match(/<(\w+)/);if(o){let p=o[1];return s.includes(p.toLowerCase())}return!1}function fn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function ds(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let o of s)if(t.startsWith(`@${o}`))return!t.includes(`@end${o}`);return!1}function ps(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(o,p,c)=>{if(!c.trim())return o;if(c.includes("<")||c.includes(`
1051
+ `)||c.includes("@"))return o;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 Us(t="index.stx",s={}){try{let o=s.force||!1,p=Vt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!o)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(o){return console.error(`Error creating file: ${o instanceof Error?o.message:String(o)}`),!1}}function xn(t){switch(t){case"basic":return vn();case"component":return us();case"layout":return fs();case"blog":return ms();case"api":return gs();case"app":return hs();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 = [
@@ -1474,7 +1474,7 @@ const features = [
1474
1474
  })();
1475
1475
  </script>
1476
1476
  </body>
1477
- </html>`}var Ws="f9c3713";function Io(t){return t}function Do(t){return t}var wn=`
1477
+ </html>`}var Ws="f9c3713";function Io(t){return t}function Do(t){return t}var Sn=`
1478
1478
  <script data-stx-helpers>
1479
1479
  (function() {
1480
1480
  'use strict'
@@ -1785,8 +1785,8 @@ 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,s){let o=Math.max(0,Math.round((s-t)/1000));if(o<60)return`${o}s ago`;if(o<3600)return`${Math.round(o/60)}m ago`;return`${Math.round(o/3600)}h ago`}function Pi(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function On(t,s="stx"){let o=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(o,"pantry","@stacksjs",s);if(Me.existsSync(c))return c;let l=Te.dirname(o);if(l===o)break;o=l}return null}var Dn=["@stacksjs/stx","bun-plugin-stx"];function Ai(t){try{let s=Me.readFileSync(Te.join(t,"package.json"),"utf8"),o=JSON.parse(s)?.version;return typeof o==="string"?o:null}catch{return null}}function Oi(t,s=6){let o=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 Dn){let S=Te.join(u,w),E=Ai(S);if(E!==null)p.push({name:w,version:E,dir:Te.relative(o,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(o,"node_modules");if(Me.existsSync(m))l(m,0);return p}function Di(t){let s=[];for(let o of Dn){let p=t.filter((m)=>m.name===o);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:`${o} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${o} 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 ${o}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${o}/package.json' -exec grep -H '"version"' {} +`})}return s}async function pr(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),o=t.resolve??Pi,p=Date.now(),c=[],l=o("@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=o("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let y of Di(Oi(s)))c.push(y);let u=On(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 fr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},o=["stx runtime resolution:"];for(let p of t.checks)if(o.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)o.push(` \u2192 ${p.fix}`);return o.push(""),o.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),o.join(`
1789
- `)}var ft={name:"bun-plugin-stx",async setup(t){let o={...await i(),...t.config?.stx},p=new Set,c=o.webComponents?.enabled?`./${_t.relative(_t.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(o.webComponents?.enabled)try{let m=await Wn(o,p);if(l.push(...m),o.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(o.cache&&o.cachePath){let x=await Zt(m,o);if(x){if(o.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}),o.debug)throw R});let v=await U.timeAsync("directive-processing",async()=>await n(b,S,m,o,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-t8kadtva.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 o=Math.max(0,Math.round((s-t)/1000));if(o<60)return`${o}s ago`;if(o<3600)return`${Math.round(o/60)}m ago`;return`${Math.round(o/3600)}h ago`}function Pi(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Dn(t,s="stx"){let o=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(o,"pantry","@stacksjs",s);if(Me.existsSync(c))return c;let l=Te.dirname(o);if(l===o)break;o=l}return null}var Mn=["@stacksjs/stx","bun-plugin-stx"];function Oi(t){try{let s=Me.readFileSync(Te.join(t,"package.json"),"utf8"),o=JSON.parse(s)?.version;return typeof o==="string"?o:null}catch{return null}}function Ai(t,s=6){let o=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=Oi(S);if(E!==null)p.push({name:w,version:E,dir:Te.relative(o,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(o,"node_modules");if(Me.existsSync(m))l(m,0);return p}function Di(t){let s=[];for(let o of Mn){let p=t.filter((m)=>m.name===o);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:`${o} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${o} 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 ${o}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${o}/package.json' -exec grep -H '"version"' {} +`})}return s}async function pr(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),o=t.resolve??Pi,p=Date.now(),c=[],l=o("@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=o("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let y of Di(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 fr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},o=["stx runtime resolution:"];for(let p of t.checks)if(o.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)o.push(` \u2192 ${p.fix}`);return o.push(""),o.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),o.join(`
1789
+ `)}var ft={name:"bun-plugin-stx",async setup(t){let o={...await i(),...t.config?.stx},p=new Set,c=o.webComponents?.enabled?`./${_t.relative(_t.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(o.webComponents?.enabled)try{let m=await Wn(o,p);if(l.push(...m),o.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(o.cache&&o.cachePath){let x=await Zt(m,o);if(x){if(o.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}),o.debug)throw R});let v=await U.timeAsync("directive-processing",async()=>await n(b,S,m,o,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-1ryby13h.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
1792
  ${R}`}if(v=await q(v),u.forEach((x)=>p.add(x)),o.cache&&o.cachePath){if(await Qt(m,v,u,o),o.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"}),o.debug)console.error("stx Plugin Error:",y);let g=y,b=g.line||null,w=g.context||null;return{contents:o.debug||D()?`<!DOCTYPE html>
@@ -1849,19 +1849,19 @@ ${R}`}if(v=await q(v),u.forEach((x)=>p.add(x)),o.cache&&o.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,s={}){let o=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||o+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 wt(S);let E=o;try{if(E=await Ye(o),E!==o)console.log(`${e.yellow}Port ${o} 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-wr78aadr.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:se}=await import("./chunk-h4avjh3q.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 Ae=Se.join(process.cwd(),"channels.ts");if(Ne.existsSync(Ae))try{let le=await se(Ae);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-hvme6tw2.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(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 se=Se.join(y,F.pathname);if(Ne.existsSync(se)&&Ne.statSync(se).isFile()){let le=Bun.file(se),W=Se.extname(se).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 Ae=Se.join(process.cwd(),"public",F.pathname);if(Ne.existsSync(Ae)&&Ne.statSync(Ae).isFile()){let le=Bun.file(Ae),W=Se.extname(Ae).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 o=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||o+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=o;try{if(E=await Ye(o),E!==o)console.log(`${e.yellow}Port ${o} 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-zzb53zgh.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:se}=await import("./chunk-h4avjh3q.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 se(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-mgcykz7g.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(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 se=Se.join(y,F.pathname);if(Ne.existsSync(se)&&Ne.statSync(se).isFile()){let le=Bun.file(se),W=Se.extname(se).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()}),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,se)=>{if(!se||Rt(se))return;if(Ct(se)){console.log(`${e.yellow}File ${e.bright}${se}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee();let $e=await b();if(await en(S),c&&l)if($e)l.reload(se);else l.error("Build failed - check console for details")}else if($t(se)){if(console.log(`${e.cyan}CSS ${e.bright}${se}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(se)}});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 s=t.map((p)=>p.split(Pe.sep)),o=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))o.push(c);else break}return o.join(Pe.sep)}async function bn(t,s={}){let o=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((Ae)=>`<option value="${Ae}"${Ae===j?" selected":""}>${Ae}</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,se)=>{if(!se||Rt(se))return;if(Ct(se)){console.log(`${e.yellow}File ${e.bright}${se}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee();let $e=await b();if(await en(S),c&&l)if($e)l.reload(se);else l.error("Build failed - check console for details")}else if($t(se)){if(console.log(`${e.cyan}CSS ${e.bright}${se}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(se)}});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 qn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Pe.sep)),o=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))o.push(c);else break}return o.join(Pe.sep)}async function bn(t,s={}){let o=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=qn(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
  `),se=`
1859
1859
  <!DOCTYPE html>
1860
1860
  <html lang="en">
1861
1861
  <head>
1862
1862
  <meta charset="UTF-8">
1863
1863
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
1864
- <title>${Un(B.title||Pe.basename(x))}</title>
1864
+ <title>${Vn(B.title||Pe.basename(x))}</title>
1865
1865
  <!-- Syntax highlighting styles -->
1866
1866
  <style id="syntax-theme">
1867
1867
  :root {
@@ -2008,7 +2008,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(j.u
2008
2008
  </head>
2009
2009
  <body>
2010
2010
  ${kt(B)}
2011
- ${vt(G)}
2011
+ ${wt(G)}
2012
2012
 
2013
2013
  ${k}
2014
2014
 
@@ -2019,15 +2019,15 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(j.u
2019
2019
  </html>
2020
2020
  `,he=`/${Pe.relative(l,x).replace(/\.md$/,"")}`;if(he.endsWith("/index"))he=he.slice(0,-6)||"/";m[he||"/"]={filePath:x,content:se,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
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}=sr(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=o;try{if(b=await Ye(o),b!==o)console.log(`${e.yellow}Port ${o} 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 se=0;se<L.paramNames.length;se++)I[L.paramNames[se]]=decodeURIComponent(j[se+1]);let F=P.content,G=`<script>window.__routeParams = ${JSON.stringify(I)};</script>`;if(F.includes("</head>"))F=F.replace("</head>",`${G}
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>",`${wn}
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>${Un(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}
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
+ </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>${Vn(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 Un(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 qn(t){try{return xt(await Bun.file(t).text())}catch{return}}function qt(t){let s=Bun.file(t),o=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(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[o]||"application/octet-stream",...l}})}async function vn(t=".",s={}){let o=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||o+1,u=ie.resolve(t),{loadStxConfig:y}=await import("./chunk-wr78aadr.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-hvme6tw2.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((A)=>ve.existsSync(A)))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:A,prefix:z}of B)if(ve.existsSync(A)){let N=M(ie.dirname(A),{pagesDir:ie.basename(A)});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 ti(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={},se=null;try{let{loadStxConfig:A}=await import("./chunk-wr78aadr.js"),z=await A(u);if(z?.apiRouter)se=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-h4avjh3q.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 oe=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${oe} broadcast channel${oe!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(oe){console.warn(`${e.yellow}Failed to load channels.ts: ${oe.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,Ae=new Set,le=async(A)=>{let z=ir(R,A);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(A,z)=>{try{let{processDirectives:N,extractVariables:V,defaultConfig:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-wr78aadr.js"),{checkCache:oe,cacheTemplate:Q,readFileCached:X,templateCache:J}=await import("./chunk-k1bm8hsv.js"),ke=await We(u),Je=(de)=>{if(!de)return de;if(ie.isAbsolute(de))return de;return ie.resolve(u,de)},O={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=Je(O.partialsDir),O.componentsDir=Je(O.componentsDir),O.layoutsDir=Je(O.layoutsDir),O.storesDir=Je(O.storesDir||"stores"),O.cachePath=Je(O.cachePath)??a(u,"cache");let be=!z&&!s.profile,pe=O.cache!==!1;if(pe&&be){let de=J.get(A.filePath);if(de)try{if((await ve.promises.stat(A.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(A.filePath);return{route:A,content:Re,status:gt?.status??await qn(A.filePath),headers:gt?.headers}}}}catch{}let Ie=await oe(A.filePath,O);if(Ie){let He=Ie;if(P)He=ge(He,{preserveHead:!0});let ze=W.get(A.filePath);return{route:A,content:He,status:ze?.status??await qn(A.filePath),headers:ze?.headers}}}let me=pe?await X(A.filePath):await Bun.file(A.filePath).text(),Ce=xt(me),{classifyAllScripts:Y}=await import("./chunk-wr78aadr.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:A.filePath,__dirname:ie.dirname(A.filePath),__stx_options:O,params:z??{},__stx_runtime_head:{}};for(let de of Ve)try{await V(de,fe,A.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,Ie?.message||Ie)}let Ke=new Set,Oe;if(s.profile){let de=performance.now();Oe=await N(ue,fe,A.filePath,O,Ke);let Ie=performance.now()-de,He=ie.relative(u,A.filePath)||A.filePath;console.log(`[stx:profile] ${He} \u2192 ${Ie.toFixed(2)}ms`)}else Oe=await N(ue,fe,A.filePath,O,Ke);if(!P)Oe=await Ge(Oe,{router:O.router});{let{interpolateScriptExpressions:de}=await import("./chunk-t8kadtva.js");Oe=Oe.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)Oe=ge(Oe,{preserveHead:!0});if(pe&&be)await Q(A.filePath,Oe,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-dyhb8ey9.js"),lt=Kn(fe),mt=fe.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let de=fe.streamBoundaries||{},Ie={...O,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},A.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)Ae.add(A.pattern);else lt=void 0;let Kt=Be(fe),Xt=Fe(fe);if(be)W.set(A.filePath,{status:Kt,headers:Xt});return{route:A,content:Oe,status:Kt??Ce,headers:Xt,boundaries:lt}}catch(N){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,N),null}},Ue=8,qe=async()=>{he.clear(),j.clear();for(let A=0;A<k.length;A+=Ue){let z=k.slice(A,A+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 A=0;A<L.length;A+=Ue){let z=L.slice(A,A+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 wt(u);let at=o;try{if(at=await Ye(o),at!==o)console.log(`${e.yellow}Port ${o} 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 A=s.hmrPort||at+1;l=Pt({wsPort:A,verbose:!1}),m=l.start(A)}let Lt=(A,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(A.includes("</head>"))return A.replace("</head>",`${V}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+A};console.log(`${e.blue}Starting server...${e.reset}`);let It=Ui({port:at,async fetch(A){let z=new URL(A.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((O)=>w(O,u,S)))return new Response("Not Found",{status:404});let[Ge,oe,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(oe?.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 O=decodeURIComponent(z.pathname.slice(16));if(O)try{let be=`<${O} />`,pe={...buildConfig,autoShell:!1},me=await processDirectives(be,{},ie.join(u,"components",`${O}.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:O}=await import("./chunk-akbb6j7s.js"),be=await O(A,{publicDir:ie.join(u,N),cacheDir:a(u,"cache","img")});if(be)return be}if(se)try{let O=await se.handleRequest(A);if(O.status!==404)return O}catch{}if(G[z.pathname])try{return await G[z.pathname](A)}catch(O){return new Response(JSON.stringify({error:O.message}),{status:500,headers:{"Content-Type":"application/json"}})}let X=await E(A);if(X)return X;let J=gn(z.pathname,k);if(J){let O=he.get(J.route.pattern),be=Ae.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)O=pe}if(O){let pe=O.status??200,me=O.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,A,{isServer:!0}),ue=await st(Ce.middleware,Ve);if(ue.redirect){let fe=ue.redirect.path,Ke=ue.redirect.options.redirectCode||302,Oe=new Headers(ue.responseHeaders);return Oe.set("Location",fe),new Response(null,{status:Ke,headers:Oe})}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>`;O.content=O.content.replace("</head>",`${fe}</head>`)}}let Y=O.content;if(P&&ni(A)){let Le=xe(Y),Ve=ae(Y),ue=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=ue?ei(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)},[Yi]:cs(),...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(O.boundaries&&O.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-dyhb8ey9.js");return Ve(Le(Y,O.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 O=L.map((pe)=>pe.route),be=gn(z.pathname,O);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 O=ke.content;if(O=await f(O,u),c)O=Xe(O,m);if(s.native)if(O.includes("<head>"))O=O.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 O="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+O;return new Response(O,{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 O=Je;if(O=await f(O,u),c)O=Xe(O,m);return new Response(O,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let z=await le(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
2029
- ${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),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 Vn(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 s=Bun.file(t),o=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(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[o]||"application/octet-stream",...l}})}async function wn(t=".",s={}){let o=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||o+1,u=ie.resolve(t),{loadStxConfig:y}=await import("./chunk-zzb53zgh.js"),g=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-mgcykz7g.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 ti(u,s.stxOptions?.shell),I){if(P=await wr(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={},se=null;try{let{loadStxConfig:O}=await import("./chunk-zzb53zgh.js"),z=await O(u);if(z?.apiRouter)se=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-h4avjh3q.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 oe=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${oe} broadcast channel${oe!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(oe){console.warn(`${e.yellow}Failed to load channels.ts: ${oe.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-zzb53zgh.js"),{checkCache:oe,cacheTemplate:Q,readFileCached:X,templateCache:J}=await import("./chunk-jphk7zc5.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 oe(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-zzb53zgh.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-1ryby13h.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-122d4nek.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=o;try{if(at=await Ye(o),at!==o)console.log(`${e.yellow}Port ${o} 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=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,oe,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(oe?.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-akbb6j7s.js"),be=await A(O,{publicDir:ie.join(u,N),cacheDir:a(u,"cache","img")});if(be)return be}if(se)try{let A=await se.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&&ni(O)){let Le=xe(Y),Ve=ae(Y),ue=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=ue?ei(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)},[Yi]:cs(),...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-122d4nek.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
+ ${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
- ${e.yellow}Routes:${e.reset}`);let jt=[...or(k,u)];for(let{route:A}of L)jt.push(`${A.pattern}`);if(jt.forEach((A,z)=>{let V=z===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${A}`)}),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()}),s.native){let A,z=ie.join(R,"index.stx");if(ve.existsSync(z)){let V=await Bun.file(z).text();A=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:!!A,sidebarConfig:A})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(oe)=>oe.startsWith("public/")||oe.startsWith("public\\"),z=(oe)=>{let Q=oe.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},N=new Map,V=()=>{let oe=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(![...oe].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))oe.add(J)}for(let[Q,X]of N)if(!oe.has(Q))X.close(),N.delete(Q);for(let Q of oe)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=(oe,Q,X)=>(we=we.catch(()=>{}).then(()=>Ge(oe,Q,X)),we),Ge=async(oe,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(A(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-k1bm8hsv.js");J(ie.resolve(oe,X)),ke.delete(ie.resolve(oe,X))}catch{}if(I&&X){if(ie.resolve(oe,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-k1bm8hsv.js");J(ie.resolve(oe,X)),ke.delete(ie.resolve(oe,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 oe of N.values())oe.close();if(l)ht();It.stop(),process.exit(0)})}return!0}export{Bs,Fs,zs,Hs,dr,Vs,Us,Ws,Io,Do,pr,fr,yn,bn,vn};
2032
+ ${e.yellow}Routes:${e.reset}`);let jt=[...or(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()}),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=(oe)=>oe.startsWith("public/")||oe.startsWith("public\\"),z=(oe)=>{let Q=oe.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},N=new Map,V=()=>{let oe=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(![...oe].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))oe.add(J)}for(let[Q,X]of N)if(!oe.has(Q))X.close(),N.delete(Q);for(let Q of oe)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=(oe,Q,X)=>(we=we.catch(()=>{}).then(()=>Ge(oe,Q,X)),we),Ge=async(oe,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-jphk7zc5.js");J(ie.resolve(oe,X)),ke.delete(ie.resolve(oe,X))}catch{}if(I&&X){if(ie.resolve(oe,X)===I||ie.basename(I)===X){let ke=await wr(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-jphk7zc5.js");J(ie.resolve(oe,X)),ke.delete(ie.resolve(oe,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 oe of N.values())oe.close();if(l)ht();It.stop(),process.exit(0)})}return!0}export{Bs,Fs,zs,Hs,dr,Vs,Us,Ws,Io,Do,pr,fr,yn,bn,wn};