@stacksjs/stx 0.2.859 → 0.2.862
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/analytics.js +3 -2
- package/dist/animation.js +3 -3
- package/dist/app-shell.js +4 -3
- package/dist/{chunk-14cvwsy1.js → chunk-01c16zw4.js} +2 -2
- package/dist/chunk-0bfgsv31.js +2 -0
- package/dist/chunk-0c9c9v03.js +14 -0
- package/dist/{chunk-wjamjgx6.js → chunk-0fh47gp0.js} +2 -2
- package/dist/chunk-0fpx3ctt.js +2 -0
- package/dist/chunk-0twkeh31.js +2 -0
- package/dist/chunk-0xtda6aw.js +2 -0
- package/dist/chunk-12sv6b9c.js +2 -0
- package/dist/chunk-194t5qat.js +2 -0
- package/dist/chunk-1crn4fv0.js +2 -0
- package/dist/chunk-1d3swbqw.js +2 -0
- package/dist/{chunk-4yfbd8ny.js → chunk-1mqcttg3.js} +6 -6
- package/dist/chunk-1qf07v41.js +2 -0
- package/dist/chunk-24hq8mka.js +3 -0
- package/dist/chunk-2asyyky3.js +2 -0
- package/dist/chunk-2dpessnc.js +54 -0
- package/dist/{chunk-ews9yzr7.js → chunk-2jgtfjyr.js} +5 -5
- package/dist/chunk-2kfayg4t.js +712 -0
- package/dist/chunk-2rff5mbj.js +4 -0
- package/dist/chunk-2s7rmn9r.js +3 -0
- package/dist/{chunk-v9h7s8ce.js → chunk-2srjavsn.js} +2 -2
- package/dist/chunk-2zqh7xct.js +2 -0
- package/dist/chunk-321fbxnm.js +1327 -0
- package/dist/chunk-3gk1e2b1.js +2 -0
- package/dist/chunk-3ryp43f3.js +2 -0
- package/dist/{chunk-12r22pf0.js → chunk-3z1mmar2.js} +2 -2
- package/dist/{chunk-zhxdpzga.js → chunk-46ddesnf.js} +3 -3
- package/dist/chunk-46pxmpeb.js +3 -0
- package/dist/chunk-4pr29yrx.js +2 -0
- package/dist/{chunk-wfd9e224.js → chunk-4xanjv22.js} +125 -126
- package/dist/chunk-4ykgjewy.js +16 -0
- package/dist/{chunk-ftwdjgzd.js → chunk-55zq2ha8.js} +5 -5
- package/dist/{chunk-9a3rv0rj.js → chunk-5a0d3048.js} +3 -3
- package/dist/chunk-5ertqfs3.js +2 -0
- package/dist/chunk-627hzzs3.js +2 -0
- package/dist/chunk-64ebysb4.js +2 -0
- package/dist/{chunk-k8pzk8v9.js → chunk-669b2bya.js} +4 -4
- package/dist/{chunk-ktnb1j54.js → chunk-67dgp45w.js} +2 -2
- package/dist/chunk-6fstz73t.js +2 -0
- package/dist/{chunk-gndxakrh.js → chunk-6ftee542.js} +2 -2
- package/dist/{chunk-5wr1qqz3.js → chunk-6k4ac74t.js} +2 -2
- package/dist/{chunk-astcp7bc.js → chunk-6m63rc7m.js} +8 -8
- package/dist/{chunk-q3cyycnh.js → chunk-6m6y9bbx.js} +1 -1
- package/dist/chunk-6pczzq5f.js +2 -0
- package/dist/{chunk-6t0xy3wk.js → chunk-7ayvybdy.js} +3 -3
- package/dist/chunk-7mjf144y.js +2 -0
- package/dist/{chunk-9qe4qsc7.js → chunk-7mpqfg98.js} +21 -21
- package/dist/chunk-7q5h2cve.js +2 -0
- package/dist/chunk-7wqevtks.js +2 -0
- package/dist/chunk-84ztb43k.js +2 -0
- package/dist/{chunk-6e44f8w8.js → chunk-8502xb4n.js} +39 -39
- package/dist/{chunk-ywk6t76q.js → chunk-85j9qh7v.js} +45 -46
- package/dist/{chunk-cxpq2zna.js → chunk-8arfg8kp.js} +3 -3
- package/dist/{chunk-33x46g87.js → chunk-8hhhmscy.js} +2 -2
- package/dist/{chunk-x9c4njvx.js → chunk-8me8hamk.js} +2 -2
- package/dist/{chunk-pb09xy77.js → chunk-8s6s6nd0.js} +2 -2
- package/dist/chunk-8v1zpdef.js +2 -0
- package/dist/chunk-94mpe1ny.js +3 -0
- package/dist/chunk-94wnfxnd.js +2 -0
- package/dist/chunk-9jxs8sw2.js +2 -0
- package/dist/{chunk-2w7csg0c.js → chunk-9y9jecky.js} +1 -1
- package/dist/{chunk-mzes9ds7.js → chunk-9zrvh3pz.js} +2 -2
- package/dist/{chunk-hf9pvmq2.js → chunk-adb045wf.js} +3 -3
- package/dist/{chunk-fpkp0bqf.js → chunk-adqh1gp1.js} +1 -1
- package/dist/chunk-az5xw3w8.js +2 -0
- package/dist/chunk-ba91r7q9.js +2 -0
- package/dist/{chunk-qkcn0exq.js → chunk-brzjass3.js} +6 -6
- package/dist/chunk-bv7g3b3b.js +2 -0
- package/dist/chunk-bwdbj60y.js +3 -0
- package/dist/chunk-bwz2ehq9.js +33 -0
- package/dist/{chunk-ts4t2n6b.js → chunk-bx5d87xx.js} +6 -7
- package/dist/chunk-bz6dg4k8.js +3 -0
- package/dist/chunk-c34qn4k8.js +16 -0
- package/dist/{chunk-0es47pwe.js → chunk-cqhwzd9y.js} +5 -5
- package/dist/chunk-cvgbtmxp.js +2 -0
- package/dist/chunk-czpn3n1p.js +2 -0
- package/dist/chunk-dhnw2qwq.js +25 -0
- package/dist/{chunk-3w3fxcyx.js → chunk-dpmayc2w.js} +2 -2
- package/dist/{chunk-6mza6zr3.js → chunk-dtarm8x9.js} +9 -9
- package/dist/chunk-dydy9zrq.js +3 -0
- package/dist/chunk-eafqxbr0.js +2 -0
- package/dist/{chunk-52b6czss.js → chunk-eeq8k81z.js} +155 -157
- package/dist/{chunk-26jt4jvh.js → chunk-ew5cey88.js} +1 -1
- package/dist/chunk-fa97kz5j.js +2 -0
- package/dist/{chunk-xppm4cs4.js → chunk-farh4p7f.js} +3 -3
- package/dist/{chunk-3248qphb.js → chunk-fnxg6134.js} +10 -10
- package/dist/chunk-g075cc67.js +2 -0
- package/dist/{chunk-618t6hxp.js → chunk-g5xth2yx.js} +6 -6
- package/dist/{chunk-xpg52hsz.js → chunk-gbtbfg7e.js} +3 -3
- package/dist/{chunk-xytq7q8j.js → chunk-gd56arnm.js} +2 -2
- package/dist/chunk-gmm3kffd.js +2 -0
- package/dist/{chunk-dbm963p9.js → chunk-gp8hgpt9.js} +4 -4
- package/dist/chunk-h2qgqjkn.js +2 -0
- package/dist/chunk-h65shwe9.js +2 -0
- package/dist/chunk-hdjn7nw9.js +20 -0
- package/dist/{chunk-yd6ej23e.js → chunk-hev4t4d5.js} +6 -6
- package/dist/chunk-hf5fj7pr.js +2 -0
- package/dist/{chunk-cj9rev2p.js → chunk-hmdkf6c6.js} +2 -2
- package/dist/chunk-hsp9h3jn.js +2 -0
- package/dist/{chunk-p9jfn4yh.js → chunk-j1efsjsb.js} +5 -5
- package/dist/chunk-j4zrq17p.js +2 -0
- package/dist/chunk-jx5mss16.js +2 -0
- package/dist/chunk-jz84z19v.js +2 -0
- package/dist/{chunk-5rxks14t.js → chunk-k32q90b2.js} +2 -2
- package/dist/{chunk-4a0x737h.js → chunk-kbdz4762.js} +8 -8
- package/dist/chunk-kw11yydy.js +2 -0
- package/dist/{chunk-v4rrgphj.js → chunk-kwk3kxrx.js} +3 -3
- package/dist/chunk-kyer53x3.js +2 -0
- package/dist/chunk-m9cperj4.js +2 -0
- package/dist/{chunk-fxxh149b.js → chunk-mcnwvh06.js} +6 -6
- package/dist/chunk-meqsd5bt.js +2 -0
- package/dist/{chunk-s4592dy0.js → chunk-mfa07erx.js} +16 -16
- package/dist/chunk-mj4wbrw7.js +2 -0
- package/dist/{chunk-0yw86e75.js → chunk-mjy98ppb.js} +9 -9
- package/dist/{chunk-jh2v1vvb.js → chunk-mrh08821.js} +3 -3
- package/dist/{chunk-gq9h36jf.js → chunk-n058hznh.js} +5 -5
- package/dist/{chunk-9n8t7v78.js → chunk-n3jw3xpj.js} +2 -2
- package/dist/chunk-nz9z3ct9.js +2 -0
- package/dist/chunk-p0tkhd12.js +2 -0
- package/dist/chunk-p2etn78y.js +2 -0
- package/dist/{chunk-1nankvf6.js → chunk-pbakxcv8.js} +2 -2
- package/dist/{chunk-t5q31st4.js → chunk-q1wxgw5s.js} +2 -2
- package/dist/chunk-qa5y30sy.js +72 -0
- package/dist/{chunk-m1qqqc2j.js → chunk-qbghf76y.js} +4 -4
- package/dist/{chunk-a9c3gndq.js → chunk-qcxrcypb.js} +2 -2
- package/dist/{chunk-fkh4xece.js → chunk-qjey0jk6.js} +2 -2
- package/dist/chunk-rqa92xm4.js +2 -0
- package/dist/chunk-rvhrtnv3.js +12 -0
- package/dist/{chunk-7m17m22p.js → chunk-s0sad753.js} +2 -2
- package/dist/chunk-s92j8k4z.js +2 -0
- package/dist/chunk-s9df8srx.js +6 -0
- package/dist/{chunk-rgjjt1mb.js → chunk-sb8n32rn.js} +1 -1
- package/dist/chunk-snz2cxqv.js +2 -0
- package/dist/{chunk-14h4n1sj.js → chunk-srgnevws.js} +2 -2
- package/dist/chunk-srgpz94e.js +42 -0
- package/dist/{chunk-2sq9pdg3.js → chunk-tnp2ta5q.js} +2 -2
- package/dist/{chunk-5t1k0dxm.js → chunk-v37zmez0.js} +2 -2
- package/dist/chunk-v408qsze.js +2 -0
- package/dist/{chunk-qgxwf9xr.js → chunk-v4xes880.js} +3 -3
- package/dist/chunk-vfx1p83g.js +33 -0
- package/dist/chunk-vk98r75z.js +2 -0
- package/dist/{chunk-ypgegzh2.js → chunk-vvzys1x7.js} +3 -3
- package/dist/{chunk-f1vvhbmw.js → chunk-w6pzkcjp.js} +2 -2
- package/dist/chunk-x0s68p47.js +2 -0
- package/dist/{chunk-g17q4y5k.js → chunk-x512h2gv.js} +4 -4
- package/dist/{chunk-shke1fcm.js → chunk-x7redxyd.js} +4 -4
- package/dist/chunk-xjxcwrqs.js +2 -0
- package/dist/chunk-xsq2jf96.js +2 -0
- package/dist/chunk-xymr4ys9.js +3 -0
- package/dist/{chunk-wdcz6d20.js → chunk-y3qg95wa.js} +8 -8
- package/dist/chunk-y7f2x57s.js +2 -0
- package/dist/chunk-ymdw4fhd.js +3 -0
- package/dist/chunk-ymjjn9pw.js +20 -0
- package/dist/chunk-ynkbv9jq.js +4 -0
- package/dist/{chunk-49j3cn9h.js → chunk-ysfeg3cn.js} +2 -2
- package/dist/chunk-ytzzth34.js +2 -0
- package/dist/chunk-yxpjj003.js +2 -0
- package/dist/chunk-z1rs6b4x.js +2 -0
- package/dist/{chunk-yehdcjn1.js → chunk-z512gt4v.js} +3 -3
- package/dist/chunk-z6ntmv5x.js +2 -0
- package/dist/{chunk-5n7m8vqx.js → chunk-zbvfjm4a.js} +2 -2
- package/dist/chunk-zsnmk5me.js +2 -0
- package/dist/cli.js +35 -35
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/dev-server/serve-app.js +3 -2
- package/dist/dev-server/serve-multi.js +3 -4
- package/dist/dev-server/ts-css.js +4 -5
- package/dist/document-shell.js +4 -3
- package/dist/document-tags.d.ts +8 -0
- package/dist/document-tags.js +37 -0
- package/dist/events.js +2 -1
- package/dist/head-injection.js +2 -1
- package/dist/heatmap.js +2 -1
- package/dist/hot-reload.js +3 -1
- package/dist/index.d.ts +1 -0
- package/dist/index.js +1 -0
- package/dist/native-build.js +3 -3
- package/dist/process.js +5 -6
- package/dist/production-build.js +3 -3
- package/dist/pwa/inject.js +3 -3
- package/dist/pwa.js +3 -3
- package/dist/reactive-bindings.js +2 -1
- package/dist/reactive.js +2 -1
- package/dist/render.js +2 -6
- package/dist/runtime-injection.js +6 -6
- package/dist/serve.js +2 -6
- package/dist/site-builder/build.js +2 -2
- package/dist/site-builder/i18n.js +2 -2
- package/dist/site-builder/router.js +2 -5
- package/dist/site-builder/theme.js +2 -2
- package/dist/ssg.js +30 -31
- package/dist/template-hydrator.js +2 -1
- package/dist/web-components/css-scoping.js +3 -3
- package/dist/x-element.js +2 -1
- package/package.json +5 -5
- package/dist/chunk-13fe3avf.js +0 -2
- package/dist/chunk-1hebvmaj.js +0 -2
- package/dist/chunk-1p47cg0g.js +0 -2
- package/dist/chunk-1v95w26e.js +0 -20
- package/dist/chunk-1z46g29d.js +0 -2
- package/dist/chunk-228cbw2p.js +0 -2
- package/dist/chunk-2bggrzv0.js +0 -2
- package/dist/chunk-2dnd2s2a.js +0 -3
- package/dist/chunk-2kc0vsnb.js +0 -54
- package/dist/chunk-34rh88vd.js +0 -2
- package/dist/chunk-3cqp0m62.js +0 -2
- package/dist/chunk-3dtzcc9j.js +0 -2
- package/dist/chunk-3rgqrs3c.js +0 -2
- package/dist/chunk-403a4pqm.js +0 -25
- package/dist/chunk-51kb36f7.js +0 -2
- package/dist/chunk-53ezn1tw.js +0 -2
- package/dist/chunk-5va6c7jf.js +0 -14
- package/dist/chunk-636j1nmd.js +0 -2
- package/dist/chunk-6w5a5ns4.js +0 -18
- package/dist/chunk-756rpwn0.js +0 -2
- package/dist/chunk-7pq02v7n.js +0 -2
- package/dist/chunk-7sht1rkv.js +0 -2
- package/dist/chunk-7trdtz0c.js +0 -3
- package/dist/chunk-7ycmnsh5.js +0 -2
- package/dist/chunk-8mdhencj.js +0 -42
- package/dist/chunk-9nh48zvm.js +0 -72
- package/dist/chunk-9rgp005c.js +0 -2
- package/dist/chunk-9xr628ew.js +0 -3
- package/dist/chunk-aq8r4rbs.js +0 -3
- package/dist/chunk-azvx5gaa.js +0 -2
- package/dist/chunk-b1kc0ka1.js +0 -712
- package/dist/chunk-ebk1723c.js +0 -2
- package/dist/chunk-emc7zqry.js +0 -2
- package/dist/chunk-eppv6knk.js +0 -2
- package/dist/chunk-f18rxz70.js +0 -2
- package/dist/chunk-f935fec7.js +0 -2
- package/dist/chunk-g0v1shhr.js +0 -2
- package/dist/chunk-g5pg0pg1.js +0 -2
- package/dist/chunk-g8x32bq2.js +0 -2
- package/dist/chunk-g978f9qg.js +0 -18
- package/dist/chunk-hk7vjyqa.js +0 -2
- package/dist/chunk-jd4dr23j.js +0 -3
- package/dist/chunk-jhm1228j.js +0 -4
- package/dist/chunk-jmaw2cdt.js +0 -2
- package/dist/chunk-jw75rmpw.js +0 -2
- package/dist/chunk-kgrvvtcy.js +0 -3
- package/dist/chunk-kpsxhm4x.js +0 -33
- package/dist/chunk-kvc9cwvx.js +0 -12
- package/dist/chunk-m3fq72f8.js +0 -2
- package/dist/chunk-n54twtm7.js +0 -2
- package/dist/chunk-np6y9evb.js +0 -2
- package/dist/chunk-p95fsnbk.js +0 -2
- package/dist/chunk-pk0mxjxw.js +0 -2
- package/dist/chunk-q87hkwfg.js +0 -3
- package/dist/chunk-q9r13taa.js +0 -2
- package/dist/chunk-qd87dk1d.js +0 -1329
- package/dist/chunk-qe6631me.js +0 -2
- package/dist/chunk-qqjhq0hb.js +0 -2
- package/dist/chunk-qsjkewah.js +0 -2
- package/dist/chunk-qttq8cje.js +0 -2
- package/dist/chunk-qw80eta1.js +0 -2
- package/dist/chunk-r51bfc2y.js +0 -2
- package/dist/chunk-rbrvepr3.js +0 -2
- package/dist/chunk-rwxg4m3h.js +0 -3
- package/dist/chunk-se4ny3q0.js +0 -2
- package/dist/chunk-shy2hkvj.js +0 -2
- package/dist/chunk-sxvv9w8t.js +0 -2
- package/dist/chunk-sy703233.js +0 -2
- package/dist/chunk-syzn6mq5.js +0 -2
- package/dist/chunk-t2nhr2tc.js +0 -2
- package/dist/chunk-tc31my2p.js +0 -20
- package/dist/chunk-v3r1wwec.js +0 -2
- package/dist/chunk-vd5d1yb9.js +0 -2
- package/dist/chunk-vj1bwnvs.js +0 -4
- package/dist/chunk-vmdsj8r5.js +0 -2
- package/dist/chunk-vmg3f76h.js +0 -2
- package/dist/chunk-w1d8t47c.js +0 -33
- package/dist/chunk-w1stsxm3.js +0 -3
- package/dist/chunk-w63c96ce.js +0 -2
- package/dist/chunk-wcgca1q6.js +0 -2
- package/dist/chunk-wv8qmwqp.js +0 -2
- package/dist/chunk-x90f7h2g.js +0 -2
- package/dist/chunk-xhnpgey5.js +0 -2
- package/dist/chunk-y54pj23g.js +0 -2
- package/dist/chunk-yhrkqcqd.js +0 -2
- package/dist/chunk-ykxpzjgy.js +0 -2
- package/dist/chunk-zhyrhxdp.js +0 -2
- package/dist/chunk-zn5tewws.js +0 -2
- package/dist/chunk-zvra3bmk.js +0 -2
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{
|
|
2
|
+
import{he,vn,Bt,Ft,h,s,be,g}from"./chunk-2kfayg4t.js";import{kt,Ne,hc,ps,zo,Ho,i}from"./chunk-321fbxnm.js";import{pe,re,Or,$e,U,Rn}from"./chunk-qa5y30sy.js";import{$t,wr,Ns,Ms,Ds,Rt,At,Pt,It,Ot,Nt,ot}from"./chunk-x512h2gv.js";import{$s,a,D}from"./chunk-4xanjv22.js";import{wt,en,Ae,z,wa,So,Qr,Je,va,Ye,Pe}from"./chunk-vfx1p83g.js";import{hr,yr}from"./chunk-2s7rmn9r.js";import{e,mn,dr,x}from"./chunk-4ykgjewy.js";import{tt}from"./chunk-2dpessnc.js";import{Oe}from"./chunk-9zrvh3pz.js";import{Mn}from"./chunk-dydy9zrq.js";import{Z,ke,_e}from"./chunk-0c9c9v03.js";import{l}from"./chunk-46pxmpeb.js";import{Y}from"./chunk-bwdbj60y.js";import{c,f}from"./chunk-s9df8srx.js";async function Wn(t){try{let n=await Bun.file(t).text(),r=Vn(n),p=qn(n,t),o=Kn(n,r),d=Xn(n,r);return{file:t,metrics:r,issues:p,suggestions:o,performance:d}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Vn(t){let n=t.split(`
|
|
3
3
|
`),r=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),o=(r?r[1]:"").split(`
|
|
4
|
-
`).length,
|
|
5
|
-
`).filter((
|
|
4
|
+
`).length,d={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};d.total=d.conditionals+d.loops+d.includes+d.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,b=u+m+y,w=(t.match(/<[A-Z][^>]*>/g)||[]).length,S=(t.match(/@(?:layout|extends)\(/g)||[]).length,T=0,R=0;for(let C of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(C)&&!/@end/.test(C)&&!/@else/.test(C))R++,T=Math.max(T,R);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(C))R--;let k=T>=4?3:0,v=Math.min(10,Math.ceil(d.total*0.5+b*0.1+w*0.3+(o>10?o*0.05:0)+k));return{lines:n.length,characters:t.length,directives:d,expressions:b,components:w,layouts:S,scriptLines:o,complexity:v}}function qn(t,n){let r=[],p=Yt(t,"if","endif");if(p>0)r.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let o=Yt(t,"foreach","endforeach");if(o>0)r.push({type:"error",category:"syntax",message:`Found ${o} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)r.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)r.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let m=t.match(/<img[^>]*>/g);if(m){let w=m.filter((S)=>!S.includes("alt="));if(w.length>0)r.push({type:"warning",category:"accessibility",message:`Found ${w.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
|
|
5
|
+
`).filter((w)=>w.length>120);if(y.length>0)r.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let b=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(b>3)r.push({type:"info",category:"maintainability",message:`Found ${b} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return r}function Kn(t,n){let r=[];if(n.complexity>7)r.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)r.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)r.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)r.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)r.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)r.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)r.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return r}function Xn(t,n){let r=1;if(r+=n.directives.conditionals*0.1,r+=n.directives.loops*0.5,r+=n.directives.includes*2,r+=n.expressions*0.05,r+=n.components*1,n.scriptLines>10)r+=n.scriptLines*0.1;let p;if(n.expressions===0&&n.directives.total===0)p="high";else if(n.expressions<5&&n.directives.total<3)p="medium";else p="low";let o=[];if(r>10)o.push("Consider optimizing template complexity");if(p==="low"&&n.directives.total>5)o.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)o.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(r*100)/100,complexityScore:n.complexity,cacheability:p,recommendations:o}}function Yt(t,n,r){let p=t.replace(/<!--[\s\S]*?-->/g,""),o=(p.match(new RegExp(`@${n}\\b`,"g"))||[]).length,d=(p.match(new RegExp(`@${r}\\b`,"g"))||[]).length;return Math.abs(o-d)}async function ia(t=["**/*.stx"],n){let r=[],p=[];for(let d of t){let u=await Array.fromAsync(new Bun.Glob(d).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...u.filter((m)=>m.endsWith(".stx")))}for(let d of p)try{let u=await Wn(d);r.push(u)}catch(u){console.warn(`Failed to analyze ${d}:`,u)}let o=Gn(r);return{results:r,summary:o}}function Gn(t){let n=t.length,r=t.reduce((b,w)=>b+w.metrics.lines,0),p=n>0?t.reduce((b,w)=>b+w.metrics.complexity,0)/n:0,o=t.reduce((b,w)=>b+w.issues.length,0),d={};t.forEach((b)=>{b.issues.forEach((w)=>{d[w.category]=(d[w.category]||0)+1})});let u=n>0?t.reduce((b,w)=>b+w.performance.estimatedRenderTime,0)/n:0,m=Math.max(1,Math.min(10,Math.round(10-u/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(o>n*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(d.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:r,avgComplexity:Math.round(p*100)/100,totalIssues:o,issuesByCategory:d,performanceScore:m,recommendations:y}}import{mkdir as Jn,readFile as Yn,readdir as Qn,stat as Qt,writeFile as Zn}from"fs/promises";import Te from"path";function sn(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 an=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function er(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function jt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function tr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function nr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function rr(t){let n=[];async function r(p){let o=await Qn(p,{withFileTypes:!0});o.sort((d,u)=>d.name.localeCompare(u.name));for(let d of o){let u=Te.join(p,d.name);if(d.isDirectory()){if(!d.name.startsWith(".")&&d.name!=="node_modules")await r(u)}else if(d.isFile()&&d.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(d.name))n.push(u)}}return await r(t),n}function or(t,n){let r=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!r)return{};let p=r[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(o){throw Error(`${n}: <script component> must contain JSON metadata (${o.message})`)}}function sr(t,n){let r={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let o of p){if(!/\bclient\b/i.test(o[1])||/\bcomponent\b|\bstx:component\b/i.test(o[1]))continue;let d;try{d=new Bun.Transpiler({loader:"ts"}).transformSync(o[2])}catch(y){throw Error(`${n}: failed to transpile <script client> (${y.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,m;while(m=u.exec(d)){let y=m[1];if(an.has(y))throw Error(`${n}: client ${sn(y)}`);let b=u.lastIndex,w=1,S="",T=!1,R=b;for(;R<d.length&&w>0;R++){let v=d[R];if(T){T=!1;continue}if(S){if(v==="\\")T=!0;else if(v===S)S="";continue}if(v==='"'||v==="'"||v==="`")S=v;else if(v==="{")w++;else if(v==="}")w--}if(w!==0)throw Error(`${n}: unterminated client function "${y}"`);let k=m[0].includes("async")?"async ":"";r[y]=`${k}${y}(${m[2]}) {${d.slice(b,R-1)}}`,u.lastIndex=R}}return r}function ir(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 Zt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
|
|
6
6
|
|
|
7
|
-
`)}function
|
|
8
|
-
`)}function
|
|
7
|
+
`)}function ar(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 cr(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 lr(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 pr(t){let n=[],r=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),o=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,d,u=(y)=>{if(p[y]!=="(")return null;let b=0,w="";for(let S=y;S<p.length;S++){let T=p[S];if(w!==""){if(T==="\\")S++;else if(T===w)w="";continue}if(T==="'"||T==='"'||T==="`"){w=T;continue}if(T==="(")b++;else if(T===")"){if(b--,b===0)return{expression:p.slice(y+1,S),end:S+1}}}return null},m=(y)=>{if(y==="")return;let b=0,w=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,S;while(S=w.exec(y)){if(S.index>b)n.push(`out += ${JSON.stringify(y.slice(b,S.index))};`);n.push(S[1]!==void 0?`out += __raw(${S[1]});`:`out += __escape(${S[2]});`),b=S.index+S[0].length}if(b<y.length)n.push(`out += ${JSON.stringify(y.slice(b))};`)};while(d=o.exec(p)){m(p.slice(r,d.index)),r=d.index+d[0].length;let b=d[1]==="if"||d[1]==="elseif"||d[1]==="foreach"?u(r):null;if(b)r=b.end,o.lastIndex=b.end;let w=b?.expression;switch(d[1]){case"if":n.push(`if (${w}) {`);break;case"elseif":n.push(`} else if (${w}) {`);break;case"else":n.push("} else {");break;case"endif":case"endforeach":n.push("}");break;case"foreach":{let S=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((w||"").trim());if(!S){n.push(`out += ${JSON.stringify(d[0]+(b?`(${w})`:""))};`);break}let[,T,R,k]=S;n.push(R?`for (const [${R}, ${k}] of __entries(${T})) {`:`for (const ${k} of __values(${T})) {`);break}}}return m(p.slice(r)),n.join(`
|
|
8
|
+
`)}function ut(t,n,r,p){if(t[n]!==r)return-1;let o=0,d=null;for(let u=n;u<t.length;u++){let m=t[u];if(d){if(m==="\\"){u++;continue}if(m===d)d=null;continue}if(m==="'"||m==='"'||m==="`"){d=m;continue}if(m===r)o++;else if(m===p){if(p===">"&&t[u-1]==="=")continue;if(o--,o===0)return u+1}}return-1}function _t(t,n,r){let p=r?"([{<":"([{",o=r?")]}>":")]}",d=[],u=0,m=null,y="";for(let b=0;b<t.length;b++){let w=t[b];if(m){if(y+=w,w==="\\"){y+=t[++b]??"";continue}if(w===m)m=null;continue}if(w==="'"||w==='"'||w==="`"){m=w,y+=w;continue}if(p.includes(w))u++;else if(o.includes(w))u--;if(u===0&&n.includes(w)){d.push(y),y="";continue}y+=w}return d.push(y),d.map((b)=>b.trim()).filter(Boolean)}function ur(t){let n=0,r=null;for(let p=0;p<t.length;p++){let o=t[p];if(r){if(o==="\\"){p++;continue}if(o===r)r=null;continue}if(o==="'"||o==='"'||o==="`"){r=o;continue}if("([{".includes(o))n++;else if(")]}".includes(o))n--;if(n!==0||o!=="=")continue;let d=t[p-1];if(t[p+1]==="="||d==="="||d==="!"||d==="<"||d===">")continue;return p}return-1}function tn(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 fr(t){let n=/\bdefineProps\b/.exec(t);if(!n)return null;let r=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let O=r.exec(t);O&&O.index<n.index;O=r.exec(t))p=O.index+O[0].indexOf(O[1]);if(p===-1)return null;let o={},d={},u=[],m={},y=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),b=()=>{while(y<t.length&&/\s/.test(t[y]))y++},w;if(t[y]==="{"){let O=ut(t,y,"{","}");if(O===-1)return null;w=t.slice(y,O),y=O}else{let O=/^[A-Za-z_$][\w$]*/.exec(t.slice(y));if(!O)return null;w=O[0],y+=O[0].length}if(b(),t[y]!=="=")return null;y++,b();let S=/^withDefaults\s*\(\s*/.exec(t.slice(y)),T=Boolean(S);if(S)y+=S[0].length;let R=/^defineProps\b/.exec(t.slice(y));if(!R)return null;y+=R[0].length;let k="";if(b(),t[y]==="<"){let O=ut(t,y,"<",">");if(O===-1)return null;k=t.slice(y+1,O-1).trim(),y=O}if(b(),t[y]!=="(")return null;let v=ut(t,y,"(",")");if(v===-1)return null;let C=t.slice(y+1,v-1).trim();if(y=v,T){if(b(),t[y]===",")y++,b();if(t[y]==="{"){let O=ut(t,y,"{","}");if(O===-1)return null;for(let[P,M]of Lt(t.slice(y,O)))d[P]=M;y=O}if(b(),t[y]===",")y++,b();if(t[y]===")")y++}if(t[y]===";")y++;let L=/^[A-Za-z_$][\w$]*$/.test(k)?k:void 0;if(k.startsWith("{"))for(let O of _t(k.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let P=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(O);if(P)o[P[1]]=P[2].trim()}if(C.startsWith("{"))for(let[O,P]of Lt(C)){if(u.push(O),!P.startsWith("{")){let M=tn(P);if(M)o[O]=M;continue}for(let[M,E]of Lt(P))if(M==="default")d[O]=E;else if(M==="type"){let _=tn(E);if(_)o[O]=_}}else if(C.startsWith("["))for(let O of _t(C.slice(1,-1),",",!1))u.push(O.replace(/^['"`]/,"").replace(/['"`]$/,""));if(w.startsWith("{")){u.length=0;for(let O of _t(w.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let P=ur(O),M=P===-1?O:O.slice(0,P),E=M.split(":")[0].trim().replace(/^\.\.\./,"");if(!E)continue;if(u.push(E),m[E]=M.trim(),P!==-1)d[E]=O.slice(P+1).trim()}}else if(u.length===0)u.push(...Object.keys(o));return{text:t.slice(p,y),propNames:u,propBindings:m,defaults:d,declared:o,typeName:L}}function Lt(t){let n=t.trim().replace(/^\{/,"").replace(/\}$/,""),r=[],p=0;while(p<n.length){let o=/\s*([A-Za-z_$][\w$]*)\s*:/y;o.lastIndex=p;let d=o.exec(n);if(!d)break;p=o.lastIndex;let u=0,m="",y=p;while(p<n.length){let w=n[p];if(m){if(w==="\\")p++;else if(w===m)m=""}else if(w==="'"||w==='"'||w==="`")m=w;else if(w==="{"||w==="["||w==="(")u++;else if(w==="}"||w==="]"||w===")")u--;else if(w===","&&u===0)break;p++}let b=n.slice(y,p).trim();if(b)r.push([d[1],b]);p++}return r}function mr(t,n,r){let o=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((R)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(R[1]));if(!o)return{imports:[],body:"",propNames:[],propBindings:{},defaults:{},declared:{}};let d=o[2],u=[],m=[],y={},b={},w={};d=d.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(R)=>{if(/from\s*['"]stx['"]/.test(R))return"";return u.push(R.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(k,v,C,L)=>{let O=Te.resolve(Te.dirname(n),C),P=Te.relative(r,O);return`${v}${P.startsWith(".")?P:`./${P}`}${L}`})),""});let S=fr(d);if(S)m.push(...S.propNames),Object.assign(y,S.propBindings),Object.assign(b,S.defaults),Object.assign(w,S.declared),d=d.replace(S.text,"");let T={};for(let R of d.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let k=[];for(let v of R[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))w[v[1]]=v[2].trim(),k.push(v[1]);T[R[1]]=k}if(S&&S.propNames.length===0&&S.typeName){for(let R of T[S.typeName]??[])if(!m.includes(R))m.push(R)}return d=d.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:u,body:d.trim(),propNames:m,propBindings:y,defaults:b,declared:w}}function gr(t){let n=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,o,d,u,m)=>{let y=o.toLowerCase();n.add(y);let b=(d||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${y}="${m}"${b?` data-stx-mod-${y}="${b}"`:""}`}),eventTypes:[...n].sort()}}function br(t){let n=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,o,d,u)=>{let m=n.length;return n.push({id:m,name:o,expression:u}),` data-stx-bind-${m}=""`}),bindings:n}}function xr(t){let n=new Set;for(let r of t.matchAll(/<slot\b([^>]*)>/gi))n.add(r[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...n].map((r)=>({name:r}))}function vr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((n)=>n[1]))].sort().map((n)=>({name:n}))}function nn(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 Sr(t,n,r){let p=Te.isAbsolute(n.file)?n.file:Te.resolve(t,n.file),o=await Yn(p,"utf8"),d=or(o,p),u=Te.basename(p,".stx"),m=n.name||d.name||er(u),y=`${jt(r.prefix||"stx")}-${jt(u)}`,b=n.tag||d.tag||y;if(!m||!/^[A-Za-z_$][\w$]*$/.test(m))throw Error(`${p}: invalid component class name "${m}"`);if(!tr(b))throw Error(`${p}: invalid custom-element tag "${b}"; tags must be lowercase and contain a hyphen`);let w=n.properties||d.properties||d.props||{},S=Object.fromEntries(Object.entries(w).map(([P,M])=>[P,nn(P,M)])),T=gr(ir(o)),R=br(T.template),k=mr(o,p,Te.resolve(r.outputDir)),v=pr(R.template);for(let P of k.propNames){if(S[P])continue;let M=k.defaults[P];S[P]=nn(P,{type:ar(k.declared[P])??cr(M),...M===void 0?{}:{default:lr(M)}})}let C=d.methods||{},L=n.methods||{},O=sr(o,p);return{file:Te.relative(t,p),sourcePath:p,name:m,tag:b,description:n.description||d.description||"",template:R.template,styles:Zt(o),shadowMode:nr(n.shadowDOM??d.shadowDOM??r.shadowDOM),progressive:n.progressive??d.progressive??r.progressive??!0,properties:S,events:n.events||d.events||{},methods:{...C,...L,...O},eventTypes:T.eventTypes,bindings:R.bindings,slots:xr(R.template),cssProperties:vr(Zt(o)),scope:k,render:v}}function kr(){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('>', '>')
|
|
@@ -314,22 +314,22 @@ export function defineComponent(Component, definition) {
|
|
|
314
314
|
}
|
|
315
315
|
return Component;
|
|
316
316
|
}
|
|
317
|
-
`}function
|
|
318
|
-
${
|
|
317
|
+
`}function Tr(t){let n=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),r=Object.entries(t.methods).map(([m,y])=>{if(an.has(m))throw Error(`${t.sourcePath}: ${sn(m)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(y.trim()))return` ${y.trim()}`;return` ${m}($event) {
|
|
318
|
+
${y}
|
|
319
319
|
}`}).join(`
|
|
320
320
|
|
|
321
|
-
`),
|
|
322
|
-
`).map((
|
|
323
|
-
`),u="";if(t.render.trim()!==""||
|
|
324
|
-
`),
|
|
325
|
-
${
|
|
326
|
-
}`),
|
|
321
|
+
`),p=t.scope,o=[...new Set([...Object.keys(t.properties),...p.propNames])].map((m)=>{let y=p.propBindings[m]||m;return p.defaults[m]===void 0?y:`${y} = ${p.defaults[m]}`}).join(", "),d=(m)=>m.split(`
|
|
322
|
+
`).map((y)=>y.trim()===""?y:` ${y}`).join(`
|
|
323
|
+
`),u="";if(t.render.trim()!==""||p.body!==""||o!==""){let m=[o?`const { ${o} } = this._props();`:"",p.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
|
|
324
|
+
`),y;try{let b=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
|
|
325
|
+
${m}
|
|
326
|
+
}`),w=b.indexOf("{"),S=b.lastIndexOf("}");y=b.slice(w+1,S).trim()}catch(b){throw Error(`${t.sourcePath}: failed to compile render (${b.message})`)}u=`
|
|
327
327
|
render(__helpers) {
|
|
328
328
|
const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
|
|
329
|
-
${
|
|
329
|
+
${d(y.trim())}
|
|
330
330
|
}
|
|
331
331
|
`}return`import { StxElement, defineComponent } from './runtime.js';
|
|
332
|
-
${
|
|
332
|
+
${p.imports.length?`${p.imports.join(`
|
|
333
333
|
`)}
|
|
334
334
|
`:""}
|
|
335
335
|
/** ${t.description||`${t.name} web component generated from ${t.file}.`} */
|
|
@@ -339,9 +339,9 @@ ${r}${u}
|
|
|
339
339
|
|
|
340
340
|
defineComponent(${t.name}, ${n});
|
|
341
341
|
export default ${t.name};
|
|
342
|
-
`}function Ht(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function
|
|
343
|
-
`),r=Object.entries(t.events).map(([o,
|
|
344
|
-
`),
|
|
342
|
+
`}function Ht(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function $r(t){let n=Object.entries(t.properties).map(([o,d])=>` ${o}${d.required?"":"?"}: ${Ht(d)}`).join(`
|
|
343
|
+
`),r=Object.entries(t.events).map(([o,d])=>` ${JSON.stringify(o)}: CustomEvent<${d.detailType||"unknown"}>`).join(`
|
|
344
|
+
`),p=Object.keys(t.methods).map((o)=>` ${o}($event?: Event): unknown`).join(`
|
|
345
345
|
`);return`export interface ${t.name}Props {
|
|
346
346
|
${n}
|
|
347
347
|
}
|
|
@@ -353,7 +353,7 @@ ${r}
|
|
|
353
353
|
export interface ${t.name} extends Required<Pick<${t.name}Props, Exclude<keyof ${t.name}Props, keyof HTMLElement>>> {}
|
|
354
354
|
|
|
355
355
|
export declare class ${t.name} extends HTMLElement {
|
|
356
|
-
${
|
|
356
|
+
${p}
|
|
357
357
|
readonly updateComplete: Promise<void>
|
|
358
358
|
requestUpdate(): Promise<void>
|
|
359
359
|
emit<T = unknown>(name: string, detail?: T, options?: CustomEventInit<T>): boolean
|
|
@@ -366,13 +366,13 @@ declare global {
|
|
|
366
366
|
}
|
|
367
367
|
|
|
368
368
|
export default ${t.name}
|
|
369
|
-
`}function
|
|
369
|
+
`}function Cr(t){return`declare global {
|
|
370
370
|
namespace JSX {
|
|
371
371
|
interface IntrinsicElements {
|
|
372
|
-
${t.map((r)=>{let
|
|
373
|
-
`),o=Object.keys(r.events).map((
|
|
372
|
+
${t.map((r)=>{let p=Object.entries(r.properties).map(([d,u])=>` ${JSON.stringify(d)}?: ${Ht(u)}`).join(`
|
|
373
|
+
`),o=Object.keys(r.events).map((d)=>` ${`on${d.split(/[-:]/).map((m)=>m.charAt(0).toUpperCase()+m.slice(1)).join("")}`}?: (event: CustomEvent<${r.events[d].detailType||"unknown"}>) => void`).join(`
|
|
374
374
|
`);return` ${JSON.stringify(r.tag)}: {
|
|
375
|
-
${
|
|
375
|
+
${p}
|
|
376
376
|
${o}
|
|
377
377
|
children?: unknown
|
|
378
378
|
slot?: string
|
|
@@ -385,9 +385,9 @@ ${o}
|
|
|
385
385
|
}
|
|
386
386
|
|
|
387
387
|
export {}
|
|
388
|
-
`}function
|
|
388
|
+
`}function Rr(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(([r,p])=>({kind:"field",name:r,description:p.description,type:{text:Ht(p)},default:p.default===void 0?void 0:JSON.stringify(p.default),attribute:p.attribute===!1?void 0:p.attribute||jt(r),reflects:p.reflect})),events:Object.entries(n.events).map(([r,p])=>({name:r,description:p.description,type:{text:`CustomEvent<${p.detailType||"unknown"}>`}})),slots:n.slots,cssProperties:n.cssProperties}],exports:[{kind:"js",name:n.name,declaration:{name:n.name,module:`./${n.tag}.js`}}]}))}}function rn(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
|
|
390
|
+
}`}function on(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Er(t){let n=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),r=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),p=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),o=Object.fromEntries(t.map((u)=>[u.tag,{template:u.template,styles:u.styles,shadowMode:u.shadowMode,properties:u.properties}])),d=t.map((u)=>`export const render${u.name} = (props = {}, slots = {}) => renderComponent('${u.tag}', props, slots);`).join(`
|
|
391
391
|
`);return`const definitions = ${JSON.stringify(o,null,2)};
|
|
392
392
|
const escapeHTML = (value) => String(value ?? '')
|
|
393
393
|
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
@@ -402,7 +402,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
|
|
|
402
402
|
let template = definition.template
|
|
403
403
|
.replace(new RegExp(${n}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
|
|
404
404
|
.replace(new RegExp(${r}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
|
|
405
|
-
.replace(new RegExp(${
|
|
405
|
+
.replace(new RegExp(${p}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
|
|
406
406
|
const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
|
|
407
407
|
if (property.attribute === false || !(name in props)) return [];
|
|
408
408
|
const attribute = property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
|
|
@@ -420,22 +420,22 @@ export function renderComponent(tag, props = {}, slots = {}) {
|
|
|
420
420
|
return '<' + tag + (attributes ? ' ' + attributes : '') + '>' + template + '</' + tag + '>';
|
|
421
421
|
}
|
|
422
422
|
|
|
423
|
-
${
|
|
424
|
-
`}async function
|
|
425
|
-
`)?
|
|
426
|
-
`,"utf8"),
|
|
427
|
-
`);if(await
|
|
428
|
-
`)),await
|
|
423
|
+
${d}
|
|
424
|
+
`}async function aa(t){let n=Te.resolve(t.inputDir),r=Te.resolve(t.outputDir);if(!(await Qt(n).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${n}`);let o=t.components?.length?t.components:(await rr(n)).map((v)=>({file:v}));if(!o.length)throw Error(`No .stx components found in ${n}`);let d=await Promise.all(o.map((v)=>Sr(n,v,t)));d.sort((v,C)=>v.tag.localeCompare(C.tag));let u=d.filter((v,C)=>d.findIndex((L)=>L.tag===v.tag)!==C);if(u.length)throw Error(`Duplicate custom-element tag: ${u[0].tag}`);let m=d.filter((v,C)=>d.findIndex((L)=>L.name===v.name)!==C);if(m.length)throw Error(`Duplicate component class name: ${m[0].name}`);await Jn(r,{recursive:!0});let y=[],b=async(v,C)=>{let L=Te.join(r,v);return await Zn(L,C.endsWith(`
|
|
425
|
+
`)?C:`${C}
|
|
426
|
+
`,"utf8"),y.push(L),L};await b("runtime.js",kr());for(let v of d){if(await b(`${v.tag}.js`,Tr(v)),t.declarations!==!1)await b(`${v.tag}.d.ts`,$r(v));if(t.css!==!1&&v.styles){let C=v.shadowMode?v.styles:rn(v);await b(`${v.tag}.css`,t.minify?on(C):C)}}let w=d.map((v)=>`export { ${v.name}, default as ${v.name}Element } from './${v.tag}.js';`).join(`
|
|
427
|
+
`);if(await b("index.js",w),await b("ssr.js",Er(d)),t.declarations!==!1)await b("index.d.ts",d.map((v)=>`export * from './${v.tag}.js'`).join(`
|
|
428
|
+
`)),await b("custom-elements.d.ts",Cr(d)),await b("ssr.d.ts",`${d.map((v)=>`export declare const render${v.name}: (props?: ${v.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
|
|
431
|
-
${
|
|
432
|
-
`)}`);let
|
|
433
|
-
|
|
434
|
-
`);if(
|
|
435
|
-
`);throw AggregateError(
|
|
436
|
-
${
|
|
437
|
-
`);throw AggregateError(
|
|
438
|
-
${
|
|
431
|
+
${d.map((v)=>`import type { ${v.name}Props } from './${v.tag}.js'`).join(`
|
|
432
|
+
`)}`);let S;if(t.manifest!==!1)S=await b("custom-elements.json",JSON.stringify(Rr(d),null,2));let T;if(t.css!==!1){let v=d.filter((C)=>!C.shadowMode&&C.styles).map(rn).join(`
|
|
433
|
+
|
|
434
|
+
`);if(v)T=await b("bundle.css",t.minify?on(v):v)}let R;if(t.bundle!==!1){R=Te.join(r,"bundle.js");let v;try{v=await Bun.build({entrypoints:[Te.join(r,"index.js")],outdir:r,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(C){let L=C instanceof AggregateError?C.errors:[C],O=L.map((P)=>String(P).trim()).filter(Boolean).join(`
|
|
435
|
+
`);throw AggregateError(L,`Failed to bundle component library${O?`
|
|
436
|
+
${O}`:""}`)}if(!v.success){let C=v.logs.map((L)=>String(L).trim()).filter(Boolean).join(`
|
|
437
|
+
`);throw AggregateError(v.logs,`Failed to bundle component library${C?`
|
|
438
|
+
${C}`:""}`)}if(y.push(R),t.sourcemap==="external")y.push(`${R}.map`)}let k=await Promise.all(y.map(async(v)=>(await Qt(v)).size));return{components:d.map((v)=>({name:v.name,tag:v.tag,source:v.sourcePath,module:Te.join(r,`${v.tag}.js`)})),files:y,manifest:S,bundle:R,cssBundle:T,totalBytes:k.reduce((v,C)=>v+C,0)}}var{serve:Hr}=globalThis.Bun;import Ut from"fs";import nt from"path";function ft(){return`
|
|
439
439
|
/* Theme selector for code blocks */
|
|
440
440
|
.theme-selector {
|
|
441
441
|
margin: 1rem 0;
|
|
@@ -485,13 +485,13 @@ ${k}`:""}`)}if(m.push(T),t.sourcemap==="external")m.push(`${T}.map`)}let w=await
|
|
|
485
485
|
|
|
486
486
|
body.dark-mode a {
|
|
487
487
|
color: #58a6ff;
|
|
488
|
-
}`}function
|
|
488
|
+
}`}function mt(t){return`
|
|
489
489
|
<div class="theme-selector">
|
|
490
490
|
Theme:
|
|
491
491
|
<select id="themeSelector" onchange="changeTheme()">
|
|
492
492
|
${t}
|
|
493
493
|
</select>
|
|
494
|
-
</div>`}function
|
|
494
|
+
</div>`}function gt(){return`
|
|
495
495
|
function changeTheme() {
|
|
496
496
|
const theme = document.getElementById('themeSelector').value;
|
|
497
497
|
|
|
@@ -507,7 +507,7 @@ else {
|
|
|
507
507
|
}
|
|
508
508
|
|
|
509
509
|
// Initialize theme on page load
|
|
510
|
-
document.addEventListener('DOMContentLoaded', changeTheme);`}function
|
|
510
|
+
document.addEventListener('DOMContentLoaded', changeTheme);`}function ht(t){if(Object.keys(t).length===0)return"";return`
|
|
511
511
|
<div class="frontmatter">
|
|
512
512
|
<h3>Frontmatter</h3>
|
|
513
513
|
${Object.entries(t).map(([n,r])=>`
|
|
@@ -515,19 +515,19 @@ else {
|
|
|
515
515
|
<span class="frontmatter-label">${n}:</span>
|
|
516
516
|
<span>${Array.isArray(r)?r.join(", "):String(r)}</span>
|
|
517
517
|
</div>`).join("")}
|
|
518
|
-
</div>`}async function
|
|
519
|
-
${
|
|
518
|
+
</div>`}async function Pr(t){let{default:n}=await import("net");return new Promise((r)=>{let p=n.createServer();p.once("error",()=>r(!1)),p.once("listening",()=>{p.close(()=>r(!0))}),p.listen(t,"0.0.0.0")})}async function Ar(t){let{default:n}=await import("net");return new Promise((r)=>{let p=n.createServer();p.once("error",()=>r(!1)),p.once("listening",()=>{p.close(()=>r(!0))}),p.listen(t,"::")})}async function Dr(t){if(!await Pr(t))return!1;return await Ar(t)}async function qe(t,n=20){t=Number(t);for(let r=0;r<n;r++){let p=t+r;if(await Dr(p))return p}throw Error(`Could not find an available port between ${t} and ${t+n-1}`)}var Mr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function _r(){try{let t=await import("./chunk-8v1zpdef.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function et(t,n={}){let r={...Mr,...n},p=await _r();if(!p)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let o=await p.openDevWindow(t,{title:r.title,width:r.width,height:r.height,darkMode:r.darkMode,hotReload:r.hotReload,titlebarHidden:r.titlebarHidden,nativeSidebar:r.nativeSidebar,sidebarWidth:r.sidebarWidth,sidebarConfig:r.sidebarConfig});if(o&&r.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return o}catch(o){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,o),!1}}function yt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let o=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(o){let d=o[1];try{let u=`
|
|
519
|
+
${d}
|
|
520
520
|
return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
|
|
521
|
-
`,
|
|
522
|
-
Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function
|
|
523
|
-
`)){let
|
|
524
|
-
`);return
|
|
521
|
+
`,y=Function(u)();if(y)return y}catch(u){console.warn("Invalid sidebarConfig:",u)}}return{sections:[]}}let r=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(r)try{return JSON.parse(r[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let o=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(o)return Function(`return ${o[1]}`)()}catch(o){console.warn("Invalid native-sidebar script configuration:",o)}return}function zt(){console.log(`
|
|
522
|
+
Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function Lr(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),zt()}function Ir(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Ke(t,n,r){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),zt();let p="";process.stdin.on("data",(o)=>{if(o==="\x03"){if(r?.onQuit)r.onQuit();n(),process.exit(0)}if(p+=o,p.endsWith("\r")||p.endsWith(`
|
|
523
|
+
`)){let d=p.trim().toLowerCase();p="",jr(d,t,n,r)}})}function jr(t,n,r,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else Ir(n);break;case"c":if(p?.onClear)p.onClear();else console.clear(),Lr(n);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),r(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else zt();break;default:break}}async function Wt(t,n={}){let r=n.port||3000,p=n.watch!==!1,o=nt.resolve(t);if(!Ut.existsSync(o))return console.error(`${e.red}Error: File not found: ${e.bright}${o}${e.reset}`),!1;if(!o.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${o}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let d=null,u=async()=>{try{let{content:S,data:T}=await Ne(o,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:D.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=n.markdown?.syntaxHighlighting||D.markdown?.syntaxHighlighting,k=R?.defaultTheme||"github-dark",v=["github-dark"],C=R?.additionalThemes||[],O=[...new Set([...v,...C])].map((P)=>`<option value="${P}"${P===k?" selected":""}>${P}</option>`).join(`
|
|
524
|
+
`);return d=`
|
|
525
525
|
<!DOCTYPE html>
|
|
526
526
|
<html lang="en">
|
|
527
527
|
<head>
|
|
528
528
|
<meta charset="UTF-8">
|
|
529
529
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
530
|
-
<title>${
|
|
530
|
+
<title>${Br(T.title||nt.basename(o))}</title>
|
|
531
531
|
<!-- Syntax highlighting styles -->
|
|
532
532
|
<style id="syntax-theme">
|
|
533
533
|
:root {
|
|
@@ -669,33 +669,33 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
|
|
|
669
669
|
min-width: 100px;
|
|
670
670
|
color: #555;
|
|
671
671
|
}
|
|
672
|
-
${
|
|
672
|
+
${ft()}
|
|
673
673
|
</style>
|
|
674
674
|
</head>
|
|
675
675
|
<body>
|
|
676
|
-
${
|
|
677
|
-
${
|
|
676
|
+
${ht(T)}
|
|
677
|
+
${mt(O)}
|
|
678
678
|
|
|
679
|
-
${
|
|
679
|
+
${S}
|
|
680
680
|
|
|
681
681
|
<script>
|
|
682
|
-
${
|
|
682
|
+
${gt()}
|
|
683
683
|
</script>
|
|
684
684
|
</body>
|
|
685
685
|
</html>
|
|
686
|
-
`,!0}catch(
|
|
687
|
-
${
|
|
686
|
+
`,!0}catch(S){return console.error(`${e.red}Error processing Markdown file:${e.reset}`,S),!1}};if(!await u())return!1;let y=r;try{if(y=await qe(r),y!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let b=Hr({port:y,fetch(S){if(new URL(S.url).pathname==="/")return new Response(d,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}});return new Response("Not Found",{status:404})},error(S){return new Response(`<pre>${S}
|
|
687
|
+
${S.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
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
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${
|
|
690
|
-
${e.yellow}Routes:${e.reset}`);let
|
|
691
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),
|
|
689
|
+
${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
|
|
690
|
+
${e.yellow}Routes:${e.reset}`);let w=nt.relative(process.cwd(),o);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${w}${e.reset}`),console.log(`
|
|
691
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(b.url.toString(),()=>{if(p)Ut.watch(nt.dirname(o),{recursive:!0}).close();b.stop()}),n.native)await et(y,{title:nt.basename(o,".md")});if(p){let S=nt.dirname(o);console.log(`${e.blue}Watching ${e.bright}${S}${e.reset} for changes...`);let T=Ut.watch(S,{recursive:!0},async(R,k)=>{if(k&&k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, reprocessing...${e.reset}`),await u()});process.on("SIGINT",()=>{T.close(),b.stop(),process.exit(0)})}return!0}function Br(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:zr}=globalThis.Bun;import Fe from"fs";import ge from"path";class cn{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let n=t??this.options.wsPort,r=20;for(let p=0;p<r;p++)try{if(this.server=Bun.serve({port:n,fetch(o,d){if(d.upgrade(o,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(o)=>{if(this.clients.add(o),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);o.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(o)=>{if(this.clients.delete(o),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(o,d)=>{let u=typeof d==="string"?d:d.toString();if(u==="ping")return;try{let m=JSON.parse(u);if(m.type==="console"&&Array.isArray(m.args)){let y=m.args.join(" "),w={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[m.level]??"\x1B[36m";console.log(`${w}[browser]${m.level!=="log"?` ${m.level}`:""}\x1B[0m ${y}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${n}`);return n}catch(o){if(o?.code==="EADDRINUSE"){n++;continue}throw o}throw Error(`Could not find an available port after ${r} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let n=JSON.stringify(t),r=0;for(let p of this.clients)try{if(p.readyState===1)p.send(n),r++}catch{this.clients.delete(p)}if(this.options.verbose&&r>0)console.log(`[HMR] Broadcast ${t.type} to ${r} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,n){this.broadcast({type:"css-update",path:t,content:n,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Fr(t,n={}){let{showOverlay:r=!0,reconnectInterval:p=1000,maxReconnectAttempts:o=10}=n;return`
|
|
692
692
|
<script>
|
|
693
693
|
(function() {
|
|
694
694
|
// stx Hot Reload Client
|
|
695
695
|
var wsUrl = 'ws://' + window.location.hostname + ':${t}';
|
|
696
696
|
var reconnectAttempts = 0;
|
|
697
697
|
var maxAttempts = ${o};
|
|
698
|
-
var reconnectInterval = ${
|
|
698
|
+
var reconnectInterval = ${p};
|
|
699
699
|
var socket = null;
|
|
700
700
|
var overlay = null;
|
|
701
701
|
var wasConnected = false; // Track if we ever connected successfully
|
|
@@ -887,10 +887,10 @@ else {
|
|
|
887
887
|
};
|
|
888
888
|
})();
|
|
889
889
|
</script>
|
|
890
|
-
`}function
|
|
891
|
-
`),
|
|
892
|
-
`+
|
|
893
|
-
${
|
|
890
|
+
`}function We(t,n,r={}){let p=Fr(n,r),o=c(t);if(o!==-1)return t.slice(0,o)+p+t.slice(o);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function bt(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function xt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>n.endsWith(p))}function vt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((r)=>r.test(t))}var rt=null;function St(t){if(!rt)rt=new cn(t);return rt}function ct(){if(rt)rt.stop(),rt=null}import Tt from"path";var st={name:"bun-plugin-stx",async setup(t){let r={...await a(),...t.config?.stx},p=new Set,o=r.webComponents?.enabled?`./${Tt.relative(Tt.dirname(t.config?.outdir||"dist"),r.webComponents.outputDir||"dist/web-components")}`:"/web-components",d=[];if(r.webComponents?.enabled)try{let u=await $s(r,p);if(d.push(...u),r.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let m=new Set;if(r.cache&&r.cachePath){let v=await hr(u,r);if(v){if(r.debug)console.log(`Using cached version of ${u}`);return{contents:v,loader:"html"}}}let y=await $e(()=>Bun.file(u).text(),"",(v)=>{throw new Or(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${v.message}`)});if(!y)throw new Or(`stx file is empty: ${u}`,u);let{scriptContent:b,templateContent:w,allScripts:S}=pe.time("script-extraction",()=>{let v=y,C=he(y);if(C)v=C.content.trim();let L=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],O="",P=[];for(let E of L){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",j=E.match(/<script\b([^>]*)>/i),K=j?j[1]:"";if(/\bserver\b/i.test(K))O=_;else P.push(E)}let M=v.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:O,templateContent:M,allScripts:P}}),T={__filename:u,__dirname:Tt.dirname(u),__stx:{webComponentsPath:o,builtComponents:d}};await $e(()=>h(b,T,u),void 0,(v)=>{let C=new re(`Script execution failed in ${u}: ${v.message}`,u,void 0,void 0,b.substring(0,100));if(U.log(C,{filePath:u,scriptContent:b}),r.debug)throw C});let k=await pe.timeAsync("directive-processing",async()=>await i(w,T,u,r,m));if(S.length>0){let{interpolateScriptsInTemplate:v}=await import("./chunk-z6ntmv5x.js"),C=v(S.join(`
|
|
891
|
+
`),T),L=k.search(/<\/body>/i);if(L!==-1)k=k.slice(0,L)+C+`
|
|
892
|
+
`+k.slice(L);else k+=`
|
|
893
|
+
${C}`}if(k=await _e(k),m.forEach((v)=>p.add(v)),r.cache&&r.cachePath){if(await yr(u,k,m,r),r.debug)console.log(`Cached template ${u} with ${m.size} dependencies`)}return{contents:k,loader:"html"}}catch(m){let y=m instanceof Error?m:new re(`Plugin processing failed: ${String(m)}`,u);if(U.log(y,{filePath:u,buildConfig:t.config}),Rn.logDetailedError(y,{filePath:u,plugin:"bun-plugin-stx"}),r.debug)console.error("stx Plugin Error:",y);let b=y,w=b.line||null,S=b.context||null;return{contents:r.debug||Y()?`<!DOCTYPE html>
|
|
894
894
|
<html lang="en">
|
|
895
895
|
<head>
|
|
896
896
|
<meta charset="UTF-8">
|
|
@@ -913,16 +913,16 @@ ${k}`}if(w=await xe(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await g
|
|
|
913
913
|
|
|
914
914
|
<div class="error-details">
|
|
915
915
|
<h3>Error Details</h3>
|
|
916
|
-
<p><strong>File:</strong> <span class="file-path">${
|
|
917
|
-
<p><strong>Error:</strong> ${
|
|
918
|
-
${
|
|
919
|
-
${
|
|
916
|
+
<p><strong>File:</strong> <span class="file-path">${g(u)}</span></p>
|
|
917
|
+
<p><strong>Error:</strong> ${g(y.message)}</p>
|
|
918
|
+
${w?`<p><strong>Line:</strong> ${g(String(w))}</p>`:""}
|
|
919
|
+
${S?`<p><strong>Context:</strong> ${g(String(S))}</p>`:""}
|
|
920
920
|
</div>
|
|
921
921
|
|
|
922
|
-
${
|
|
922
|
+
${y.stack?`
|
|
923
923
|
<div class="error-details">
|
|
924
924
|
<h3>Stack Trace</h3>
|
|
925
|
-
<pre class="error-code">${
|
|
925
|
+
<pre class="error-code">${g(y.stack)}</pre>
|
|
926
926
|
</div>`:""}
|
|
927
927
|
|
|
928
928
|
<div class="help-section">
|
|
@@ -931,7 +931,7 @@ ${k}`}if(w=await xe(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await g
|
|
|
931
931
|
<li>Check the syntax of your stx directives (e.g., @if, @foreach)</li>
|
|
932
932
|
<li>Verify that all variables used in the template are properly defined</li>
|
|
933
933
|
<li>Ensure script tags have valid JavaScript/TypeScript syntax</li>
|
|
934
|
-
<li>Run <code>stx debug ${
|
|
934
|
+
<li>Run <code>stx debug ${g(Tt.basename(u))}</code> for detailed analysis</li>
|
|
935
935
|
<li>Enable debug mode in your stx config for more detailed error messages</li>
|
|
936
936
|
</ul>
|
|
937
937
|
</div>
|
|
@@ -950,12 +950,12 @@ ${k}`}if(w=await xe(w),f.forEach((y)=>d.add(y)),r.cache&&r.cachePath){if(await g
|
|
|
950
950
|
<h1>Something went wrong</h1>
|
|
951
951
|
<p>An internal error occurred. Please try again later.</p>
|
|
952
952
|
</body>
|
|
953
|
-
</html>`,loader:"html"}}})}};async function
|
|
954
|
-
${
|
|
953
|
+
</html>`,loader:"html"}}})}};async function Kr(t,n={}){let r=n.port||3000,p=n.watch!==!1,o=n.hotReload!==!1&&p,d=null,u=n.hmrPort||r+1,m=ge.resolve(t);if(!Fe.existsSync(m))return console.error(`${e.red}Error: File not found: ${e.bright}${m}${e.reset}`),!1;if(m.endsWith(".md"))return Wt(m,n);else if(!m.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${m}${e.reset}. Only .stx and .md files are supported.`),!1;let y=l(process.cwd(),"output");Fe.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let b=null,w=async()=>{try{let _={name:"public-assets",setup(ve){ve.onResolve({filter:/^\/(images|fonts|assets|public)\//},(de)=>({path:de.path,external:!0}))}},j=await Bun.build({entrypoints:[m],outdir:y,plugins:[_,st],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!j.success)return console.error(`${e.red}Build failed:${e.reset}`,j.logs),!1;let K=j.outputs.find((ve)=>ve.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return b=await Bun.file(K.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await w())return!1;let T=ge.dirname(m);await mn(T);let R=r;try{if(R=await qe(r),R!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${R} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let _=n.hmrPort||R+1;d=St({wsPort:_,verbose:!1}),u=d.start(_)}let k={},v=null,C;try{let{loadStxConfig:_}=await import("./chunk-9jxs8sw2.js"),j=await _();if(C=n.stxOptions?.serverApi??j.serverApi,j?.apiRouter)v=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){k=j.apiRoutes;let K=Object.keys(k).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Q}=await import("./chunk-rqa92xm4.js"),ve=j.broadcasting;await K(ve);let de=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${de}/ws${e.reset}`);let Re=ge.join(process.cwd(),"channels.ts");if(Fe.existsSync(Re))try{let se=await Q(Re);console.log(`${e.blue}Loaded ${e.bright}${se} broadcast channel${se!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(se){console.warn(`${e.yellow}Failed to load channels.ts: ${se.message}${e.reset}`)}}catch(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:L,isServerApiSource:O}=await import("./chunk-hsp9h3jn.js"),P=await L(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${R}/${e.reset}...`),o)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let M=zr({port:R,async fetch(_){return Mn(_,await(async()=>{let j=new URL(_.url);if([y,ge.dirname(m),ge.join(process.cwd(),"public")].some((se)=>O(ge.join(se,j.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(v)try{let se=await v.handleRequest(_);if(se.status!==404)return se}catch{}if(k[j.pathname])try{return await k[j.pathname](_)}catch(se){return new Response(JSON.stringify({error:se.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await P(_);if(K)return K;if(j.pathname==="/")return(async()=>{let N=await x(b||"");if(o)N=We(N,u);if(n.native)if(N.includes("<head>"))N=N.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(N.includes("<html"))N=N.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 N="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+N;if(n.titlebarHidden)if(N.includes("<head>"))N=N.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(N.includes("<html"))N=N.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 N=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${N}`;return N})().then((N)=>new Response(N,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Q=ge.join(y,j.pathname);if(Fe.existsSync(Q)&&Fe.statSync(Q).isFile()){let se=Bun.file(Q),N=ge.extname(Q).toLowerCase(),I="text/plain";if(N===".ts"||N===".tsx"){let ze=new Bun.Transpiler({loader:N===".tsx"?"tsx":"ts"}),Ue=await se.text(),Qe=ze.transformSync(Ue);return new Response(Qe,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(N){case".html":I="text/html";break;case".css":I="text/css";break;case".js":I="text/javascript";break;case".json":I="application/json";break;case".png":I="image/png";break;case".jpg":case".jpeg":I="image/jpeg";break;case".gif":I="image/gif";break;case".woff":I="font/woff";break;case".woff2":I="font/woff2";break;case".ttf":I="font/ttf";break;case".otf":I="font/otf";break;case".eot":I="application/vnd.ms-fontobject";break}return new Response(se,{headers:{"Content-Type":I}})}let ve=ge.dirname(m),de=ge.join(ve,j.pathname);if(Fe.existsSync(de)&&Fe.statSync(de).isFile()){let se=Bun.file(de),N=ge.extname(de).toLowerCase(),I="text/plain";if(N===".ts"||N===".tsx"){let ze=new Bun.Transpiler({loader:N===".tsx"?"tsx":"ts"}),Ue=await se.text(),Qe=ze.transformSync(Ue);return new Response(Qe,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(N){case".html":I="text/html";break;case".css":I="text/css";break;case".js":I="text/javascript";break;case".json":I="application/json";break;case".png":I="image/png";break;case".jpg":case".jpeg":I="image/jpeg";break;case".gif":I="image/gif";break;case".svg":I="image/svg+xml";break;case".ico":I="image/x-icon";break;case".woff":I="font/woff";break;case".woff2":I="font/woff2";break;case".ttf":I="font/ttf";break;case".otf":I="font/otf";break;case".eot":I="application/vnd.ms-fontobject";break}return new Response(se,{headers:{"Content-Type":I}})}let Re=ge.join(process.cwd(),"public",j.pathname);if(Fe.existsSync(Re)&&Fe.statSync(Re).isFile()){let se=Bun.file(Re),N=ge.extname(Re).toLowerCase(),I="application/octet-stream";if(N===".ts"||N===".tsx"){let ze=new Bun.Transpiler({loader:N===".tsx"?"tsx":"ts"}),Ue=await se.text(),Qe=ze.transformSync(Ue);return new Response(Qe,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(N){case".html":I="text/html";break;case".css":I="text/css";break;case".js":I="text/javascript";break;case".json":I="application/json";break;case".png":I="image/png";break;case".jpg":case".jpeg":I="image/jpeg";break;case".gif":I="image/gif";break;case".svg":I="image/svg+xml";break;case".ico":I="image/x-icon";break;case".woff":I="font/woff";break;case".woff2":I="font/woff2";break;case".ttf":I="font/ttf";break;case".otf":I="font/otf";break;case".eot":I="application/vnd.ms-fontobject";break}return new Response(se,{headers:{"Content-Type":I}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
|
|
954
|
+
${_.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
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${
|
|
957
|
-
${e.yellow}Routes:${e.reset}`);let
|
|
958
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),
|
|
956
|
+
${e.bright}\u2192 ${e.cyan}http://localhost:${R}/${e.reset}`),console.log(`
|
|
957
|
+
${e.yellow}Routes:${e.reset}`);let E=ge.relative(process.cwd(),m);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${E}${e.reset}`),console.log(`
|
|
958
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(M.url.toString(),()=>{if(p)Fe.watch(ge.dirname(m),{recursive:!0}).close();M.stop()}),n.native){let _=await Bun.file(m).text(),j=yt(_);await et(R,{title:ge.basename(m,".stx"),titlebarHidden:n.titlebarHidden===!0,nativeSidebar:!!j,sidebarConfig:j})}if(p){let _=ge.dirname(m);console.log(`${e.blue}Watching ${e.bright}${_}${e.reset} for changes...`);let j=Fe.watch(_,{recursive:!0},async(K,Q)=>{if(!Q||vt(Q))return;if(xt(Q)){console.log(`${e.yellow}File ${e.bright}${Q}${e.yellow} changed, rebuilding...${e.reset}`),tt.clear(),be();let ve=await w();if(await dr(T),o&&d)if(ve)d.reload(Q);else d.error("Build failed - check console for details")}else if(bt(Q)){if(console.log(`${e.cyan}CSS ${e.bright}${Q}${e.cyan} changed${e.reset}`),o&&d)d.updateCss(Q)}});process.on("SIGINT",()=>{if(j.close(),d)ct();M.stop(),process.exit(0)})}return!0}var{serve:Nr}=globalThis.Bun;import Xe from"fs";import Ce from"path";var ln=`
|
|
959
959
|
<script data-stx-helpers>
|
|
960
960
|
(function() {
|
|
961
961
|
'use strict'
|
|
@@ -1266,14 +1266,14 @@ else {
|
|
|
1266
1266
|
|
|
1267
1267
|
})()
|
|
1268
1268
|
</script>
|
|
1269
|
-
`;function
|
|
1270
|
-
`),
|
|
1269
|
+
`;function pn(t){if(t.length===0)return"";if(t.length===1)return t[0];let n=t.map((p)=>p.split(Ce.sep)),r=[];for(let p=0;p<n[0].length;p++){let o=n[0][p];if(n.every((d)=>d[p]===o))r.push(o);else break}return r.join(Ce.sep)}async function Gr(t,n={}){let r=n.port||3000,p=n.watch!==!1;for(let k of t){let v=Ce.resolve(k);if(!Xe.existsSync(v))return console.error(`${e.red}Error: File not found: ${e.bright}${v}${e.reset}`),!1;if(!v.endsWith(".stx")&&!v.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${v}${e.reset}. Only .stx and .md files are supported.`),!1}let o=l(process.cwd(),"output");Xe.mkdirSync(o,{recursive:!0});let d=pn(t.map((k)=>Ce.dirname(Ce.resolve(k))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let u={},m=[],y=async()=>{try{for(let k of t){let v=Ce.resolve(k);if(v.endsWith(".md"))try{let{content:L,data:O}=await Ne(v,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:D.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),P=n.markdown?.syntaxHighlighting||D.markdown?.syntaxHighlighting,M=P?.defaultTheme||"github-dark",E=["github-dark"],_=P?.additionalThemes||[],K=[...new Set([...E,..._])].map((Re)=>`<option value="${Re}"${Re===M?" selected":""}>${Re}</option>`).join(`
|
|
1270
|
+
`),Q=`
|
|
1271
1271
|
<!DOCTYPE html>
|
|
1272
1272
|
<html lang="en">
|
|
1273
1273
|
<head>
|
|
1274
1274
|
<meta charset="UTF-8">
|
|
1275
1275
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1276
|
-
<title>${
|
|
1276
|
+
<title>${dn(O.title||Ce.basename(v))}</title>
|
|
1277
1277
|
<!-- Syntax highlighting styles -->
|
|
1278
1278
|
<style id="syntax-theme">
|
|
1279
1279
|
:root {
|
|
@@ -1415,40 +1415,38 @@ else {
|
|
|
1415
1415
|
min-width: 100px;
|
|
1416
1416
|
color: #555;
|
|
1417
1417
|
}
|
|
1418
|
-
${
|
|
1418
|
+
${ft()}
|
|
1419
1419
|
</style>
|
|
1420
1420
|
</head>
|
|
1421
1421
|
<body>
|
|
1422
|
-
${
|
|
1423
|
-
${
|
|
1422
|
+
${ht(O)}
|
|
1423
|
+
${mt(K)}
|
|
1424
1424
|
|
|
1425
|
-
${
|
|
1425
|
+
${L}
|
|
1426
1426
|
|
|
1427
1427
|
<script>
|
|
1428
|
-
${
|
|
1428
|
+
${gt()}
|
|
1429
1429
|
</script>
|
|
1430
1430
|
</body>
|
|
1431
1431
|
</html>
|
|
1432
|
-
`,
|
|
1433
|
-
${
|
|
1434
|
-
</
|
|
1435
|
-
</head>`);return new Response(R,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let E=Re.join(o,y.pathname);if(qe.existsSync(E)&&qe.statSync(E).isFile()){let R=Bun.file(E),A=Re.extname(E).toLowerCase(),C="text/plain";if(A===".ts"||A===".tsx"){let D=new Bun.Transpiler({loader:A===".tsx"?"tsx":"ts"}),L=await R.text(),V=D.transformSync(L);return new Response(V,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(A){case".html":C="text/html";break;case".css":C="text/css";break;case".js":C="text/javascript";break;case".json":C="application/json";break;case".png":C="image/png";break;case".jpg":case".jpeg":C="image/jpeg";break;case".gif":C="image/gif";break;case".svg":C="image/svg+xml";break;case".ico":C="image/x-icon";break;case".woff":C="font/woff";break;case".woff2":C="font/woff2";break;case".ttf":C="font/ttf";break;case".otf":C="font/otf";break;case".eot":C="application/vnd.ms-fontobject";break}return new Response(R,{headers:{"Content-Type":C}})}if(y.pathname!=="/"&&u["/"]){let R=Te(w);return b(u["/"].content).then((A)=>{if(R){let C=A.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(C){let D=A.match(/<title[^>]*>([\s\S]*?)<\/title>/i),L=D?D[1]:"",V=`<!DOCTYPE html><html><head><title>${an(L)}</title></head><body><main>${C[1]}</main></body></html>`;return new Response(V,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...j(),"Cache-Control":ht,Pragma:"no-cache",Expires:"0"}})}}return new Response(A,{headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(w){return new Response(`<pre>${w}
|
|
1436
|
-
${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1432
|
+
`,de=`/${Ce.relative(d,v).replace(/\.md$/,"")}`;if(de.endsWith("/index"))de=de.slice(0,-6)||"/";u[de||"/"]={filePath:v,content:Q,fileType:"md"}}catch(L){console.error(`${e.red}Error processing Markdown file ${e.bright}${k}${e.reset}:`,L);continue}else{let L={name:"public-assets",setup(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(_)=>({path:_.path,external:!0}))}},O;try{let E=await Bun.build({entrypoints:[v],outdir:o,plugins:[L,st],define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${k}${e.reset}:`,Oe(E.logs,v));continue}let _=E.outputs.find((j)=>j.path.endsWith(".html"));if(!_){console.error(`${e.red}No HTML output found for ${e.bright}${k}${e.reset}`);continue}O=await Bun.file(_.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${k}${e.reset}:
|
|
1433
|
+
${Oe(E,v)}`);continue}let M=`/${Ce.relative(d,v).replace(/\.stx$/,"")}`;if(M.endsWith("/index"))M=M.slice(0,-6)||"/";if(M.includes("[")){let{regex:E,params:_}=Ns(M,{page:!0});m.push({pattern:E,paramNames:_,filePath:v,routeTemplate:M,fileType:"stx"}),u[M]={filePath:v,content:O,fileType:"stx"}}else u[M||"/"]={filePath:v,content:O,fileType:"stx"}}}if(Object.keys(u).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(k){return console.error(`${e.red}Error processing files:${e.reset}`,Oe(k)),!1}};if(!await y())return!1;let w=r;try{if(w=await qe(r),w!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${w} 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:${w}/${e.reset}...`);let S=Nr({port:w,async fetch(k){let v=new URL(k.url),C=Ce.join(process.cwd(),"public",v.pathname);if(Xe.existsSync(C)&&Xe.statSync(C).isFile()){let P=Bun.file(C),M=Ce.extname(C).toLowerCase(),E="application/octet-stream";if(M===".ts"||M===".tsx"){let _=new Bun.Transpiler({loader:M===".tsx"?"tsx":"ts"}),j=await P.text(),K=_.transformSync(j);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(M){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(P,{headers:{"Content-Type":E}})}let L=u[v.pathname];if(!L&&!v.pathname.endsWith("/"))L=u[`${v.pathname}/`];if(!L)for(let P of m){let M=v.pathname.match(P.pattern);if(M){let E=u[P.routeTemplate];if(E){let _={};for(let Q=0;Q<P.paramNames.length;Q++)_[P.paramNames[Q]]=decodeURIComponent(M[Q+1]);let j=E.content,K=`<script>window.__routeParams = ${JSON.stringify(_)};</script>`;if(j.includes("</head>"))j=f(j,K);else j=K+j;L={...E,content:j}}break}}if(L)return x(L.content).then((P)=>{if(P.includes("</head>"))P=f(P,ln);return new Response(P,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let O=Ce.join(o,v.pathname);if(Xe.existsSync(O)&&Xe.statSync(O).isFile()){let P=Bun.file(O),M=Ce.extname(O).toLowerCase(),E="text/plain";if(M===".ts"||M===".tsx"){let _=new Bun.Transpiler({loader:M===".tsx"?"tsx":"ts"}),j=await P.text(),K=_.transformSync(j);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(M){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(P,{headers:{"Content-Type":E}})}if(v.pathname!=="/"&&u["/"]){let P=Ae(k);return x(u["/"].content).then((M)=>{if(P){let E=M.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let _=M.match(/<title[^>]*>([\s\S]*?)<\/title>/i),j=_?_[1]:"",K=`<!DOCTYPE html><html><head><title>${dn(j)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(K,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...z(),"Cache-Control":wt,Pragma:"no-cache",Expires:"0"}})}}return new Response(M,{headers:{"Content-Type":"text/html",...z(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(k){return new Response(`<pre>${k}
|
|
1434
|
+
${k.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1437
1435
|
${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
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${
|
|
1439
|
-
${e.yellow}Routes:${e.reset}`);let
|
|
1440
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(v.url.toString(),()=>{if(d)qe.watch(l,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=qe.watch(l,{recursive:!0},async(y,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Ze.clear(),me(),await m()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Fr}=globalThis.Bun;import ue from"fs";import ne from"path";async function ln(t){try{return yn(await Bun.file(t).text())}catch{return}}function Nt(t){let n=Bun.file(t),r=ne.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[r]||"application/octet-stream",...l}})}async function qr(t=".",n={}){let r=n.port||3000,d=n.watch!==!1,o=n.hotReload!==!1&&d,l=null,u=n.hmrPort||r+1,f=ne.resolve(t),{loadStxConfig:m}=await import("./chunk-756rpwn0.js"),h=await m(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-3dtzcc9j.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?ne.join(f,h.root):f,y=n.pagesDir||h.pagesDir||"pages",k=ne.join(w,y);if(!ue.existsSync(k)&&!h._layerPageDirs?.some((P)=>ue.existsSync(P)))return console.error(`${e.red}Error: No '${y}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${y}/index.stx for the homepage.${e.reset}`),!1;let M=X(w,{pagesDir:y,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(M.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${M.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:P,prefix:I}of E)if(ue.existsSync(P)){let N=X(ne.dirname(P),{pagesDir:ne.basename(P)});for(let Q of N){let q=I==="/"?Q.pattern:`${I}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:I})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${I}${e.reset}`)}let A=new Map,C=null,D=null;if(n.stxOptions?.shell!==!1){if(D=await ma(f,n.stxOptions?.shell),D){if(C=await wo(D,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${ne.relative(f,D)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Et(),await $t(f);let L=Tt();if(L.length>0)console.log(`${e.blue}Loaded ${e.bright}${L.length}${e.blue} middleware: ${e.dim}${L.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-756rpwn0.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-vd5d1yb9.js"),q=I.broadcasting;await N(q);let Oe=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let we=ne.join(process.cwd(),"channels.ts");if(ue.existsSync(we))try{let U=await Q(we);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let be=c(f,"output");ue.mkdirSync(be,{recursive:!0});let ce=new Map,Ee=new Set,re=async(P)=>{let I=Is(k,P);if(!I)return null;try{let N=await Bun.build({entrypoints:[I],outdir:be,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,_=async(P,I)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Oe,injectRouterScript:we}=await import("./chunk-756rpwn0.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:de}=await import("./chunk-228cbw2p.js"),K=await Oe(f),Ue=(ie)=>{if(!ie)return ie;if(ne.isAbsolute(ie))return ie;return ne.resolve(f,ie)},ae={...q,...K,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ae.debug=!0;ae.partialsDir=Ue(ae.partialsDir),ae.componentsDir=Ue(ae.componentsDir),ae.layoutsDir=Ue(ae.layoutsDir),ae.storesDir=Ue(ae.storesDir||"stores"),ae.cachePath=Ue(ae.cachePath)??c(f,"cache");let H=!I&&!n.profile,oe=ae.cache!==!1;if(oe&&H){let ie=de.get(P.filePath);if(ie)try{if((await ue.promises.stat(P.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!ue.existsSync(Se)){He=!1;break}if((await ue.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=Ke(Se,{preserveHead:!0});let st=F.get(P.filePath);return{route:P,content:Se,status:st?.status??await ln(P.filePath),headers:st?.headers}}}}catch{}let Ie=await U(P.filePath,ae);if(Ie){let je=Ie;if(C)je=Ke(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await ln(P.filePath),headers:He?.headers}}}let Z=oe?await W(P.filePath):await Bun.file(P.filePath).text(),se=yn(Z),{classifyAllScripts:pe}=await import("./chunk-756rpwn0.js"),B=pe(Z),Le=B.server.map((ie)=>ie.content),Me=Z;for(let ie of B.server)Me=Me.replace(ie.fullTag,"");let te={__filename:P.filePath,__dirname:ne.dirname(P.filePath),__stx_options:ae,params:I??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,te,P.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,te,P.filePath,ae,De);let Ie=performance.now()-ie,je=ne.relative(f,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,te,P.filePath,ae,De);if(!C)he=await we(he,{router:ae.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-v3r1wwec.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,te)}</script>`})}if(C)he=Ke(he,{preserveHead:!0});if(oe&&H)await J(P.filePath,he,De,ae);let{extractStreamBoundaries:ct}=await import("./chunk-x90f7h2g.js"),Ye=ct(te),ot=te.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=te.streamBoundaries||{},Ie={...ae,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...te,$boundary:st},P.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Ye=[...(Ye||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Ye&&Ye.length>0)Ee.add(P.pattern);else Ye=void 0;let Vt=Dt(te),qt=Lt(te);if(H)F.set(P.filePath,{status:Vt,headers:qt});return{route:P,content:he,status:Vt??se,headers:qt,boundaries:Ye}}catch(N){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let P=new Set(ce.keys()),I=new Set(A.keys());ce.clear(),A.clear();let N=n.prebuild===!1?M.filter((q)=>P.has(q.pattern)):M,Q=n.prebuild===!1?R.filter(({route:q})=>I.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Oe=N.slice(q,q+Fe),we=await Promise.all(Oe.map((U)=>_(U)));for(let U of we)if(U)ce.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Oe=Q.slice(q,q+Fe),we=await Promise.all(Oe.map(({route:U})=>_(U)));for(let U of we)if(U)A.set(U.route.pattern,U)}return ce.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?M.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await pn(f);let Xe=r;try{if(Xe=await We(r),Xe!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let P=n.hmrPort||Xe+1;l=xt({wsPort:P,verbose:!1}),u=l.start(P)}let kt=(P,I)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(I).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Ot=Fr({port:Xe,hostname:n.hostname,async fetch(P){let I=new URL(P.url),N=n.stxOptions?.offline??h.offline;if(I.pathname===jo&&N?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:Bo(N,ls()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=ne.join(f,Q,I.pathname),Oe=ne.join(f,I.pathname),we=ne.join(be,I.pathname);if([q,Oe,we].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([ue.promises.stat(q).catch(()=>null),ue.promises.stat(Oe).catch(()=>null),ue.promises.stat(we).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return Nt(q);if(J?.isFile()&&!v(Oe,f,S))return Nt(Oe);if(W?.isFile()&&!v(we,f,S))return Nt(we);if(I.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(I.pathname.slice(16));if(H)try{let oe=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(oe,{},ne.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(oe){return new Response(`<div class="stx-async-error">${oe.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(I.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-34rh88vd.js"),oe=await H(P,{publicDir:ne.join(f,Q),cacheDir:c(f,"cache","img")});if(oe)return oe}if(Y)try{let H=await Y.handleRequest(P);if(H.status!==404)return H}catch{}if(V[I.pathname])try{return await V[I.pathname](P)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await T(P);if(de)return de;let K=hr(I.pathname,M);if(K){let H=ce.get(K.route.pattern),oe=Ee.has(K.route.pattern);if(!H||K.route.isDynamic&&Object.keys(K.params).length>0||oe){let Z=await _(K.route,K.params);if(Z){if(H=Z,!K.route.isDynamic&&!oe)ce.set(K.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},pe=(K.route.filePath?vt(await Bun.file(K.route.filePath).text().catch(()=>"")):null)??{};if(pe.validate){if(!await pe.validate({params:K.params})){let Me=await re(404);if(Me){let te=Me;if(te=await b(te,f),o)te=Ne(te,u);return new Response(te,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(pe.middleware){let Le=Rt(I.pathname,K.params,pe,I.search),Me=At(Le,null,P,{isServer:!0}),te=await Pt(pe.middleware,Me);if(te.redirect){let De=te.redirect.path,he=te.redirect.options.redirectCode||302,ct=new Headers(te.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(te.abort){let{statusCode:De,message:he}=te.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(te.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(te.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let B=H.content;if(C&&ha(P)&&Ge(B,h?.router?.container||"main")){let Le=nt(B),Me=ve(B),te=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=te?Yt(te[1].trim()):"";if(Object.keys(K.params).length>0)B=kt(B,K.params);B=await b(B,f);let he=h?.router?.container||"main";return B=$e(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[pc]:ls(),...j(),"Cache-Control":ht}})}if(C)B=Jr(C,B);if(Object.keys(K.params).length>0)B=kt(B,K.params);if(B=await b(B,f),o)B=Ne(B,u);if(n.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;if(n.titlebarHidden)if(B.includes("<head>"))B=B.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else B=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${B}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-x90f7h2g.js");return Me(Le(B,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(B,{status:Z,headers:{"Content-Type":"text/html",...j(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),oe=hr(I.pathname,H);if(oe){let Z=A.get(oe.route.pattern);if(!Z||oe.route.isDynamic){let se=await _(oe.route,oe.params);if(se){if(Z=se,!oe.route.isDynamic)A.set(oe.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=Jr(C,se);if(Object.keys(oe.params).length>0)se=kt(se,oe.params);if(se=await b(se,f),o)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&I.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let pe=R.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(pe){let B=await _(pe.route);if(B)se=B,A.set(pe.route.pattern,B)}}if(se){let pe=se.content;if(C)pe=Jr(C,pe);if(pe=await b(pe,f),o)pe=Ne(pe,u);return new Response(pe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ct(I.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=ce.get("/");if(Ue){let H=Ue.content;if(H=await b(H,f),o)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ae=await re(404);if(ae){let H=ae;if(H=await b(H,f),o)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let I=await re(500);if(I)return new Response(I,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1441
|
-
${
|
|
1436
|
+
${e.bright}\u2192 ${e.cyan}http://localhost:${w}/${e.reset}`),console.log(`
|
|
1437
|
+
${e.yellow}Routes:${e.reset}`);let T=new Set(m.map((k)=>k.routeTemplate)),R=Object.entries(u).filter(([k])=>!T.has(k)).sort(([k],[v])=>k.localeCompare(v)).map(([k,v])=>({route:k==="/"?"/":k,filePath:Ce.relative(process.cwd(),v.filePath),fileType:v.fileType}));for(let k of m){let v=k.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");R.push({route:v,filePath:Ce.relative(process.cwd(),k.filePath),fileType:"stx"})}if(R.sort((k,v)=>k.route.localeCompare(v.route)),R.forEach((k,v)=>{let L=v===R.length-1?"\u2514\u2500 ":"\u251C\u2500 ",O=k.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${L}${k.route}${e.reset} \u2192 ${e.bright}${k.filePath}${e.reset} ${O}`)}),console.log(`
|
|
1438
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(S.url.toString(),()=>{if(p)Xe.watch(d,{recursive:!0}).close();S.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let k=Xe.watch(d,{recursive:!0},async(v,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),tt.clear(),be(),await y()});process.on("SIGINT",()=>{k.close(),S.stop(),process.exit(0)})}return!0}function dn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Ur}=globalThis.Bun;import me from"fs";import oe from"path";async function un(t){try{return vn(await Bun.file(t).text())}catch{return}}function Vt(t){let n=Bun.file(t),r=oe.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},d=[".js",".css",".json"].includes(r)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":p[r]||"application/octet-stream",...d}})}async function Xr(t=".",n={}){let r=n.port||3000,p=n.watch!==!1,o=n.hotReload!==!1&&p,d=null,u=n.hmrPort||r+1,m=oe.resolve(t),{loadStxConfig:y}=await import("./chunk-9jxs8sw2.js"),b=await y(m),{createServerApi:w,isServerApiSource:S}=await import("./chunk-hsp9h3jn.js"),T=n.stxOptions?.serverApi??b.serverApi,R=await w(m,T),k=b.root&&b.root!=="."?oe.join(m,b.root):m,v=n.pagesDir||b.pagesDir||"pages",C=oe.join(k,v);if(!me.existsSync(C)&&!b._layerPageDirs?.some((A)=>me.existsSync(A)))return console.error(`${e.red}Error: No '${v}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${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 ${v}/index.stx for the homepage.${e.reset}`),!1;let L=Z(k,{pagesDir:v,pagesDirs:b._layerPageDirs?[C,...b._layerPageDirs.slice(1)]:void 0});if(L.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${L.length}${e.blue} routes${e.reset}`);let O=b?._pluginPageDirs||[],P=[];for(let{dir:A,prefix:H}of O)if(me.existsSync(A)){let W=Z(oe.dirname(A),{pagesDir:oe.basename(A)});for(let ee of W){let X=H==="/"?ee.pattern:`${H}${ee.pattern==="/"?"":ee.pattern}`;P.push({route:{...ee,pattern:X},prefix:H})}if(W.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${W.length}${e.blue} routes at ${e.cyan}${H}${e.reset}`)}let M=new Map,E=null,_=null;if(n.stxOptions?.shell!==!1){if(_=await wa(m,n.stxOptions?.shell),_){if(E=await So(_,n.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${oe.relative(m,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Rt(),await Pt(m);let j=At();if(j.length>0)console.log(`${e.blue}Loaded ${e.bright}${j.length}${e.blue} middleware: ${e.dim}${j.join(", ")}${e.reset}`);let K={},Q=null;try{let{loadStxConfig:A}=await import("./chunk-9jxs8sw2.js"),H=await A(m);if(H?.apiRouter)Q=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){K=H.apiRoutes;let W=Object.keys(K).length;if(W>0)console.log(`${e.blue}Loaded ${e.bright}${W} API route${W>1?"s":""}${e.reset}`)}if(H?.broadcasting?.enabled)try{let{startBroadcasting:W,loadChannels:ee}=await import("./chunk-rqa92xm4.js"),X=H.broadcasting;await W(X);let Ee=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ee}/ws${e.reset}`);let we=oe.join(process.cwd(),"channels.ts");if(me.existsSync(we))try{let V=await ee(we);console.log(`${e.blue}Loaded ${e.bright}${V} broadcast channel${V!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(V){console.warn(`${e.yellow}Failed to load channels.ts: ${V.message}${e.reset}`)}}catch(W){console.warn(`${e.yellow}Broadcasting failed to start: ${W.message}${e.reset}`)}}catch{}let ve=l(m,"output");me.mkdirSync(ve,{recursive:!0});let de=new Map,Re=new Set,se=async(A)=>{let H=Ms(C,A);if(!H)return null;try{let W=await Bun.build({entrypoints:[H],outdir:ve,plugins:[st],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!W.success)return null;let ee=W.outputs.find((X)=>X.path.endsWith(".html"));if(!ee)return null;return await Bun.file(ee.path).text()}catch{return null}},N=new Map,I=async(A,H)=>{try{let{processDirectives:W,extractVariables:ee,defaultConfig:X,loadStxConfig:Ee,injectRouterScript:we}=await import("./chunk-9jxs8sw2.js"),{checkCache:V,cacheTemplate:J,readFileCached:q,templateCache:ue}=await import("./chunk-g075cc67.js"),G=await Ee(m),Ve=(ce)=>{if(!ce)return ce;if(oe.isAbsolute(ce))return ce;return oe.resolve(m,ce)},le={...X,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)le.debug=!0;le.partialsDir=Ve(le.partialsDir),le.componentsDir=Ve(le.componentsDir),le.layoutsDir=Ve(le.layoutsDir),le.storesDir=Ve(le.storesDir||"stores"),le.cachePath=Ve(le.cachePath)??l(m,"cache");let B=!H&&!n.profile,ie=le.cache!==!1;if(ie&&B){let ce=ue.get(A.filePath);if(ce)try{if((await me.promises.stat(A.filePath)).mtime.getTime()<=ce.mtime){let Be=!0;for(let Se of ce.dependencies){if(!me.existsSync(Se)){Be=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>ce.mtime){Be=!1;break}}if(Be){let Se=ce.output;if(E)Se=Je(Se,{preserveHead:!0});let at=N.get(A.filePath);return{route:A,content:Se,status:at?.status??await un(A.filePath),headers:at?.headers}}}}catch{}let je=await V(A.filePath,le);if(je){let He=je;if(E)He=Je(He,{preserveHead:!0});let Be=N.get(A.filePath);return{route:A,content:He,status:Be?.status??await un(A.filePath),headers:Be?.headers}}}let te=ie?await q(A.filePath):await Bun.file(A.filePath).text(),ae=vn(te),{classifyAllScripts:fe}=await import("./chunk-9jxs8sw2.js"),F=fe(te),Ie=F.server.map((ce)=>ce.content),Me=te;for(let ce of F.server)Me=Me.replace(ce.fullTag,"");let ne={__filename:A.filePath,__dirname:oe.dirname(A.filePath),__stx_options:le,params:H??{},__stx_runtime_head:{}};for(let ce of Ie)try{await ee(ce,ne,A.filePath)}catch(je){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,je?.message||je)}let De=new Set,ye;if(n.profile){let ce=performance.now();ye=await W(Me,ne,A.filePath,le,De);let je=performance.now()-ce,He=oe.relative(m,A.filePath)||A.filePath;console.log(`[stx:profile] ${He} \u2192 ${je.toFixed(2)}ms`)}else ye=await W(Me,ne,A.filePath,le,De);if(!E)ye=await we(ye,{router:le.router});{let{interpolateScriptExpressions:ce}=await import("./chunk-z6ntmv5x.js");ye=ye.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(je,He,Be)=>{if(!/function\s+__stx_setup_/.test(Be))return je;return`<script${He}>${ce(Be,ne)}</script>`})}if(E)ye=Je(ye,{preserveHead:!0});if(ie&&B)await J(A.filePath,ye,De,le);let{extractStreamBoundaries:pt}=await import("./chunk-84ztb43k.js"),Ze=pt(ne),it=ne.__streamTemplates;if(it&&typeof it==="object"&&Object.keys(it).length>0){let ce=ne.streamBoundaries||{},je={...le,autoShell:!1},He=Object.keys(it).map((Se)=>({id:Se,render:async()=>{let at=typeof ce[Se]==="function"?await ce[Se]():void 0;return W(it[Se],{...ne,$boundary:at},A.filePath,je,new Set)}})),Be=new Set(He.map((Se)=>Se.id));Ze=[...(Ze||[]).filter((Se)=>!Be.has(Se.id)),...He]}if(Ze&&Ze.length>0)Re.add(A.pattern);else Ze=void 0;let Xt=Bt(ne),Gt=Ft(ne);if(B)N.set(A.filePath,{status:Xt,headers:Gt});return{route:A,content:ye,status:Xt??ae,headers:Gt,boundaries:Ze}}catch(W){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,W),null}},ze=8,Ue=async()=>{let A=new Set(de.keys()),H=new Set(M.keys());de.clear(),M.clear();let W=n.prebuild===!1?L.filter((X)=>A.has(X.pattern)):L,ee=n.prebuild===!1?P.filter(({route:X})=>H.has(X.pattern)):P;for(let X=0;X<W.length;X+=ze){let Ee=W.slice(X,X+ze),we=await Promise.all(Ee.map((V)=>I(V)));for(let V of we)if(V)de.set(V.route.pattern,V)}for(let X=0;X<ee.length;X+=ze){let Ee=ee.slice(X,X+ze),we=await Promise.all(Ee.map(({route:V})=>I(V)));for(let V of we)if(V)M.set(V.route.pattern,V)}return de.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?L.length+P.length>0:await Ue()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await mn(m);let Ge=r;try{if(Ge=await qe(r),Ge!==r)console.log(`${e.yellow}Port ${r} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(o){let A=n.hmrPort||Ge+1;d=St({wsPort:A,verbose:!1}),u=d.start(A)}let Et=(A,H)=>{let ee=`<script data-stx-route-params>(function(){var p=${JSON.stringify(H).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(A.includes("</head>"))return f(A,ee,"");if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${ee}`);return ee+A};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Ur({port:Ge,hostname:n.hostname,async fetch(A){let H=new URL(A.url),W=n.stxOptions?.offline??b.offline;if(H.pathname===zo&&W?.enabled){if(!["GET","HEAD"].includes(A.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(A.method==="HEAD"?null:Ho(W,ps()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let ee=b?.publicDir||"public",X=oe.join(m,ee,H.pathname),Ee=oe.join(m,H.pathname),we=oe.join(ve,H.pathname);if([X,Ee,we].some((B)=>S(B,m,T)))return new Response("Not Found",{status:404});let[V,J,q]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Ee).catch(()=>null),me.promises.stat(we).catch(()=>null)]);if(V?.isFile()&&!S(X,m,T))return Vt(X);if(J?.isFile()&&!S(Ee,m,T))return Vt(Ee);if(q?.isFile()&&!S(we,m,T))return Vt(we);if(H.pathname.startsWith("/_stx/component/")){let B=decodeURIComponent(H.pathname.slice(16));if(B)try{let ie=`<${B} />`,te={...buildConfig,autoShell:!1},ae=await processDirectives(ie,{},oe.join(m,"components",`${B}.stx`),te,new Set);return new Response(ae,{headers:{"Content-Type":"text/html"}})}catch(ie){return new Response(`<div class="stx-async-error">${ie.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(H.pathname==="/_stx/img"){let{handleImageRequest:B}=await import("./chunk-z1rs6b4x.js"),ie=await B(A,{publicDir:oe.join(m,ee),cacheDir:l(m,"cache","img")});if(ie)return ie}if(Q)try{let B=await Q.handleRequest(A);if(B.status!==404)return B}catch{}if(K[H.pathname])try{return await K[H.pathname](A)}catch(B){return new Response(JSON.stringify({error:B.message}),{status:500,headers:{"Content-Type":"application/json"}})}let ue=await R(A);if(ue)return ue;let G=wr(H.pathname,L);if(G){let B=de.get(G.route.pattern),ie=Re.has(G.route.pattern);if(!B||G.route.isDynamic&&Object.keys(G.params).length>0||ie){let te=await I(G.route,G.params);if(te){if(B=te,!G.route.isDynamic&&!ie)de.set(G.route.pattern,te)}}if(B){let te=B.status??200,ae=B.headers??{},fe=(G.route.filePath?kt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let Me=await se(404);if(Me){let ne=Me;if(ne=await x(ne,m),o)ne=We(ne,u);return new Response(ne,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Ie=It(H.pathname,G.params,fe,H.search),Me=Ot(Ie,null,A,{isServer:!0}),ne=await Nt(fe.middleware,Me);if(ne.redirect){let De=ne.redirect.path,ye=ne.redirect.options.redirectCode||302,pt=new Headers(ne.responseHeaders);return pt.set("Location",De),new Response(null,{status:ye,headers:pt})}if(ne.abort){let{statusCode:De,message:ye}=ne.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${ye}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ne.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ne.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;B.content=f(B.content,De,"")}}let F=B.content;if(E&&va(A)&&Ye(F,b?.router?.container||"main")){let Ie=ot(F),Me=ke(F),ne=F.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ne?en(ne[1].trim()):"";if(Object.keys(G.params).length>0)F=Et(F,G.params);F=await x(F,m);let ye=b?.router?.container||"main";return F=Pe(F,ye,!0),new Response(F,{status:te,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Ie.layout,"X-STX-Layout-Group":Ie.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[hc]:ps(),...z(),"Cache-Control":wt}})}if(E)F=Qr(E,F);if(Object.keys(G.params).length>0)F=Et(F,G.params);if(F=await x(F,m),o)F=We(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 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 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}`;if(B.boundaries&&B.boundaries.length>0){let{renderStreamingPage:Ie,streamToResponse:Me}=await import("./chunk-84ztb43k.js");return Me(Ie(F,B.boundaries,{timeoutMs:30000}),{status:te,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(F,{status:te,headers:{"Content-Type":"text/html",...z(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ae}})}}if(P.length>0){let B=P.map((te)=>te.route),ie=wr(H.pathname,B);if(ie){let te=M.get(ie.route.pattern);if(!te||ie.route.isDynamic){let ae=await I(ie.route,ie.params);if(ae){if(te=ae,!ie.route.isDynamic)M.set(ie.route.pattern,ae)}}if(te){let ae=te.content;if(E)ae=Qr(E,ae);if(Object.keys(ie.params).length>0)ae=Et(ae,ie.params);if(ae=await x(ae,m),o)ae=We(ae,u);return new Response(ae,{status:te.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:te}of O)if(te!=="/"&&H.pathname.startsWith(te)){let ae=M.get(te)||M.get(te+"/");if(!ae){let fe=P.find(({route:F})=>F.pattern===te||F.pattern===`${te}/`);if(fe){let F=await I(fe.route);if(F)ae=F,M.set(fe.route.pattern,F)}}if(ae){let fe=ae.content;if(E)fe=Qr(E,fe);if(fe=await x(fe,m),o)fe=We(fe,u);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if($t(H.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ve=de.get("/");if(Ve){let B=Ve.content;if(B=await x(B,m),o)B=We(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;return new Response(B,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let le=await se(404);if(le){let B=le;if(B=await x(B,m),o)B=We(B,u);return new Response(B,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let H=await se(500);if(H)return new Response(H,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
|
|
1439
|
+
${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1442
1440
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1443
|
-
${e.bright}\u2192 ${e.cyan}http://localhost:${
|
|
1444
|
-
${e.yellow}Routes:${e.reset}`);let Mt=[...
|
|
1445
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),
|
|
1446
|
-
`).map((
|
|
1447
|
-
`).map((
|
|
1448
|
-
`);u=`<${
|
|
1449
|
-
${
|
|
1450
|
-
/>`}return{name:
|
|
1451
|
-
`).map((
|
|
1441
|
+
${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),o)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
|
|
1442
|
+
${e.yellow}Routes:${e.reset}`);let Mt=[...Ds(L,m)];for(let{route:A}of P)Mt.push(`${A.pattern}`);if(Mt.forEach((A,H)=>{let ee=H===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${ee}${e.reset}${A}`)}),console.log(`
|
|
1443
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(Dt.url.toString(),()=>{if(d)ct();Dt.stop()}),n.native){let A,H=oe.join(C,"index.stx");if(me.existsSync(H)){let ee=await Bun.file(H).text();A=yt(ee)}let W=b?.app?.window??{};await et(Ge,{title:b?.app?.head?.title||oe.basename(m)||"stx App",width:W.width,height:W.height,darkMode:W.darkMode,hotReload:W.hotReload,titlebarHidden:W.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(V)=>V.startsWith("public/")||V.startsWith("public\\"),H=(V)=>{let J=V.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},W=new Map,ee=()=>{let V=new Set([m,...b._layerGraph?.layers.map((J)=>J.root)??[],...b._layerGraph?.configDependencies.map((J)=>oe.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of b._layerGraph?.layers??[])for(let q of Object.values(J.resources)){if(!me.existsSync(q))continue;let ue=me.realpathSync(q);if(![...V].some((G)=>ue===G||ue.startsWith(`${G}${oe.sep}`)))V.add(ue)}for(let[J,q]of W)if(!V.has(J))q.close(),W.delete(J);for(let J of V)if(!W.has(J)&&me.existsSync(J))W.set(J,me.watch(J,{recursive:!0},(q,ue)=>{Ee(J,q,ue).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Ee=(V,J,q)=>(X=X.catch(()=>{}).then(()=>we(V,J,q)),X),we=async(V,J,q)=>{if(!q||vt(q))return;if(xt(q)){if(b._layerGraph){let ue=await y(m);Object.assign(b,ue),L.splice(0,L.length,...Z(k,{pagesDir:v,pagesDirs:ue._layerPageDirs?[C,...ue._layerPageDirs.slice(1)]:void 0})),ee()}if(A(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),o&&d)d.reload(q)}else if(H(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),tt.clear(),be();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-g075cc67.js");ue(oe.resolve(V,q)),G.delete(oe.resolve(V,q))}catch{}if(_&&q){if(oe.resolve(V,q)===_||oe.basename(_)===q){let G=await So(_,n.stxOptions||{});if(G)E=G}}if(await Ue(),await dr(m),o&&d)d.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),tt.clear(),be();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-g075cc67.js");ue(oe.resolve(V,q)),G.delete(oe.resolve(V,q))}catch{}if(await Ue(),o&&d)d.reload(q)}}else if(bt(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),o&&d)d.updateCss(q)}};ee(),process.on("SIGINT",()=>{for(let V of W.values())V.close();if(d)ct();Dt.stop(),process.exit(0)})}return!0}import qt from"fs";import lt from"path";async function Wr(t){try{let r=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!r)return[];let p=r[1],o=[],d=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=d.exec(p))!==null){let m=u[1],y=u[2]||u[3]||u[4];if(!y)continue;let b={name:y},w=m.match(/@type\s+\{([^}]+)\}/i);if(w)b.type=w[1].trim();if(m.match(/@required/i))b.required=!0;let T=m.match(/@default\s+(.+?)(?:\s+|$)/i);if(T)b.default=T[1].trim();let R=m.split(`
|
|
1444
|
+
`).map((k)=>k.trim().replace(/^\*\s*/,"")).filter((k)=>!k.startsWith("@")&&k.length>0);b.description=R.join(" ").trim(),o.push(b)}if(o.length===0){let m=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(m){let b=m[1].split(",").map((w)=>w.trim()).filter(Boolean);for(let w of b){let[S]=w.split(":").map((T)=>T.trim());if(S)o.push({name:S})}}}return o}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Vr(t){try{let n=await Bun.file(t).text(),r=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(r)return r[1].split(`
|
|
1445
|
+
`).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function qr(t,n=!1,r){let p=lt.basename(t,".stx"),o=await Wr(t),d=await Vr(t),u="";if(n&&r)u=`<${r}></${r}>`;else{let m=o.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
|
|
1446
|
+
`);u=`<${p}
|
|
1447
|
+
${m}
|
|
1448
|
+
/>`}return{name:p,path:t,description:d,props:o,example:u,isWebComponent:n,tag:r}}async function fn(t){try{if(!await s(t))return console.warn(`Components directory does not exist: ${t}`),[];let n=await qt.promises.readdir(t,{withFileTypes:!0}),r=[];for(let p of n){let o=lt.join(t,p.name);if(p.isDirectory()){let d=await fn(o);r.push(...d)}else if(p.isFile()&&p.name.endsWith(".stx"))r.push(o)}return r}catch(n){return console.error(`Error finding component files in ${t}:`,n),[]}}async function Jr(t,n){try{if(!await s(t))return[];let r=await fn(t),p=[],o=new Map;if(n?.components?.length)for(let d of n.components)o.set(d.file,d);for(let d of r){let u=o.get(d),m=!!u,y=u?.tag,b=await qr(d,m,y);p.push(b)}return p}catch(r){return console.error("Error generating component docs:",r),[]}}async function Yr(t){try{if(!await s(t))return[];let n=await qt.promises.readdir(t,{withFileTypes:!0}),r=[];for(let p of n){if(!p.isFile()||!p.name.endsWith(".stx"))continue;let o=lt.join(t,p.name),d=await Bun.file(o).text(),u=lt.basename(o,".stx"),m=d.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||d.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),y=m?m[1].split(`
|
|
1449
|
+
`).map((v)=>v.trim().replace(/^\*\s*/,"")).join(" ").trim():"",b=/@component\(\s*['"]([^'"]+)['"]/g,w=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,S=new Set,T;while((T=b.exec(d))!==null)S.add(T[1]);while((T=w.exec(d))!==null)if(T[1]&&T[1]!=="slot")S.add(T[1]);let R=/@([a-z]+)(?:\s*\(|\s+|$)/g,k=new Set;while((T=R.exec(d))!==null)k.add(T[1]);r.push({name:u,path:o,description:y,components:[...S],directives:[...k]})}return r}catch(n){return console.error("Error generating template docs:",n),[]}}async function Zr(t=[]){try{let n=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
|
|
1452
1450
|
<p>Welcome, {{ user.name }}!</p>
|
|
1453
1451
|
@endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
|
|
1454
1452
|
<p>Welcome back!</p>
|
|
@@ -1468,49 +1466,49 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.
|
|
|
1468
1466
|
<p>Page {{ page }}</p>
|
|
1469
1467
|
@endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
|
|
1470
1468
|
{{ This will be displayed as-is }}
|
|
1471
|
-
@endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let r of t)n.push({name:r.name,description:r.description||"",hasEndTag:r.hasEndTag||!1,example:""});return n}catch(n){return console.error("Error generating directive docs:",n),[]}}function
|
|
1469
|
+
@endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let r of t)n.push({name:r.name,description:r.description||"",hasEndTag:r.hasEndTag||!1,example:""});return n}catch(n){return console.error("Error generating directive docs:",n),[]}}function eo(t=[],n=[],r=[],p){let o=`# stx Documentation
|
|
1472
1470
|
|
|
1473
|
-
`;if(
|
|
1471
|
+
`;if(p)o+=`${p}
|
|
1474
1472
|
|
|
1475
1473
|
`;if(t.length>0){o+=`## Components
|
|
1476
1474
|
|
|
1477
|
-
`;for(let
|
|
1475
|
+
`;for(let d of t){if(o+=`### ${d.name}
|
|
1478
1476
|
|
|
1479
|
-
`,
|
|
1477
|
+
`,d.description)o+=`${d.description}
|
|
1480
1478
|
|
|
1481
|
-
`;if(
|
|
1479
|
+
`;if(d.isWebComponent)o+=`**Web Component Tag:** \`${d.tag}\`
|
|
1482
1480
|
|
|
1483
|
-
`;if(
|
|
1481
|
+
`;if(d.props.length>0){o+=`#### Properties
|
|
1484
1482
|
|
|
1485
1483
|
`,o+=`| Name | Type | Required | Default | Description |
|
|
1486
1484
|
`,o+=`| ---- | ---- | -------- | ------- | ----------- |
|
|
1487
|
-
`;for(let u of
|
|
1485
|
+
`;for(let u of d.props)o+=`| ${u.name} | ${u.type||"any"} | ${u.required?"Yes":"No"} | ${u.default||"-"} | ${u.description||"-"} |
|
|
1488
1486
|
`;o+=`
|
|
1489
|
-
`}if(
|
|
1487
|
+
`}if(d.example)o+=`#### Example
|
|
1490
1488
|
|
|
1491
|
-
`,o+="```html\n",o+=
|
|
1489
|
+
`,o+="```html\n",o+=d.example,o+="\n```\n\n"}}if(n.length>0){o+=`## Templates
|
|
1492
1490
|
|
|
1493
|
-
`;for(let
|
|
1491
|
+
`;for(let d of n){if(o+=`### ${d.name}
|
|
1494
1492
|
|
|
1495
|
-
`,
|
|
1493
|
+
`,d.description)o+=`${d.description}
|
|
1496
1494
|
|
|
1497
|
-
`;if(
|
|
1495
|
+
`;if(d.components&&d.components.length>0)o+=`**Components Used:** ${d.components.join(", ")}
|
|
1498
1496
|
|
|
1499
|
-
`;if(
|
|
1497
|
+
`;if(d.directives&&d.directives.length>0)o+=`**Directives Used:** ${d.directives.join(", ")}
|
|
1500
1498
|
|
|
1501
1499
|
`}}if(r.length>0){o+=`## Directives
|
|
1502
1500
|
|
|
1503
1501
|
`,o+=`| Directive | Description | Has End Tag |
|
|
1504
1502
|
`,o+=`| --------- | ----------- | ----------- |
|
|
1505
|
-
`;for(let
|
|
1503
|
+
`;for(let d of r)o+=`| @${d.name} | ${d.description||"-"} | ${d.hasEndTag?"Yes":"No"} |
|
|
1506
1504
|
`;o+=`
|
|
1507
|
-
`;for(let
|
|
1505
|
+
`;for(let d of r)if(d.example)o+=`### @${d.name}
|
|
1508
1506
|
|
|
1509
|
-
`,o+=`${
|
|
1507
|
+
`,o+=`${d.description||""}
|
|
1510
1508
|
|
|
1511
1509
|
`,o+=`#### Example
|
|
1512
1510
|
|
|
1513
|
-
`,o+="```html\n",o+=
|
|
1511
|
+
`,o+="```html\n",o+=d.example,o+="\n```\n\n"}return o}function to(t=[],n=[],r=[],p){let o=`<!DOCTYPE html>
|
|
1514
1512
|
<html lang="en">
|
|
1515
1513
|
<head>
|
|
1516
1514
|
<meta charset="UTF-8">
|
|
@@ -1553,7 +1551,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.
|
|
|
1553
1551
|
</head>
|
|
1554
1552
|
<body>
|
|
1555
1553
|
<h1>stx Documentation</h1>
|
|
1556
|
-
`;if(
|
|
1554
|
+
`;if(p)o+=`<div>${p}</div>`;if(t.length>0){o+="<h2>Components</h2>";for(let d of t){if(o+=`<h3>${d.name}</h3>`,d.description)o+=`<p>${d.description}</p>`;if(d.isWebComponent)o+=`<p><strong>Web Component Tag:</strong> <code>${d.tag}</code></p>`;if(d.props.length>0){o+="<h4>Properties</h4>",o+=`<table>
|
|
1557
1555
|
<thead>
|
|
1558
1556
|
<tr>
|
|
1559
1557
|
<th>Name</th>
|
|
@@ -1563,13 +1561,13 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.
|
|
|
1563
1561
|
<th>Description</th>
|
|
1564
1562
|
</tr>
|
|
1565
1563
|
</thead>
|
|
1566
|
-
<tbody>`;for(let u of
|
|
1564
|
+
<tbody>`;for(let u of d.props)o+=`<tr>
|
|
1567
1565
|
<td>${u.name}</td>
|
|
1568
1566
|
<td>${u.type||"any"}</td>
|
|
1569
1567
|
<td>${u.required?"Yes":"No"}</td>
|
|
1570
1568
|
<td>${u.default||"-"}</td>
|
|
1571
1569
|
<td>${u.description||"-"}</td>
|
|
1572
|
-
</tr>`;o+="</tbody></table>"}if(
|
|
1570
|
+
</tr>`;o+="</tbody></table>"}if(d.example)o+="<h4>Example</h4>",o+=`<pre><code>${d.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}}if(n.length>0){o+="<h2>Templates</h2>";for(let d of n){if(o+=`<h3>${d.name}</h3>`,d.description)o+=`<p>${d.description}</p>`;if(d.components&&d.components.length>0)o+=`<p><strong>Components Used:</strong> ${d.components.join(", ")}</p>`;if(d.directives&&d.directives.length>0)o+=`<p><strong>Directives Used:</strong> ${d.directives.join(", ")}</p>`}}if(r.length>0){o+="<h2>Directives</h2>",o+=`<table>
|
|
1573
1571
|
<thead>
|
|
1574
1572
|
<tr>
|
|
1575
1573
|
<th>Directive</th>
|
|
@@ -1577,27 +1575,27 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ve(Ot.
|
|
|
1577
1575
|
<th>Has End Tag</th>
|
|
1578
1576
|
</tr>
|
|
1579
1577
|
</thead>
|
|
1580
|
-
<tbody>`;for(let
|
|
1581
|
-
<td>@${
|
|
1582
|
-
<td>${
|
|
1583
|
-
<td>${
|
|
1584
|
-
</tr>`;o+="</tbody></table>";for(let
|
|
1585
|
-
`;let
|
|
1578
|
+
<tbody>`;for(let d of r)o+=`<tr>
|
|
1579
|
+
<td>@${d.name}</td>
|
|
1580
|
+
<td>${d.description||"-"}</td>
|
|
1581
|
+
<td>${d.hasEndTag?"Yes":"No"}</td>
|
|
1582
|
+
</tr>`;o+="</tbody></table>";for(let d of r)if(d.example)o+=`<h3>@${d.name}</h3>`,o+=`<p>${d.description||""}</p>`,o+="<h4>Example</h4>",o+=`<pre><code>${d.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return o+="</body></html>",o}function no(t=[],n=[],r=[],p){return JSON.stringify({components:t,templates:n,directives:r,extraContent:p||""},null,2)}async function ro(t){try{let{componentsDir:n,templatesDir:r,webComponentsConfig:p,customDirectives:o,config:d}=t;if(!d.enabled)return!1;let u=d.outputDir||"docs";if(await qt.promises.mkdir(u,{recursive:!0}),console.log("Generating documentation..."),n)console.log(`Components directory: ${n}`);if(r)console.log(`Templates directory: ${r}`);console.log(`Output directory: ${u}`);let m=[];if(d.components!==!1&&n)console.log("Generating component documentation..."),m=await Jr(n,p),console.log(`Found ${m.length} components`);let y=[];if(d.templates!==!1&&r)console.log("Generating template documentation..."),y=await Yr(r),console.log(`Found ${y.length} templates`);let b=[];if(d.directives!==!1)console.log("Generating directive documentation..."),b=await Zr(o),console.log(`Found ${b.length} directives`);let w=d.format||"markdown",S=d.extraContent,T="",R="";switch(w){case"markdown":T=eo(m,y,b,S),R="md";break;case"html":T=to(m,y,b,S),R="html";break;case"json":T=no(m,y,b,S),R="json";break;default:throw Error(`Unsupported documentation format: ${w}`)}let k=lt.join(u,`stx-docs.${R}`);return await Bun.write(k,T),console.log(`Documentation generated: ${k}`),!0}catch(n){return console.error("Error generating documentation:",n),!1}}async function ca(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},r=t.componentsDir||D.componentsDir,p=t.templatesDir||".";return ro({componentsDir:r,templatesDir:p,webComponentsConfig:D.webComponents,customDirectives:D.customDirectives,config:n})}var hn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function go(t,n={}){let r={...hn,...n};if(t.trim()==="")return`
|
|
1583
|
+
`;let p=t;if(r.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=io(p,r),p=po(p,r),p=ao(p,r),r.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,""),p=p.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(p=p.replace(/\r\n/g,`
|
|
1586
1584
|
`).replace(/\r/g,`
|
|
1587
|
-
`),!
|
|
1588
|
-
`))
|
|
1589
|
-
`;return
|
|
1590
|
-
`;let
|
|
1591
|
-
`),
|
|
1592
|
-
`),
|
|
1593
|
-
`).map((
|
|
1594
|
-
`);return`${
|
|
1595
|
-
${
|
|
1596
|
-
${
|
|
1585
|
+
`),!p.endsWith(`
|
|
1586
|
+
`))p+=`
|
|
1587
|
+
`;return p}function la(t,n={}){let r={...hn,...n};if(t.trim()==="")return`
|
|
1588
|
+
`;let p=t;if(p=p.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(o,d,u,m,y)=>{let b=m.split(`
|
|
1589
|
+
`),w=b.filter((v)=>v.trim().length>0);if(w.length===0)return o;let S=Math.min(...w.map((v)=>{let C=v.match(/^( *)/);return C?C[1].length:0})),T=b.map((v)=>{if(v.trim().length===0)return"";return v.substring(S)}).join(`
|
|
1590
|
+
`),k=go(T,r).trimEnd().split(`
|
|
1591
|
+
`).map((v)=>{if(v.trim().length===0)return"";return d+v}).join(`
|
|
1592
|
+
`);return`${d}\`\`\`${u}
|
|
1593
|
+
${k}
|
|
1594
|
+
${d}\`\`\``}),r.trimTrailingWhitespace)p=p.replace(/[ \t]+$/gm,"");if(p=p.replace(/\r\n/g,`
|
|
1597
1595
|
`).replace(/\r/g,`
|
|
1598
|
-
`),!
|
|
1599
|
-
`))
|
|
1600
|
-
`;return
|
|
1596
|
+
`),!p.endsWith(`
|
|
1597
|
+
`))p+=`
|
|
1598
|
+
`;return p}function so(t){let n=t,r=[],p="__PROTECTED_BLOCK_";return n=n.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(o)=>{let d=r.length;return r.push(o),`${p}${d}__`}),n=n.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1601
1599
|
$1
|
|
1602
1600
|
`),n=n.replace(/(@end\w+)/g,`
|
|
1603
1601
|
$1
|
|
@@ -1605,16 +1603,16 @@ $1
|
|
|
1605
1603
|
$1
|
|
1606
1604
|
`),n=n.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
|
|
1607
1605
|
$1
|
|
1608
|
-
`),n=n.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(o,
|
|
1609
|
-
${o}`}),n=n.replace(/(>)(<\/)/g,(o,
|
|
1610
|
-
${u}`}),n=n.replace(/(<\/[^>]+>)(?=<|$)/g,(o,
|
|
1611
|
-
`}),n=n.replace(new RegExp(`${
|
|
1606
|
+
`),n=n.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(o,d,u,m)=>{let y=m.substring(u+o.length,Math.min(m.length,u+o.length+20)),b=o.match(/<(\w+)/)?.[1];if(b&&y.match(new RegExp(`^</${b}>`)))return o;return`
|
|
1607
|
+
${o}`}),n=n.replace(/(>)(<\/)/g,(o,d,u,m,y)=>{let b=y.substring(Math.max(0,m-50),m),S=y.substring(m+o.length,Math.min(y.length,m+o.length+20)).match(/^(\w+)>/)?.[1],T=b.match(/<(\w+)[^>]*$/)?.[1];if(T&&S&&T===S)return o;return`${d}
|
|
1608
|
+
${u}`}),n=n.replace(/(<\/[^>]+>)(?=<|$)/g,(o,d,u,m)=>{let y=m.substring(Math.max(0,u-20),u),b=o.match(/<\/(\w+)>/)?.[1],w=new RegExp(`<${b}[^>]*>$`);if(b&&y.match(w))return o;return`${o}
|
|
1609
|
+
`}),n=n.replace(new RegExp(`${p}(\\d+)__`,"g"),(o,d)=>r[Number.parseInt(d,10)]),n=n.replace(/\n{2,}/g,`
|
|
1612
1610
|
`),n=n.split(`
|
|
1613
1611
|
`).map((o)=>o.trim()).join(`
|
|
1614
|
-
`),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function
|
|
1615
|
-
`),o=[],
|
|
1616
|
-
`)}function
|
|
1617
|
-
`)||o.includes("@"))return r;let
|
|
1612
|
+
`),n=n.replace(/^\n+/,"").replace(/\n+$/,""),n}function io(t,n){let p=so(t).split(`
|
|
1613
|
+
`),o=[],d=0,u=!1,m=n.useTabs?"\t":" ".repeat(n.indentSize);for(let y=0;y<p.length;y++){let b=p[y],w=b.trim();if(w===""){o.push("");continue}let S=w.match(/<script\b/i),T=w.match(/<\/script>/i);if(u&&!T){o.push(b);continue}let R=w===">";if(gn(w)&&!w.startsWith("<")&&!w.startsWith("@")){o.push(m.repeat(d)+w);continue}let k=w.startsWith("@end"),v=w.startsWith("@else")||w.startsWith("@elseif"),C=w.startsWith("@")&&lo(w),L=w.startsWith("<!DOCTYPE")||w.startsWith("<!doctype"),O=w.startsWith("<!--"),P=w.startsWith("</"),M=w.startsWith("<")&&!P&&!O&&!L,E=w.includes("/>")||co(w),_=gn(w);if(P||k)d=Math.max(0,d-1);let j=v?Math.max(0,d-1):d;if(R)o.push(b);else o.push(m.repeat(j)+w);if(M&&!E&&!_&&!R||C)d++;if(S)u=!0;if(T)u=!1}return o.join(`
|
|
1614
|
+
`)}function ao(t,n){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(r,p,o)=>{let d=o.trim().replace(/\s+/g," ");return`@${p}(${d})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(r,p,o)=>{if(o.trim()==="")return`@${p}`;return`@${p}(${o.trim()})`}),n.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(r,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(r,p)=>`{!! ${p.trim()} !!}`);return t}function co(t){let n=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let r=t.match(/<(\w+)/);if(r){let p=r[1];return n.includes(p.toLowerCase())}return!1}function gn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function lo(t){let n=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let r of n)if(t.startsWith(`@${r}`))return!t.includes(`@end${r}`);return!1}function po(t,n){if(!n.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(r,p,o)=>{if(!o.trim())return r;if(o.includes("<")||o.includes(`
|
|
1615
|
+
`)||o.includes("@"))return r;let d=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,u=[],m;while((m=d.exec(o))!==null)u.push({name:m[1],value:m[2]});u.sort((b,w)=>{if(b.name==="id")return-1;if(w.name==="id")return 1;if(b.name==="class")return-1;if(w.name==="class")return 1;return b.name.localeCompare(w.name)});let y=u.map((b)=>b.value?`${b.name}=${b.value}`:b.name).join(" ");return`<${p}${y?` ${y}`:""}>`})}import yn from"fs";import Kt from"path";async function ua(t="index.stx",n={}){try{let r=n.force||!1,p=Kt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!r)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let o=Kt.dirname(p);if(!yn.existsSync(o))yn.mkdirSync(o,{recursive:!0});let d;if(n.template){let u=Kt.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.`);d=await Bun.file(u).text(),console.warn(`Using template from ${n.template}`)}else if(n.preset)d=bn(n.preset),console.warn(`Using '${n.preset}' preset template`);else d=bn("basic");return await Bun.write(p,d),console.warn(`Created new stx file: ${t}`),!0}catch(r){return console.error(`Error creating file: ${r instanceof Error?r.message:String(r)}`),!1}}function bn(t){switch(t){case"basic":return xn();case"component":return uo();case"layout":return fo();case"blog":return yo();case"api":return bo();case"app":return xo();default:return xn()}}function xn(){return`<script>
|
|
1618
1616
|
const title = "My stx Page"
|
|
1619
1617
|
const description = "A page built with stx"
|
|
1620
1618
|
const features = [
|
|
@@ -1639,7 +1637,7 @@ const features = [
|
|
|
1639
1637
|
</div>
|
|
1640
1638
|
@endforeach
|
|
1641
1639
|
</main>
|
|
1642
|
-
@endsection`}function
|
|
1640
|
+
@endsection`}function uo(){return`{{-- Component: Card --}}
|
|
1643
1641
|
{{-- Props: title, variant, collapsible --}}
|
|
1644
1642
|
{{-- Usage: @component('card', { title: "Hello", variant: "primary", collapsible: true }) Content @endcomponent --}}
|
|
1645
1643
|
<script>
|
|
@@ -1684,7 +1682,7 @@ const features = [
|
|
|
1684
1682
|
.card.collapsed .card__toggle { transform: rotate(-90deg); }
|
|
1685
1683
|
.card__body { padding: 1rem; }
|
|
1686
1684
|
.card.collapsed .card__body { display: none; }
|
|
1687
|
-
</style>`}function
|
|
1685
|
+
</style>`}function fo(){return`<!DOCTYPE html>
|
|
1688
1686
|
<html lang="en">
|
|
1689
1687
|
<head>
|
|
1690
1688
|
<meta charset="UTF-8">
|
|
@@ -1735,7 +1733,7 @@ const features = [
|
|
|
1735
1733
|
|
|
1736
1734
|
@yield('scripts')
|
|
1737
1735
|
</body>
|
|
1738
|
-
</html>`}function
|
|
1736
|
+
</html>`}function yo(){return`<script>
|
|
1739
1737
|
// Article metadata
|
|
1740
1738
|
const title = "My Blog Post"
|
|
1741
1739
|
const author = "Your Name"
|
|
@@ -1780,7 +1778,7 @@ const features = [
|
|
|
1780
1778
|
<p>Wrap up your thoughts here.</p>
|
|
1781
1779
|
</div>
|
|
1782
1780
|
</article>
|
|
1783
|
-
@endsection`}function
|
|
1781
|
+
@endsection`}function bo(){return`<script>
|
|
1784
1782
|
// API endpoint configuration
|
|
1785
1783
|
const endpoint = "/api/data"
|
|
1786
1784
|
const method = "GET"
|
|
@@ -1815,7 +1813,7 @@ const features = [
|
|
|
1815
1813
|
}
|
|
1816
1814
|
@else
|
|
1817
1815
|
{{ JSON.stringify(data, null, 2) }}
|
|
1818
|
-
@endif`}function
|
|
1816
|
+
@endif`}function xo(){return`<!DOCTYPE html>
|
|
1819
1817
|
<html lang="en">
|
|
1820
1818
|
<head>
|
|
1821
1819
|
<meta charset="UTF-8">
|
|
@@ -2040,5 +2038,5 @@ const features = [
|
|
|
2040
2038
|
})();
|
|
2041
2039
|
</script>
|
|
2042
2040
|
</body>
|
|
2043
|
-
</html>`}var
|
|
2044
|
-
`)}export{
|
|
2041
|
+
</html>`}var da="f9c3713";function Fl(t){return t}function zl(t){return t}function oa(t,n){let r=[],p=`${n}=`;for(let o=0;o<t.length;o++){let d=t[o];if(d.startsWith(p)){let u=d.slice(p.length);if(u)r.push(u);continue}if(d===n){let u=t[o+1];if(u!==void 0&&!u.startsWith("-"))r.push(u),o++}}return r}import Le from"fs";import xe from"path";function Pn(t){try{return Le.statSync(t).mtimeMs}catch{return null}}function Ct(t,n){let r=Math.max(0,Math.round((n-t)/1000));if(r<60)return`${r}s ago`;if(r<3600)return`${Math.round(r/60)}m ago`;return`${Math.round(r/3600)}h ago`}function Ri(t,n){try{return globalThis.Bun?.resolveSync(t,n)??null}catch{return null}}function On(t,n="stx"){let r=xe.resolve(t);for(let p=0;p<10;p++){let o=xe.join(r,"pantry","@stacksjs",n);if(Le.existsSync(o))return o;let d=xe.dirname(r);if(d===r)break;r=d}return null}var An=["@stacksjs/stx","bun-plugin-stx"];function Ei(t){try{let n=Le.readFileSync(xe.join(t,"package.json"),"utf8"),r=JSON.parse(n)?.version;return typeof r==="string"?r:null}catch{return null}}function Pi(t,n=6){let r=xe.resolve(t),p=[],o=new Set;function d(m,y){if(y>n)return;let b;try{b=Le.realpathSync(m)}catch{return}if(o.has(b))return;o.add(b);for(let S of An){let T=xe.join(m,S),R=Ei(T);if(R!==null)p.push({name:S,version:R,dir:xe.relative(r,T)||T,nested:y>0})}let w;try{w=Le.readdirSync(m,{withFileTypes:!0})}catch{return}for(let S of w){if(!S.isDirectory()&&!S.isSymbolicLink())continue;if(S.name===".bin"||S.name===".cache")continue;let T=xe.join(m,S.name);if(S.name.startsWith("@")){let k;try{k=Le.readdirSync(T,{withFileTypes:!0})}catch{continue}for(let v of k){let C=xe.join(T,v.name,"node_modules");if(Le.existsSync(C))d(C,y+1)}continue}let R=xe.join(T,"node_modules");if(Le.existsSync(R))d(R,y+1)}}let u=xe.join(r,"node_modules");if(Le.existsSync(u))d(u,0);return p}function Oi(t){let n=[];for(let r of An){let p=t.filter((u)=>u.name===r);if(p.length<=1)continue;let o=[...new Set(p.map((u)=>u.version))],d=p.map((u)=>`${u.version} at ${u.dir}`).join("; ");if(o.length===1){n.push({name:`${r} copies`,status:"info",detail:`${p.length} copies, all ${o[0]} \u2014 duplicated but in agreement`});continue}n.push({name:`${r} copies disagree`,status:"error",detail:`${o.length} versions installed, so which one runs depends on who imports it: ${d}`,fix:`remove the nested copies, or add an overrides entry pinning ${r}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${r}/package.json' -exec grep -H '"version"' {} +`})}return n}async function mo(t={}){let n=t.cwd?xe.resolve(t.cwd):process.cwd(),r=t.resolve??Ri,p=Date.now(),o=[],d=r("@stacksjs/stx",n);o.push(d?{name:"@stacksjs/stx resolves to",status:"ok",detail:d}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let u=r("bun-plugin-stx",n);if(u)o.push({name:"bun-plugin-stx resolves to",status:"ok",detail:u});for(let y of Oi(Pi(n)))o.push(y);let m=On(n,"stx");if(!m)o.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let y=xe.join(m,"src/signals.ts"),b=[xe.join(m,"dist/index.js"),xe.join(m,"dist/signals.js")].find((k)=>Le.existsSync(k))||null,w=Pn(y),S=b?Pn(b):null;if(w==null)o.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${m} but no src/signals.ts to compare`});else if(S==null)o.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${m} && bun build.ts`});else if(S<w){let k=Math.round((w-S)/1000);o.push({name:"pantry dist freshness",status:"error",detail:`dist (${Ct(S,p)}) is OLDER than src/signals.ts (${Ct(w,p)}) by ${k}s \u2014 your edit isn't built`,fix:`cd ${m} && bun build.ts`})}else o.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Ct(w,p)}, dist ${Ct(S,p)})`});let T=xe.join(n,"node_modules/@stacksjs/stx"),R=null;try{R=Le.lstatSync(T)}catch{R=null}if(!R)o.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(R.isSymbolicLink()){let k=null;try{k=Le.realpathSync(T)}catch{}let v=(()=>{try{return Le.realpathSync(m)}catch{return m}})();o.push(k===v?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${k||"(dangling)"}, not pantry`})}else o.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(o.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let b=t.generateRuntime().length;o.push(b>1000?{name:"signals runtime",status:"ok",detail:`generated ${b.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${b} chars \u2014 suspiciously short`})}catch(y){o.push({name:"signals runtime",status:"error",detail:`failed to generate: ${y.message}`})}return{checks:o,ok:!o.some((y)=>y.status==="error")}}function ho(t){let n={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},r=["stx runtime resolution:"];for(let p of t.checks)if(r.push(` ${n[p.status]} ${p.name}: ${p.detail}`),p.fix)r.push(` \u2192 ${p.fix}`);return r.push(""),r.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),r.join(`
|
|
2042
|
+
`)}export{oa,ia,aa,ca,go,la,ua,da,Fl,zl,mo,ho,Kr,Gr,Xr};
|