@stacksjs/stx 0.2.845 → 0.2.846
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.
- package/dist/builtins/image-worker.d.ts +1 -17
- package/dist/builtins/image-worker.js +3 -16
- package/dist/{chunk-vf0xbptq.js → chunk-098mrr5f.js} +2 -2
- package/dist/{chunk-ndsygfeb.js → chunk-0e4y6h1h.js} +14 -14
- package/dist/chunk-13sp1247.js +2 -0
- package/dist/chunk-1kdtapc1.js +2 -0
- package/dist/{chunk-6x6w0v1k.js → chunk-1qp5808r.js} +3 -3
- package/dist/{chunk-hc1f1yq8.js → chunk-1w5hte9z.js} +2 -2
- package/dist/chunk-263gby2p.js +2 -0
- package/dist/{chunk-4dxq7ft1.js → chunk-2a792g5e.js} +2 -2
- package/dist/{chunk-kbv5nwwd.js → chunk-30g5kqy0.js} +1 -1
- package/dist/chunk-33ggd5at.js +2 -0
- package/dist/chunk-3q19w77r.js +2 -0
- package/dist/{chunk-5a7etvxz.js → chunk-4041q9sd.js} +4 -4
- package/dist/chunk-40x0vwza.js +2 -0
- package/dist/{chunk-c62wxswd.js → chunk-444sbdm8.js} +27 -27
- package/dist/chunk-4cmda04d.js +2 -0
- package/dist/{chunk-5y3m5vzg.js → chunk-4jmkvzns.js} +2 -2
- package/dist/{chunk-0gg7k9cj.js → chunk-4v6mbvqv.js} +4 -4
- package/dist/{chunk-rncmfgpk.js → chunk-50tnhq5f.js} +25 -25
- package/dist/{chunk-pb9347sn.js → chunk-5903tzcw.js} +3 -3
- package/dist/chunk-5xt4tjpm.js +2 -0
- package/dist/chunk-6289h3tr.js +2 -0
- package/dist/{chunk-nqj1mkkz.js → chunk-66e0d2t7.js} +1 -1
- package/dist/{chunk-1c6kczkt.js → chunk-6g7wrn48.js} +1 -1
- package/dist/{chunk-3rjgm7qk.js → chunk-6pgq75h9.js} +5 -5
- package/dist/chunk-6q7ke5p0.js +2 -0
- package/dist/{chunk-y06rw18j.js → chunk-6x6xthsv.js} +2 -2
- package/dist/chunk-6ya0860g.js +2 -0
- package/dist/{chunk-jabw4ck5.js → chunk-7qwfbafg.js} +2 -2
- package/dist/{chunk-r4jwhy37.js → chunk-7rcc2tzz.js} +3 -3
- package/dist/{chunk-tpyk6b4c.js → chunk-81nmqdht.js} +2 -2
- package/dist/{chunk-py5x8fkq.js → chunk-82vf29ty.js} +2 -2
- package/dist/{chunk-48vnw9t9.js → chunk-84myqca7.js} +2 -2
- package/dist/{chunk-fs5mshcs.js → chunk-8az9e5b9.js} +5 -5
- package/dist/chunk-8k7rfy77.js +3 -0
- package/dist/{chunk-28zze2wm.js → chunk-9d9sartn.js} +1 -1
- package/dist/chunk-9enwmg0z.js +2 -0
- package/dist/{chunk-c6yc6qsv.js → chunk-9hfk5wf1.js} +5 -5
- package/dist/chunk-a7z6j9ga.js +2 -0
- package/dist/chunk-ab6dw6f4.js +2 -0
- package/dist/chunk-adnntqk3.js +2 -0
- package/dist/{chunk-47n5s7wk.js → chunk-an6vb4ng.js} +2 -2
- package/dist/chunk-bhzbcmm7.js +2 -0
- package/dist/{chunk-k1tbgnhf.js → chunk-bsr6kf34.js} +1 -1
- package/dist/{chunk-md84j62m.js → chunk-c78dsx3f.js} +10 -10
- package/dist/{chunk-ntg8ttm4.js → chunk-caw0wzns.js} +3 -3
- package/dist/chunk-cfez1qbm.js +2 -0
- package/dist/chunk-cgyddqxw.js +2 -0
- package/dist/chunk-cng4fhpt.js +2 -0
- package/dist/{chunk-6trgwvt0.js → chunk-cpdfxy8g.js} +12 -12
- package/dist/chunk-ctq1qy1g.js +2 -0
- package/dist/chunk-cyghcps7.js +2 -0
- package/dist/{chunk-2cafvex6.js → chunk-d1pat213.js} +2 -2
- package/dist/{chunk-f34ce0pn.js → chunk-d4jhyxp6.js} +6 -6
- package/dist/{chunk-xr8hg79c.js → chunk-ds1vj0dw.js} +4 -4
- package/dist/{chunk-kxj5sp5w.js → chunk-dspmqeg0.js} +4 -4
- package/dist/chunk-e26aqarz.js +2 -0
- package/dist/chunk-e7816ep3.js +2 -0
- package/dist/{chunk-mnt7jbek.js → chunk-ea5w92vs.js} +3 -3
- package/dist/chunk-en8hnq2q.js +2 -0
- package/dist/chunk-enz6fsdx.js +2 -0
- package/dist/{chunk-tjnf4a8g.js → chunk-evww725k.js} +59 -59
- package/dist/chunk-eydqn4gz.js +2 -0
- package/dist/chunk-fk7gs41v.js +2 -0
- package/dist/chunk-fnfq6fkk.js +12 -0
- package/dist/chunk-fx04tq90.js +2 -0
- package/dist/chunk-fzba0b0n.js +2 -0
- package/dist/chunk-g7tj2tnz.js +2 -0
- package/dist/chunk-ga0293gz.js +2 -0
- package/dist/chunk-gab3h25h.js +2 -0
- package/dist/{chunk-1h6pb8d1.js → chunk-gs33xdk7.js} +4 -4
- package/dist/{chunk-ka5ea34g.js → chunk-h76wsqr4.js} +2 -2
- package/dist/chunk-hczqyk7c.js +2 -0
- package/dist/{chunk-3sskqw4b.js → chunk-hff8z61n.js} +1 -1
- package/dist/{chunk-k7am94hr.js → chunk-hp8ny2zb.js} +5 -5
- package/dist/chunk-hs6fg0k9.js +2 -0
- package/dist/chunk-hsg4ggt0.js +2 -0
- package/dist/chunk-j1n2xb48.js +3 -0
- package/dist/{chunk-zwxncs2e.js → chunk-j3zy3mrn.js} +6 -6
- package/dist/{chunk-02qbawwq.js → chunk-jx14j83s.js} +3 -3
- package/dist/chunk-k3pfadjb.js +2 -0
- package/dist/chunk-kmnre1tq.js +2 -0
- package/dist/{chunk-6tyjvxgb.js → chunk-krdfnsz6.js} +8 -8
- package/dist/{chunk-x0dx1pyf.js → chunk-m8cpabd2.js} +3 -3
- package/dist/chunk-mgtp037k.js +3 -0
- package/dist/chunk-mp42d9v5.js +2 -0
- package/dist/chunk-mtmgrccj.js +2 -0
- package/dist/{chunk-r3jf8v5a.js → chunk-mzyx6y1a.js} +30 -30
- package/dist/chunk-n20tsy6a.js +2 -0
- package/dist/{chunk-fm8gfj2g.js → chunk-n475s55q.js} +2 -2
- package/dist/{chunk-b6qf7w2b.js → chunk-neh3kewg.js} +4 -4
- package/dist/{chunk-y7aqf8r7.js → chunk-ng8nkbp2.js} +2 -2
- package/dist/{chunk-eaz30495.js → chunk-nhn69eva.js} +2 -2
- package/dist/{chunk-7r4p7zjn.js → chunk-nsc93haq.js} +6 -6
- package/dist/{chunk-rk2ex6qx.js → chunk-p8ry1q7c.js} +2 -2
- package/dist/chunk-pdt1phnh.js +2 -0
- package/dist/{chunk-s68p10zh.js → chunk-ph57nv7v.js} +2 -2
- package/dist/{chunk-7s411sa9.js → chunk-prrf0j54.js} +5 -5
- package/dist/chunk-q87wwwra.js +2 -0
- package/dist/{chunk-87ksn02m.js → chunk-qttjrja7.js} +2 -2
- package/dist/{chunk-hgk1v60t.js → chunk-r1984y6y.js} +10 -10
- package/dist/chunk-r1mvd96m.js +2 -0
- package/dist/{chunk-78q3apyy.js → chunk-r3v1zaj0.js} +2 -2
- package/dist/{chunk-vhxrrqrg.js → chunk-rg2gfyy0.js} +2 -2
- package/dist/{chunk-rpapxkdm.js → chunk-rgy9c7d8.js} +3 -3
- package/dist/{chunk-97bvpszy.js → chunk-rn7710jg.js} +3 -3
- package/dist/{chunk-8g5dsjr0.js → chunk-s2a51j0k.js} +6 -6
- package/dist/chunk-s321pb85.js +2 -0
- package/dist/{chunk-11kp389s.js → chunk-s6qzmwp3.js} +1 -1
- package/dist/{chunk-bqsrtvad.js → chunk-serwcna2.js} +2 -2
- package/dist/chunk-stss2b88.js +2 -0
- package/dist/chunk-svxkcdhh.js +2 -0
- package/dist/{chunk-ncrrxp60.js → chunk-sxsjxme0.js} +4 -4
- package/dist/{chunk-r8xwd8r1.js → chunk-t3e95q80.js} +13 -13
- package/dist/chunk-t6gm8z7x.js +2 -0
- package/dist/chunk-tkssavxx.js +2 -0
- package/dist/chunk-tw6y23ew.js +2 -0
- package/dist/{chunk-302gek13.js → chunk-tzqnf28n.js} +3 -3
- package/dist/{chunk-tzdwg9rw.js → chunk-v8y01jbr.js} +4 -4
- package/dist/{chunk-9mtyxvhk.js → chunk-vh8wn94m.js} +2 -2
- package/dist/chunk-vm34qp5k.js +2 -0
- package/dist/chunk-vtg2tqzt.js +2 -0
- package/dist/{chunk-6hb75r07.js → chunk-vxayh4az.js} +6 -6
- package/dist/{chunk-5p96rafz.js → chunk-vyggv4k0.js} +2 -2
- package/dist/{chunk-fg80w4zk.js → chunk-wbx27kdd.js} +2 -2
- package/dist/{chunk-315q48qy.js → chunk-wd632rge.js} +7 -7
- package/dist/chunk-wddaxpep.js +2 -0
- package/dist/{chunk-mveqaxkr.js → chunk-wvsnp294.js} +7 -7
- package/dist/{chunk-rb6vr5v9.js → chunk-wzpd3htt.js} +7 -7
- package/dist/{chunk-8qjf16yr.js → chunk-x1n01gc1.js} +4 -4
- package/dist/{chunk-4rfedg2f.js → chunk-x3pxxx7j.js} +3 -3
- package/dist/chunk-x6bt567m.js +2 -0
- package/dist/{chunk-8hy5g1hq.js → chunk-xdzs2mxv.js} +5 -5
- package/dist/chunk-xf4d9gam.js +2 -0
- package/dist/chunk-xf5db38j.js +2 -0
- package/dist/{chunk-2ytaezad.js → chunk-xhytkzg7.js} +2 -2
- package/dist/{chunk-3ba0nqwm.js → chunk-xj5j18nf.js} +2 -2
- package/dist/{chunk-79wb76ya.js → chunk-xq9w5g23.js} +1 -1
- package/dist/{chunk-010yhk6m.js → chunk-xskygt2v.js} +5 -5
- package/dist/chunk-y5t7ec69.js +2 -0
- package/dist/chunk-yk90sqqv.js +2 -0
- package/dist/chunk-z231es22.js +2 -0
- package/dist/{chunk-n91sm385.js → chunk-z26fg4p0.js} +2 -2
- package/dist/{chunk-dhgjq9jx.js → chunk-zkn55966.js} +5 -5
- package/dist/chunk-zphekzv8.js +2 -0
- package/dist/chunk-zsft5466.js +2 -0
- package/dist/{chunk-9vg3jtzw.js → chunk-zx2xwrp3.js} +6 -6
- package/dist/{chunk-69b8mr68.js → chunk-zyt8k9n0.js} +2 -2
- package/dist/cli.js +19 -19
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/framework-composables.js +13 -1
- package/dist/installed-entry.d.ts +8 -0
- package/dist/installed-entry.js +19 -0
- package/dist/pwa.js +3 -3
- package/dist/ssg.js +4 -4
- package/package.json +5 -5
- package/dist/chunk-01gwdj2y.js +0 -2
- package/dist/chunk-12tkqtrv.js +0 -2
- package/dist/chunk-168fwztf.js +0 -2
- package/dist/chunk-1cdxe8yt.js +0 -2
- package/dist/chunk-1k751fgt.js +0 -2
- package/dist/chunk-3qa40hgd.js +0 -2
- package/dist/chunk-3qstewq3.js +0 -2
- package/dist/chunk-40r740w1.js +0 -2
- package/dist/chunk-469nzheq.js +0 -2
- package/dist/chunk-5hhyqze9.js +0 -2
- package/dist/chunk-60jtrz9f.js +0 -2
- package/dist/chunk-64evx0my.js +0 -2
- package/dist/chunk-6vcpmt0y.js +0 -2
- package/dist/chunk-7tdwa595.js +0 -2
- package/dist/chunk-7xp2ec0v.js +0 -2
- package/dist/chunk-8nq2snvy.js +0 -2
- package/dist/chunk-8s27mteq.js +0 -2
- package/dist/chunk-8weaawqm.js +0 -2
- package/dist/chunk-afyvnpr9.js +0 -2
- package/dist/chunk-as6x6be8.js +0 -2
- package/dist/chunk-aw45yjrw.js +0 -2
- package/dist/chunk-b30fzxwd.js +0 -2
- package/dist/chunk-b3wcs8bk.js +0 -2
- package/dist/chunk-bygxt820.js +0 -3
- package/dist/chunk-c3y7cxe7.js +0 -2
- package/dist/chunk-d5bjpjbv.js +0 -2
- package/dist/chunk-dmmt4psb.js +0 -12
- package/dist/chunk-e1vf62ck.js +0 -2
- package/dist/chunk-emzz6seq.js +0 -2
- package/dist/chunk-exr9599h.js +0 -2
- package/dist/chunk-f1wv2q2z.js +0 -2
- package/dist/chunk-fpc1n3je.js +0 -2
- package/dist/chunk-fyesbfvr.js +0 -2
- package/dist/chunk-fz433ybr.js +0 -2
- package/dist/chunk-hbkh87n2.js +0 -2
- package/dist/chunk-hpw6hq7p.js +0 -2
- package/dist/chunk-j274w1ac.js +0 -2
- package/dist/chunk-jf37tpj2.js +0 -2
- package/dist/chunk-jv2z9qb7.js +0 -2
- package/dist/chunk-k609nyan.js +0 -2
- package/dist/chunk-msd0ezxm.js +0 -2
- package/dist/chunk-n4c8srx8.js +0 -2
- package/dist/chunk-nfxd6y75.js +0 -2
- package/dist/chunk-pj1xj34h.js +0 -2
- package/dist/chunk-pv2mrc9g.js +0 -2
- package/dist/chunk-pwdnqe30.js +0 -2
- package/dist/chunk-qeej9h56.js +0 -2
- package/dist/chunk-rapk2r7b.js +0 -2
- package/dist/chunk-sss23kn5.js +0 -2
- package/dist/chunk-sv52qc36.js +0 -3
- package/dist/chunk-t4n23dh5.js +0 -2
- package/dist/chunk-vkrxrt0a.js +0 -2
- package/dist/chunk-vzpbxgg7.js +0 -2
- package/dist/chunk-wvwca1e9.js +0 -2
- package/dist/chunk-xjbc3bhs.js +0 -2
- package/dist/chunk-xtbmntht.js +0 -2
- package/dist/chunk-xvd3vdrw.js +0 -2
- package/dist/chunk-xvtp7nyj.js +0 -2
- package/dist/chunk-xy45tx27.js +0 -2
- package/dist/chunk-yg5a54pj.js +0 -2
- package/dist/chunk-yhzakgpp.js +0 -2
- package/dist/chunk-z3qgv971.js +0 -2
- package/dist/chunk-zztfp9qh.js +0 -2
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pe,hn,Nt,Dt,m,r,ge,p}from"./chunk-
|
|
2
|
+
import{pe,hn,Nt,Dt,m,r,ge,p}from"./chunk-evww725k.js";import{bt,Ae,cc,cs,Lo,jo,i}from"./chunk-50tnhq5f.js";import{ae,ce,Rr,_e,z,Cn}from"./chunk-t3e95q80.js";import{kt,mr,As,Ps,Is,_t,Ct,Et,Tt,$t,Rt,tt}from"./chunk-dspmqeg0.js";import{_s,a,O}from"./chunk-c78dsx3f.js";import{gt,On,Ee,j,pa,bo,Gr,qe,fa,Ke,Te}from"./chunk-xdzs2mxv.js";import{pr,fr}from"./chunk-ng8nkbp2.js";import{e,ln,ar,b}from"./chunk-j3zy3mrn.js";import{Ye}from"./chunk-wd632rge.js";import{Re}from"./chunk-4y6hes3h.js";import{Pn}from"./chunk-ph57nv7v.js";import{G,we,ve}from"./chunk-nsc93haq.js";import{c}from"./chunk-8k7rfy77.js";import{X}from"./chunk-7qwfbafg.js";async function zn(t){try{let n=await Bun.file(t).text(),o=Nn(n),d=Un(n,t),s=Wn(n,o),l=Vn(n,o);return{file:t,metrics:o,issues:d,suggestions:s,performance:l}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Nn(t){let n=t.split(`
|
|
3
3
|
`),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),s=(o?o[1]:"").split(`
|
|
4
4
|
`).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,g=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+g,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,y=Math.min(10,Math.ceil(l.total*0.5+h*0.1+x*0.3+(s>10?s*0.05:0)+w));return{lines:n.length,characters:t.length,directives:l,expressions:h,components:x,layouts:v,scriptLines:s,complexity:y}}function Un(t,n){let o=[],d=Xt(t,"if","endif");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let s=Xt(t,"foreach","endforeach");if(s>0)o.push({type:"error",category:"syntax",message:`Found ${s} 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 u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)o.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)o.push({type:"warning",category:"accessibility",message:`Found ${x.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let g=t.split(`
|
|
5
|
-
`).filter((x)=>x.length>120);if(g.length>0)o.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)o.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function Wn(t,n){let o=[];if(n.complexity>7)o.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function Vn(t,n){let o=1;if(o+=n.directives.conditionals*0.1,o+=n.directives.loops*0.5,o+=n.directives.includes*2,o+=n.expressions*0.05,o+=n.components*1,n.scriptLines>10)o+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let s=[];if(o>10)s.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)s.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)s.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:s}}function Xt(t,n,o){let d=t.replace(/<!--[\s\S]*?-->/g,""),s=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(s-l)}async function
|
|
5
|
+
`).filter((x)=>x.length>120);if(g.length>0)o.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)o.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function Wn(t,n){let o=[];if(n.complexity>7)o.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function Vn(t,n){let o=1;if(o+=n.directives.conditionals*0.1,o+=n.directives.loops*0.5,o+=n.directives.includes*2,o+=n.expressions*0.05,o+=n.components*1,n.scriptLines>10)o+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let s=[];if(o>10)s.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)s.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)s.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:s}}function Xt(t,n,o){let d=t.replace(/<!--[\s\S]*?-->/g,""),s=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(s-l)}async function Qi(t=["**/*.stx"],n){let o=[],d=[];for(let l of t){let u=await Array.fromAsync(new Bun.Glob(l).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let l of d)try{let u=await zn(l);o.push(u)}catch(u){console.warn(`Failed to analyze ${l}:`,u)}let s=qn(o);return{results:o,summary:s}}function qn(t){let n=t.length,o=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,s=t.reduce((h,x)=>h+x.issues.length,0),l={};t.forEach((h)=>{h.issues.forEach((x)=>{l[x.category]=(l[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),g=[];if(d>6)g.push("Project has high average complexity. Consider refactoring complex templates.");if(s>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:o,avgComplexity:Math.round(d*100)/100,totalIssues:s,issuesByCategory:l,performanceScore:f,recommendations:g}}import{mkdir as Kn,readFile as Xn,readdir as Gn,stat as Gt,writeFile as Jn}from"fs/promises";import ke from"path";function tn(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 nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Yn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Qn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function Zn(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function er(t){let n=[];async function o(d){let s=await Gn(d,{withFileTypes:!0});s.sort((l,u)=>l.name.localeCompare(u.name));for(let l of s){let u=ke.join(d,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await o(u)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))n.push(u)}}return await o(t),n}function tr(t,n){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let d=o[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(s){throw Error(`${n}: <script component> must contain JSON metadata (${s.message})`)}}function nr(t,n){let o={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let s of d){if(!/\bclient\b/i.test(s[1])||/\bcomponent\b|\bstx:component\b/i.test(s[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(s[2])}catch(g){throw Error(`${n}: failed to transpile <script client> (${g.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(l)){let g=f[1];if(nn.has(g))throw Error(`${n}: client ${tn(g)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<l.length&&x>0;T++){let y=l[T];if(S){S=!1;continue}if(v){if(y==="\\")S=!0;else if(y===v)v="";continue}if(y==='"'||y==="'"||y==="`")v=y;else if(y==="{")x++;else if(y==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";o[g]=`${w}${g}(${f[2]}) {${l.slice(h,T-1)}}`,u.lastIndex=T}}return o}function rr(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
|
|
6
6
|
|
|
7
7
|
`)}function or(t){if(!t)return null;let n=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(n))return"string";if(/^number$/.test(n))return"number";if(/^boolean$/.test(n))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(n))return"string";return"object"}function sr(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function ir(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function cr(t){let n=[],o=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),s=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,u=(g)=>{if(d[g]!=="(")return null;let h=0,x="";for(let v=g;v<d.length;v++){let S=d[v];if(x!==""){if(S==="\\")v++;else if(S===x)x="";continue}if(S==="'"||S==='"'||S==="`"){x=S;continue}if(S==="(")h++;else if(S===")"){if(h--,h===0)return{expression:d.slice(g+1,v),end:v+1}}}return null},f=(g)=>{if(g==="")return;let h=0,x=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,v;while(v=x.exec(g)){if(v.index>h)n.push(`out += ${JSON.stringify(g.slice(h,v.index))};`);n.push(v[1]!==void 0?`out += __raw(${v[1]});`:`out += __escape(${v[2]});`),h=v.index+v[0].length}if(h<g.length)n.push(`out += ${JSON.stringify(g.slice(h))};`)};while(l=s.exec(d)){f(d.slice(o,l.index)),o=l.index+l[0].length;let h=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?u(o):null;if(h)o=h.end,s.lastIndex=h.end;let x=h?.expression;switch(l[1]){case"if":n.push(`if (${x}) {`);break;case"elseif":n.push(`} else if (${x}) {`);break;case"else":n.push("} else {");break;case"endif":case"endforeach":n.push("}");break;case"foreach":{let v=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((x||"").trim());if(!v){n.push(`out += ${JSON.stringify(l[0]+(h?`(${x})`:""))};`);break}let[,S,T,w]=v;n.push(T?`for (const [${T}, ${w}] of __entries(${S})) {`:`for (const ${w} of __values(${S})) {`);break}}}return f(d.slice(o)),n.join(`
|
|
8
|
-
`)}function lt(t,n,o,d){if(t[n]!==o)return-1;let s=0,l=null;for(let u=n;u<t.length;u++){let f=t[u];if(l){if(f==="\\"){u++;continue}if(f===l)l=null;continue}if(f==="'"||f==='"'||f==="`"){l=f;continue}if(f===o)s++;else if(f===d){if(d===">"&&t[u-1]==="=")continue;if(s--,s===0)return u+1}}return-1}function Mt(t,n,o){let d=o?"([{<":"([{",s=o?")]}>":")]}",l=[],u=0,f=null,g="";for(let h=0;h<t.length;h++){let x=t[h];if(f){if(g+=x,x==="\\"){g+=t[++h]??"";continue}if(x===f)f=null;continue}if(x==="'"||x==='"'||x==="`"){f=x,g+=x;continue}if(d.includes(x))u++;else if(s.includes(x))u--;if(u===0&&n.includes(x)){l.push(g),g="";continue}g+=x}return l.push(g),l.map((h)=>h.trim()).filter(Boolean)}function lr(t){let n=0,o=null;for(let d=0;d<t.length;d++){let s=t[d];if(o){if(s==="\\"){d++;continue}if(s===o)o=null;continue}if(s==="'"||s==='"'||s==="`"){o=s;continue}if("([{".includes(s))n++;else if(")]}".includes(s))n--;if(n!==0||s!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Yt(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
|
|
8
|
+
`)}function lt(t,n,o,d){if(t[n]!==o)return-1;let s=0,l=null;for(let u=n;u<t.length;u++){let f=t[u];if(l){if(f==="\\"){u++;continue}if(f===l)l=null;continue}if(f==="'"||f==='"'||f==="`"){l=f;continue}if(f===o)s++;else if(f===d){if(d===">"&&t[u-1]==="=")continue;if(s--,s===0)return u+1}}return-1}function Mt(t,n,o){let d=o?"([{<":"([{",s=o?")]}>":")]}",l=[],u=0,f=null,g="";for(let h=0;h<t.length;h++){let x=t[h];if(f){if(g+=x,x==="\\"){g+=t[++h]??"";continue}if(x===f)f=null;continue}if(x==="'"||x==='"'||x==="`"){f=x,g+=x;continue}if(d.includes(x))u++;else if(s.includes(x))u--;if(u===0&&n.includes(x)){l.push(g),g="";continue}g+=x}return l.push(g),l.map((h)=>h.trim()).filter(Boolean)}function lr(t){let n=0,o=null;for(let d=0;d<t.length;d++){let s=t[d];if(o){if(s==="\\"){d++;continue}if(s===o)o=null;continue}if(s==="'"||s==='"'||s==="`"){o=s;continue}if("([{".includes(s))n++;else if(")]}".includes(s))n--;if(n!==0||s!=="=")continue;let l=t[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Yt(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function dr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let o=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let E=o.exec(t);E&&E.index<n.index;E=o.exec(t))d=E.index+E[0].indexOf(E[1]);if(d===-1)return null;let s={},l={},u=[],f={},g=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(g<t.length&&/\s/.test(t[g]))g++},x;if(t[g]==="{"){let E=lt(t,g,"{","}");if(E===-1)return null;x=t.slice(g,E),g=E}else{let E=/^[A-Za-z_$][\w$]*/.exec(t.slice(g));if(!E)return null;x=E[0],g+=E[0].length}if(h(),t[g]!=="=")return null;g++,h();let v=/^withDefaults\s*\(\s*/.exec(t.slice(g)),S=Boolean(v);if(v)g+=v[0].length;let T=/^defineProps\b/.exec(t.slice(g));if(!T)return null;g+=T[0].length;let w="";if(h(),t[g]==="<"){let E=lt(t,g,"<",">");if(E===-1)return null;w=t.slice(g+1,E-1).trim(),g=E}if(h(),t[g]!=="(")return null;let y=lt(t,g,"(",")");if(y===-1)return null;let k=t.slice(g+1,y-1).trim();if(g=y,S){if(h(),t[g]===",")g++,h();if(t[g]==="{"){let E=lt(t,g,"{","}");if(E===-1)return null;for(let[R,A]of Lt(t.slice(g,E)))l[R]=A;g=E}if(h(),t[g]===",")g++,h();if(t[g]===")")g++}if(t[g]===";")g++;let M=/^[A-Za-z_$][\w$]*$/.test(w)?w:void 0;if(w.startsWith("{"))for(let E of Mt(w.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let R=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(E);if(R)s[R[1]]=R[2].trim()}if(k.startsWith("{"))for(let[E,R]of Lt(k)){if(u.push(E),!R.startsWith("{")){let A=Yt(R);if(A)s[E]=A;continue}for(let[A,C]of Lt(R))if(A==="default")l[E]=C;else if(A==="type"){let D=Yt(C);if(D)s[E]=D}}else if(k.startsWith("["))for(let E of Mt(k.slice(1,-1),",",!1))u.push(E.replace(/^['"`]/,"").replace(/['"`]$/,""));if(x.startsWith("{")){u.length=0;for(let E of Mt(x.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let R=lr(E),A=R===-1?E:E.slice(0,R),C=A.split(":")[0].trim().replace(/^\.\.\./,"");if(!C)continue;if(u.push(C),f[C]=A.trim(),R!==-1)l[C]=E.slice(R+1).trim()}}else if(u.length===0)u.push(...Object.keys(s));return{text:t.slice(d,g),propNames:u,propBindings:f,defaults:l,declared:s,typeName:M}}function Lt(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),o=[],d=0;while(d<n.length){let s=/\s*([A-Za-z_$][\w$]*)\s*:/y;s.lastIndex=d;let l=s.exec(n);if(!l)break;d=s.lastIndex;let u=0,f="",g=d;while(d<n.length){let x=n[d];if(f){if(x==="\\")d++;else if(x===f)f=""}else if(x==="'"||x==='"'||x==="`")f=x;else if(x==="{"||x==="["||x==="(")u++;else if(x==="}"||x==="]"||x===")")u--;else if(x===","&&u===0)break;d++}let h=n.slice(g,d).trim();if(h)o.push([l[1],h]);d++}return o}function ur(t,n,o){let s=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((T)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(T[1]));if(!s)return{imports:[],body:"",propNames:[],propBindings:{},defaults:{},declared:{}};let l=s[2],u=[],f=[],g={},h={},x={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(T)=>{if(/from\s*['"]stx['"]/.test(T))return"";return u.push(T.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(w,y,k,M)=>{let E=ke.resolve(ke.dirname(n),k),R=ke.relative(o,E);return`${y}${R.startsWith(".")?R:`./${R}`}${M}`})),""});let v=dr(l);if(v)f.push(...v.propNames),Object.assign(g,v.propBindings),Object.assign(h,v.defaults),Object.assign(x,v.declared),l=l.replace(v.text,"");let S={};for(let T of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let w=[];for(let y of T[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))x[y[1]]=y[2].trim(),w.push(y[1]);S[T[1]]=w}if(v&&v.propNames.length===0&&v.typeName){for(let T of S[v.typeName]??[])if(!f.includes(T))f.push(T)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:l.trim(),propNames:f,propBindings:g,defaults:h,declared:x}}function gr(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,s,l,u,f)=>{let g=s.toLowerCase();n.add(g);let h=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${g}="${f}"${h?` data-stx-mod-${g}="${h}"`:""}`}),eventTypes:[...n].sort()}}function hr(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,s,l,u)=>{let f=n.length;return n.push({id:f,name:s,expression:u}),` data-stx-bind-${f}=""`}),bindings:n}}function yr(t){let n=new Set;for(let o of t.matchAll(/<slot\b([^>]*)>/gi))n.add(o[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((o)=>({name:o}))}function br(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function Qt(t,n){if(!n||!new Set(["string","number","boolean","object","array"]).has(n.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...n,reflect:n.reflect??n.attribute!==!1}}async function xr(t,n,o){let d=ke.isAbsolute(n.file)?n.file:ke.resolve(t,n.file),s=await Xn(d,"utf8"),l=tr(s,d),u=ke.basename(d,".stx"),f=n.name||l.name||Yn(u),g=`${It(o.prefix||"stx")}-${It(u)}`,h=n.tag||l.tag||g;if(!f||!/^[A-Za-z_$][\w$]*$/.test(f))throw Error(`${d}: invalid component class name "${f}"`);if(!Qn(h))throw Error(`${d}: invalid custom-element tag "${h}"; tags must be lowercase and contain a hyphen`);let x=n.properties||l.properties||l.props||{},v=Object.fromEntries(Object.entries(x).map(([R,A])=>[R,Qt(R,A)])),S=gr(rr(s)),T=hr(S.template),w=ur(s,d,ke.resolve(o.outputDir)),y=cr(T.template);for(let R of w.propNames){if(v[R])continue;let A=w.defaults[R];v[R]=Qt(R,{type:or(w.declared[R])??sr(A),...A===void 0?{}:{default:ir(A)}})}let k=l.methods||{},M=n.methods||{},E=nr(s,d);return{file:ke.relative(t,d),sourcePath:d,name:f,tag:h,description:n.description||l.description||"",template:T.template,styles:Jt(s),shadowMode:Zn(n.shadowDOM??l.shadowDOM??o.shadowDOM),progressive:n.progressive??l.progressive??o.progressive??!0,properties:v,events:n.events||l.events||{},methods:{...k,...M,...E},eventTypes:S.eventTypes,bindings:T.bindings,slots:yr(T.template),cssProperties:br(Jt(s)),scope:w,render:y}}function vr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),n=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
|
|
9
9
|
|
|
10
10
|
const escapeHTML = (value) => String(value ?? '')
|
|
11
11
|
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
@@ -387,7 +387,7 @@ ${s}
|
|
|
387
387
|
export {}
|
|
388
388
|
`}function Tr(t){return{schemaVersion:"1.0.0",modules:t.map((n)=>({kind:"javascript-module",path:`./${n.tag}.js`,declarations:[{kind:"class",name:n.name,description:n.description||void 0,customElement:!0,tagName:n.tag,members:Object.entries(n.properties).map(([o,d])=>({kind:"field",name:o,description:d.description,type:{text:jt(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||It(o),reflects:d.reflect})),events:Object.entries(n.events).map(([o,d])=>({name:o,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:n.slots,cssProperties:n.cssProperties}],exports:[{kind:"js",name:n.name,declaration:{name:n.name,module:`./${n.tag}.js`}}]}))}}function Zt(t){if(!t.styles)return"";let n=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(n))return n;return`@scope (${t.tag}) {
|
|
389
389
|
${n}
|
|
390
|
-
}`}function en(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function
|
|
390
|
+
}`}function en(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function $r(t){let n=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),o=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),d=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),s=Object.fromEntries(t.map((u)=>[u.tag,{template:u.template,styles:u.styles,shadowMode:u.shadowMode,properties:u.properties}])),l=t.map((u)=>`export const render${u.name} = (props = {}, slots = {}) => renderComponent('${u.tag}', props, slots);`).join(`
|
|
391
391
|
`);return`const definitions = ${JSON.stringify(s,null,2)};
|
|
392
392
|
const escapeHTML = (value) => String(value ?? '')
|
|
393
393
|
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
@@ -421,10 +421,10 @@ export function renderComponent(tag, props = {}, slots = {}) {
|
|
|
421
421
|
}
|
|
422
422
|
|
|
423
423
|
${l}
|
|
424
|
-
`}async function
|
|
424
|
+
`}async function ea(t){let n=ke.resolve(t.inputDir),o=ke.resolve(t.outputDir);if(!(await Gt(n).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${n}`);let s=t.components?.length?t.components:(await er(n)).map((y)=>({file:y}));if(!s.length)throw Error(`No .stx components found in ${n}`);let l=await Promise.all(s.map((y)=>xr(n,y,t)));l.sort((y,k)=>y.tag.localeCompare(k.tag));let u=l.filter((y,k)=>l.findIndex((M)=>M.tag===y.tag)!==k);if(u.length)throw Error(`Duplicate custom-element tag: ${u[0].tag}`);let f=l.filter((y,k)=>l.findIndex((M)=>M.name===y.name)!==k);if(f.length)throw Error(`Duplicate component class name: ${f[0].name}`);await Kn(o,{recursive:!0});let g=[],h=async(y,k)=>{let M=ke.join(o,y);return await Jn(M,k.endsWith(`
|
|
425
425
|
`)?k:`${k}
|
|
426
426
|
`,"utf8"),g.push(M),M};await h("runtime.js",vr());for(let y of l){if(await h(`${y.tag}.js`,wr(y)),t.declarations!==!1)await h(`${y.tag}.d.ts`,Sr(y));if(t.css!==!1&&y.styles){let k=y.shadowMode?y.styles:Zt(y);await h(`${y.tag}.css`,t.minify?en(k):k)}}let x=l.map((y)=>`export { ${y.name}, default as ${y.name}Element } from './${y.tag}.js';`).join(`
|
|
427
|
-
`);if(await h("index.js",x),await h("ssr.js"
|
|
427
|
+
`);if(await h("index.js",x),await h("ssr.js",$r(l)),t.declarations!==!1)await h("index.d.ts",l.map((y)=>`export * from './${y.tag}.js'`).join(`
|
|
428
428
|
`)),await h("custom-elements.d.ts",kr(l)),await h("ssr.d.ts",`${l.map((y)=>`export declare const render${y.name}: (props?: ${y.name}Props, slots?: Record<string, string>) => string`).join(`
|
|
429
429
|
`)}
|
|
430
430
|
export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
|
|
@@ -515,7 +515,7 @@ else {
|
|
|
515
515
|
<span class="frontmatter-label">${n}:</span>
|
|
516
516
|
<span>${Array.isArray(o)?o.join(", "):String(o)}</span>
|
|
517
517
|
</div>`).join("")}
|
|
518
|
-
</div>`}async function
|
|
518
|
+
</div>`}async function Cr(t){let{default:n}=await import("net");return new Promise((o)=>{let d=n.createServer();d.once("error",()=>o(!1)),d.once("listening",()=>{d.close(()=>o(!0))}),d.listen(t,"0.0.0.0")})}async function Er(t){let{default:n}=await import("net");return new Promise((o)=>{let d=n.createServer();d.once("error",()=>o(!1)),d.once("listening",()=>{d.close(()=>o(!0))}),d.listen(t,"::")})}async function Pr(t){if(!await Cr(t))return!1;return await Er(t)}async function We(t,n=20){t=Number(t);for(let o=0;o<n;o++){let d=t+o;if(await Pr(d))return d}throw Error(`Could not find an available port between ${t} and ${t+n-1}`)}var Or={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Ar(){try{let t=await import("./chunk-enz6fsdx.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function Ze(t,n={}){let o={...Or,...n},d=await Ar();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let s=await d.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(s&&o.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return s}catch(s){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,s),!1}}function mt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let s=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(s){let l=s[1];try{let u=`
|
|
519
519
|
${l}
|
|
520
520
|
return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
|
|
521
521
|
`,g=Function(u)();if(g)return g}catch(u){console.warn("Invalid sidebarConfig:",u)}}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 d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let s=d[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(s)return Function(`return ${s[1]}`)()}catch(s){console.warn("Invalid native-sidebar script configuration:",s)}return}function Ht(){console.log(`
|
|
@@ -688,7 +688,7 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
688
688
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
689
689
|
${e.bright}\u2192 ${e.cyan}http://localhost:${g}/${e.reset}`),console.log(`
|
|
690
690
|
${e.yellow}Routes:${e.reset}`);let x=et.relative(process.cwd(),s);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${x}${e.reset}`),console.log(`
|
|
691
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(h.url.toString(),()=>{if(d)Bt.watch(et.dirname(s),{recursive:!0}).close();h.stop()}),n.native)await Ze(g,{title:et.basename(s,".md")});if(d){let v=et.dirname(s);console.log(`${e.blue}Watching ${e.bright}${v}${e.reset} for changes...`);let S=Bt.watch(v,{recursive:!0},async(T,w)=>{if(w&&w.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${w}${e.yellow} changed, reprocessing...${e.reset}`),await u()});process.on("SIGINT",()=>{S.close(),h.stop(),process.exit(0)})}return!0}function Ir(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:
|
|
691
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(h.url.toString(),()=>{if(d)Bt.watch(et.dirname(s),{recursive:!0}).close();h.stop()}),n.native)await Ze(g,{title:et.basename(s,".md")});if(d){let v=et.dirname(s);console.log(`${e.blue}Watching ${e.bright}${v}${e.reset} for changes...`);let S=Bt.watch(v,{recursive:!0},async(T,w)=>{if(w&&w.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${w}${e.yellow} changed, reprocessing...${e.reset}`),await u()});process.on("SIGINT",()=>{S.close(),h.stop(),process.exit(0)})}return!0}function Ir(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Hr}=globalThis.Bun;import Be from"fs";import me from"path";class rn{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let n=t??this.options.wsPort,o=20;for(let d=0;d<o;d++)try{if(this.server=Bun.serve({port:n,fetch(s,l){if(l.upgrade(s,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(s)=>{if(this.clients.add(s),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);s.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(s)=>{if(this.clients.delete(s),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(s,l)=>{let u=typeof l==="string"?l:l.toString();if(u==="ping")return;try{let f=JSON.parse(u);if(f.type==="console"&&Array.isArray(f.args)){let g=f.args.join(" "),x={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[f.level]??"\x1B[36m";console.log(`${x}[browser]${f.level!=="log"?` ${f.level}`:""}\x1B[0m ${g}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${n}`);return n}catch(s){if(s?.code==="EADDRINUSE"){n++;continue}throw s}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 n=JSON.stringify(t),o=0;for(let d of this.clients)try{if(d.readyState===1)d.send(n),o++}catch{this.clients.delete(d)}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,n){this.broadcast({type:"css-update",path:t,content:n,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function jr(t,n={}){let{showOverlay:o=!0,reconnectInterval:d=1000,maxReconnectAttempts:s=10}=n;return`
|
|
692
692
|
<script>
|
|
693
693
|
(function() {
|
|
694
694
|
// stx Hot Reload Client
|
|
@@ -887,10 +887,10 @@ else {
|
|
|
887
887
|
};
|
|
888
888
|
})();
|
|
889
889
|
</script>
|
|
890
|
-
`}function Ne(t,n,o={}){let d=jr(n,o),s=t.lastIndexOf("</body>");if(s!==-1)return t.slice(0,s)+d+t.slice(s);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function yt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var nt=null;function vt(t){if(!nt)nt=new rn(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let o={...await a(),...t.config?.stx},d=new Set,s=o.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(o.webComponents?.enabled)try{let u=await
|
|
890
|
+
`}function Ne(t,n,o={}){let d=jr(n,o),s=t.lastIndexOf("</body>");if(s!==-1)return t.slice(0,s)+d+t.slice(s);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function yt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var nt=null;function vt(t){if(!nt)nt=new rn(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let o={...await a(),...t.config?.stx},d=new Set,s=o.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(o.webComponents?.enabled)try{let u=await _s(o,d);if(l.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(o.cache&&o.cachePath){let y=await pr(u,o);if(y){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:y,loader:"html"}}}let g=await _e(()=>Bun.file(u).text(),"",(y)=>{throw new Rr(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${y.message}`)});if(!g)throw new Rr(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=ae.time("script-extraction",()=>{let y=g,k=pe(g);if(k)y=k.content.trim();let M=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of M){let D=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",L=C.match(/<script\b([^>]*)>/i),V=L?L[1]:"";if(/\bserver\b/i.test(V))E=D;else R.push(C)}let A=y.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:s,builtComponents:l}};await _e(()=>m(h,S,u),void 0,(y)=>{let k=new ce(`Script execution failed in ${u}: ${y.message}`,u,void 0,void 0,h.substring(0,100));if(z.log(k,{filePath:u,scriptContent:h}),o.debug)throw k});let w=await ae.timeAsync("directive-processing",async()=>await i(x,S,u,o,f));if(v.length>0){let{interpolateScriptsInTemplate:y}=await import("./chunk-a7z6j9ga.js"),k=y(v.join(`
|
|
891
891
|
`),S),M=w.search(/<\/body>/i);if(M!==-1)w=w.slice(0,M)+k+`
|
|
892
892
|
`+w.slice(M);else w+=`
|
|
893
|
-
${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),o.cache&&o.cachePath){if(await
|
|
893
|
+
${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),o.cache&&o.cachePath){if(await fr(u,w,f,o),o.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let g=f instanceof Error?f:new ce(`Plugin processing failed: ${String(f)}`,u);if(z.log(g,{filePath:u,buildConfig:t.config}),Cn.logDetailedError(g,{filePath:u,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",g);let h=g,x=h.line||null,v=h.context||null;return{contents:o.debug||X()?`<!DOCTYPE html>
|
|
894
894
|
<html lang="en">
|
|
895
895
|
<head>
|
|
896
896
|
<meta charset="UTF-8">
|
|
@@ -950,12 +950,12 @@ ${k}`}if(w=await ve(w),f.forEach((y)=>d.add(y)),o.cache&&o.cachePath){if(await p
|
|
|
950
950
|
<h1>Something went wrong</h1>
|
|
951
951
|
<p>An internal error occurred. Please try again later.</p>
|
|
952
952
|
</body>
|
|
953
|
-
</html>`,loader:"html"}}})}};async function
|
|
953
|
+
</html>`,loader:"html"}}})}};async function Vr(t,n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,l=null,u=n.hmrPort||o+1,f=me.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=c(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let D={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},L=await Bun.build({entrypoints:[f],outdir:g,plugins:[D,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!L.success)return console.error(`${e.red}Build failed:${e.reset}`,L.logs),!1;let V=L.outputs.find((be)=>be.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(D){return console.error(`${e.red}Error building stx file:${e.reset}`,D),!1}};if(!await x())return!1;let S=me.dirname(f);await ln(S);let T=o;try{if(T=await We(o),T!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let D=n.hmrPort||T+1;l=vt({wsPort:D,verbose:!1}),u=l.start(D)}let w={},y=null,k;try{let{loadStxConfig:D}=await import("./chunk-wddaxpep.js"),L=await D();if(k=n.stxOptions?.serverApi??L.serverApi,L?.apiRouter)y=L?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(L?.apiRoutes){w=L.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(L?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-en8hnq2q.js"),be=L.broadcasting;await V(be);let le=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Ce=me.join(process.cwd(),"channels.ts");if(Be.existsSync(Ce))try{let ne=await Y(Ce);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:M,isServerApiSource:E}=await import("./chunk-cng4fhpt.js"),R=await M(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),s)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Hr({port:T,async fetch(D){return Pn(D,await(async()=>{let L=new URL(D.url);if([g,me.dirname(f),me.join(process.cwd(),"public")].some((ne)=>E(me.join(ne,L.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(y)try{let ne=await y.handleRequest(D);if(ne.status!==404)return ne}catch{}if(w[L.pathname])try{return await w[L.pathname](D)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(D);if(V)return V;if(L.pathname==="/")return(async()=>{let F=await b(h||"");if(s)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=me.join(g,L.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=me.extname(Y).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let be=me.dirname(f),le=me.join(be,L.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=me.extname(le).toLowerCase(),_="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}let Ce=me.join(process.cwd(),"public",L.pathname);if(Be.existsSync(Ce)&&Be.statSync(Ce).isFile()){let ne=Bun.file(Ce),F=me.extname(Ce).toLowerCase(),_="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":_="text/html";break;case".css":_="text/css";break;case".js":_="text/javascript";break;case".json":_="application/json";break;case".png":_="image/png";break;case".jpg":case".jpeg":_="image/jpeg";break;case".gif":_="image/gif";break;case".svg":_="image/svg+xml";break;case".ico":_="image/x-icon";break;case".woff":_="font/woff";break;case".woff2":_="font/woff2";break;case".ttf":_="font/ttf";break;case".otf":_="font/otf";break;case".eot":_="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":_}})}return new Response("Not Found",{status:404})})())},error(D){return new Response(`<pre>${D}
|
|
954
954
|
${D.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
955
955
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
956
956
|
${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
|
|
957
957
|
${e.yellow}Routes:${e.reset}`);let C=me.relative(process.cwd(),f);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${C}${e.reset}`),console.log(`
|
|
958
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(A.url.toString(),()=>{if(d)Be.watch(me.dirname(f),{recursive:!0}).close();A.stop()}),n.native){let D=await Bun.file(f).text(),L=mt(D);await Ze(T,{title:me.basename(f,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!L,sidebarConfig:L})}if(d){let D=me.dirname(f);console.log(`${e.blue}Watching ${e.bright}${D}${e.reset} for changes...`);let L=Be.watch(D,{recursive:!0},async(V,Y)=>{if(!Y||xt(Y))return;if(yt(Y)){console.log(`${e.yellow}File ${e.bright}${Y}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge();let be=await x();if(await ar(S),s&&l)if(be)l.reload(Y);else l.error("Build failed - check console for details")}else if(ht(Y)){if(console.log(`${e.cyan}CSS ${e.bright}${Y}${e.cyan} changed${e.reset}`),s&&l)l.updateCss(Y)}});process.on("SIGINT",()=>{if(L.close(),l)it();A.stop(),process.exit(0)})}return!0}var{serve:
|
|
958
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(A.url.toString(),()=>{if(d)Be.watch(me.dirname(f),{recursive:!0}).close();A.stop()}),n.native){let D=await Bun.file(f).text(),L=mt(D);await Ze(T,{title:me.basename(f,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!L,sidebarConfig:L})}if(d){let D=me.dirname(f);console.log(`${e.blue}Watching ${e.bright}${D}${e.reset} for changes...`);let L=Be.watch(D,{recursive:!0},async(V,Y)=>{if(!Y||xt(Y))return;if(yt(Y)){console.log(`${e.yellow}File ${e.bright}${Y}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge();let be=await x();if(await ar(S),s&&l)if(be)l.reload(Y);else l.error("Build failed - check console for details")}else if(ht(Y)){if(console.log(`${e.cyan}CSS ${e.bright}${Y}${e.cyan} changed${e.reset}`),s&&l)l.updateCss(Y)}});process.on("SIGINT",()=>{if(L.close(),l)it();A.stop(),process.exit(0)})}return!0}var{serve:Br}=globalThis.Bun;import Xe from"fs";import $e from"path";var on=`
|
|
959
959
|
<script data-stx-helpers>
|
|
960
960
|
(function() {
|
|
961
961
|
'use strict'
|
|
@@ -1266,7 +1266,7 @@ else {
|
|
|
1266
1266
|
|
|
1267
1267
|
})()
|
|
1268
1268
|
</script>
|
|
1269
|
-
`;function an(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((d)=>d.split($e.sep)),o=[];for(let d=0;d<n[0].length;d++){let s=n[0][d];if(n.every((l)=>l[d]===s))o.push(s);else break}return o.join($e.sep)}async function
|
|
1269
|
+
`;function an(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((d)=>d.split($e.sep)),o=[];for(let d=0;d<n[0].length;d++){let s=n[0][d];if(n.every((l)=>l[d]===s))o.push(s);else break}return o.join($e.sep)}async function Ur(t,n={}){let o=n.port||3000,d=n.watch!==!1;for(let w of t){let y=$e.resolve(w);if(!Xe.existsSync(y))return console.error(`${e.red}Error: File not found: ${e.bright}${y}${e.reset}`),!1;if(!y.endsWith(".stx")&&!y.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${y}${e.reset}. Only .stx and .md files are supported.`),!1}let s=c(process.cwd(),"output");Xe.mkdirSync(s,{recursive:!0});let l=an(t.map((w)=>$e.dirname($e.resolve(w))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let u={},f=[],g=async()=>{try{for(let w of t){let y=$e.resolve(w);if(y.endsWith(".md"))try{let{content:M,data:E}=await Ae(y,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:O.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=n.markdown?.syntaxHighlighting||O.markdown?.syntaxHighlighting,A=R?.defaultTheme||"github-dark",C=["github-dark"],D=R?.additionalThemes||[],V=[...new Set([...C,...D])].map((Ce)=>`<option value="${Ce}"${Ce===A?" selected":""}>${Ce}</option>`).join(`
|
|
1270
1270
|
`),Y=`
|
|
1271
1271
|
<!DOCTYPE html>
|
|
1272
1272
|
<html lang="en">
|
|
@@ -1430,24 +1430,24 @@ else {
|
|
|
1430
1430
|
</body>
|
|
1431
1431
|
</html>
|
|
1432
1432
|
`,le=`/${$e.relative(l,y).replace(/\.md$/,"")}`;if(le.endsWith("/index"))le=le.slice(0,-6)||"/";u[le||"/"]={filePath:y,content:Y,fileType:"md"}}catch(M){console.error(`${e.red}Error processing Markdown file ${e.bright}${w}${e.reset}:`,M);continue}else{let M={name:"public-assets",setup(C){C.onResolve({filter:/^\/(images|fonts|assets|public)\//},(D)=>({path:D.path,external:!0}))}},E;try{let C=await Bun.build({entrypoints:[y],outdir:s,plugins:[M,rt],define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!C.success){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:`,Re(C.logs,y));continue}let D=C.outputs.find((L)=>L.path.endsWith(".html"));if(!D){console.error(`${e.red}No HTML output found for ${e.bright}${w}${e.reset}`);continue}E=await Bun.file(D.path).text()}catch(C){console.error(`${e.red}Build failed for ${e.bright}${w}${e.reset}:
|
|
1433
|
-
${Re(C,y)}`);continue}let A=`/${$e.relative(l,y).replace(/\.stx$/,"")}`;if(A.endsWith("/index"))A=A.slice(0,-6)||"/";if(A.includes("[")){let{regex:C,params:D}=
|
|
1433
|
+
${Re(C,y)}`);continue}let A=`/${$e.relative(l,y).replace(/\.stx$/,"")}`;if(A.endsWith("/index"))A=A.slice(0,-6)||"/";if(A.includes("[")){let{regex:C,params:D}=As(A,{page:!0});f.push({pattern:C,paramNames:D,filePath:y,routeTemplate:A,fileType:"stx"}),u[A]={filePath:y,content:E,fileType:"stx"}}else u[A||"/"]={filePath:y,content:E,fileType:"stx"}}}if(Object.keys(u).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(w){return console.error(`${e.red}Error processing files:${e.reset}`,Re(w)),!1}};if(!await g())return!1;let x=o;try{if(x=await We(o),x!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${x} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${x}/${e.reset}...`);let v=Br({port:x,async fetch(w){let y=new URL(w.url),k=$e.join(process.cwd(),"public",y.pathname);if(Xe.existsSync(k)&&Xe.statSync(k).isFile()){let R=Bun.file(k),A=$e.extname(k).toLowerCase(),C="application/octet-stream";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}let M=u[y.pathname];if(!M&&!y.pathname.endsWith("/"))M=u[`${y.pathname}/`];if(!M)for(let R of f){let A=y.pathname.match(R.pattern);if(A){let C=u[R.routeTemplate];if(C){let D={};for(let Y=0;Y<R.paramNames.length;Y++)D[R.paramNames[Y]]=decodeURIComponent(A[Y+1]);let L=C.content,V=`<script>window.__routeParams = ${JSON.stringify(D)};</script>`;if(L.includes("</head>"))L=L.replace("</head>",`${V}
|
|
1434
1434
|
</head>`);else L=V+L;M={...C,content:L}}break}}if(M)return b(M.content).then((R)=>{if(R.includes("</head>"))R=R.replace("</head>",`${on}
|
|
1435
1435
|
</head>`);return new Response(R,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let E=$e.join(s,y.pathname);if(Xe.existsSync(E)&&Xe.statSync(E).isFile()){let R=Bun.file(E),A=$e.extname(E).toLowerCase(),C="text/plain";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}if(y.pathname!=="/"&&u["/"]){let R=Ee(w);return b(u["/"].content).then((A)=>{if(R){let C=A.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(C){let D=A.match(/<title[^>]*>([\s\S]*?)<\/title>/i),L=D?D[1]:"",V=`<!DOCTYPE html><html><head><title>${sn(L)}</title></head><body><main>${C[1]}</main></body></html>`;return new Response(V,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...j(),"Cache-Control":gt,Pragma:"no-cache",Expires:"0"}})}}return new Response(A,{headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
|
|
1436
1436
|
${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1437
1437
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1438
1438
|
${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
|
|
1439
1439
|
${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[y])=>w.localeCompare(y)).map(([w,y])=>({route:w==="/"?"/":w,filePath:$e.relative(process.cwd(),y.filePath),fileType:y.fileType}));for(let w of f){let y=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:y,filePath:$e.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,y)=>w.route.localeCompare(y.route)),T.forEach((w,y)=>{let M=y===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${M}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
|
|
1440
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function sn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:zr}=globalThis.Bun;import fe from"fs";import te from"path";async function cn(t){try{return hn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),o=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[o]||"application/octet-stream",...l}})}async function Ur(t=".",n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,l=null,u=n.hmrPort||o+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-pwdnqe30.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-sss23kn5.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=te.join(w,y);if(!fe.existsSync(k)&&!h._layerPageDirs?.some((P)=>fe.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${y}/index.stx for the homepage.${e.reset}`),!1;let M=G(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(fe.existsSync(P)){let N=G(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await da(f,n.stxOptions?.shell),D){if(C=await yo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}_t(),await Et(f);let L=Ct();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-pwdnqe30.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-vkrxrt0a.js"),q=I.broadcasting;await N(q);let Pe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Pe}/ws${e.reset}`);let xe=te.join(process.cwd(),"channels.ts");if(fe.existsSync(xe))try{let U=await Q(xe);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");fe.mkdirSync(be,{recursive:!0});let le=new Map,Ce=new Set,ne=async(P)=>{let I=As(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Pe,injectRouterScript:xe}=await import("./chunk-pwdnqe30.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-7tdwa595.js"),K=await Pe(f),Ue=(se)=>{if(!se)return se;if(te.isAbsolute(se))return se;return te.resolve(f,se)},ie={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ie.debug=!0;ie.partialsDir=Ue(ie.partialsDir),ie.componentsDir=Ue(ie.componentsDir),ie.layoutsDir=Ue(ie.layoutsDir),ie.storesDir=Ue(ie.storesDir||"stores"),ie.cachePath=Ue(ie.cachePath)??c(f,"cache");let H=!I&&!n.profile,re=ie.cache!==!1;if(re&&H){let se=de.get(P.filePath);if(se)try{if((await fe.promises.stat(P.filePath)).mtime.getTime()<=se.mtime){let He=!0;for(let Se of se.dependencies){if(!fe.existsSync(Se)){He=!1;break}if((await fe.promises.stat(Se)).mtime.getTime()>se.mtime){He=!1;break}}if(He){let Se=se.output;if(C)Se=qe(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await cn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ie);if(Ie){let je=Ie;if(C)je=qe(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await cn(P.filePath),headers:He?.headers}}}let Z=re?await W(P.filePath):await Bun.file(P.filePath).text(),oe=hn(Z),{classifyAllScripts:ue}=await import("./chunk-pwdnqe30.js"),B=ue(Z),Le=B.server.map((se)=>se.content),De=Z;for(let se of B.server)De=De.replace(se.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ie,params:I??{},__stx_runtime_head:{}};for(let se of Le)try{await Q(se,ee,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Oe=new Set,he;if(n.profile){let se=performance.now();he=await N(De,ee,P.filePath,ie,Oe);let Ie=performance.now()-se,je=te.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(De,ee,P.filePath,ie,Oe);if(!C)he=await xe(he,{router:ie.router});{let{interpolateScriptExpressions:se}=await import("./chunk-xjbc3bhs.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${se(He,ee)}</script>`})}if(C)he=qe(he,{preserveHead:!0});if(re&&H)await J(P.filePath,he,Oe,ie);let{extractStreamBoundaries:ct}=await import("./chunk-exr9599h.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let se=ee.streamBoundaries||{},Ie={...ie,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof se[Se]==="function"?await se[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Ce.add(P.pattern);else Qe=void 0;let Vt=Nt(ee),qt=Dt(ee);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??oe,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),I=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Pe=N.slice(q,q+Fe),xe=await Promise.all(Pe.map((U)=>_(U)));for(let U of xe)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Pe=Q.slice(q,q+Fe),xe=await Promise.all(Pe.map(({route:U})=>_(U)));for(let U of xe)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await ln(f);let Ge=o;try{if(Ge=await We(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let P=n.hmrPort||Ge+1;l=vt({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Ot=zr({port:Ge,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===Mo&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Lo(N,as()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,I.pathname),Pe=te.join(f,I.pathname),xe=te.join(be,I.pathname);if([q,Pe,xe].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([fe.promises.stat(q).catch(()=>null),fe.promises.stat(Pe).catch(()=>null),fe.promises.stat(xe).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Pe,f,S))return zt(Pe);if(W?.isFile()&&!v(xe,f,S))return zt(xe);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-jv2z9qb7.js"),re=await H(P,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=gr(I.pathname,M);if(K){let H=le.get(K.route.pattern),re=Ce.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||re){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!re)le.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,oe=H.headers??{},ue=(K.route.filePath?bt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:K.params})){let De=await ne(404);if(De){let ee=De;if(ee=await b(ee,f),s)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Tt(I.pathname,K.params,ue,I.search),De=$t(Le,null,P,{isServer:!0}),ee=await Rt(ue.middleware,De);if(ee.redirect){let Oe=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",Oe),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:Oe,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Oe}</title></head><body><h1>Error ${Oe}</h1><p>${he}</p></body></html>`,{status:Oe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Oe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${Oe}</head>`)}}let B=H.content;if(C&&pa(P)&&Ke(B,h?.router?.container||"main")){let Le=tt(B),De=we(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Oe=ee?On(ee[1].trim()):"";if(Object.keys(K.params).length>0)B=Pt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=Te(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Oe&&{"X-STX-Title":encodeURIComponent(Oe)},[ac]:as(),...j(),"Cache-Control":gt}})}if(C)B=Xr(C,B);if(Object.keys(K.params).length>0)B=Pt(B,K.params);if(B=await b(B,f),s)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-exr9599h.js");return De(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=gr(I.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await _(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)A.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(C)oe=Xr(C,oe);if(Object.keys(re.params).length>0)oe=Pt(oe,re.params);if(oe=await b(oe,f),s)oe=Ne(oe,u);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&I.pathname.startsWith(Z)){let oe=A.get(Z)||A.get(Z+"/");if(!oe){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await _(ue.route);if(B)oe=B,A.set(ue.route.pattern,B)}}if(oe){let ue=oe.content;if(C)ue=Xr(C,ue);if(ue=await b(ue,f),s)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(kt(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),s)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ie=await ne(404);if(ie){let H=ie;if(H=await b(H,f),s)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await ne(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1440
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)Xe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ye.clear(),ge(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function sn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Fr}=globalThis.Bun;import fe from"fs";import te from"path";async function cn(t){try{return hn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),o=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[o]||"application/octet-stream",...l}})}async function Wr(t=".",n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,l=null,u=n.hmrPort||o+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-wddaxpep.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-cng4fhpt.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=te.join(w,y);if(!fe.existsSync(k)&&!h._layerPageDirs?.some((P)=>fe.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${y}/index.stx for the homepage.${e.reset}`),!1;let M=G(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(fe.existsSync(P)){let N=G(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await pa(f,n.stxOptions?.shell),D){if(C=await bo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}_t(),await Et(f);let L=Ct();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-wddaxpep.js"),I=await P(f);if(I?.apiRouter)Y=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){V=I.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-en8hnq2q.js"),q=I.broadcasting;await N(q);let Pe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Pe}/ws${e.reset}`);let xe=te.join(process.cwd(),"channels.ts");if(fe.existsSync(xe))try{let U=await Q(xe);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");fe.mkdirSync(be,{recursive:!0});let le=new Map,Ce=new Set,ne=async(P)=>{let I=Ps(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Pe,injectRouterScript:xe}=await import("./chunk-wddaxpep.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-s321pb85.js"),K=await Pe(f),Ue=(se)=>{if(!se)return se;if(te.isAbsolute(se))return se;return te.resolve(f,se)},ie={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ie.debug=!0;ie.partialsDir=Ue(ie.partialsDir),ie.componentsDir=Ue(ie.componentsDir),ie.layoutsDir=Ue(ie.layoutsDir),ie.storesDir=Ue(ie.storesDir||"stores"),ie.cachePath=Ue(ie.cachePath)??c(f,"cache");let H=!I&&!n.profile,re=ie.cache!==!1;if(re&&H){let se=de.get(P.filePath);if(se)try{if((await fe.promises.stat(P.filePath)).mtime.getTime()<=se.mtime){let He=!0;for(let Se of se.dependencies){if(!fe.existsSync(Se)){He=!1;break}if((await fe.promises.stat(Se)).mtime.getTime()>se.mtime){He=!1;break}}if(He){let Se=se.output;if(C)Se=qe(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await cn(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ie);if(Ie){let je=Ie;if(C)je=qe(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await cn(P.filePath),headers:He?.headers}}}let Z=re?await W(P.filePath):await Bun.file(P.filePath).text(),oe=hn(Z),{classifyAllScripts:ue}=await import("./chunk-wddaxpep.js"),B=ue(Z),Le=B.server.map((se)=>se.content),De=Z;for(let se of B.server)De=De.replace(se.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ie,params:I??{},__stx_runtime_head:{}};for(let se of Le)try{await Q(se,ee,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Oe=new Set,he;if(n.profile){let se=performance.now();he=await N(De,ee,P.filePath,ie,Oe);let Ie=performance.now()-se,je=te.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(De,ee,P.filePath,ie,Oe);if(!C)he=await xe(he,{router:ie.router});{let{interpolateScriptExpressions:se}=await import("./chunk-a7z6j9ga.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${se(He,ee)}</script>`})}if(C)he=qe(he,{preserveHead:!0});if(re&&H)await J(P.filePath,he,Oe,ie);let{extractStreamBoundaries:ct}=await import("./chunk-n20tsy6a.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let se=ee.streamBoundaries||{},Ie={...ie,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof se[Se]==="function"?await se[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Ce.add(P.pattern);else Qe=void 0;let Vt=Nt(ee),qt=Dt(ee);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??oe,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),I=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Pe=N.slice(q,q+Fe),xe=await Promise.all(Pe.map((U)=>_(U)));for(let U of xe)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Pe=Q.slice(q,q+Fe),xe=await Promise.all(Pe.map(({route:U})=>_(U)));for(let U of xe)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await ln(f);let Ge=o;try{if(Ge=await We(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let P=n.hmrPort||Ge+1;l=vt({wsPort:P,verbose:!1}),u=l.start(P)}let Pt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Ot=Fr({port:Ge,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===Lo&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:jo(N,cs()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,I.pathname),Pe=te.join(f,I.pathname),xe=te.join(be,I.pathname);if([q,Pe,xe].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([fe.promises.stat(q).catch(()=>null),fe.promises.stat(Pe).catch(()=>null),fe.promises.stat(xe).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Pe,f,S))return zt(Pe);if(W?.isFile()&&!v(xe,f,S))return zt(xe);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-xf5db38j.js"),re=await H(P,{publicDir:te.join(f,Q),cacheDir:c(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=mr(I.pathname,M);if(K){let H=le.get(K.route.pattern),re=Ce.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||re){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!re)le.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,oe=H.headers??{},ue=(K.route.filePath?bt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:K.params})){let De=await ne(404);if(De){let ee=De;if(ee=await b(ee,f),s)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Tt(I.pathname,K.params,ue,I.search),De=$t(Le,null,P,{isServer:!0}),ee=await Rt(ue.middleware,De);if(ee.redirect){let Oe=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",Oe),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:Oe,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Oe}</title></head><body><h1>Error ${Oe}</h1><p>${he}</p></body></html>`,{status:Oe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Oe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${Oe}</head>`)}}let B=H.content;if(C&&fa(P)&&Ke(B,h?.router?.container||"main")){let Le=tt(B),De=we(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Oe=ee?On(ee[1].trim()):"";if(Object.keys(K.params).length>0)B=Pt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=Te(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Oe&&{"X-STX-Title":encodeURIComponent(Oe)},[cc]:cs(),...j(),"Cache-Control":gt}})}if(C)B=Gr(C,B);if(Object.keys(K.params).length>0)B=Pt(B,K.params);if(B=await b(B,f),s)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-n20tsy6a.js");return De(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=mr(I.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await _(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)A.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(C)oe=Gr(C,oe);if(Object.keys(re.params).length>0)oe=Pt(oe,re.params);if(oe=await b(oe,f),s)oe=Ne(oe,u);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&I.pathname.startsWith(Z)){let oe=A.get(Z)||A.get(Z+"/");if(!oe){let ue=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(ue){let B=await _(ue.route);if(B)oe=B,A.set(ue.route.pattern,B)}}if(oe){let ue=oe.content;if(C)ue=Gr(C,ue);if(ue=await b(ue,f),s)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(kt(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),s)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ie=await ne(404);if(ie){let H=ie;if(H=await b(H,f),s)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await ne(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1441
1441
|
${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1442
1442
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1443
1443
|
${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),s)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
|
|
1444
|
-
${e.yellow}Routes:${e.reset}`);let At=[...
|
|
1445
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.url.toString(),()=>{if(l)it();Ot.stop()}),n.native){let P,I=te.join(k,"index.stx");if(fe.existsSync(I)){let Q=await Bun.file(I).text();P=mt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),I=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>fe.existsSync(J)).map((J)=>fe.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!fe.existsSync(W))continue;let de=fe.realpathSync(W);if(![...U].some((K)=>de===K||de.startsWith(`${K}${te.sep}`)))U.add(de)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&fe.existsSync(J))N.set(J,fe.watch(J,{recursive:!0},(W,de)=>{Pe(J,W,de).catch((K)=>console.error("[stx] Layer rebuild failed:",K))}))},q=Promise.resolve(),Pe=(U,J,W)=>(q=q.catch(()=>{}).then(()=>xe(U,J,W)),q),xe=async(U,J,W)=>{if(!W||xt(W))return;if(yt(W)){if(h._layerGraph){let de=await g(f);Object.assign(h,de),M.splice(0,M.length,...G(w,{pagesDir:y,pagesDirs:de._layerPageDirs?[k,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),s&&l)l.reload(W)}else if(I(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-
|
|
1446
|
-
`).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),s.push(h)}if(s.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)s.push({name:v})}}}return s}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function
|
|
1447
|
-
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function qr(t,n=!1,o){let d=at.basename(t,".stx"),s=await
|
|
1444
|
+
${e.yellow}Routes:${e.reset}`);let At=[...Is(M,f)];for(let{route:P}of R)At.push(`${P.pattern}`);if(At.forEach((P,I)=>{let Q=I===At.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
|
|
1445
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.url.toString(),()=>{if(l)it();Ot.stop()}),n.native){let P,I=te.join(k,"index.stx");if(fe.existsSync(I)){let Q=await Bun.file(I).text();P=mt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(U)=>U.startsWith("public/")||U.startsWith("public\\"),I=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>fe.existsSync(J)).map((J)=>fe.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!fe.existsSync(W))continue;let de=fe.realpathSync(W);if(![...U].some((K)=>de===K||de.startsWith(`${K}${te.sep}`)))U.add(de)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&fe.existsSync(J))N.set(J,fe.watch(J,{recursive:!0},(W,de)=>{Pe(J,W,de).catch((K)=>console.error("[stx] Layer rebuild failed:",K))}))},q=Promise.resolve(),Pe=(U,J,W)=>(q=q.catch(()=>{}).then(()=>xe(U,J,W)),q),xe=async(U,J,W)=>{if(!W||xt(W))return;if(yt(W)){if(h._layerGraph){let de=await g(f);Object.assign(h,de),M.splice(0,M.length,...G(w,{pagesDir:y,pagesDirs:de._layerPageDirs?[k,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),s&&l)l.reload(W)}else if(I(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-s321pb85.js");de(te.resolve(U,W)),K.delete(te.resolve(U,W))}catch{}if(D&&W){if(te.resolve(U,W)===D||te.basename(D)===W){let K=await bo(D,n.stxOptions||{});if(K)C=K}}if(await ze(),await ar(f),s&&l)l.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Ye.clear(),ge();try{let{invalidateFileCache:de,templateCache:K}=await import("./chunk-s321pb85.js");de(te.resolve(U,W)),K.delete(te.resolve(U,W))}catch{}if(await ze(),s&&l)l.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),s&&l)l.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(l)it();Ot.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function zr(t){try{let o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],s=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=l.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
|
|
1446
|
+
`).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),s.push(h)}if(s.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)s.push({name:v})}}}return s}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Nr(t){try{let n=await Bun.file(t).text(),o=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
|
|
1447
|
+
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function qr(t,n=!1,o){let d=at.basename(t,".stx"),s=await zr(t),l=await Nr(t),u="";if(n&&o)u=`<${o}></${o}>`;else{let f=s.map((g)=>{if(g.type==="boolean")return`:${g.name}="true"`;return`${g.name}="value"`}).join(`
|
|
1448
1448
|
`);u=`<${d}
|
|
1449
1449
|
${f}
|
|
1450
|
-
/>`}return{name:d,path:t,description:l,props:s,example:u,isWebComponent:n,tag:o}}async function dn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),o=[];for(let d of n){let s=at.join(t,d.name);if(d.isDirectory()){let l=await dn(s);o.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))o.push(s)}return o}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Kr(t,n){try{if(!await r(t))return[];let o=await dn(t),d=[],s=new Map;if(n?.components?.length)for(let l of n.components)s.set(l.file,l);for(let l of o){let u=s.get(l),f=!!u,g=u?.tag,h=await qr(l,f,g);d.push(h)}return d}catch(o){return console.error("Error generating component docs:",o),[]}}async function
|
|
1450
|
+
/>`}return{name:d,path:t,description:l,props:s,example:u,isWebComponent:n,tag:o}}async function dn(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),o=[];for(let d of n){let s=at.join(t,d.name);if(d.isDirectory()){let l=await dn(s);o.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))o.push(s)}return o}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Kr(t,n){try{if(!await r(t))return[];let o=await dn(t),d=[],s=new Map;if(n?.components?.length)for(let l of n.components)s.set(l.file,l);for(let l of o){let u=s.get(l),f=!!u,g=u?.tag,h=await qr(l,f,g);d.push(h)}return d}catch(o){return console.error("Error generating component docs:",o),[]}}async function Xr(t){try{if(!await r(t))return[];let n=await Ut.promises.readdir(t,{withFileTypes:!0}),o=[];for(let d of n){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let s=at.join(t,d.name),l=await Bun.file(s).text(),u=at.basename(s,".stx"),f=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),g=f?f[1].split(`
|
|
1451
1451
|
`).map((y)=>y.trim().replace(/^\*\s*/,"")).join(" ").trim():"",h=/@component\(\s*['"]([^'"]+)['"]/g,x=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,v=new Set,S;while((S=h.exec(l))!==null)v.add(S[1]);while((S=x.exec(l))!==null)if(S[1]&&S[1]!=="slot")v.add(S[1]);let T=/@([a-z]+)(?:\s*\(|\s+|$)/g,w=new Set;while((S=T.exec(l))!==null)w.add(S[1]);o.push({name:u,path:s,description:g,components:[...v],directives:[...w]})}return o}catch(n){return console.error("Error generating template docs:",n),[]}}async function Jr(t=[]){try{let n=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
|
|
1452
1452
|
<p>Welcome, {{ user.name }}!</p>
|
|
1453
1453
|
@endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
|
|
@@ -1581,15 +1581,15 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.
|
|
|
1581
1581
|
<td>@${l.name}</td>
|
|
1582
1582
|
<td>${l.description||"-"}</td>
|
|
1583
1583
|
<td>${l.hasEndTag?"Yes":"No"}</td>
|
|
1584
|
-
</tr>`;s+="</tbody></table>";for(let l of o)if(l.example)s+=`<h3>@${l.name}</h3>`,s+=`<p>${l.description||""}</p>`,s+="<h4>Example</h4>",s+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return s+="</body></html>",s}function Zr(t=[],n=[],o=[],d){return JSON.stringify({components:t,templates:n,directives:o,extraContent:d||""},null,2)}async function eo(t){try{let{componentsDir:n,templatesDir:o,webComponentsConfig:d,customDirectives:s,config:l}=t;if(!l.enabled)return!1;let u=l.outputDir||"docs";if(await Ut.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(o)console.log(`Templates directory: ${o}`);console.log(`Output directory: ${u}`);let f=[];if(l.components!==!1&&n)console.log("Generating component documentation..."),f=await Kr(n,d),console.log(`Found ${f.length} components`);let g=[];if(l.templates!==!1&&o)console.log("Generating template documentation..."),g=await
|
|
1584
|
+
</tr>`;s+="</tbody></table>";for(let l of o)if(l.example)s+=`<h3>@${l.name}</h3>`,s+=`<p>${l.description||""}</p>`,s+="<h4>Example</h4>",s+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return s+="</body></html>",s}function Zr(t=[],n=[],o=[],d){return JSON.stringify({components:t,templates:n,directives:o,extraContent:d||""},null,2)}async function eo(t){try{let{componentsDir:n,templatesDir:o,webComponentsConfig:d,customDirectives:s,config:l}=t;if(!l.enabled)return!1;let u=l.outputDir||"docs";if(await Ut.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(o)console.log(`Templates directory: ${o}`);console.log(`Output directory: ${u}`);let f=[];if(l.components!==!1&&n)console.log("Generating component documentation..."),f=await Kr(n,d),console.log(`Found ${f.length} components`);let g=[];if(l.templates!==!1&&o)console.log("Generating template documentation..."),g=await Xr(o),console.log(`Found ${g.length} templates`);let h=[];if(l.directives!==!1)console.log("Generating directive documentation..."),h=await Jr(s),console.log(`Found ${h.length} directives`);let x=l.format||"markdown",v=l.extraContent,S="",T="";switch(x){case"markdown":S=Yr(f,g,h,v),T="md";break;case"html":S=Qr(f,g,h,v),T="html";break;case"json":S=Zr(f,g,h,v),T="json";break;default:throw Error(`Unsupported documentation format: ${x}`)}let w=at.join(u,`stx-docs.${T}`);return await Bun.write(w,S),console.log(`Documentation generated: ${w}`),!0}catch(n){return console.error("Error generating documentation:",n),!1}}async function ta(t){let n={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||O.componentsDir,d=t.templatesDir||".";return eo({componentsDir:o,templatesDir:d,webComponentsConfig:O.webComponents,customDirectives:O.customDirectives,config:n})}var un={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function lo(t,n={}){let o={...un,...n};if(t.trim()==="")return`
|
|
1585
1585
|
`;let d=t;if(o.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=ro(d,o),d=ao(d,o),d=oo(d,o),o.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
|
|
1586
1586
|
`).replace(/\r/g,`
|
|
1587
1587
|
`),!d.endsWith(`
|
|
1588
1588
|
`))d+=`
|
|
1589
|
-
`;return d}function
|
|
1589
|
+
`;return d}function na(t,n={}){let o={...un,...n};if(t.trim()==="")return`
|
|
1590
1590
|
`;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(s,l,u,f,g)=>{let h=f.split(`
|
|
1591
1591
|
`),x=h.filter((y)=>y.trim().length>0);if(x.length===0)return s;let v=Math.min(...x.map((y)=>{let k=y.match(/^( *)/);return k?k[1].length:0})),S=h.map((y)=>{if(y.trim().length===0)return"";return y.substring(v)}).join(`
|
|
1592
|
-
`),w=
|
|
1592
|
+
`),w=lo(S,o).trimEnd().split(`
|
|
1593
1593
|
`).map((y)=>{if(y.trim().length===0)return"";return l+y}).join(`
|
|
1594
1594
|
`);return`${l}\`\`\`${u}
|
|
1595
1595
|
${w}
|
|
@@ -1614,7 +1614,7 @@ ${u}`}),n=n.replace(/(<\/[^>]+>)(?=<|$)/g,(s,l,u,f)=>{let g=f.substring(Math.max
|
|
|
1614
1614
|
`),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function ro(t,n){let d=no(t).split(`
|
|
1615
1615
|
`),s=[],l=0,u=!1,f=n.useTabs?"\t":" ".repeat(n.indentSize);for(let g=0;g<d.length;g++){let h=d[g],x=h.trim();if(x===""){s.push("");continue}let v=x.match(/<script\b/i),S=x.match(/<\/script>/i);if(u&&!S){s.push(h);continue}let T=x===">";if(pn(x)&&!x.startsWith("<")&&!x.startsWith("@")){s.push(f.repeat(l)+x);continue}let w=x.startsWith("@end"),y=x.startsWith("@else")||x.startsWith("@elseif"),k=x.startsWith("@")&&io(x),M=x.startsWith("<!DOCTYPE")||x.startsWith("<!doctype"),E=x.startsWith("<!--"),R=x.startsWith("</"),A=x.startsWith("<")&&!R&&!E&&!M,C=x.includes("/>")||so(x),D=pn(x);if(R||w)l=Math.max(0,l-1);let L=y?Math.max(0,l-1):l;if(T)s.push(h);else s.push(f.repeat(L)+x);if(A&&!C&&!D&&!T||k)l++;if(v)u=!0;if(S)u=!1}return s.join(`
|
|
1616
1616
|
`)}function oo(t,n){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(o,d,s)=>{let l=s.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(o,d,s)=>{if(s.trim()==="")return`@${d}`;return`@${d}(${s.trim()})`}),n.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(o,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(o,d)=>`{!! ${d.trim()} !!}`);return t}function so(t){let n=["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 d=o[1];return n.includes(d.toLowerCase())}return!1}function pn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function io(t){let n=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let o of n)if(t.startsWith(`@${o}`))return!t.includes(`@end${o}`);return!1}function ao(t,n){if(!n.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(o,d,s)=>{if(!s.trim())return o;if(s.includes("<")||s.includes(`
|
|
1617
|
-
`)||s.includes("@"))return o;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],f;while((f=l.exec(s))!==null)u.push({name:f[1],value:f[2]});u.sort((h,x)=>{if(h.name==="id")return-1;if(x.name==="id")return 1;if(h.name==="class")return-1;if(x.name==="class")return 1;return h.name.localeCompare(x.name)});let g=u.map((h)=>h.value?`${h.name}=${h.value}`:h.name).join(" ");return`<${d}${g?` ${g}`:""}>`})}import fn from"fs";import Wt from"path";async function
|
|
1617
|
+
`)||s.includes("@"))return o;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],f;while((f=l.exec(s))!==null)u.push({name:f[1],value:f[2]});u.sort((h,x)=>{if(h.name==="id")return-1;if(x.name==="id")return 1;if(h.name==="class")return-1;if(x.name==="class")return 1;return h.name.localeCompare(x.name)});let g=u.map((h)=>h.value?`${h.name}=${h.value}`:h.name).join(" ");return`<${d}${g?` ${g}`:""}>`})}import fn from"fs";import Wt from"path";async function ra(t="index.stx",n={}){try{let o=n.force||!1,d=Wt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!o)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let s=Wt.dirname(d);if(!fn.existsSync(s))fn.mkdirSync(s,{recursive:!0});let l;if(n.template){let u=Wt.resolve(process.cwd(),n.template);if(!await Bun.file(u).exists())throw Error(`Template file ${n.template} does not exist.`);if(!u.endsWith(".stx"))console.warn(`Warning: Template file ${n.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(u).text(),console.warn(`Using template from ${n.template}`)}else if(n.preset)l=mn(n.preset),console.warn(`Using '${n.preset}' preset template`);else l=mn("basic");return await Bun.write(d,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 mn(t){switch(t){case"basic":return gn();case"component":return co();case"layout":return fo();case"blog":return mo();case"api":return go();case"app":return ho();default:return gn()}}function gn(){return`<script>
|
|
1618
1618
|
const title = "My stx Page"
|
|
1619
1619
|
const description = "A page built with stx"
|
|
1620
1620
|
const features = [
|
|
@@ -1639,7 +1639,7 @@ const features = [
|
|
|
1639
1639
|
</div>
|
|
1640
1640
|
@endforeach
|
|
1641
1641
|
</main>
|
|
1642
|
-
@endsection`}function
|
|
1642
|
+
@endsection`}function co(){return`{{-- Component: Card --}}
|
|
1643
1643
|
{{-- Props: title, variant, collapsible --}}
|
|
1644
1644
|
{{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
|
|
1645
1645
|
<script>
|
|
@@ -2040,5 +2040,5 @@ const features = [
|
|
|
2040
2040
|
})();
|
|
2041
2041
|
</script>
|
|
2042
2042
|
</body>
|
|
2043
|
-
</html>`}var
|
|
2044
|
-
`)}export{
|
|
2043
|
+
</html>`}var sa="f9c3713";function Pl(t){return t}function Il(t){return t}function Zi(t,n){let o=[],d=`${n}=`;for(let s=0;s<t.length;s++){let l=t[s];if(l.startsWith(d)){let u=l.slice(d.length);if(u)o.push(u);continue}if(l===n){let u=t[s+1];if(u!==void 0&&!u.startsWith("-"))o.push(u),s++}}return o}import Me from"fs";import ye from"path";function Tn(t){try{return Me.statSync(t).mtimeMs}catch{return null}}function St(t,n){let o=Math.max(0,Math.round((n-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 Ti(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function $n(t,n="stx"){let o=ye.resolve(t);for(let d=0;d<10;d++){let s=ye.join(o,"pantry","@stacksjs",n);if(Me.existsSync(s))return s;let l=ye.dirname(o);if(l===o)break;o=l}return null}var Rn=["@stacksjs/stx","bun-plugin-stx"];function $i(t){try{let n=Me.readFileSync(ye.join(t,"package.json"),"utf8"),o=JSON.parse(n)?.version;return typeof o==="string"?o:null}catch{return null}}function Ci(t,n=6){let o=ye.resolve(t),d=[],s=new Set;function l(f,g){if(g>n)return;let h;try{h=Me.realpathSync(f)}catch{return}if(s.has(h))return;s.add(h);for(let v of Rn){let S=ye.join(f,v),T=$i(S);if(T!==null)d.push({name:v,version:T,dir:ye.relative(o,S)||S,nested:g>0})}let x;try{x=Me.readdirSync(f,{withFileTypes:!0})}catch{return}for(let v of x){if(!v.isDirectory()&&!v.isSymbolicLink())continue;if(v.name===".bin"||v.name===".cache")continue;let S=ye.join(f,v.name);if(v.name.startsWith("@")){let w;try{w=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let y of w){let k=ye.join(S,y.name,"node_modules");if(Me.existsSync(k))l(k,g+1)}continue}let T=ye.join(S,"node_modules");if(Me.existsSync(T))l(T,g+1)}}let u=ye.join(o,"node_modules");if(Me.existsSync(u))l(u,0);return d}function Ri(t){let n=[];for(let o of Rn){let d=t.filter((u)=>u.name===o);if(d.length<=1)continue;let s=[...new Set(d.map((u)=>u.version))],l=d.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(s.length===1){n.push({name:`${o} copies`,status:"info",detail:`${d.length} copies, all ${s[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${o} copies disagree`,status:"error",detail:`${s.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 n}async function uo(t={}){let n=t.cwd?ye.resolve(t.cwd):process.cwd(),o=t.resolve??Ti,d=Date.now(),s=[],l=o("@stacksjs/stx",n);s.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let u=o("bun-plugin-stx",n);if(u)s.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let g of Ri(Ci(n)))s.push(g);let f=$n(n,"stx");if(!f)s.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let g=ye.join(f,"src/signals.ts"),h=[ye.join(f,"dist/index.js"),ye.join(f,"dist/signals.js")].find((w)=>Me.existsSync(w))||null,x=Tn(g),v=h?Tn(h):null;if(x==null)s.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${f} but no src/signals.ts to compare`});else if(v==null)s.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${f} && bun build.ts`});else if(v<x){let w=Math.round((x-v)/1000);s.push({name:"pantry dist freshness",status:"error",detail:`dist (${St(v,d)}) is OLDER than src/signals.ts (${St(x,d)}) by ${w}s \u2014 your edit isn't built`,fix:`cd ${f} && bun build.ts`})}else s.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${St(x,d)}, dist ${St(v,d)})`});let S=ye.join(n,"node_modules/@stacksjs/stx"),T=null;try{T=Me.lstatSync(S)}catch{T=null}if(!T)s.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(T.isSymbolicLink()){let w=null;try{w=Me.realpathSync(S)}catch{}let y=(()=>{try{return Me.realpathSync(f)}catch{return f}})();s.push(w===y?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${w||"(dangling)"}, not pantry`})}else s.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(s.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let h=t.generateRuntime().length;s.push(h>1000?{name:"signals runtime",status:"ok",detail:`generated ${h.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${h} chars \u2014 suspiciously short`})}catch(g){s.push({name:"signals runtime",status:"error",detail:`failed to generate: ${g.message}`})}return{checks:s,ok:!s.some((g)=>g.status==="error")}}function po(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},o=["stx runtime resolution:"];for(let d of t.checks)if(o.push(` ${n[d.status]} ${d.name}: ${d.detail}`),d.fix)o.push(` \u2192 ${d.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(`
|
|
2044
|
+
`)}export{Zi,Qi,ea,ta,lo,na,ra,sa,Pl,Il,uo,po,Vr,Ur,Wr};
|
|
@@ -72,7 +72,7 @@ else {
|
|
|
72
72
|
${t}
|
|
73
73
|
})();
|
|
74
74
|
</script>
|
|
75
|
-
`}function
|
|
75
|
+
`}function Jm(i,n,o){f=0;let l=/@defer\s*\(([^)]*)\)\s*([\s\S]*?)@enddefer/g;return i.replace(l,(t,e,s)=>{let a=v(),r=p(t,e,s),d=r.placeholder?`<div data-defer-placeholder>${r.placeholder}</div>`:"",c=r.loading?`<div data-defer-loading style="display: none;">${r.loading}</div>`:'<div data-defer-loading style="display: none;"></div>',g=r.error?`<div data-defer-error style="display: none;">${r.error}</div>`:"",u=`<div data-defer-content style="display: none;">${r.content}</div>`,h=E(a,r);return`
|
|
76
76
|
<div id="${a}" class="stx-defer" data-defer-trigger="${r.trigger}">
|
|
77
77
|
${d}
|
|
78
78
|
${c}
|
|
@@ -81,4 +81,4 @@ else {
|
|
|
81
81
|
</div>
|
|
82
82
|
${h}
|
|
83
83
|
`})}
|
|
84
|
-
export{
|
|
84
|
+
export{Jm};
|