@stacksjs/stx 0.2.884 → 0.2.886
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/{chunk-4qzytgtg.js → chunk-0a3qft0p.js} +3 -3
- package/dist/{chunk-rw5sxr5a.js → chunk-0gkxqcpj.js} +1 -1
- package/dist/{chunk-we9k6vtw.js → chunk-12wjs7bn.js} +3 -3
- package/dist/{chunk-jyyyzazb.js → chunk-1ey78497.js} +1 -1
- package/dist/chunk-22sa2r8a.js +2 -0
- package/dist/chunk-2b4ds30m.js +2 -0
- package/dist/{chunk-pxt57028.js → chunk-2m6rf0f8.js} +1 -1
- package/dist/chunk-37dj6p9d.js +182 -0
- package/dist/{chunk-19q3j7cd.js → chunk-38xckpr9.js} +1 -1
- package/dist/chunk-3cq4a4x7.js +7 -0
- package/dist/{chunk-n2nxpgzc.js → chunk-3hwdg5mf.js} +4 -4
- package/dist/chunk-3t6cxcys.js +2 -0
- package/dist/{chunk-0c913abf.js → chunk-5519xwrm.js} +1 -1
- package/dist/{chunk-yv1w9dqr.js → chunk-56kd82yp.js} +4 -4
- package/dist/{chunk-pw2bfb6k.js → chunk-5fjs602p.js} +6 -6
- package/dist/{chunk-6ha9vbjv.js → chunk-6b17yg7a.js} +2 -2
- package/dist/{chunk-2bvms1pz.js → chunk-6g6pxww1.js} +2 -2
- package/dist/{chunk-twhahqbd.js → chunk-6n9y8faw.js} +6 -6
- package/dist/chunk-6nhm9bep.js +2 -0
- package/dist/{chunk-gksn30x7.js → chunk-7dzhar6y.js} +21 -20
- package/dist/{chunk-vh1sewja.js → chunk-7fhtvgqc.js} +1 -1
- package/dist/chunk-85c2vh7f.js +2 -0
- package/dist/{chunk-8t8yzdzq.js → chunk-8cyg4602.js} +1 -1
- package/dist/{chunk-2nt2wjb2.js → chunk-8kx666yb.js} +1 -1
- package/dist/{chunk-rqbqxs01.js → chunk-a4e4xbpd.js} +1 -1
- package/dist/chunk-a5kr9s4x.js +2 -0
- package/dist/chunk-aedm101q.js +2 -0
- package/dist/{chunk-kg7w5xwh.js → chunk-agqj0z54.js} +1 -1
- package/dist/chunk-arf21n16.js +3 -0
- package/dist/{chunk-rzq0s8k3.js → chunk-asnabfnj.js} +1 -1
- package/dist/chunk-bcxwe3e3.js +2 -0
- package/dist/{chunk-szwde015.js → chunk-bv415td7.js} +1 -1
- package/dist/{chunk-nb6erf75.js → chunk-c47stwqj.js} +1 -1
- package/dist/{chunk-hd6hc981.js → chunk-cd5kgd3s.js} +1 -1
- package/dist/{chunk-mdb4pvv9.js → chunk-d1xx1jy5.js} +1 -1
- package/dist/chunk-d59ywxag.js +2 -0
- package/dist/chunk-dyccssdv.js +2 -0
- package/dist/chunk-ef01vj6j.js +2 -0
- package/dist/chunk-f4k8bqse.js +2 -0
- package/dist/{chunk-4fkcn6z5.js → chunk-fg67643b.js} +1 -1
- package/dist/{chunk-ntk07yeh.js → chunk-ftsv4h6f.js} +4 -4
- package/dist/{chunk-7xc81f1w.js → chunk-jkg6ns57.js} +2 -2
- package/dist/chunk-jkgdm99m.js +2 -0
- package/dist/{chunk-bnawaxh5.js → chunk-jq97q0f7.js} +1 -1
- package/dist/chunk-keg5fej5.js +2 -0
- package/dist/{chunk-7kqgp3p7.js → chunk-kqgspa3s.js} +1 -1
- package/dist/{chunk-a60ztvnp.js → chunk-kwf3kfr0.js} +1 -1
- package/dist/{chunk-00tq7ghn.js → chunk-n22xtagg.js} +2 -2
- package/dist/{chunk-n4d7qk9w.js → chunk-n4bwmjj7.js} +1 -1
- package/dist/{chunk-v5zm24gy.js → chunk-nmf70gbp.js} +1 -1
- package/dist/{chunk-rcxer2km.js → chunk-pc8dt8xs.js} +1 -1
- package/dist/chunk-ptmvcmd0.js +2 -0
- package/dist/{chunk-d80re6y8.js → chunk-q396f1wc.js} +4 -4
- package/dist/{chunk-3sema2js.js → chunk-qt39mb2a.js} +1 -1
- package/dist/{chunk-rx94z3d5.js → chunk-rnyrdpbg.js} +1 -1
- package/dist/{chunk-rcjkms52.js → chunk-rs84k601.js} +5 -5
- package/dist/{chunk-sb1e0rd8.js → chunk-rvcce9zt.js} +1 -1
- package/dist/chunk-s7z4at02.js +2 -0
- package/dist/{chunk-k06xctna.js → chunk-v23x8f5d.js} +1 -1
- package/dist/{chunk-tvhm8t45.js → chunk-vhkq715p.js} +1 -1
- package/dist/{chunk-q910pjr4.js → chunk-vkswqg3s.js} +1 -1
- package/dist/{chunk-gn2x58yq.js → chunk-vpztm6vk.js} +1 -1
- package/dist/{chunk-z9cz0vxm.js → chunk-wf09a2z6.js} +1 -1
- package/dist/{chunk-swwn1pa7.js → chunk-wmd952xa.js} +1 -1
- package/dist/{chunk-xs8fccfq.js → chunk-xma57d6t.js} +1 -1
- package/dist/{chunk-5kh07k1p.js → chunk-y9p3b2w0.js} +2 -2
- package/dist/{chunk-q8dkdnvg.js → chunk-ynrjg03j.js} +1 -1
- package/dist/{chunk-7vggqc7d.js → chunk-z83pyccp.js} +10 -10
- package/dist/{chunk-0q117rw8.js → chunk-z9x5pn5j.js} +1 -1
- package/dist/chunk-zfwanbre.js +2 -0
- package/dist/chunk-zfx54b65.js +2 -0
- package/dist/{chunk-rptq6d7b.js → chunk-zpe4zz7r.js} +3 -3
- package/dist/{chunk-yh2hnt3m.js → chunk-zpj6ggee.js} +2 -2
- package/dist/{chunk-be201zh7.js → chunk-zzpg1bg5.js} +5 -5
- package/dist/cli.js +9 -9
- package/dist/component-library.js +5 -2
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/message-catalogs.d.ts +3 -1
- package/dist/message-catalogs.js +7 -3
- package/dist/native/compiler/bundle.js +19 -1
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +6 -6
- package/dist/types/component-types.d.ts +2 -0
- package/package.json +5 -5
- package/dist/chunk-188st53m.js +0 -2
- package/dist/chunk-3t0pf47w.js +0 -2
- package/dist/chunk-5a73eghg.js +0 -2
- package/dist/chunk-5fn9s4e7.js +0 -2
- package/dist/chunk-bx301nnn.js +0 -2
- package/dist/chunk-ccv21bj8.js +0 -2
- package/dist/chunk-egmkawq6.js +0 -2
- package/dist/chunk-fa3syk1m.js +0 -3
- package/dist/chunk-fzxynhyc.js +0 -2
- package/dist/chunk-gg4vcn6m.js +0 -2
- package/dist/chunk-h573cegy.js +0 -2
- package/dist/chunk-j5gcwg3k.js +0 -2
- package/dist/chunk-mcc01ts7.js +0 -2
- package/dist/chunk-nsa675xs.js +0 -2
- package/dist/chunk-pzm31te2.js +0 -2
- package/dist/chunk-s7c1f3h4.js +0 -2
- package/dist/chunk-se4xbbh5.js +0 -2
- package/dist/chunk-sn4ndpd7.js +0 -7
- package/dist/chunk-t25pwp2a.js +0 -177
- package/dist/chunk-vc3sz26f.js +0 -2
- package/dist/chunk-wkgzyjyv.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R}from"./chunk-s29hp1qw.js";import{Re,Vt,se,B,Pn,ie,P}from"./chunk-gksn30x7.js";import{Wi,lo,d,m,N,ht,p,uo,n,u,k}from"./chunk-295bykzd.js";import{wr}from"./chunk-6ha9vbjv.js";import{fe}from"./chunk-d2pexm3z.js";import{Is}from"./chunk-cb0c6959.js";var he=1000,me=!1;function xe(t,r){let i=/@(include|partial)\s*\(\s*(['"])([^'"]+)\2\s*,\s*/g,e="",o=0,s;while((s=i.exec(t))!==null){let l=s.index+s[0].length,b=s.index+s[0].indexOf("("),x=k(t,"(",")",b);if(x===-1)continue;let f=t.slice(l,x).trim();if(!f)continue;if(!Object.keys(r).some((a)=>new RegExp(`(?:^|[^\\w$.])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w$])`).test(f)))continue;let h;try{let a=N(f,r);if(!a||typeof a!=="object")continue;h=JSON.stringify(a)}catch{continue}e+=t.slice(o,l)+h,o=x,i.lastIndex=x}return o===0?t:e+t.slice(o)}function be(t,r){let i=/@component\s*\(/g,e=t,o,s=[];while((o=i.exec(e))!==null){let l=o.index,b=l+o[0].length-1,x=1,f=b+1;while(f<e.length&&x>0){if(e[f]==="(")x++;else if(e[f]===")"){if(x--,x===0)break}f++}if(x!==0)continue;let c=e.substring(b+1,f),h=f+1,a=c.match(/^\s*['"]([^'"]+)['"]/);if(!a)continue;let y=a[1],g=c.slice(a[0].length),A=g.match(/^\s*,\s*/);if(!A)continue;let O=g.slice(A[0].length).trim();if(!O)continue;try{let S=N(O,r),W=JSON.stringify(S),I=`@component('${y}', ${W})`;s.push({start:l,end:h,replacement:I})}catch{continue}}for(let l=s.length-1;l>=0;l--){let{start:b,end:x,replacement:f}=s[l];e=e.substring(0,b)+f+e.substring(x)}return e}function oe(t,r,i){let e=t,o=new RegExp(`${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\(`),s;while((s=o.exec(e))!==null){let l=s.index,b=l+s[0].length-1,x=1,f=b+1,c=null,h=!1;while(f<e.length&&x>0){let g=e[f];if(h){h=!1,f++;continue}if(g==="\\"&&c){h=!0,f++;continue}if(c){if(g===c)c=null;f++;continue}if(g==='"'||g==="'"||g==="`"){c=g,f++;continue}if(g==="(")x++;else if(g===")"){if(x--,x===0)break}f++}if(x!==0)break;let a=e.substring(b+1,f),y=i(a);e=e.substring(0,l)+y+e.substring(f+1)}return e}function ye(t,r){let i=t;return i=i.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)(?=\s+[^=]|\s*\/?>|\s*$)/g,(e,o)=>{if(o in r)return`:${o}="${o}"`;return e}),i=i.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)"/g,(e,o,s)=>{try{if(B(s,r.__stx_client_signal_names||[]))return e;let l=Object.keys(r),b=Object.values(r);Wi(s);let x=!1,c=p(s,l,()=>{x=!0})(...b);if(x)return e;let h=JSON.stringify(c);if(h===void 0){if(!ht(s).some((g)=>!(g in r)))return"";return e}let a=Buffer.from(h,"utf8").toString("base64");return`__stx_${o}="${a}"`}catch(l){return e}}),i}var Q="<!--__STX_BREAK__-->",ee="<!--__STX_CONTINUE__-->";function ae(t,r){let i=/\{\{\{?|\{!!|@(break|continue)(?![\w$])/g,e="",o=0;for(let s=i.exec(t);s;s=i.exec(t)){if(!s[1]){let f=s[0].length===3&&s[0]==="{{{"?3:2,c=s[0]==="{!!"?t.indexOf("!!}",i.lastIndex):Re(t,s.index,f);if(c<0)break;i.lastIndex=c+(s[0]==="{!!"?3:f);continue}let l=i.lastIndex,b=!0,x=/^\s*\(/.exec(t.slice(l));if(x){let f=l+x[0].length-1,c=k(t,"(",")",f);if(c<0)break;l=c+1;try{let h=`!!(${t.slice(f+1,c).trim()})`;b=m(h)?Boolean(p(h,Object.keys(r))(...Object.values(r))):Boolean(d(h,r))}catch{b=!1}}if(e+=t.slice(o,s.index),b)return e+(s[1]==="break"?Q:ee);o=l,i.lastIndex=l}return e+t.slice(o)}function ue(t){let r=(o)=>o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${"),i="",e=0;return Pn(t,(o,s,l)=>(i+=ce(r(t.slice(e,l))),i+=`\${__stxRenderLoopValue(${l}, (${s}), ${o.length})}`,e=l+o.length,o)),i+ce(r(t.slice(e)))}function ge(t,r,i,e){return ie(t,r,i==null?"":String(i),!1,e)}function ce(t){let r=t;return r=oe(r,"@break",(i)=>{let e=i.trim();if(!uo(e))return"";return`\`; if (${e}) { break; } result += \``}),r=oe(r,"@continue",(i)=>{let e=i.trim();if(!uo(e))return"";return`\`; if (${e}) { continue; } result += \``}),r=r.replace(/@break(?!\()/g,"`; break; result += `"),r=r.replace(/@continue(?!\()/g,"`; continue; result += `"),r}function Ee(t){let r=/@forelse\s*\(/g,i,e=[],o=/@foreach\s*\(/g,s=/@endforeach/g,l;while((l=o.exec(t))!==null)e.push({pos:l.index,delta:1});while((l=s.exec(t))!==null)e.push({pos:l.index,delta:-1});e.sort((c,h)=>c.pos-h.pos);let b=[],x=0;for(let c of e)x+=c.delta,b.push({pos:c.pos,depth:x});function f(c){let h=0,a=b.length-1,y=0;while(h<=a){let g=h+a>>1;if(b[g].pos<=c)y=b[g].depth,h=g+1;else a=g-1}return y}while((i=r.exec(t))!==null){if(f(i.index)>0)continue;let c=i.index,h=i.index+i[0].length-1,a=1,y=h+1,g=-1;while(y<t.length&&a>0){if(t[y]==="(")a++;else if(t[y]===")"){if(a--,a===0){g=y;break}}y++}if(g===-1)continue;let A=t.substring(h+1,g),O=Vt(A);if(!O)continue;let{arrayExpr:S,itemVar:W}=O,I=g+1,_=1,T=I,K=/@forelse\s*\(/g,C=/@endforelse/g,L=-1;while(_>0&&T<t.length){K.lastIndex=T,C.lastIndex=T;let F=K.exec(t),E=C.exec(t);if(!E)break;if(F&&F.index<E.index)_++,T=F.index+F[0].length;else{if(_--,_===0){L=E.index;break}T=E.index+11}}if(L===-1)continue;let w=t.substring(I,L),Z=L+11,z=-1,D=0,V=0;while(V<w.length){let F=w.indexOf("@",V);if(F===-1)break;let E=w.substring(F);if(/^@forelse\s*\(/.test(E))D++,V=F+1;else if(E.startsWith("@endforelse"))D--,V=F+11;else if(D===0&&E.startsWith("@empty")){if(w.length<=F+6||!/[a-z]/i.test(w[F+6])){z=F;break}V=F+1}else V=F+1}if(z===-1)continue;return{start:c,end:Z,arrayExpr:S,itemVar:W,foreachContent:w.substring(0,z),emptyContent:w.substring(z+6)}}return null}function le(t,r){let i=t;while(!0){let e=Ee(i);if(!e)break;let{start:o,end:s,arrayExpr:l,itemVar:b,foreachContent:x,emptyContent:f}=e;try{let c;if(m(l))c=p(l,Object.keys(r))(...Object.values(r));else c=d(l,r);let h;if(!Array.isArray(c)||c.length===0)h=f;else h=`@foreach (${l} as ${b})${x}@endforeach`;i=i.substring(0,o)+h+i.substring(s)}catch(c){let h=c instanceof Error?c.message:String(c),a=u("Forelse",`Error in @forelse(${l} as ${b}): ${h}`,n.EVALUATION_ERROR);i=i.substring(0,o)+a+i.substring(s)}}return i}var de="<!--stx:foreach-not-iterable:",_e=/<!--stx:foreach-not-iterable:([^|>]*)\|([^>]*?)-->/g;function $e(t,r){return`${de}${encodeURIComponent(t)}|${encodeURIComponent(r)}-->`}function Ae(t,r){console.warn(`[stx] @foreach(${t}) in ${r}: ${t} is not iterable server-side, so the loop rendered nothing. `+"Values a server loop reads must come from <script server> or the page context \u2014 "+"a plain <script> runs in the browser.")}function Es(t){if(!t.includes(de))return t;return t.replace(_e,(r,i,e)=>(Ae(decodeURIComponent(i),decodeURIComponent(e)),""))}function lg(t,r,i,e,o=!1){let s=ne(t,r,i,e,o),l=s.next();while(!l.done)l=s.next();return l.value}async function si(t,r,i,e,o=!1){let s=ne(t,r,i,e,o),l=s.next();while(!l.done)await R(),l=s.next();return l.value}function*ne(t,r,i,e,o=!1){let s=t,l=new Set(r.__stx_client_signal_names||[]);for(let c of wr(t))l.add(c);if(l.size)r={...r,__stx_client_signal_names:[...l]};s=le(s,r);function b(c){let h=/@foreach\s*\(/g,a;while((a=h.exec(c))!==null){let y=a.index,g=a.index+a[0].length-1,A=1,O=g+1,S=-1;while(O<c.length&&A>0){if(c[O]==="(")A++;else if(c[O]===")"){if(A--,A===0){S=O;break}}O++}if(S===-1)continue;let W=c.substring(g+1,S),I=Vt(W);if(!I)continue;let _=y,{arrayExpr:T,itemVar:K}=I,C=S+1,L=1,w=C,Z=/@foreach\s*\(/g,z=/@endforeach/g;while(L>0&&w<c.length){Z.lastIndex=w,z.lastIndex=w;let D=Z.exec(c),V=z.exec(c);if(!V)break;if(D&&D.index<V.index)L++,w=D.index+D[0].length;else{if(L--,L===0){let F=c.substring(C,V.index),E=V.index+11;return{start:_,end:E,arrayExpr:T,itemVar:K,content:F}}w=V.index+11}}}return null}function*x(c,h){let a=c;while(!0){let y=b(a);if(!y)break;let{start:g,end:A,arrayExpr:O,itemVar:S,content:W}=y;try{let I=O.trim(),_;if(m(I))_=p(I,Object.keys(h))(...Object.values(h));else _=d(I,h);let T=!1;if(!Array.isArray(_))if(_ instanceof Map)_=Array.from(_),T=!0;else if(_ instanceof Set)_=Array.from(_);else if(typeof _==="string")_=Array.from(_);else if(_&&typeof _==="object"&&!(_ instanceof Date)&&!(_ instanceof RegExp))_=Object.entries(_),T=!0;else{let E=$e(I,i)+u("Foreach",`Error in @foreach: ${I} is not iterable`,n.TYPE_ERROR);a=a.substring(0,g)+E+a.substring(A);continue}let K=e?.loops?.useAltLoopVariable??me,C=S.trim(),L=null,w,Z=!1;if(C.includes("=>")){let E=C.split("=>").map((j)=>j.trim());if(E.length===2&&E[0]&&E[1])L=E[0],w=E[1];else w=C}else if(!C.startsWith("[")&&!C.startsWith("{")&&C.includes(",")){let E=C.split(",").map((j)=>j.trim());if(E.length===2&&E[0]&&E[1])w=E[0],L=E[1],Z=!0;else w=C}else w=C;let z="",D=new Set(se(`${O} as ${S}`)),V=_,F=h[lo]??new WeakMap;for(let E=0;E<V.length;E++){if(E%16===0)yield;let j=V[E],te={index:E,iteration:E+1,first:E===0,last:E===V.length-1,count:V.length},M={...h,loop:te,$loop:te,[lo]:F};if(Array.isArray(h.__stx_client_signal_names))M.__stx_client_signal_names=h.__stx_client_signal_names.filter((H)=>!D.has(H));if(w.startsWith("[")&&w.endsWith("]")){let H=w.slice(1,-1).split(",").map((U)=>U.trim());if(Array.isArray(j))H.forEach((U,X)=>{if(U)M[U]=j[X]});else M[w]=j}else if(w.startsWith("{")&&w.endsWith("}")){let H=w.slice(1,-1).split(",").map((U)=>U.trim()).filter(Boolean);if(j!==null&&typeof j==="object")H.forEach((U)=>{let X=U.indexOf(":"),Y=(X===-1?U:U.slice(0,X)).trim(),re=X===-1?Y:U.slice(X+1).trim();if(Y&&re)M[re]=j[Y]});else M[w]=j}else M[w]=j;if(L)if(!Z&&T&&Array.isArray(j)&&j.length===2)M[L]=j[0],M[w]=j[1];else M[L]=E;let v=le(W,M);v=yield*ne(v,M,i,e,!0),v=fe(v,M,i),v=ae(v,M);let J=v.indexOf(Q),G=v.indexOf(ee),q=J<0?G:G<0?J:Math.min(J,G);if(q>=0)v=v.slice(0,q);if(v=P(v,M,i),v=ye(v,M),v=be(v,M),v=xe(v,M),z+=v,q>=0&&q===J)break}a=a.substring(0,g)+z+a.substring(A)}catch(I){let _=u("Foreach",`Error in @foreach(${O.trim()} as ${S.trim()}): ${I instanceof Error?I.message:String(I)}`,n.EVALUATION_ERROR);a=a.substring(0,g)+_+a.substring(A)}}return a}s=yield*x(s,r),s=we(s,r,i,e);let f=e?.loops?.maxWhileIterations??he;return s=Ie(s,r,f),o?s:Es(s)}function ug(t){let r=/^(\s*)([A-Za-z_$][\w$]*|\[[^\]]*\]|\{[^}]*\})(\s+(?:of|in)\s)/.exec(t);if(!r||/^(?:const|let|var)$/.test(r[2]))return t;return`${r[1]}let ${t.slice(r[1].length)}`}function pe(t){return uo(t)}function we(t,r,i,e){let o=t,s=!0;while(s){s=!1;let l=o.match(/@for\s*\(/);if(!l||l.index===void 0)break;let b=l.index,x=b+l[0].length-1,f=k(o,"(",")",x);if(f===-1)break;let c=ug(o.slice(x+1,f)),h=f+1,a=Is(o.slice(b),"for","endfor");if(a.length===0)break;let y=a[0].content,g=b+a[0].end;if(!pe(c)){let A=u("For",`Unsafe expression in @for: ${c}`,n.UNSAFE_EXPRESSION);o=o.substring(0,b)+A+o.substring(g),s=!0;continue}try{let A=Oe(c),O=/@(?:for|foreach|if|unless)\s*\(/.test(y);if(A.length>0&&O){let K=ke({forExpr:c,content:y,iterVarNames:A,context:r,filePath:i,options:e});o=o.substring(0,b)+K+o.substring(g),s=!0;continue}let S=Object.keys(r),W=Object.values(r),I=ue(y),T=Function(...S,"__stxRenderLoopValue",`
|
|
2
|
+
import{R}from"./chunk-s29hp1qw.js";import{Re,Vt,se,B,Pn,ie,P}from"./chunk-7dzhar6y.js";import{Wi,lo,d,m,N,ht,p,uo,n,u,k}from"./chunk-295bykzd.js";import{wr}from"./chunk-6b17yg7a.js";import{fe}from"./chunk-d2pexm3z.js";import{Is}from"./chunk-cb0c6959.js";var he=1000,me=!1;function xe(t,r){let i=/@(include|partial)\s*\(\s*(['"])([^'"]+)\2\s*,\s*/g,e="",o=0,s;while((s=i.exec(t))!==null){let l=s.index+s[0].length,b=s.index+s[0].indexOf("("),x=k(t,"(",")",b);if(x===-1)continue;let f=t.slice(l,x).trim();if(!f)continue;if(!Object.keys(r).some((a)=>new RegExp(`(?:^|[^\\w$.])${a.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}(?![\\w$])`).test(f)))continue;let h;try{let a=N(f,r);if(!a||typeof a!=="object")continue;h=JSON.stringify(a)}catch{continue}e+=t.slice(o,l)+h,o=x,i.lastIndex=x}return o===0?t:e+t.slice(o)}function be(t,r){let i=/@component\s*\(/g,e=t,o,s=[];while((o=i.exec(e))!==null){let l=o.index,b=l+o[0].length-1,x=1,f=b+1;while(f<e.length&&x>0){if(e[f]==="(")x++;else if(e[f]===")"){if(x--,x===0)break}f++}if(x!==0)continue;let c=e.substring(b+1,f),h=f+1,a=c.match(/^\s*['"]([^'"]+)['"]/);if(!a)continue;let y=a[1],g=c.slice(a[0].length),A=g.match(/^\s*,\s*/);if(!A)continue;let O=g.slice(A[0].length).trim();if(!O)continue;try{let S=N(O,r),W=JSON.stringify(S),I=`@component('${y}', ${W})`;s.push({start:l,end:h,replacement:I})}catch{continue}}for(let l=s.length-1;l>=0;l--){let{start:b,end:x,replacement:f}=s[l];e=e.substring(0,b)+f+e.substring(x)}return e}function oe(t,r,i){let e=t,o=new RegExp(`${r.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\(`),s;while((s=o.exec(e))!==null){let l=s.index,b=l+s[0].length-1,x=1,f=b+1,c=null,h=!1;while(f<e.length&&x>0){let g=e[f];if(h){h=!1,f++;continue}if(g==="\\"&&c){h=!0,f++;continue}if(c){if(g===c)c=null;f++;continue}if(g==='"'||g==="'"||g==="`"){c=g,f++;continue}if(g==="(")x++;else if(g===")"){if(x--,x===0)break}f++}if(x!==0)break;let a=e.substring(b+1,f),y=i(a);e=e.substring(0,l)+y+e.substring(f+1)}return e}function ye(t,r){let i=t;return i=i.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)(?=\s+[^=]|\s*\/?>|\s*$)/g,(e,o)=>{if(o in r)return`:${o}="${o}"`;return e}),i=i.replace(/:([a-zA-Z_][a-zA-Z0-9_-]*)\s*=\s*"([^"]*)"/g,(e,o,s)=>{try{if(B(s,r.__stx_client_signal_names||[]))return e;let l=Object.keys(r),b=Object.values(r);Wi(s);let x=!1,c=p(s,l,()=>{x=!0})(...b);if(x)return e;let h=JSON.stringify(c);if(h===void 0){if(!ht(s).some((g)=>!(g in r)))return"";return e}let a=Buffer.from(h,"utf8").toString("base64");return`__stx_${o}="${a}"`}catch(l){return e}}),i}var Q="<!--__STX_BREAK__-->",ee="<!--__STX_CONTINUE__-->";function ae(t,r){let i=/\{\{\{?|\{!!|@(break|continue)(?![\w$])/g,e="",o=0;for(let s=i.exec(t);s;s=i.exec(t)){if(!s[1]){let f=s[0].length===3&&s[0]==="{{{"?3:2,c=s[0]==="{!!"?t.indexOf("!!}",i.lastIndex):Re(t,s.index,f);if(c<0)break;i.lastIndex=c+(s[0]==="{!!"?3:f);continue}let l=i.lastIndex,b=!0,x=/^\s*\(/.exec(t.slice(l));if(x){let f=l+x[0].length-1,c=k(t,"(",")",f);if(c<0)break;l=c+1;try{let h=`!!(${t.slice(f+1,c).trim()})`;b=m(h)?Boolean(p(h,Object.keys(r))(...Object.values(r))):Boolean(d(h,r))}catch{b=!1}}if(e+=t.slice(o,s.index),b)return e+(s[1]==="break"?Q:ee);o=l,i.lastIndex=l}return e+t.slice(o)}function ue(t){let r=(o)=>o.replace(/\\/g,"\\\\").replace(/`/g,"\\`").replace(/\$\{/g,"\\${"),i="",e=0;return Pn(t,(o,s,l)=>(i+=ce(r(t.slice(e,l))),i+=`\${__stxRenderLoopValue(${l}, (${s}), ${o.length})}`,e=l+o.length,o)),i+ce(r(t.slice(e)))}function ge(t,r,i,e){return ie(t,r,i==null?"":String(i),!1,e)}function ce(t){let r=t;return r=oe(r,"@break",(i)=>{let e=i.trim();if(!uo(e))return"";return`\`; if (${e}) { break; } result += \``}),r=oe(r,"@continue",(i)=>{let e=i.trim();if(!uo(e))return"";return`\`; if (${e}) { continue; } result += \``}),r=r.replace(/@break(?!\()/g,"`; break; result += `"),r=r.replace(/@continue(?!\()/g,"`; continue; result += `"),r}function Ee(t){let r=/@forelse\s*\(/g,i,e=[],o=/@foreach\s*\(/g,s=/@endforeach/g,l;while((l=o.exec(t))!==null)e.push({pos:l.index,delta:1});while((l=s.exec(t))!==null)e.push({pos:l.index,delta:-1});e.sort((c,h)=>c.pos-h.pos);let b=[],x=0;for(let c of e)x+=c.delta,b.push({pos:c.pos,depth:x});function f(c){let h=0,a=b.length-1,y=0;while(h<=a){let g=h+a>>1;if(b[g].pos<=c)y=b[g].depth,h=g+1;else a=g-1}return y}while((i=r.exec(t))!==null){if(f(i.index)>0)continue;let c=i.index,h=i.index+i[0].length-1,a=1,y=h+1,g=-1;while(y<t.length&&a>0){if(t[y]==="(")a++;else if(t[y]===")"){if(a--,a===0){g=y;break}}y++}if(g===-1)continue;let A=t.substring(h+1,g),O=Vt(A);if(!O)continue;let{arrayExpr:S,itemVar:W}=O,I=g+1,_=1,T=I,K=/@forelse\s*\(/g,C=/@endforelse/g,L=-1;while(_>0&&T<t.length){K.lastIndex=T,C.lastIndex=T;let F=K.exec(t),E=C.exec(t);if(!E)break;if(F&&F.index<E.index)_++,T=F.index+F[0].length;else{if(_--,_===0){L=E.index;break}T=E.index+11}}if(L===-1)continue;let w=t.substring(I,L),Z=L+11,z=-1,D=0,V=0;while(V<w.length){let F=w.indexOf("@",V);if(F===-1)break;let E=w.substring(F);if(/^@forelse\s*\(/.test(E))D++,V=F+1;else if(E.startsWith("@endforelse"))D--,V=F+11;else if(D===0&&E.startsWith("@empty")){if(w.length<=F+6||!/[a-z]/i.test(w[F+6])){z=F;break}V=F+1}else V=F+1}if(z===-1)continue;return{start:c,end:Z,arrayExpr:S,itemVar:W,foreachContent:w.substring(0,z),emptyContent:w.substring(z+6)}}return null}function le(t,r){let i=t;while(!0){let e=Ee(i);if(!e)break;let{start:o,end:s,arrayExpr:l,itemVar:b,foreachContent:x,emptyContent:f}=e;try{let c;if(m(l))c=p(l,Object.keys(r))(...Object.values(r));else c=d(l,r);let h;if(!Array.isArray(c)||c.length===0)h=f;else h=`@foreach (${l} as ${b})${x}@endforeach`;i=i.substring(0,o)+h+i.substring(s)}catch(c){let h=c instanceof Error?c.message:String(c),a=u("Forelse",`Error in @forelse(${l} as ${b}): ${h}`,n.EVALUATION_ERROR);i=i.substring(0,o)+a+i.substring(s)}}return i}var de="<!--stx:foreach-not-iterable:",_e=/<!--stx:foreach-not-iterable:([^|>]*)\|([^>]*?)-->/g;function $e(t,r){return`${de}${encodeURIComponent(t)}|${encodeURIComponent(r)}-->`}function Ae(t,r){console.warn(`[stx] @foreach(${t}) in ${r}: ${t} is not iterable server-side, so the loop rendered nothing. `+"Values a server loop reads must come from <script server> or the page context \u2014 "+"a plain <script> runs in the browser.")}function Es(t){if(!t.includes(de))return t;return t.replace(_e,(r,i,e)=>(Ae(decodeURIComponent(i),decodeURIComponent(e)),""))}function lg(t,r,i,e,o=!1){let s=ne(t,r,i,e,o),l=s.next();while(!l.done)l=s.next();return l.value}async function si(t,r,i,e,o=!1){let s=ne(t,r,i,e,o),l=s.next();while(!l.done)await R(),l=s.next();return l.value}function*ne(t,r,i,e,o=!1){let s=t,l=new Set(r.__stx_client_signal_names||[]);for(let c of wr(t))l.add(c);if(l.size)r={...r,__stx_client_signal_names:[...l]};s=le(s,r);function b(c){let h=/@foreach\s*\(/g,a;while((a=h.exec(c))!==null){let y=a.index,g=a.index+a[0].length-1,A=1,O=g+1,S=-1;while(O<c.length&&A>0){if(c[O]==="(")A++;else if(c[O]===")"){if(A--,A===0){S=O;break}}O++}if(S===-1)continue;let W=c.substring(g+1,S),I=Vt(W);if(!I)continue;let _=y,{arrayExpr:T,itemVar:K}=I,C=S+1,L=1,w=C,Z=/@foreach\s*\(/g,z=/@endforeach/g;while(L>0&&w<c.length){Z.lastIndex=w,z.lastIndex=w;let D=Z.exec(c),V=z.exec(c);if(!V)break;if(D&&D.index<V.index)L++,w=D.index+D[0].length;else{if(L--,L===0){let F=c.substring(C,V.index),E=V.index+11;return{start:_,end:E,arrayExpr:T,itemVar:K,content:F}}w=V.index+11}}}return null}function*x(c,h){let a=c;while(!0){let y=b(a);if(!y)break;let{start:g,end:A,arrayExpr:O,itemVar:S,content:W}=y;try{let I=O.trim(),_;if(m(I))_=p(I,Object.keys(h))(...Object.values(h));else _=d(I,h);let T=!1;if(!Array.isArray(_))if(_ instanceof Map)_=Array.from(_),T=!0;else if(_ instanceof Set)_=Array.from(_);else if(typeof _==="string")_=Array.from(_);else if(_&&typeof _==="object"&&!(_ instanceof Date)&&!(_ instanceof RegExp))_=Object.entries(_),T=!0;else{let E=$e(I,i)+u("Foreach",`Error in @foreach: ${I} is not iterable`,n.TYPE_ERROR);a=a.substring(0,g)+E+a.substring(A);continue}let K=e?.loops?.useAltLoopVariable??me,C=S.trim(),L=null,w,Z=!1;if(C.includes("=>")){let E=C.split("=>").map((j)=>j.trim());if(E.length===2&&E[0]&&E[1])L=E[0],w=E[1];else w=C}else if(!C.startsWith("[")&&!C.startsWith("{")&&C.includes(",")){let E=C.split(",").map((j)=>j.trim());if(E.length===2&&E[0]&&E[1])w=E[0],L=E[1],Z=!0;else w=C}else w=C;let z="",D=new Set(se(`${O} as ${S}`)),V=_,F=h[lo]??new WeakMap;for(let E=0;E<V.length;E++){if(E%16===0)yield;let j=V[E],te={index:E,iteration:E+1,first:E===0,last:E===V.length-1,count:V.length},M={...h,loop:te,$loop:te,[lo]:F};if(Array.isArray(h.__stx_client_signal_names))M.__stx_client_signal_names=h.__stx_client_signal_names.filter((H)=>!D.has(H));if(w.startsWith("[")&&w.endsWith("]")){let H=w.slice(1,-1).split(",").map((U)=>U.trim());if(Array.isArray(j))H.forEach((U,X)=>{if(U)M[U]=j[X]});else M[w]=j}else if(w.startsWith("{")&&w.endsWith("}")){let H=w.slice(1,-1).split(",").map((U)=>U.trim()).filter(Boolean);if(j!==null&&typeof j==="object")H.forEach((U)=>{let X=U.indexOf(":"),Y=(X===-1?U:U.slice(0,X)).trim(),re=X===-1?Y:U.slice(X+1).trim();if(Y&&re)M[re]=j[Y]});else M[w]=j}else M[w]=j;if(L)if(!Z&&T&&Array.isArray(j)&&j.length===2)M[L]=j[0],M[w]=j[1];else M[L]=E;let v=le(W,M);v=yield*ne(v,M,i,e,!0),v=fe(v,M,i),v=ae(v,M);let J=v.indexOf(Q),G=v.indexOf(ee),q=J<0?G:G<0?J:Math.min(J,G);if(q>=0)v=v.slice(0,q);if(v=P(v,M,i),v=ye(v,M),v=be(v,M),v=xe(v,M),z+=v,q>=0&&q===J)break}a=a.substring(0,g)+z+a.substring(A)}catch(I){let _=u("Foreach",`Error in @foreach(${O.trim()} as ${S.trim()}): ${I instanceof Error?I.message:String(I)}`,n.EVALUATION_ERROR);a=a.substring(0,g)+_+a.substring(A)}}return a}s=yield*x(s,r),s=we(s,r,i,e);let f=e?.loops?.maxWhileIterations??he;return s=Ie(s,r,f),o?s:Es(s)}function ug(t){let r=/^(\s*)([A-Za-z_$][\w$]*|\[[^\]]*\]|\{[^}]*\})(\s+(?:of|in)\s)/.exec(t);if(!r||/^(?:const|let|var)$/.test(r[2]))return t;return`${r[1]}let ${t.slice(r[1].length)}`}function pe(t){return uo(t)}function we(t,r,i,e){let o=t,s=!0;while(s){s=!1;let l=o.match(/@for\s*\(/);if(!l||l.index===void 0)break;let b=l.index,x=b+l[0].length-1,f=k(o,"(",")",x);if(f===-1)break;let c=ug(o.slice(x+1,f)),h=f+1,a=Is(o.slice(b),"for","endfor");if(a.length===0)break;let y=a[0].content,g=b+a[0].end;if(!pe(c)){let A=u("For",`Unsafe expression in @for: ${c}`,n.UNSAFE_EXPRESSION);o=o.substring(0,b)+A+o.substring(g),s=!0;continue}try{let A=Oe(c),O=/@(?:for|foreach|if|unless)\s*\(/.test(y);if(A.length>0&&O){let K=ke({forExpr:c,content:y,iterVarNames:A,context:r,filePath:i,options:e});o=o.substring(0,b)+K+o.substring(g),s=!0;continue}let S=Object.keys(r),W=Object.values(r),I=ue(y),T=Function(...S,"__stxRenderLoopValue",`
|
|
3
3
|
let result = '';
|
|
4
4
|
for (${c}) {
|
|
5
5
|
result += \`${I}\`;
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{xt,St,kt}from"./chunk-zek9t5za.js";import"./chunk-
|
|
2
|
+
import{xt,St,kt}from"./chunk-zek9t5za.js";import"./chunk-n22xtagg.js";import"./chunk-hxhmhw23.js";import"./chunk-s29hp1qw.js";import"./chunk-kwf3kfr0.js";import{h}from"./chunk-7dzhar6y.js";import"./chunk-295bykzd.js";import"./chunk-6t04tqvh.js";import"./chunk-a4e4xbpd.js";import{tn,vo,nn,ga,vt,ma,xo,rn,ya,sn}from"./chunk-g2xy0z0e.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{ma("Config file changed, restarting...");try{await e.onChange()}catch(p){vt(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),u=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,f=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:f,variantViews:n,avgTimeSpent:u}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",ct=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:ct,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:dt(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function dt(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
|
|
3
3
|
<script>
|
|
4
4
|
(function() {
|
|
5
5
|
const ws = new WebSocket('${t}');
|
|
@@ -556,7 +556,7 @@ window.__stxPerformance = {
|
|
|
556
556
|
|
|
557
557
|
window.clearPerformanceMetrics = () => window.__stxPerformance.clear();
|
|
558
558
|
</script>
|
|
559
|
-
`}import T from"fs";import K from"path";var lt=".stx/story/presets.json",R=1,mt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ut(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,mt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ut(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-
|
|
559
|
+
`}import T from"fs";import K from"path";var lt=".stx/story/presets.json",R=1,mt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ut(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,mt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ut(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-85c2vh7f.js"),p={},u=y(n);if(u)try{await h(u,p,e)}catch(g){o.push(`Warning: Could not extract script variables: ${g instanceof Error?g.message:String(g)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),m=y(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:m,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function gt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=y(e);if(!r)return null;let s={};if(await h(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await gt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return ft(t,a.source,c);return b(t,e.path,{props:c})}async function ft(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-85c2vh7f.js"),c={...r},n=y(e);if(n)try{await h(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:y(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
560
560
|
`)}function Q(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/^\s*\n/gm,"").trim()}function y(t){let e=[],r=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
561
561
|
`)}function tt(t,e){let r=`<script>window.__stxProps = ${JSON.stringify(e)};</script>`;return t+r}function et(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function rt(t,e){let r=await rn(t);St(t,r);let s=sn(t.config,r);kt(t,s),console.log(` Found ${r.length} story files`);let o=typeof e.host==="string"?e.host:e.host===!0?"0.0.0.0":"localhost",a=new I(t.root),c=new P(t.root),n=new k(t.root),d=N(),p=Bun.serve({port:e.port,hostname:o,fetch:async(i,l)=>{let g=new URL(i.url).pathname;if(g==="/__hmr"){if(l.upgrade(i,{data:{isHmr:!0}}))return;return new Response("WebSocket upgrade failed",{status:400})}if(g.startsWith("/api/"))return yt(t,g,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return ht(t,g,e.port)},websocket:{open(i){d.open(i)},close(i){d.close(i)},message(i,l){d.message(i,l)}}}),u=`http://${o}:${e.port}`,f=ya(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let m=await rn(t);St(t,m);let g=sn(t.config,m);if(kt(t,g),i==="add")H(l.id,{fileName:l.fileName});else if(i==="unlink")O(l.id);else V(l.id,{fileName:l.fileName})});if(e.open){let i=u;try{let{exec:l}=await import("child_process"),m=process.platform;l(`${m==="darwin"?"open":m==="win32"?"start":"xdg-open"} ${i}`)}catch{}}return{server:p,url:u,close:async()=>{f(),p.stop()}}}async function yt(t,e,r,s){let{presetsManager:o,bookmarksManager:a,analyticsTracker:c}=s;if(e==="/api/stories")return Response.json({files:t.storyFiles.map((n)=>({id:n.id,fileName:n.fileName,relativePath:n.relativePath,treePath:n.treePath})),tree:t.tree});if(e.startsWith("/api/story/")){let n=e.slice(11),d=t.storyFiles.find((p)=>p.id===n);if(!d)return new Response("Story not found",{status:404});try{let p=await Bun.file(d.path).text();return Response.json({id:d.id,fileName:d.fileName,relativePath:d.relativePath,content:p})}catch{return new Response("Error reading story",{status:500})}}if(e==="/api/config")return Response.json({theme:t.config.theme,responsivePresets:t.config.responsivePresets,backgroundPresets:t.config.backgroundPresets});if(e.startsWith("/api/render/")){let n=new URL(r.url),d=e.slice(12).split("/"),p=d[0],u=d[1]||"default",f,i=n.searchParams.get("props");if(i)try{f=JSON.parse(i)}catch{}let l=t.storyFiles.find((m)=>m.id===p);if(!l)return new Response("Story not found",{status:404});try{let m=await Y(t,l,u,f);return Response.json({html:m.html,css:m.css,js:m.js,errors:m.errors,duration:m.duration})}catch(m){return Response.json({html:"",css:"",js:"",errors:[m instanceof Error?m.message:String(m)],duration:0},{status:500})}}if(e==="/api/presets"&&r.method==="GET")return Response.json({presets:o.getAllPresets()});if(e==="/api/presets"&&r.method==="POST")try{let n=await r.json(),d=o.createPreset(n.name,n.props,{componentId:n.componentId,description:n.description});return await o.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/presets/")&&!e.includes("/use")&&r.method==="GET"){let n=e.slice(13),d=o.getPreset(n);if(!d)return new Response("Preset not found",{status:404});return Response.json(d)}if(e.endsWith("/use")&&r.method==="POST"){let n=e.slice(13,-4),d=o.usePreset(n);if(!d)return new Response("Preset not found",{status:404});return await o.save(),Response.json(d)}if(e.startsWith("/api/presets/")&&r.method==="DELETE"){let n=e.slice(13);if(!o.deletePreset(n))return new Response("Preset not found",{status:404});return await o.save(),Response.json({success:!0})}if(e==="/api/bookmarks"&&r.method==="GET")return Response.json({bookmarks:a.getAllBookmarks()});if(e==="/api/bookmarks"&&r.method==="POST")try{let n=await r.json(),d=a.addBookmark(n.storyId,n.variantId,n.props,{name:n.name,notes:n.notes,color:n.color});return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/bookmarks/toggle"&&r.method==="POST")try{let n=await r.json(),d=a.toggleBookmark(n.storyId,n.variantId,n.props);return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/bookmarks/")&&e!=="/api/bookmarks/toggle"&&r.method==="GET"){let n=e.slice(15),d=a.getBookmark(n);if(!d)return new Response("Bookmark not found",{status:404});return Response.json(d)}if(e.startsWith("/api/bookmarks/")&&r.method==="DELETE"){let n=e.slice(15);if(!a.deleteBookmark(n))return new Response("Bookmark not found",{status:404});return await a.save(),Response.json({success:!0})}if(e==="/api/analytics/track"&&r.method==="POST")try{let n=await r.json();if(n.type==="view"&&n.componentId)c.trackView(n.componentId,n.variantId);else if(n.type==="prop_change"&&n.componentId&&n.propName)c.trackPropChange(n.componentId,n.propName,null);else if(n.type==="variant_switch"&&n.componentId&&n.variantId)c.trackVariantSwitch(n.componentId,n.variantId);else if(n.type==="search"&&n.query)c.trackSearch(n.query,0);return await c.save(),Response.json({success:!0})}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/analytics/summary"&&r.method==="GET")return Response.json({mostViewed:c.getMostViewedComponents(10),mostChangedProps:c.getMostChangedProps(10),searchAnalytics:c.getSearchAnalytics()});if(e.startsWith("/api/analytics/component/")&&r.method==="GET"){let n=e.slice(25),d=t.storyFiles.find((u)=>u.id===n),p=c.getComponentAnalytics(n,d?.fileName||n);return Response.json(p)}return new Response("Not found",{status:404})}function ht(t,e,r){let s=bt(t,r);return new Response(s,{headers:{"Content-Type":"text/html; charset=utf-8"}})}function bt(t,e){let{theme:r}=t.config,s=r.title||"STX Story",o=`ws://localhost:${e}/__hmr`,a=F(o);return`<!DOCTYPE html>
|
|
562
562
|
<html lang="en" class="${r.darkClass||"dark"}">
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ae,Li,ji,Ng,Kt,bl,Mg,wl,Cy,qe,Rn,Ke}from"./chunk-
|
|
2
|
+
import{Ae,Li,ji,Ng,Kt,bl,Mg,wl,Cy,qe,Rn,Ke}from"./chunk-7dzhar6y.js";import"./chunk-a4e4xbpd.js";import"./chunk-6t04tqvh.js";import"./chunk-295bykzd.js";import"./chunk-hxhmhw23.js";import"./chunk-kwf3kfr0.js";import{Dl,t}from"./chunk-zpj6ggee.js";import"./chunk-s29hp1qw.js";import"./chunk-n22xtagg.js";export{Ae as BROWSER_CORE_IMPORTS,Ng as STX_AUTO_IMPORTS,Li as extractAndStripCssImports,qe as extractBridgeData,Dl as findInterpolationEnd,wl as generateAutoImportDestructuring,Cy as generateBrowserAutoImportDestructuring,Rn as generateServerDataBridge,Kt as injectBrowserCoreAutoImports,Ke as processClientScript,Mg as referencesName,ji as renderVendorStyleTags,t as stripCommentsAndLiterals,bl as transformAutoImports};
|
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{S,
|
|
3
|
-
${l.trim()}`)}catch(l){console.warn(`[stx] Failed to load composable ${o}:`,l)}if(F.length===0||
|
|
4
|
-
`),O=JSON.stringify([...
|
|
2
|
+
import{S,C,A,Ie,J,Qs,oe}from"./chunk-7dzhar6y.js";import{De}from"./chunk-kwf3kfr0.js";import{_}from"./chunk-n22xtagg.js";import{M,jn}from"./chunk-hxhmhw23.js";import{a}from"./chunk-6g6pxww1.js";import{Ce,hn,yn,bn}from"./chunk-ftsv4h6f.js";import{Pt}from"./chunk-6b17yg7a.js";import{Tt,er,ln,be}from"./chunk-97kgrevs.js";import{Z}from"./chunk-c47stwqj.js";import{I,et}from"./chunk-ws2h92mm.js";import y from"path";var B=new Map,P=new Map,R=S(64),T=new Map,te=["composables","functions"];function W(e){let s=y.basename(e,".ts");return s==="index"||s==="types"||e.endsWith(".d.ts")}async function ne(e){if(e)return y.resolve(e);let s=`<default>:${process.cwd()}`,i=T.get(s);if(i!==void 0)return i;let t=await se();if(t!==null)T.set(s,t);return t}async function se(){let e=await a(),s=e.root||process.cwd(),i=e.composablesDir;if(i)return y.resolve(s,i);for(let t of te){let n=y.resolve(s,t);try{let c=new Bun.Glob("**/*.ts");for await(let r of c.scan({cwd:n,absolute:!0}))if(!W(r))return n}catch{}}return null}async function X(e){let s=Array.isArray(e)?e:e?[y.resolve(e)]:(await a())._layerComposableDirs??[await ne()].filter((t)=>!!t),i=new Map;for(let t of s){let n=new Bun.Glob("**/*.ts");try{for await(let c of n.scan({cwd:t,absolute:!0})){let r=y.relative(t,c);if(!W(c)&&!i.has(r))i.set(r,c)}}catch{}}return{key:s.join("\x00"),files:[...i.values()].sort()}}async function Lo(e){let{files:s}=await X(e),i=oe({loader:"ts",target:"browser",define:A()}),t=[];for(let n of s)try{let c=await Bun.file(n).text(),r=i.scan(c).exports.filter((d)=>d!=="default");if(r.length>0)t.push({file:n,names:r})}catch{}return t}function re(e,s){return new RegExp(`\\b${s.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\b`).test(e)}function Q(e,s){let i=new Set(e.match(/\w+/g)),t=new Set;for(let n of s)if(/^\w+$/.test(n)?i.has(n):re(e,n))t.add(n);return t}var H=S(64);function U(e,s){let i=C(e,s.size),t=H.get(i);if(t)return t;let n;try{n=De(e,s)}catch{n=Q(e,s)}let c=[...e.matchAll(/(?:const|let|var)\s*\{([^}]*)\}\s*=\s*window\.__composables\u0008/g),...e.matchAll(/import\s*\{([^}]*)\}\s*from\s*['"]@composables['"]/g)];for(let r of c)for(let d of r[1].split(",")){let f=d.trim().split(/\s*(?::|\u0008as\u0008)\s*/)[0];if(f&&s.has(f))n.add(f)}return H.set(i,n),n}function ie(e){return!e||/^(?:module|(?:text|application)\/(?:java|ecma)script|application\/stx-[\w-]+)$/i.test(e)}var q=S(256);function ae(e,s){let i=new Set(s),t="",n=0,c=new Set;for(let r of Ie(e)){t+=e.slice(n,r.start),n=r.end;let d=J(r.attrs),f=e.slice(r.bodyStart,r.bodyEnd),u=d.get("type"),m=typeof u==="string"?u.trim():void 0;if(!ie(m)){if(!/json/i.test(m??""))t+=` ${f} `;continue}let x=Q(f,i);if(x.size===0)continue;let b=C(f,[...x].sort().join(",")),w=q.get(b);if(!w)w=U(f,x),q.set(b,w);for(let j of w)c.add(j)}t+=e.slice(n);for(let r of Qs(t))for(let d of U(r.code,i))c.add(d);return c}function ce(e,s,i){let t=new Map;for(let{file:f,names:u}of e)for(let m of u)if(!t.has(m))t.set(m,f);let n=new Set(t.keys()),c=(f)=>{let u=[];for(let m of U(f,n))u.push(t.get(m));return u},r=new Set,d=i.flatMap((f,u)=>u===0?[...ae(f,t.keys())].map((m)=>t.get(m)):c(f));while(d.length>0){let f=[];for(let u of d){if(r.has(u))continue;r.add(u);for(let m of c(s.get(u)??""))if(!r.has(m))f.push(m)}d=f}return r}async function jh(e,s,i,t){let{key:n,files:c}=await X(e);if(!n)return null;let r=()=>[...new Set([...c,...c.flatMap((o)=>Ce(o))])],d=Tt(r());if(c.length===0)return be(B,n,d,""),null;c.sort();let f=oe({loader:"ts",target:"browser",define:A()}),u=ln(P,n,d);if(!u){let o=new Map,l=[];for(let p of c)try{let v=await Bun.file(p).text();o.set(p,v);let g=f.scan(v).exports.filter((ee)=>ee!=="default");if(g.length>0)l.push({file:p,names:g})}catch{o.set(p,"")}u=be(P,n,d,{codeByFile:o,modules:l})}let{codeByFile:m,modules:x}=u,b;if(s===void 0)b=new Set(c);else{let o=i?[s,...i]:[s],l=C(o.join("\x00"),n,o.length,d),p=R.get(l);if(b=p??ce(x,m,o),!p)R.set(l,b)}if(b.size===0)return null;let w=c.filter((o)=>b.has(o)),j=()=>{if(!t)return;for(let o of w)t.push(o,...Ce(o))},E=`${n}\x00${w.join("\x00")}\x00${yn()}`,z=ln(B,E,d);if(z!==void 0)return j(),z||null;let F=[],N=new Set,K=new Set;for(let o of w)try{let l=m.get(o)??await Bun.file(o).text(),p=y.basename(o,".ts");for(let g of l.matchAll(/\b(?:const|let|var|function|class)\s+([A-Z_a-z$][\w$]*)/g))if(g[1])K.add(g[1]);let v=[];try{for(let g of f.scan(l).exports)if(g!=="default")N.add(g),v.push(g)}catch{}if(l=M(l),hn(l))l=await bn(l,o,{projectRoot:process.cwd(),externalizeUserModules:!1,expose:v}),l=Pt(l);l=jn(l),l=l.replace(/^export\s+(default\s+)?/gm,""),l=f.transformSync(l),F.push(`// Composable: ${p}
|
|
3
|
+
${l.trim()}`)}catch(l){console.warn(`[stx] Failed to load composable ${o}:`,l)}if(F.length===0||N.size===0)return be(B,E,d,""),null;let V=[...N].map((o)=>` try { if (!(${JSON.stringify(o)} in __c)) __c[${JSON.stringify(o)}] = ${o}; } catch (e) {}`).join(`
|
|
4
|
+
`),O=JSON.stringify([...N]),k=F.join(`
|
|
5
5
|
|
|
6
|
-
`),Y=
|
|
7
|
-
`),h=JSON.stringify(new Bun.CryptoHasher("md5").update(`${O}\x00${
|
|
6
|
+
`),Y=_.filter((o)=>!K.has(o)&&new RegExp(`\\b${o}\\b`).test(k)).map((o)=>`var ${o} = __stx[${JSON.stringify(o)}];`).join(`
|
|
7
|
+
`),h=JSON.stringify(new Bun.CryptoHasher("md5").update(`${O}\x00${k}`).digest("hex").slice(0,12)),D=Z(k),G=`;${D?"await (async function":"(function"}(){
|
|
8
8
|
var __bundles = window.__stxComposableBundles || (window.__stxComposableBundles = {});
|
|
9
|
-
if (__bundles[${h}]) { ${
|
|
10
|
-
${
|
|
9
|
+
if (__bundles[${h}]) { ${D?"await __bundles["+h+"];":""} return; }
|
|
10
|
+
${D?`var __resolveBundle, __rejectBundle;
|
|
11
11
|
__bundles[${h}]=new Promise(function(resolve,reject){__resolveBundle=resolve;__rejectBundle=reject;});
|
|
12
12
|
__bundles[${h}].catch(function(){});
|
|
13
13
|
try {`:`__bundles[${h}] = true;`}
|
|
@@ -16,7 +16,7 @@ window.__composables = window.__composables || {};
|
|
|
16
16
|
var __c = window.__composables;
|
|
17
17
|
var __stx = window.stx || {};
|
|
18
18
|
${Y}
|
|
19
|
-
${
|
|
19
|
+
${k}
|
|
20
20
|
${V}
|
|
21
21
|
var __names = ${O};
|
|
22
22
|
for (var __i = 0; __i < __names.length; __i++) {
|
|
@@ -32,7 +32,7 @@ ${V}
|
|
|
32
32
|
window[__n] = __c[__n];
|
|
33
33
|
__published[__n] = true;
|
|
34
34
|
}
|
|
35
|
-
${
|
|
35
|
+
${D?`__resolveBundle();
|
|
36
36
|
} catch(error) { delete __bundles[${h}]; __rejectBundle(error); throw error; }`:""}
|
|
37
|
-
})();`,L=I()?et(G):G;return d=Tt(r()),be(B,
|
|
37
|
+
})();`,L=I()?et(G):G;return d=Tt(r()),be(B,E,d,L),j(),L}function Bh(){B.clear(),er(),P.clear(),R.clear(),T.clear()}
|
|
38
38
|
export{Lo,jh,Bh};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{fg,dy,py,fy,gy,gg,mg,my,hy,fi,yy,Sr,kr,Os}from"./chunk-
|
|
2
|
+
import{fg,dy,py,fy,gy,gg,mg,my,hy,fi,yy,Sr,kr,Os}from"./chunk-7fhtvgqc.js";import{ft}from"./chunk-6c1vm6bs.js";import"./chunk-7dzhar6y.js";import"./chunk-a4e4xbpd.js";import"./chunk-6t04tqvh.js";import"./chunk-295bykzd.js";import"./chunk-hxhmhw23.js";import"./chunk-kwf3kfr0.js";import"./chunk-s29hp1qw.js";import"./chunk-n22xtagg.js";export{gy as __setSignalsGeneratorsForTest,ft as cacheEngineFingerprint,kr as cacheTemplate,Sr as checkCache,yy as clearDevCaches,mg as getCachedRouterScript,gg as getCachedSignalsRuntime,my as getServeClientAsset,fi as getServeModuleBundle,Os as hashFilePath,py as invalidateFileCache,fy as invalidateFileCacheByDir,dy as readFileCached,hy as registerServeModuleBundle,fg as templateCache};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ql,eu}from"./chunk-zzpg1bg5.js";import"./chunk-94ctmp0j.js";import"./chunk-vpztm6vk.js";import"./chunk-nmf70gbp.js";import"./chunk-vkswqg3s.js";import"./chunk-4n45qa0b.js";import"./chunk-czcx3nbx.js";import"./chunk-6n9y8faw.js";import"./chunk-wmd952xa.js";import"./chunk-zpe4zz7r.js";import"./chunk-2r0nrvqe.js";import"./chunk-q1mb0fbt.js";import"./chunk-pdprhg5k.js";import"./chunk-d1xx1jy5.js";import"./chunk-q74affc4.js";import"./chunk-gbncp2gp.js";import"./chunk-yp4tn4zn.js";import"./chunk-8va3fs07.js";import"./chunk-sv7fdqmc.js";import"./chunk-a7ryj8z8.js";import"./chunk-cd5kgd3s.js";import"./chunk-1ey78497.js";import"./chunk-aaea157p.js";import"./chunk-8e1cv1hh.js";import"./chunk-ybjgnnyf.js";import"./chunk-a0q0kb0s.js";import"./chunk-5fjs602p.js";import"./chunk-z83pyccp.js";import"./chunk-fg67643b.js";import"./chunk-jkg6ns57.js";import"./chunk-kee5a3ce.js";import"./chunk-59er0fc7.js";import{fn}from"./chunk-38xckpr9.js";import{Qf}from"./chunk-ftsv4h6f.js";import"./chunk-agqj0z54.js";import"./chunk-9f31gs4m.js";import{ze,i}from"./chunk-3hwdg5mf.js";import"./chunk-rs84k601.js";import"./chunk-56kd82yp.js";import"./chunk-c0g30cjs.js";import"./chunk-8cyg4602.js";import"./chunk-arf21n16.js";import"./chunk-xma57d6t.js";import"./chunk-d2pexm3z.js";import"./chunk-6b17yg7a.js";import{$e}from"./chunk-q396f1wc.js";import"./chunk-cb0c6959.js";import{Sr,kr}from"./chunk-7fhtvgqc.js";import"./chunk-c47stwqj.js";import{Ms,W,a}from"./chunk-6g6pxww1.js";import"./chunk-rvcce9zt.js";import"./chunk-h63ma36g.js";import"./chunk-ssg6ne5b.js";import"./chunk-0rdh8bw3.js";import"./chunk-agd2b928.js";import{j,h,Ke}from"./chunk-7dzhar6y.js";import"./chunk-a4e4xbpd.js";import"./chunk-6t04tqvh.js";import"./chunk-295bykzd.js";import"./chunk-hxhmhw23.js";import"./chunk-kwf3kfr0.js";import"./chunk-s29hp1qw.js";import"./chunk-n22xtagg.js";import{ra}from"./chunk-xpbakn6t.js";import"./chunk-463weehv.js";import"./chunk-shcnt6aa.js";export{Ms as buildWebComponents,kr as cacheTemplate,Sr as checkCache,fn as classifyAllScripts,Ql as createMiddleware,eu as createRoute,W as defaultConfig,h as extractVariables,j as findSfcTemplateBlock,$e as injectRouterScript,ra as insertBeforeBodyClose,a as loadStxConfig,Ke as processClientScript,i as processDirectives,ze as readMarkdownFile,Qf as withinBundlerCallback};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{gu,Um,mu,hu,Wm,qm}from"./chunk-d1xx1jy5.js";import"./chunk-7dzhar6y.js";import"./chunk-a4e4xbpd.js";import"./chunk-6t04tqvh.js";import"./chunk-295bykzd.js";import"./chunk-hxhmhw23.js";import"./chunk-kwf3kfr0.js";import"./chunk-s29hp1qw.js";import"./chunk-n22xtagg.js";export{qm as applySlots,Wm as extractSlotContent,Um as parseSlotElement,gu as parseSlots,hu as processSlots,mu as renderSlot};
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Dn}from"./chunk-295bykzd.js";import{j,Q,w,Wt,qt,Lr,h,Cl,Fi,Y,O}from"./chunk-
|
|
2
|
+
import{Dn}from"./chunk-295bykzd.js";import{j,Q,w,Wt,qt,Lr,h,Cl,Fi,Y,O}from"./chunk-7dzhar6y.js";import{fn}from"./chunk-38xckpr9.js";import{r}from"./chunk-arf21n16.js";import{te}from"./chunk-ws2h92mm.js";import{D,c}from"./chunk-xpbakn6t.js";var X=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function J(t){let s=[],e=/<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|template)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,n;while((n=e.exec(t))!==null)s.push({start:n.index,end:n.index+n[0].length});return s}function F(t,s){return s.some((e)=>t>=e.start&&t<e.end)}function K(t){let s=(t||"").trim();if(!s)return null;if(/[\s>+~,:]/.test(s))return null;let e={},n=s,i=n.match(/^[a-z][\w-]*/i);if(i)e.tag=i[0].toLowerCase(),n=n.slice(i[0].length);while(n.length>0){let o=n.match(/^\[([\w-]+)(?:=(["']?)([^\]"']*)\2)?\]/);if(o){if(e.attr=o[1],o[3]!==void 0&&o[3]!=="")e.attrValue=o[3];n=n.slice(o[0].length);continue}let l=n.match(/^#([\w-]+)/);if(l){e.id=l[1],n=n.slice(l[0].length);continue}let a=n.match(/^\.([\w-]+)/);if(a){e.className=a[1],n=n.slice(a[0].length);continue}return null}if(!e.tag&&!e.attr&&!e.id&&!e.className)return null;return e}function Z(t,s){if(s.attr){if(!(s.attrValue===void 0?new RegExp(`\\b${s.attr}(?=[\\s=>/]|$)`,"i"):new RegExp(`\\b${s.attr}\\s*=\\s*(["'])\\s*${s.attrValue}\\s*\\1`,"i")).test(t))return!1}if(s.id){if(!new RegExp(`\\bid\\s*=\\s*(["'])\\s*${s.id}\\s*\\1`,"i").test(t))return!1}if(s.className){let e=t.match(/\bclass\s*=\s*(["'])([\s\S]*?)\1/i);if(!e)return!1;if(!e[2].split(/\s+/).includes(s.className))return!1}return!0}function P(t,s="main"){let e=K(s);if(!e)return null;let n=/<([a-z][\w-]*)\b([^>]*)>/gi,i=J(t),o;while((o=n.exec(t))!==null){if(F(o.index,i))continue;let l=o[1].toLowerCase(),a=o[2]||"";if(a.trimEnd().endsWith("/")||X.has(l))continue;if(e.tag&&e.tag!==l)continue;if(!Z(a,e))continue;let u=o[0],g=o.index+u.length,f=new RegExp(`<(/?)${l}\\b([^>]*)>`,"gi");f.lastIndex=g;let d=1,x;while((x=f.exec(t))!==null){if(F(x.index,i))continue;let y=x[1]==="/";if(!y&&(x[2]||"").trimEnd().endsWith("/"))continue;if(d+=y?-1:1,d===0)return{openTag:u,openIndex:o.index,start:g,end:x.index,tagName:l}}return null}return null}var Ct="private, no-store";function an(t){return t.replace(/&#(\d+);/g,(s,e)=>L(Number(e),s)).replace(/&#x([0-9a-f]+);/gi,(s,e)=>L(Number.parseInt(e,16),s)).replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")}function L(t,s){if(!Number.isInteger(t)||t<0||t>1114111)return s;try{return String.fromCodePoint(t)}catch{return s}}function Le(t){return t.headers.get("X-STX-Router")==="true"}function tt(t,s){if(!t)return s;return t.split(",").some((n)=>n.trim().toLowerCase()===s.toLowerCase())?t:`${t}, ${s}`}function V(t){return{Vary:tt(t,"X-STX-Router")}}function E(t){return t.replace(/"/g,""").replace(/</g,"<").replace(/>/g,">")}function H(t){let s=/<head\b[^>]*>([\s\S]*?)<\/head\s*>/i.exec(t)?.[1]??"",e=/<(meta|link)\b(?:[^>"']|"[^"]*"|'[^']*')*>|<title\b[^>]*>[\s\S]*?<\/title\s*>/giy;return w(s,(n,i)=>(e.lastIndex=i,e.exec(n)?e.lastIndex:-1)).map(({token:n})=>n)}function B(t){let s=Object.create(null),e=t.replace(/^<\w+\b|>$/g,"");for(let n of e.matchAll(/([^\s=/>]+)(?:\s*=\s*(?:"([^"]*)"|'([^']*)'|([^\s"'=<>`]+)))?/g)){let i=n[1].toLowerCase();if(!(i in s))s[i]=n[2]??n[3]??n[4]??""}return s}function Vn(t){let s=[];for(let e of H(t)){if(/^<title\b/i.test(e)){s.push(`<title>${E(e.replace(/^<title\b[^>]*>|<\/title\s*>$/gi,""))}</title>`);continue}let n=B(e);if(/^<meta\b/i.test(e)){let i=n.property?"property":"name",o=an(n[i]??"").toLowerCase();if(o==="description"||/^(?:og|twitter):[\w:]+$/.test(o))s.push(`<meta ${i}="${r(o)}" content="${E(n.content??"")}">`)}else{let i=an(n.rel??"").toLowerCase();if(i==="canonical"||i==="alternate"&&n.hreflang)s.push(`<link rel="${i}" href="${E(n.href??"")}"${i==="alternate"?` hreflang="${E(n.hreflang)}"`:""}>`)}}return`<template data-stx-page-head="1">${s.join("")}</template>
|
|
3
3
|
`}var et=["media","crossorigin","integrity"];function Un(t){let s=[];for(let e of H(t)){if(!/^<link\b/i.test(e))continue;let n=B(e);if(an(n.rel??"").trim().toLowerCase()!=="stylesheet")continue;if(!n.href||"data-css"in n||"disabled"in n)continue;let i=et.filter((o)=>(o in n)).map((o)=>` ${o}="${E(n[o])}"`).join("");s.push(`<link rel="stylesheet" href="${E(n.href)}"${i}>`)}return s.length?`<template data-stx-page-css="1">${s.join("")}</template>
|
|
4
|
-
`:""}import T from"path";var st="stx-page-head:",it=/<!--stx-page-head:([A-Za-z0-9+/=]+)-->\n?/,_={dev:null,prod:null};function ot(){let t=te()?"dev":"prod",s=_[t];if(s!==null)return s;try{let e=import.meta.require("./chunk-1z6rrqvm.js"),n=t==="dev"&&typeof e.getRouterScriptDev==="function"?e.getRouterScriptDev:e.getRouterScript;_[t]=`<script>${n()}</script>`}catch{_[t]=""}return _[t]}async function Aa(t,s){if(s===!1)return null;if(s&&typeof s==="string"){let n=T.resolve(t,s);if(await Bun.file(n).exists())return n;return null}let e=T.join(t,"app.stx");if(await Bun.file(e).exists())return e;return null}async function Oo(t,s){try{let e=await Bun.file(t).text(),n=e,i=j(e);if(i)n=i.content.trim();let o=fn(e),l=[...o.client.map((p)=>p.fullTag),...o.signals.map((p)=>p.fullTag)],a=[],u=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,g;while((g=u.exec(e))!==null)a.push(g[0]);let f=n;for(let p of o.server)f=f.replace(p.fullTag,"");for(let p of o.client)f=f.replace(p.fullTag,"");f=f.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"");let d="<!--__STX_PAGE_SLOT__-->";if(f=f.replace(/<slot\s*\/>/gi,d).replace(/<slot\s*>\s*<\/slot>/gi,d),!f.includes(d))return console.warn(`[stx] Shell ${t} has no <slot /> \u2014 pages won't be injected`),null;let{processDirectives:x,extractVariables:y,defaultConfig:R,loadStxConfig:b}=await import("./chunk-
|
|
4
|
+
`:""}import T from"path";var st="stx-page-head:",it=/<!--stx-page-head:([A-Za-z0-9+/=]+)-->\n?/,_={dev:null,prod:null};function ot(){let t=te()?"dev":"prod",s=_[t];if(s!==null)return s;try{let e=import.meta.require("./chunk-1z6rrqvm.js"),n=t==="dev"&&typeof e.getRouterScriptDev==="function"?e.getRouterScriptDev:e.getRouterScript;_[t]=`<script>${n()}</script>`}catch{_[t]=""}return _[t]}async function Aa(t,s){if(s===!1)return null;if(s&&typeof s==="string"){let n=T.resolve(t,s);if(await Bun.file(n).exists())return n;return null}let e=T.join(t,"app.stx");if(await Bun.file(e).exists())return e;return null}async function Oo(t,s){try{let e=await Bun.file(t).text(),n=e,i=j(e);if(i)n=i.content.trim();let o=fn(e),l=[...o.client.map((p)=>p.fullTag),...o.signals.map((p)=>p.fullTag)],a=[],u=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,g;while((g=u.exec(e))!==null)a.push(g[0]);let f=n;for(let p of o.server)f=f.replace(p.fullTag,"");for(let p of o.client)f=f.replace(p.fullTag,"");f=f.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"");let d="<!--__STX_PAGE_SLOT__-->";if(f=f.replace(/<slot\s*\/>/gi,d).replace(/<slot\s*>\s*<\/slot>/gi,d),!f.includes(d))return console.warn(`[stx] Shell ${t} has no <slot /> \u2014 pages won't be injected`),null;let{processDirectives:x,extractVariables:y,defaultConfig:R,loadStxConfig:b}=await import("./chunk-zfwanbre.js"),k=await b(),m={__filename:t,__dirname:T.dirname(t)};for(let p of l){let A=p.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(A&&!p.includes("client")&&!p.includes('type="module"'))await y(A[1],m,t)}let S=await x(f,m,t,{...R,...k,...s},new Set),C=S.indexOf(d);if(C===-1)return console.warn("[stx] Shell slot placeholder lost during processing"),null;return{beforeSlot:S.substring(0,C),afterSlot:S.substring(C+d.length),filePath:t,shellScripts:l,shellStyles:a}}catch(e){return console.error(`[stx] Error processing shell ${t}:`,e),null}}function is(t,s,e){let n,i="",o=s.match(it);if(o){s=s.replace(o[0],"");try{let f=Buffer.from(o[1],"base64").toString("utf8"),d=f.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(d)n=d[1].trim();i=f.replace(/<title[^>]*>[\s\S]*?<\/title>/i,"").trim()}catch{}}let l=e||n||"stx App",a=ot(),u="<script>window.__stxRouterConfig={container:'[data-stx-content]'};</script>";return`<!DOCTYPE html>
|
|
5
5
|
<html lang="en">
|
|
6
6
|
<head>
|
|
7
7
|
<meta charset="UTF-8">
|
|
@@ -29,5 +29,5 @@ ${a}
|
|
|
29
29
|
`));if(o.length>0)m.push(o.filter((S)=>!g.has(S)).join(`
|
|
30
30
|
`));if(R.length>0)m.push(R.filter((S)=>!g.has(S)).join(`
|
|
31
31
|
`));return m.push(y),m.join(`
|
|
32
|
-
`)}import M from"fs";import z from"path";function Ia(t,s,e){return{version:1,buildTime:new Date().toISOString(),routes:t,assets:s,outputDir:e}}function Oa(t,s){let e=z.join(s,"manifest.json");M.writeFileSync(e,JSON.stringify(t,null,2))}function Na(t){let s=z.join(t,"manifest.json");if(!M.existsSync(s))return null;try{let e=M.readFileSync(s,"utf-8"),n=JSON.parse(e);if(n.version!==1)return console.warn(`[stx] Manifest version mismatch: expected 1, got ${n.version}`),null;return n}catch(e){return console.warn("[stx] Failed to load manifest:",e),null}}function I(t,s,e={}){let n=`${encodeURIComponent(t)}=${encodeURIComponent(s)}`;if(e.maxAge!==void 0)n+=`; Max-Age=${e.maxAge}`;if(e.expires)n+=`; Expires=${e.expires.toUTCString()}`;if(e.path)n+=`; Path=${e.path}`;if(e.domain)n+=`; Domain=${e.domain}`;if(e.secure)n+="; Secure";if(e.httpOnly)n+="; HttpOnly";if(e.sameSite)n+=`; SameSite=${e.sameSite}`;return n}async function ct(t){let s=t.headers.get("content-type")||"",e={},n=(i,o)=>{let l=e[i];if(l===void 0)e[i]=o;else if(Array.isArray(l))l.push(o);else e[i]=[l,o]};if(s.includes("multipart/form-data")){let i=await t.formData();for(let[o,l]of i.entries())if(typeof l==="string")n(o,l);return e}if(s.includes("application/x-www-form-urlencoded")){for(let[i,o]of new URLSearchParams(await t.text()).entries())n(i,o);return e}return e}function No(t){if(!t)return!1;let s=t.toUpperCase();return s!=="GET"&&s!=="HEAD"}async function G(t,s={}){let e=s.request,n=s.method??e?.method;if(!e||!No(n))return{ran:!1};if(typeof t.action!=="function")return{ran:!1};let i={};try{i=await ct(e)}catch{}let o=await t.action({request:e,form:i,params:s.params??{},query:t.query??{},cookies:s.cookies??{}});if(o&&typeof o==="object"){let l=o,a=lt(l.cookies),u=l.redirect;if(typeof u==="string"&&u)return{redirect:u,ran:!0,...a.length>0?{cookies:a}:{}};let{cookies:g,redirect:f,...d}=l;if(Object.assign(t,d),a.length>0)return{ran:!0,cookies:a}}return{ran:!0}}function lt(t){if(!t||typeof t!=="object"||Array.isArray(t))return[];let s=[];for(let[e,n]of Object.entries(t)){if(!e)continue;if(typeof n==="string"){s.push(I(e,n));continue}if(n&&typeof n==="object"){let i=n;if(typeof i.value!=="string")continue;s.push(I(e,i.value,i))}}return s}function Ma(t,s=[],e){let n=new Headers({Location:t,"Cache-Control":"no-store"});for(let i of s)n.append("Set-Cookie",i);for(let[i,o]of Object.entries(e??{}))if(i.toLowerCase()!=="location")n.set(i,o);return new Response(null,{status:303,headers:n})}async function Wn(t,s={}){let{html:e,context:n,redirect:i,cookies:o}=await ut(t,s),l=Wt(n),a=qt(n);if(i)return{html:e,redirect:i,cookies:o,status:l,headers:a};let{extractStreamBoundaries:u}=await import("./chunk-
|
|
32
|
+
`)}import M from"fs";import z from"path";function Ia(t,s,e){return{version:1,buildTime:new Date().toISOString(),routes:t,assets:s,outputDir:e}}function Oa(t,s){let e=z.join(s,"manifest.json");M.writeFileSync(e,JSON.stringify(t,null,2))}function Na(t){let s=z.join(t,"manifest.json");if(!M.existsSync(s))return null;try{let e=M.readFileSync(s,"utf-8"),n=JSON.parse(e);if(n.version!==1)return console.warn(`[stx] Manifest version mismatch: expected 1, got ${n.version}`),null;return n}catch(e){return console.warn("[stx] Failed to load manifest:",e),null}}function I(t,s,e={}){let n=`${encodeURIComponent(t)}=${encodeURIComponent(s)}`;if(e.maxAge!==void 0)n+=`; Max-Age=${e.maxAge}`;if(e.expires)n+=`; Expires=${e.expires.toUTCString()}`;if(e.path)n+=`; Path=${e.path}`;if(e.domain)n+=`; Domain=${e.domain}`;if(e.secure)n+="; Secure";if(e.httpOnly)n+="; HttpOnly";if(e.sameSite)n+=`; SameSite=${e.sameSite}`;return n}async function ct(t){let s=t.headers.get("content-type")||"",e={},n=(i,o)=>{let l=e[i];if(l===void 0)e[i]=o;else if(Array.isArray(l))l.push(o);else e[i]=[l,o]};if(s.includes("multipart/form-data")){let i=await t.formData();for(let[o,l]of i.entries())if(typeof l==="string")n(o,l);return e}if(s.includes("application/x-www-form-urlencoded")){for(let[i,o]of new URLSearchParams(await t.text()).entries())n(i,o);return e}return e}function No(t){if(!t)return!1;let s=t.toUpperCase();return s!=="GET"&&s!=="HEAD"}async function G(t,s={}){let e=s.request,n=s.method??e?.method;if(!e||!No(n))return{ran:!1};if(typeof t.action!=="function")return{ran:!1};let i={};try{i=await ct(e)}catch{}let o=await t.action({request:e,form:i,params:s.params??{},query:t.query??{},cookies:s.cookies??{}});if(o&&typeof o==="object"){let l=o,a=lt(l.cookies),u=l.redirect;if(typeof u==="string"&&u)return{redirect:u,ran:!0,...a.length>0?{cookies:a}:{}};let{cookies:g,redirect:f,...d}=l;if(Object.assign(t,d),a.length>0)return{ran:!0,cookies:a}}return{ran:!0}}function lt(t){if(!t||typeof t!=="object"||Array.isArray(t))return[];let s=[];for(let[e,n]of Object.entries(t)){if(!e)continue;if(typeof n==="string"){s.push(I(e,n));continue}if(n&&typeof n==="object"){let i=n;if(typeof i.value!=="string")continue;s.push(I(e,i.value,i))}}return s}function Ma(t,s=[],e){let n=new Headers({Location:t,"Cache-Control":"no-store"});for(let i of s)n.append("Set-Cookie",i);for(let[i,o]of Object.entries(e??{}))if(i.toLowerCase()!=="location")n.set(i,o);return new Response(null,{status:303,headers:n})}async function Wn(t,s={}){let{html:e,context:n,redirect:i,cookies:o}=await ut(t,s),l=Wt(n),a=qt(n);if(i)return{html:e,redirect:i,cookies:o,status:l,headers:a};let{extractStreamBoundaries:u}=await import("./chunk-3t6cxcys.js"),g=u(n),f=t.streamTemplates;if(f&&Object.keys(f).length>0){let{processDirectives:d}=await import("./chunk-85c2vh7f.js"),{defaultConfig:x}=await import("./chunk-ptmvcmd0.js"),y=n.streamBoundaries||{},R={...x,autoShell:!1},b=Object.keys(f).map((m)=>({id:m,render:async()=>{let S=typeof y[m]==="function"?await y[m]():void 0;return d(f[m],{...n,$boundary:S},t.sourceFile,R,new Set)}})),k=new Set(b.map((m)=>m.id));g=[...(g||[]).filter((m)=>!k.has(m.id)),...b]}return{html:e,boundaries:g&&g.length>0?g:void 0,cookies:o,status:l,headers:a}}async function ut(t,s){let e={__filename:t.sourceFile,__dirname:t.sourceFile.replace(/[/\\][^/\\]+$/,""),...s};if(!t.hasServerScripts&&!Fi(t.html))return{html:t.html,context:e};for(let l of t.serverScriptContent)try{await h(l,e,t.sourceFile)}catch(a){if(s.__stx_strict_hydration)throw a;console.warn(`[stx] Server script error in ${t.sourceFile}:`,a)}let n=await G(e,{request:s.request,method:s.method,params:s.params??{},cookies:s.cookies??{}}),i=(l)=>{let a=l.replace(/<script\b[^>]*\bdata-stx-server-data\b[^>]*>[\s\S]*?<\/script>/gi,""),u=Lr(e);if(!u)return a;let g=D(a);return g<0?u+a:a.slice(0,g)+u+a.slice(g)};if(n.redirect)return{html:t.html,context:e,redirect:n.redirect,cookies:n.cookies};if(!Fi(t.html))return{html:i(t.html),context:e,cookies:n.cookies};let o=new Map;for(let[l,a]of Object.entries(t.placeholders))if(a.expression)try{let u=O(a.expression,e);if(a.type==="raw")o.set(l,u!==void 0&&u!==null?String(u):"");else o.set(l,u!==void 0&&u!==null?Y(String(u)):"")}catch(u){if(s.__stx_strict_hydration)throw u;o.set(l,"")}return{html:i(Cl(t.html,o)),context:e,cookies:n.cookies}}
|
|
33
33
|
export{Ct,an,Le,V,Vn,Un,Aa,Oo,is,nt,Pa,rt,je,Ia,Oa,Na,No,Ma,Wn};
|
|
@@ -8,5 +8,5 @@ function b(e,s){let i=e[s],n=s+1;while(n<e.length){if(e[n]==="\\"){n+=2;continue
|
|
|
8
8
|
`?`
|
|
9
9
|
`:" ",n++}i+=s?"$":" ",n++,l=g,r="";continue}if(u==="/"&&o(l,r)){let h=p(e,n);if(h!==-1){i+=`/${" ".repeat(h-n-2)}/`,n=h,l=g,r="";continue}}if(u==="`"){i+=s?"(":" ",n++;while(n<e.length&&e[n]!=="`"){if(e[n]==="\\"){i+=" ",n+=2;continue}if(e[n]==="$"&&e[n+1]==="{"){let h=n+2,a=Dl(e,h);if(i+=s?" {":" ",i+=w(e.slice(h,a),s),a<e.length)i+=s?"}":" ";n=a+1;continue}i+=e[n]===`
|
|
10
10
|
`?`
|
|
11
|
-
`:" ",n++}i+=s?")":" ",n++,l=g,r="";continue}if(i+=u,n++,/[\w$]/.test(u))r=/[\w$]/.test(l)?r+u:u,l=u;else if(!/\s/.test(u))l=u,r=""}return i}function
|
|
12
|
-
export{Dl,t,Bn,
|
|
11
|
+
`:" ",n++}i+=s?")":" ",n++,l=g,r="";continue}if(i+=u,n++,/[\w$]/.test(u))r=/[\w$]/.test(l)?r+u:u,l=u;else if(!/\s/.test(u))l=u,r=""}return i}function E(e){let s=new Uint16Array(e.length),i=0,n=!0;for(let l=0;l<e.length;l++){let r=e[l];if(r===")"||r==="]"||r==="}")if(i===0)n=!1;else i--;if(s[l]=i,r==="("||r==="["||r==="{")i++}return{depths:s,balanced:n&&i===0}}
|
|
12
|
+
export{Dl,t,Bn,E};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{j,Tn,Wt,qt,h,s,ke,g}from"./chunk-
|
|
2
|
+
import{j,Tn,Wt,qt,h,s,ke,g}from"./chunk-7dzhar6y.js";import{Rt,ze,Tc,vs,Zo,Qo,i}from"./chunk-3hwdg5mf.js";import{ye}from"./chunk-s29hp1qw.js";import{ae,Br,Ne,q,Mn}from"./chunk-295bykzd.js";import{Nt,Cr,zs,Hs,Vs,Mt,Dt,Lt,jt,Bt,Ft,dt}from"./chunk-agd2b928.js";import{Ms,a,L}from"./chunk-6g6pxww1.js";import{Ct,an,Le,V,Aa,Oo,is,nt,Pa,rt,je}from"./chunk-zpe4zz7r.js";import{Sr,kr}from"./chunk-7fhtvgqc.js";import{e,xn,yr,x}from"./chunk-rs84k601.js";import{at}from"./chunk-56kd82yp.js";import{Fe}from"./chunk-9f31gs4m.js";import{zn}from"./chunk-vkswqg3s.js";import{ne,Te,$e}from"./chunk-q396f1wc.js";import{l}from"./chunk-s7xywsqd.js";import{te}from"./chunk-ws2h92mm.js";import{c,f}from"./chunk-xpbakn6t.js";async function Pn(n){try{let t=await Bun.file(n).text(),o=En(t),d=On(t,n),r=An(t,o),p=Dn(t,o);return{file:n,metrics:o,issues:d,suggestions:r,performance:p}}catch(t){throw Error(`Failed to analyze template ${n}: ${t instanceof Error?t.message:String(t)}`)}}function En(n){let t=n.split(`
|
|
3
3
|
`),o=n.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),r=(o?o[1]:"").split(`
|
|
4
4
|
`).length,p={conditionals:(n.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(n.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(n.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};p.total=p.conditionals+p.loops+p.includes+p.custom;let u=(n.match(/\{\{[\s\S]*?\}\}/g)||[]).length,m=(n.match(/\{!![\s\S]*?!!\}/g)||[]).length,b=(n.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,y=u+m+b,v=(n.match(/<[A-Z][^>]*>/g)||[]).length,C=(n.match(/@(?:layout|extends)\(/g)||[]).length,R=0,O=0;for(let A of t)if(/@(?:if|unless|foreach|for|while|section)\b/.test(A)&&!/@end/.test(A)&&!/@else/.test(A))O++,R=Math.max(R,O);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(A))O--;let w=R>=4?3:0,S=Math.min(10,Math.ceil(p.total*0.5+y*0.1+v*0.3+(r>10?r*0.05:0)+w));return{lines:t.length,characters:n.length,directives:p,expressions:y,components:v,layouts:C,scriptLines:r,complexity:S}}function On(n,t){let o=[],d=Ut(n,"if","endif");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let r=Ut(n,"foreach","endforeach");if(r>0)o.push({type:"error",category:"syntax",message:`Found ${r} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let p=n.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(n.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)o.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let m=n.match(/<img[^>]*>/g);if(m){let v=m.filter((C)=>!C.includes("alt="));if(v.length>0)o.push({type:"warning",category:"accessibility",message:`Found ${v.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let b=n.split(`
|
|
5
5
|
`).filter((v)=>v.length>120);if(b.length>0)o.push({type:"info",category:"maintainability",message:`Found ${b.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let y=(n.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(y>3)o.push({type:"info",category:"maintainability",message:`Found ${y} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function An(n,t){let o=[];if(t.complexity>7)o.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(t.complexity>5&&t.directives.total>8)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(t.lines>100&&t.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(t.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=n.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(t.directives.total===0&&t.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(t.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function Dn(n,t){let o=1;if(o+=t.directives.conditionals*0.1,o+=t.directives.loops*0.5,o+=t.directives.includes*2,o+=t.expressions*0.05,o+=t.components*1,t.scriptLines>10)o+=t.scriptLines*0.1;let d;if(t.expressions===0&&t.directives.total===0)d="high";else if(t.expressions<5&&t.directives.total<3)d="medium";else d="low";let r=[];if(o>10)r.push("Consider optimizing template complexity");if(d==="low"&&t.directives.total>5)r.push("Reduce dynamic content for better caching");if(t.components===0&&t.lines>40)r.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:t.complexity,cacheability:d,recommendations:r}}function Ut(n,t,o){let d=n.replace(/<!--[\s\S]*?-->/g,""),r=(d.match(new RegExp(`@${t}\\b`,"g"))||[]).length,p=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(r-p)}async function wa(n=["**/*.stx"],t){let o=[],d=[];for(let p of n){let u=await Array.fromAsync(new Bun.Glob(p).scan({cwd:t||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((m)=>m.endsWith(".stx")))}for(let p of d)try{let u=await Pn(p);o.push(u)}catch(u){console.warn(`Failed to analyze ${p}:`,u)}let r=_n(o);return{results:o,summary:r}}function _n(n){let t=n.length,o=n.reduce((y,v)=>y+v.metrics.lines,0),d=t>0?n.reduce((y,v)=>y+v.metrics.complexity,0)/t:0,r=n.reduce((y,v)=>y+v.issues.length,0),p={};n.forEach((y)=>{y.issues.forEach((v)=>{p[v.category]=(p[v.category]||0)+1})});let u=t>0?n.reduce((y,v)=>y+v.performance.estimatedRenderTime,0)/t:0,m=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),b=[];if(d>6)b.push("Project has high average complexity. Consider refactoring complex templates.");if(r>t*2)b.push("High number of issues detected. Run detailed analysis on individual files.");if(p.security>0)b.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:t,totalLines:o,avgComplexity:Math.round(d*100)/100,totalIssues:r,issuesByCategory:p,performanceScore:m,recommendations:b}}var{serve:Wn}=globalThis.Bun;import Pt from"fs";import Qe from"path";function pt(){return`
|
|
@@ -454,7 +454,7 @@ else {
|
|
|
454
454
|
};
|
|
455
455
|
})();
|
|
456
456
|
</script>
|
|
457
|
-
`}function Ue(n,t,o={}){let d=qn(t,o),r=c(n);if(r!==-1)return n.slice(0,r)+d+n.slice(r);if(n.includes("</html>"))return n.replace("</html>",`${d}</html>`);return n+d}function ht(n){let t=n.toLowerCase();return t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".sass")||t.endsWith(".less")}function yt(n){let t=n.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>t.endsWith(d))}function xt(n){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(n))}var Ze=null;function bt(n){if(!Ze)Ze=new Vt(n);return Ze}function st(){if(Ze)Ze.stop(),Ze=null}import vt from"path";var et={name:"bun-plugin-stx",async setup(n){let o={...await a(),...n.config?.stx},d=new Set,r=o.webComponents?.enabled?`./${vt.relative(vt.dirname(n.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",p=[];if(o.webComponents?.enabled)try{let u=await Ms(o,d);if(p.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}n.onLoad({filter:/\.stx$/},async({path:u})=>{try{let m=new Set;if(o.cache&&o.cachePath){let S=await Sr(u,o);if(S){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:S,loader:"html"}}}let b=await Ne(()=>Bun.file(u).text(),"",(S)=>{throw new Br(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${S.message}`)});if(!b)throw new Br(`stx file is empty: ${u}`,u);let{scriptContent:y,templateContent:v,allScripts:C}=ye.time("script-extraction",()=>{let S=b,A=j(b);if(A)S=A.content.trim();let U=b.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],oe="",H=[];for(let k of U){let P=k.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",D=k.match(/<script\b([^>]*)>/i),K=D?D[1]:"";if(/\bserver\b/i.test(K))oe=P;else H.push(k)}let I=S.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:oe,templateContent:I,allScripts:H}}),R={__filename:u,__dirname:vt.dirname(u),__stx:{webComponentsPath:r,builtComponents:p}};await Ne(()=>h(y,R,u),void 0,(S)=>{let A=new ae(`Script execution failed in ${u}: ${S.message}`,u,void 0,void 0,y.substring(0,100));if(q.log(A,{filePath:u,scriptContent:y}),o.debug)throw A});let w=await ye.timeAsync("directive-processing",async()=>await i(v,R,u,o,m));if(C.length>0){let{interpolateScriptsInTemplate:S}=await import("./chunk-
|
|
457
|
+
`}function Ue(n,t,o={}){let d=qn(t,o),r=c(n);if(r!==-1)return n.slice(0,r)+d+n.slice(r);if(n.includes("</html>"))return n.replace("</html>",`${d}</html>`);return n+d}function ht(n){let t=n.toLowerCase();return t.endsWith(".css")||t.endsWith(".scss")||t.endsWith(".sass")||t.endsWith(".less")}function yt(n){let t=n.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>t.endsWith(d))}function xt(n){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(n))}var Ze=null;function bt(n){if(!Ze)Ze=new Vt(n);return Ze}function st(){if(Ze)Ze.stop(),Ze=null}import vt from"path";var et={name:"bun-plugin-stx",async setup(n){let o={...await a(),...n.config?.stx},d=new Set,r=o.webComponents?.enabled?`./${vt.relative(vt.dirname(n.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",p=[];if(o.webComponents?.enabled)try{let u=await Ms(o,d);if(p.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}n.onLoad({filter:/\.stx$/},async({path:u})=>{try{let m=new Set;if(o.cache&&o.cachePath){let S=await Sr(u,o);if(S){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:S,loader:"html"}}}let b=await Ne(()=>Bun.file(u).text(),"",(S)=>{throw new Br(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${S.message}`)});if(!b)throw new Br(`stx file is empty: ${u}`,u);let{scriptContent:y,templateContent:v,allScripts:C}=ye.time("script-extraction",()=>{let S=b,A=j(b);if(A)S=A.content.trim();let U=b.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],oe="",H=[];for(let k of U){let P=k.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",D=k.match(/<script\b([^>]*)>/i),K=D?D[1]:"";if(/\bserver\b/i.test(K))oe=P;else H.push(k)}let I=S.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:oe,templateContent:I,allScripts:H}}),R={__filename:u,__dirname:vt.dirname(u),__stx:{webComponentsPath:r,builtComponents:p}};await Ne(()=>h(y,R,u),void 0,(S)=>{let A=new ae(`Script execution failed in ${u}: ${S.message}`,u,void 0,void 0,y.substring(0,100));if(q.log(A,{filePath:u,scriptContent:y}),o.debug)throw A});let w=await ye.timeAsync("directive-processing",async()=>await i(v,R,u,o,m));if(C.length>0){let{interpolateScriptsInTemplate:S}=await import("./chunk-jq97q0f7.js"),A=S(C.join(`
|
|
458
458
|
`),R),U=w.search(/<\/body>/i);if(U!==-1)w=w.slice(0,U)+A+`
|
|
459
459
|
`+w.slice(U);else w+=`
|
|
460
460
|
${A}`}if(w=await $e(w),m.forEach((S)=>d.add(S)),o.cache&&o.cachePath){if(await kr(u,w,m,o),o.debug)console.log(`Cached template ${u} with ${m.size} dependencies`)}return{contents:w,loader:"html"}}catch(m){let b=m instanceof Error?m:new ae(`Plugin processing failed: ${String(m)}`,u);if(q.log(b,{filePath:u,buildConfig:n.config}),Mn.logDetailedError(b,{filePath:u,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",b);let y=b,v=y.line||null,C=y.context||null;return{contents:o.debug||te()?`<!DOCTYPE html>
|
|
@@ -517,7 +517,7 @@ ${A}`}if(w=await $e(w),m.forEach((S)=>d.add(S)),o.cache&&o.cachePath){if(await k
|
|
|
517
517
|
<h1>Something went wrong</h1>
|
|
518
518
|
<p>An internal error occurred. Please try again later.</p>
|
|
519
519
|
</body>
|
|
520
|
-
</html>`,loader:"html"}}})}};async function es(n,t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=ge.resolve(n);if(!Ie.existsSync(m))return console.error(`${e.red}Error: File not found: ${e.bright}${m}${e.reset}`),!1;if(m.endsWith(".md"))return Et(m,t);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 b=l(process.cwd(),"output");Ie.mkdirSync(b,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${n}${e.reset}...`);let y=null,v=async()=>{try{let P={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(pe)=>({path:pe.path,external:!0}))}},D=await Bun.build({entrypoints:[m],outdir:b,plugins:[P,et],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!D.success)return console.error(`${e.red}Build failed:${e.reset}`,D.logs),!1;let K=D.outputs.find((be)=>be.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return y=await Bun.file(K.path).text(),!0}catch(P){return console.error(`${e.red}Error building stx file:${e.reset}`,P),!1}};if(!await v())return!1;let R=ge.dirname(m);await xn(R);let O=o;try{if(O=await Ve(o),O!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${O} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let P=t.hmrPort||O+1;p=bt({wsPort:P,verbose:!1}),u=p.start(P)}let w={},S=null,A;try{let{loadStxConfig:P}=await import("./chunk-
|
|
520
|
+
</html>`,loader:"html"}}})}};async function es(n,t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=ge.resolve(n);if(!Ie.existsSync(m))return console.error(`${e.red}Error: File not found: ${e.bright}${m}${e.reset}`),!1;if(m.endsWith(".md"))return Et(m,t);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 b=l(process.cwd(),"output");Ie.mkdirSync(b,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${n}${e.reset}...`);let y=null,v=async()=>{try{let P={name:"public-assets",setup(be){be.onResolve({filter:/^\/(images|fonts|assets|public)\//},(pe)=>({path:pe.path,external:!0}))}},D=await Bun.build({entrypoints:[m],outdir:b,plugins:[P,et],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!D.success)return console.error(`${e.red}Build failed:${e.reset}`,D.logs),!1;let K=D.outputs.find((be)=>be.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return y=await Bun.file(K.path).text(),!0}catch(P){return console.error(`${e.red}Error building stx file:${e.reset}`,P),!1}};if(!await v())return!1;let R=ge.dirname(m);await xn(R);let O=o;try{if(O=await Ve(o),O!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${O} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let P=t.hmrPort||O+1;p=bt({wsPort:P,verbose:!1}),u=p.start(P)}let w={},S=null,A;try{let{loadStxConfig:P}=await import("./chunk-zfwanbre.js"),D=await P();if(A=t.stxOptions?.serverApi??D.serverApi,D?.apiRouter)S=D?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(D?.apiRoutes){w=D.apiRoutes;let K=Object.keys(w).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(D?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Y}=await import("./chunk-5rd0an89.js"),be=D.broadcasting;await K(be);let pe=be.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${pe}/ws${e.reset}`);let Ce=ge.join(process.cwd(),"channels.ts");if(Ie.existsSync(Ce))try{let se=await Y(Ce);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:U,isServerApiSource:oe}=await import("./chunk-5519xwrm.js"),H=await U(process.cwd(),A);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${O}/${e.reset}...`),r)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let I=Kn({port:O,async fetch(P){return zn(P,await(async()=>{let D=new URL(P.url);if([b,ge.dirname(m),ge.join(process.cwd(),"public")].some((se)=>oe(ge.join(se,D.pathname),process.cwd(),A)))return new Response("Not Found",{status:404});if(S)try{let se=await S.handleRequest(P);if(se.status!==404)return se}catch{}if(w[D.pathname])try{return await w[D.pathname](P)}catch(se){return new Response(JSON.stringify({error:se.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await H(P);if(K)return K;if(D.pathname==="/")return(async()=>{let F=await x(y||"");if(r)F=Ue(F,u);if(t.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(t.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(F.includes("<html"))F=F.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;return F})().then((F)=>new Response(F,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(b,D.pathname);if(Ie.existsSync(Y)&&Ie.statSync(Y).isFile()){let se=Bun.file(Y),F=ge.extname(Y).toLowerCase(),E="text/plain";if(F===".ts"||F===".tsx"){let He=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),Be=await se.text(),Ge=He.transformSync(Be);return new Response(Ge,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){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".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(se,{headers:{"Content-Type":E}})}let be=ge.dirname(m),pe=ge.join(be,D.pathname);if(Ie.existsSync(pe)&&Ie.statSync(pe).isFile()){let se=Bun.file(pe),F=ge.extname(pe).toLowerCase(),E="text/plain";if(F===".ts"||F===".tsx"){let He=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),Be=await se.text(),Ge=He.transformSync(Be);return new Response(Ge,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){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(se,{headers:{"Content-Type":E}})}let Ce=ge.join(process.cwd(),"public",D.pathname);if(Ie.existsSync(Ce)&&Ie.statSync(Ce).isFile()){let se=Bun.file(Ce),F=ge.extname(Ce).toLowerCase(),E="application/octet-stream";if(F===".ts"||F===".tsx"){let He=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),Be=await se.text(),Ge=He.transformSync(Be);return new Response(Ge,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){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(se,{headers:{"Content-Type":E}})}return new Response("Not Found",{status:404})})())},error(P){return new Response(`<pre>${P}
|
|
521
521
|
${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
522
522
|
${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(`
|
|
523
523
|
${e.bright}\u2192 ${e.cyan}http://localhost:${O}/${e.reset}`),console.log(`
|
|
@@ -1002,12 +1002,12 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1002
1002
|
${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(`
|
|
1003
1003
|
${e.bright}\u2192 ${e.cyan}http://localhost:${v}/${e.reset}`),console.log(`
|
|
1004
1004
|
${e.yellow}Routes:${e.reset}`);let R=new Set(m.map((w)=>w.routeTemplate)),O=Object.entries(u).filter(([w])=>!R.has(w)).sort(([w],[S])=>w.localeCompare(S)).map(([w,S])=>({route:w==="/"?"/":w,filePath:Se.relative(process.cwd(),S.filePath),fileType:S.fileType}));for(let w of m){let S=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");O.push({route:S,filePath:Se.relative(process.cwd(),w.filePath),fileType:"stx"})}if(O.sort((w,S)=>w.route.localeCompare(S.route)),O.forEach((w,S)=>{let U=S===O.length-1?"\u2514\u2500 ":"\u251C\u2500 ",oe=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${U}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${oe}`)}),console.log(`
|
|
1005
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(C.url.toString(),()=>{if(d)Ke.watch(p,{recursive:!0}).close();C.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Ke.watch(p,{recursive:!0},async(S,A)=>{if(!A)return;if(A.endsWith(".stx")||A.endsWith(".js")||A.endsWith(".ts")||A.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${A}${e.yellow} changed, rebuilding...${e.reset}`),at.clear(),ke(),await b()});process.on("SIGINT",()=>{w.close(),C.stop(),process.exit(0)})}return!0}function Xt(n){return String(n??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Gn}=globalThis.Bun;import me from"fs";import re from"path";async function Jt(n){try{return Tn(await Bun.file(n).text())}catch{return}}function Ot(n){let t=Bun.file(n),o=re.extname(n).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"},p=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(t,{headers:{"Content-Type":d[o]||"application/octet-stream",...p}})}async function ns(n=".",t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=re.resolve(n),{loadStxConfig:b}=await import("./chunk-mcc01ts7.js"),y=await b(m),{createServerApi:v,isServerApiSource:C}=await import("./chunk-0c913abf.js"),R=t.stxOptions?.serverApi??y.serverApi,O=await v(m,R),w=y.root&&y.root!=="."?re.join(m,y.root):m,S=t.pagesDir||y.pagesDir||"pages",A=re.join(w,S);if(!me.existsSync(A)&&!y._layerPageDirs?.some((T)=>me.existsSync(T)))return console.error(`${e.red}Error: No '${S}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${A}${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 ${S}/index.stx for the homepage.${e.reset}`),!1;let U=ne(w,{pagesDir:S,pagesDirs:y._layerPageDirs?[A,...y._layerPageDirs.slice(1)]:void 0});if(U.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${A}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${U.length}${e.blue} routes${e.reset}`);let oe=y?._pluginPageDirs||[],H=[];for(let{dir:T,prefix:M}of oe)if(me.existsSync(T)){let z=ne(re.dirname(T),{pagesDir:re.basename(T)});for(let Q of z){let X=M==="/"?Q.pattern:`${M}${Q.pattern==="/"?"":Q.pattern}`;H.push({route:{...Q,pattern:X},prefix:M})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${M}${e.reset}`)}let I=new Map,k=null,P=null;if(t.stxOptions?.shell!==!1){if(P=await Aa(m,t.stxOptions?.shell),P){if(k=await Oo(P,t.stxOptions||{}),k)console.log(`${e.blue}Using app shell: ${e.bright}${re.relative(m,P)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Mt(),await Lt(m);let D=Dt();if(D.length>0)console.log(`${e.blue}Loaded ${e.bright}${D.length}${e.blue} middleware: ${e.dim}${D.join(", ")}${e.reset}`);let K={},Y=null;try{let{loadStxConfig:T}=await import("./chunk-mcc01ts7.js"),M=await T(m);if(M?.apiRouter)Y=M?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(M?.apiRoutes){K=M.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(M?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-5rd0an89.js"),X=M.broadcasting;await z(X);let Re=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Re}/ws${e.reset}`);let ve=re.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let N=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let be=l(m,"output");me.mkdirSync(be,{recursive:!0});let pe=new Map,Ce=new Set,se=async(T)=>{let M=Hs(A,T);if(!M)return null;try{let z=await Bun.build({entrypoints:[M],outdir:be,plugins:[et],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!z.success)return null;let Q=z.outputs.find((X)=>X.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,E=async(T,M)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Re,injectRouterScript:ve}=await import("./chunk-mcc01ts7.js"),{checkCache:N,cacheTemplate:J,readFileCached:W,templateCache:ue}=await import("./chunk-0q117rw8.js"),G=await Re(m),We=(le)=>{if(!le)return le;if(re.isAbsolute(le))return le;return re.resolve(m,le)},de={...X,...G,...t.stxOptions,autoShell:!0};if(t.debugDirectives)de.debug=!0;de.partialsDir=We(de.partialsDir),de.componentsDir=We(de.componentsDir),de.layoutsDir=We(de.layoutsDir),de.storesDir=We(de.storesDir||"stores"),de.cachePath=We(de.cachePath)??l(m,"cache");let _=!M&&!t.profile,ie=de.cache!==!1;if(ie&&_){let le=ue.get(T.filePath);if(le)try{if((await me.promises.stat(T.filePath)).mtime.getTime()<=le.mtime){let _e=!0;for(let we of le.dependencies){if(!me.existsSync(we)){_e=!1;break}if((await me.promises.stat(we)).mtime.getTime()>le.mtime){_e=!1;break}}if(_e){let we=le.output;if(k)we=nt(we,{preserveHead:!0});let ot=F.get(T.filePath);return{route:T,content:we,status:ot?.status??await Jt(T.filePath),headers:ot?.headers}}}}catch{}let De=await N(T.filePath,de);if(De){let Me=De;if(k)Me=nt(Me,{preserveHead:!0});let _e=F.get(T.filePath);return{route:T,content:Me,status:_e?.status??await Jt(T.filePath),headers:_e?.headers}}}let Z=ie?await W(T.filePath):await Bun.file(T.filePath).text(),ce=Tn(Z),{classifyAllScripts:fe}=await import("./chunk-mcc01ts7.js"),B=fe(Z),Ae=B.server.map((le)=>le.content),Ee=Z;for(let le of B.server)Ee=Ee.replace(le.fullTag,"");let ee={__filename:T.filePath,__dirname:re.dirname(T.filePath),__stx_options:de,params:M??{},__stx_runtime_head:{}};for(let le of Ae)try{await Q(le,ee,T.filePath)}catch(De){if(t.stxOptions?.debug)console.error("[stx] variable extraction error",T.filePath,De?.message||De)}let Pe=new Set,he;if(t.profile){let le=performance.now();he=await z(Ee,ee,T.filePath,de,Pe);let De=performance.now()-le,Me=re.relative(m,T.filePath)||T.filePath;console.log(`[stx:profile] ${Me} \u2192 ${De.toFixed(2)}ms`)}else he=await z(Ee,ee,T.filePath,de,Pe);if(!k)he=await ve(he,{router:de.router});{let{interpolateScriptExpressions:le}=await import("./chunk-bnawaxh5.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(De,Me,_e)=>{if(!/function\s+__stx_setup_/.test(_e))return De;return`<script${Me}>${le(_e,ee)}</script>`})}if(k)he=nt(he,{preserveHead:!0});if(ie&&_)await J(T.filePath,he,Pe,de);let{extractStreamBoundaries:lt}=await import("./chunk-s7c1f3h4.js"),Je=lt(ee),tt=ee.__streamTemplates;if(tt&&typeof tt==="object"&&Object.keys(tt).length>0){let le=ee.streamBoundaries||{},De={...de,autoShell:!1},Me=Object.keys(tt).map((we)=>({id:we,render:async()=>{let ot=typeof le[we]==="function"?await le[we]():void 0;return z(tt[we],{...ee,$boundary:ot},T.filePath,De,new Set)}})),_e=new Set(Me.map((we)=>we.id));Je=[...(Je||[]).filter((we)=>!_e.has(we.id)),...Me]}if(Je&&Je.length>0)Ce.add(T.pattern);else Je=void 0;let It=Wt(ee),Ht=qt(ee);if(_)F.set(T.filePath,{status:It,headers:Ht});return{route:T,content:he,status:It??ce,headers:Ht,boundaries:Je}}catch(z){return console.error(`${e.red}Error building ${e.bright}${T.pattern}${e.reset}:`,z),null}},He=8,Be=async()=>{let T=new Set(pe.keys()),M=new Set(I.keys());pe.clear(),I.clear();let z=t.prebuild===!1?U.filter((X)=>T.has(X.pattern)):U,Q=t.prebuild===!1?H.filter(({route:X})=>M.has(X.pattern)):H;for(let X=0;X<z.length;X+=He){let Re=z.slice(X,X+He),ve=await Promise.all(Re.map((N)=>E(N)));for(let N of ve)if(N)pe.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=He){let Re=Q.slice(X,X+He),ve=await Promise.all(Re.map(({route:N})=>E(N)));for(let N of ve)if(N)I.set(N.route.pattern,N)}return pe.size>0};if(console.log(`${e.blue}${t.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(t.prebuild===!1?U.length+H.length>0:await Be()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await xn(m);let Xe=o;try{if(Xe=await Ve(o),Xe!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let T=t.hmrPort||Xe+1;p=bt({wsPort:T,verbose:!1}),u=p.start(T)}let St=(T,M)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(M).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(T.includes("</head>"))return f(T,Q,"");if(T.includes("<body"))return T.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+T};console.log(`${e.blue}Starting server...${e.reset}`);let kt=Gn({port:Xe,hostname:t.hostname,async fetch(T){let M=new URL(T.url),z=t.stxOptions?.offline??y.offline;if(M.pathname===Zo&&z?.enabled){if(!["GET","HEAD"].includes(T.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(T.method==="HEAD"?null:Qo(z,vs()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=y?.publicDir||"public",X=re.join(m,Q,M.pathname),Re=re.join(m,M.pathname),ve=re.join(be,M.pathname);if([X,Re,ve].some((_)=>C(_,m,R)))return new Response("Not Found",{status:404});let[N,J,W]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Re).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(N?.isFile()&&!C(X,m,R))return Ot(X);if(J?.isFile()&&!C(Re,m,R))return Ot(Re);if(W?.isFile()&&!C(ve,m,R))return Ot(ve);if(M.pathname.startsWith("/_stx/component/")){let _=decodeURIComponent(M.pathname.slice(16));if(_)try{let ie=`<${_} />`,Z={...buildConfig,autoShell:!1},ce=await processDirectives(ie,{},re.join(m,"components",`${_}.stx`),Z,new Set);return new Response(ce,{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(M.pathname==="/_stx/img"){let{handleImageRequest:_}=await import("./chunk-53cc06w7.js"),ie=await _(T,{publicDir:re.join(m,Q),cacheDir:l(m,"cache","img")});if(ie)return ie}if(Y)try{let _=await Y.handleRequest(T);if(_.status!==404)return _}catch{}if(K[M.pathname])try{return await K[M.pathname](T)}catch(_){return new Response(JSON.stringify({error:_.message}),{status:500,headers:{"Content-Type":"application/json"}})}let ue=await O(T);if(ue)return ue;let G=Cr(M.pathname,U);if(G){let _=pe.get(G.route.pattern),ie=Ce.has(G.route.pattern);if(!_||G.route.isDynamic&&Object.keys(G.params).length>0||ie){let Z=await E(G.route,G.params);if(Z){if(_=Z,!G.route.isDynamic&&!ie)pe.set(G.route.pattern,Z)}}if(_){let Z=_.status??200,ce=_.headers??{},fe=(G.route.filePath?Rt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let Ee=await se(404);if(Ee){let ee=Ee;if(ee=await x(ee,m),r)ee=Ue(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Ae=jt(M.pathname,G.params,fe,M.search),Ee=Bt(Ae,null,T,{isServer:!0}),ee=await Ft(fe.middleware,Ee);if(ee.redirect){let Pe=ee.redirect.path,he=ee.redirect.options.redirectCode||302,lt=new Headers(ee.responseHeaders);return lt.set("Location",Pe),new Response(null,{status:he,headers:lt})}if(ee.abort){let{statusCode:Pe,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Pe}</title></head><body><h1>Error ${Pe}</h1><p>${he}</p></body></html>`,{status:Pe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Pe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;_.content=f(_.content,Pe,"")}}let B=_.content;if(k&&Pa(T)&&rt(B,y?.router?.container||"main")){let Ae=dt(B),Ee=Te(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Pe=ee?an(ee[1].trim()):"";if(Object.keys(G.params).length>0)B=St(B,G.params);B=await x(B,m);let he=y?.router?.container||"main";return B=je(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Ae.layout,"X-STX-Layout-Group":Ae.group,"X-STX-Runtime":Ee?"true":"false",...Pe&&{"X-STX-Title":encodeURIComponent(Pe)},[Tc]:vs(),...V(),"Cache-Control":Ct}})}if(k)B=is(k,B);if(Object.keys(G.params).length>0)B=St(B,G.params);if(B=await x(B,m),r)B=Ue(B,u);if(t.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(t.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(_.boundaries&&_.boundaries.length>0){let{renderStreamingPage:Ae,streamToResponse:Ee}=await import("./chunk-s7c1f3h4.js");return Ee(Ae(B,_.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",...V(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ce}})}}if(H.length>0){let _=H.map((Z)=>Z.route),ie=Cr(M.pathname,_);if(ie){let Z=I.get(ie.route.pattern);if(!Z||ie.route.isDynamic){let ce=await E(ie.route,ie.params);if(ce){if(Z=ce,!ie.route.isDynamic)I.set(ie.route.pattern,ce)}}if(Z){let ce=Z.content;if(k)ce=is(k,ce);if(Object.keys(ie.params).length>0)ce=St(ce,ie.params);if(ce=await x(ce,m),r)ce=Ue(ce,u);return new Response(ce,{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 oe)if(Z!=="/"&&M.pathname.startsWith(Z)){let ce=I.get(Z)||I.get(Z+"/");if(!ce){let fe=H.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(fe){let B=await E(fe.route);if(B)ce=B,I.set(fe.route.pattern,B)}}if(ce){let fe=ce.content;if(k)fe=is(k,fe);if(fe=await x(fe,m),r)fe=Ue(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(Nt(M.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let We=pe.get("/");if(We){let _=We.content;if(_=await x(_,m),r)_=Ue(_,u);if(t.native)if(_.includes("<head>"))_=_.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 _="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+_;return new Response(_,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let de=await se(404);if(de){let _=de;if(_=await x(_,m),r)_=Ue(_,u);return new Response(_,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(T){let M=await se(500);if(M)return new Response(M,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${T}
|
|
1005
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(C.url.toString(),()=>{if(d)Ke.watch(p,{recursive:!0}).close();C.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Ke.watch(p,{recursive:!0},async(S,A)=>{if(!A)return;if(A.endsWith(".stx")||A.endsWith(".js")||A.endsWith(".ts")||A.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${A}${e.yellow} changed, rebuilding...${e.reset}`),at.clear(),ke(),await b()});process.on("SIGINT",()=>{w.close(),C.stop(),process.exit(0)})}return!0}function Xt(n){return String(n??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Gn}=globalThis.Bun;import me from"fs";import re from"path";async function Jt(n){try{return Tn(await Bun.file(n).text())}catch{return}}function Ot(n){let t=Bun.file(n),o=re.extname(n).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"},p=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(t,{headers:{"Content-Type":d[o]||"application/octet-stream",...p}})}async function ns(n=".",t={}){let o=t.port||3000,d=t.watch!==!1,r=t.hotReload!==!1&&d,p=null,u=t.hmrPort||o+1,m=re.resolve(n),{loadStxConfig:b}=await import("./chunk-zfwanbre.js"),y=await b(m),{createServerApi:v,isServerApiSource:C}=await import("./chunk-5519xwrm.js"),R=t.stxOptions?.serverApi??y.serverApi,O=await v(m,R),w=y.root&&y.root!=="."?re.join(m,y.root):m,S=t.pagesDir||y.pagesDir||"pages",A=re.join(w,S);if(!me.existsSync(A)&&!y._layerPageDirs?.some((T)=>me.existsSync(T)))return console.error(`${e.red}Error: No '${S}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${A}${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 ${S}/index.stx for the homepage.${e.reset}`),!1;let U=ne(w,{pagesDir:S,pagesDirs:y._layerPageDirs?[A,...y._layerPageDirs.slice(1)]:void 0});if(U.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${A}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${U.length}${e.blue} routes${e.reset}`);let oe=y?._pluginPageDirs||[],H=[];for(let{dir:T,prefix:M}of oe)if(me.existsSync(T)){let z=ne(re.dirname(T),{pagesDir:re.basename(T)});for(let Q of z){let X=M==="/"?Q.pattern:`${M}${Q.pattern==="/"?"":Q.pattern}`;H.push({route:{...Q,pattern:X},prefix:M})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${M}${e.reset}`)}let I=new Map,k=null,P=null;if(t.stxOptions?.shell!==!1){if(P=await Aa(m,t.stxOptions?.shell),P){if(k=await Oo(P,t.stxOptions||{}),k)console.log(`${e.blue}Using app shell: ${e.bright}${re.relative(m,P)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Mt(),await Lt(m);let D=Dt();if(D.length>0)console.log(`${e.blue}Loaded ${e.bright}${D.length}${e.blue} middleware: ${e.dim}${D.join(", ")}${e.reset}`);let K={},Y=null;try{let{loadStxConfig:T}=await import("./chunk-zfwanbre.js"),M=await T(m);if(M?.apiRouter)Y=M?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(M?.apiRoutes){K=M.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(M?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-5rd0an89.js"),X=M.broadcasting;await z(X);let Re=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Re}/ws${e.reset}`);let ve=re.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let N=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${N} broadcast channel${N!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(N){console.warn(`${e.yellow}Failed to load channels.ts: ${N.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let be=l(m,"output");me.mkdirSync(be,{recursive:!0});let pe=new Map,Ce=new Set,se=async(T)=>{let M=Hs(A,T);if(!M)return null;try{let z=await Bun.build({entrypoints:[M],outdir:be,plugins:[et],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...t.stxOptions});if(!z.success)return null;let Q=z.outputs.find((X)=>X.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},F=new Map,E=async(T,M)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Re,injectRouterScript:ve}=await import("./chunk-zfwanbre.js"),{checkCache:N,cacheTemplate:J,readFileCached:W,templateCache:ue}=await import("./chunk-z9x5pn5j.js"),G=await Re(m),We=(le)=>{if(!le)return le;if(re.isAbsolute(le))return le;return re.resolve(m,le)},de={...X,...G,...t.stxOptions,autoShell:!0};if(t.debugDirectives)de.debug=!0;de.partialsDir=We(de.partialsDir),de.componentsDir=We(de.componentsDir),de.layoutsDir=We(de.layoutsDir),de.storesDir=We(de.storesDir||"stores"),de.cachePath=We(de.cachePath)??l(m,"cache");let _=!M&&!t.profile,ie=de.cache!==!1;if(ie&&_){let le=ue.get(T.filePath);if(le)try{if((await me.promises.stat(T.filePath)).mtime.getTime()<=le.mtime){let _e=!0;for(let we of le.dependencies){if(!me.existsSync(we)){_e=!1;break}if((await me.promises.stat(we)).mtime.getTime()>le.mtime){_e=!1;break}}if(_e){let we=le.output;if(k)we=nt(we,{preserveHead:!0});let ot=F.get(T.filePath);return{route:T,content:we,status:ot?.status??await Jt(T.filePath),headers:ot?.headers}}}}catch{}let De=await N(T.filePath,de);if(De){let Me=De;if(k)Me=nt(Me,{preserveHead:!0});let _e=F.get(T.filePath);return{route:T,content:Me,status:_e?.status??await Jt(T.filePath),headers:_e?.headers}}}let Z=ie?await W(T.filePath):await Bun.file(T.filePath).text(),ce=Tn(Z),{classifyAllScripts:fe}=await import("./chunk-zfwanbre.js"),B=fe(Z),Ae=B.server.map((le)=>le.content),Ee=Z;for(let le of B.server)Ee=Ee.replace(le.fullTag,"");let ee={__filename:T.filePath,__dirname:re.dirname(T.filePath),__stx_options:de,params:M??{},__stx_runtime_head:{}};for(let le of Ae)try{await Q(le,ee,T.filePath)}catch(De){if(t.stxOptions?.debug)console.error("[stx] variable extraction error",T.filePath,De?.message||De)}let Pe=new Set,he;if(t.profile){let le=performance.now();he=await z(Ee,ee,T.filePath,de,Pe);let De=performance.now()-le,Me=re.relative(m,T.filePath)||T.filePath;console.log(`[stx:profile] ${Me} \u2192 ${De.toFixed(2)}ms`)}else he=await z(Ee,ee,T.filePath,de,Pe);if(!k)he=await ve(he,{router:de.router});{let{interpolateScriptExpressions:le}=await import("./chunk-jq97q0f7.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(De,Me,_e)=>{if(!/function\s+__stx_setup_/.test(_e))return De;return`<script${Me}>${le(_e,ee)}</script>`})}if(k)he=nt(he,{preserveHead:!0});if(ie&&_)await J(T.filePath,he,Pe,de);let{extractStreamBoundaries:lt}=await import("./chunk-3t6cxcys.js"),Je=lt(ee),tt=ee.__streamTemplates;if(tt&&typeof tt==="object"&&Object.keys(tt).length>0){let le=ee.streamBoundaries||{},De={...de,autoShell:!1},Me=Object.keys(tt).map((we)=>({id:we,render:async()=>{let ot=typeof le[we]==="function"?await le[we]():void 0;return z(tt[we],{...ee,$boundary:ot},T.filePath,De,new Set)}})),_e=new Set(Me.map((we)=>we.id));Je=[...(Je||[]).filter((we)=>!_e.has(we.id)),...Me]}if(Je&&Je.length>0)Ce.add(T.pattern);else Je=void 0;let It=Wt(ee),Ht=qt(ee);if(_)F.set(T.filePath,{status:It,headers:Ht});return{route:T,content:he,status:It??ce,headers:Ht,boundaries:Je}}catch(z){return console.error(`${e.red}Error building ${e.bright}${T.pattern}${e.reset}:`,z),null}},He=8,Be=async()=>{let T=new Set(pe.keys()),M=new Set(I.keys());pe.clear(),I.clear();let z=t.prebuild===!1?U.filter((X)=>T.has(X.pattern)):U,Q=t.prebuild===!1?H.filter(({route:X})=>M.has(X.pattern)):H;for(let X=0;X<z.length;X+=He){let Re=z.slice(X,X+He),ve=await Promise.all(Re.map((N)=>E(N)));for(let N of ve)if(N)pe.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=He){let Re=Q.slice(X,X+He),ve=await Promise.all(Re.map(({route:N})=>E(N)));for(let N of ve)if(N)I.set(N.route.pattern,N)}return pe.size>0};if(console.log(`${e.blue}${t.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(t.prebuild===!1?U.length+H.length>0:await Be()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await xn(m);let Xe=o;try{if(Xe=await Ve(o),Xe!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Xe} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(r){let T=t.hmrPort||Xe+1;p=bt({wsPort:T,verbose:!1}),u=p.start(T)}let St=(T,M)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(M).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(T.includes("</head>"))return f(T,Q,"");if(T.includes("<body"))return T.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+T};console.log(`${e.blue}Starting server...${e.reset}`);let kt=Gn({port:Xe,hostname:t.hostname,async fetch(T){let M=new URL(T.url),z=t.stxOptions?.offline??y.offline;if(M.pathname===Zo&&z?.enabled){if(!["GET","HEAD"].includes(T.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(T.method==="HEAD"?null:Qo(z,vs()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=y?.publicDir||"public",X=re.join(m,Q,M.pathname),Re=re.join(m,M.pathname),ve=re.join(be,M.pathname);if([X,Re,ve].some((_)=>C(_,m,R)))return new Response("Not Found",{status:404});let[N,J,W]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Re).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(N?.isFile()&&!C(X,m,R))return Ot(X);if(J?.isFile()&&!C(Re,m,R))return Ot(Re);if(W?.isFile()&&!C(ve,m,R))return Ot(ve);if(M.pathname.startsWith("/_stx/component/")){let _=decodeURIComponent(M.pathname.slice(16));if(_)try{let ie=`<${_} />`,Z={...buildConfig,autoShell:!1},ce=await processDirectives(ie,{},re.join(m,"components",`${_}.stx`),Z,new Set);return new Response(ce,{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(M.pathname==="/_stx/img"){let{handleImageRequest:_}=await import("./chunk-53cc06w7.js"),ie=await _(T,{publicDir:re.join(m,Q),cacheDir:l(m,"cache","img")});if(ie)return ie}if(Y)try{let _=await Y.handleRequest(T);if(_.status!==404)return _}catch{}if(K[M.pathname])try{return await K[M.pathname](T)}catch(_){return new Response(JSON.stringify({error:_.message}),{status:500,headers:{"Content-Type":"application/json"}})}let ue=await O(T);if(ue)return ue;let G=Cr(M.pathname,U);if(G){let _=pe.get(G.route.pattern),ie=Ce.has(G.route.pattern);if(!_||G.route.isDynamic&&Object.keys(G.params).length>0||ie){let Z=await E(G.route,G.params);if(Z){if(_=Z,!G.route.isDynamic&&!ie)pe.set(G.route.pattern,Z)}}if(_){let Z=_.status??200,ce=_.headers??{},fe=(G.route.filePath?Rt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let Ee=await se(404);if(Ee){let ee=Ee;if(ee=await x(ee,m),r)ee=Ue(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Ae=jt(M.pathname,G.params,fe,M.search),Ee=Bt(Ae,null,T,{isServer:!0}),ee=await Ft(fe.middleware,Ee);if(ee.redirect){let Pe=ee.redirect.path,he=ee.redirect.options.redirectCode||302,lt=new Headers(ee.responseHeaders);return lt.set("Location",Pe),new Response(null,{status:he,headers:lt})}if(ee.abort){let{statusCode:Pe,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Pe}</title></head><body><h1>Error ${Pe}</h1><p>${he}</p></body></html>`,{status:Pe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Pe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;_.content=f(_.content,Pe,"")}}let B=_.content;if(k&&Pa(T)&&rt(B,y?.router?.container||"main")){let Ae=dt(B),Ee=Te(B),ee=B.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Pe=ee?an(ee[1].trim()):"";if(Object.keys(G.params).length>0)B=St(B,G.params);B=await x(B,m);let he=y?.router?.container||"main";return B=je(B,he,!0),new Response(B,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Ae.layout,"X-STX-Layout-Group":Ae.group,"X-STX-Runtime":Ee?"true":"false",...Pe&&{"X-STX-Title":encodeURIComponent(Pe)},[Tc]:vs(),...V(),"Cache-Control":Ct}})}if(k)B=is(k,B);if(Object.keys(G.params).length>0)B=St(B,G.params);if(B=await x(B,m),r)B=Ue(B,u);if(t.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(t.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(_.boundaries&&_.boundaries.length>0){let{renderStreamingPage:Ae,streamToResponse:Ee}=await import("./chunk-3t6cxcys.js");return Ee(Ae(B,_.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",...V(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ce}})}}if(H.length>0){let _=H.map((Z)=>Z.route),ie=Cr(M.pathname,_);if(ie){let Z=I.get(ie.route.pattern);if(!Z||ie.route.isDynamic){let ce=await E(ie.route,ie.params);if(ce){if(Z=ce,!ie.route.isDynamic)I.set(ie.route.pattern,ce)}}if(Z){let ce=Z.content;if(k)ce=is(k,ce);if(Object.keys(ie.params).length>0)ce=St(ce,ie.params);if(ce=await x(ce,m),r)ce=Ue(ce,u);return new Response(ce,{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 oe)if(Z!=="/"&&M.pathname.startsWith(Z)){let ce=I.get(Z)||I.get(Z+"/");if(!ce){let fe=H.find(({route:B})=>B.pattern===Z||B.pattern===`${Z}/`);if(fe){let B=await E(fe.route);if(B)ce=B,I.set(fe.route.pattern,B)}}if(ce){let fe=ce.content;if(k)fe=is(k,fe);if(fe=await x(fe,m),r)fe=Ue(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(Nt(M.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let We=pe.get("/");if(We){let _=We.content;if(_=await x(_,m),r)_=Ue(_,u);if(t.native)if(_.includes("<head>"))_=_.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 _="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+_;return new Response(_,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let de=await se(404);if(de){let _=de;if(_=await x(_,m),r)_=Ue(_,u);return new Response(_,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(T){let M=await se(500);if(M)return new Response(M,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${T}
|
|
1006
1006
|
${T.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1007
1007
|
${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(`
|
|
1008
1008
|
${e.bright}\u2192 ${e.cyan}http://localhost:${Xe}/${e.reset}`),r)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
|
|
1009
1009
|
${e.yellow}Routes:${e.reset}`);let Tt=[...Vs(U,m)];for(let{route:T}of H)Tt.push(`${T.pattern}`);if(Tt.forEach((T,M)=>{let Q=M===Tt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${T}`)}),console.log(`
|
|
1010
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(kt.url.toString(),()=>{if(p)st();kt.stop()}),t.native){let T,M=re.join(A,"index.stx");if(me.existsSync(M)){let Q=await Bun.file(M).text();T=gt(Q)}let z=y?.app?.window??{};await Ye(Xe,{title:y?.app?.head?.title||re.basename(m)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??t.titlebarHidden===!0,nativeSidebar:!!T,sidebarConfig:T})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let T=(N)=>N.startsWith("public/")||N.startsWith("public\\"),M=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([m,...y._layerGraph?.layers.map((J)=>J.root)??[],...y._layerGraph?.configDependencies.map((J)=>re.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of y._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let ue=me.realpathSync(W);if(![...N].some((G)=>ue===G||ue.startsWith(`${G}${re.sep}`)))N.add(ue)}for(let[J,W]of z)if(!N.has(J))W.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(W,ue)=>{Re(J,W,ue).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Re=(N,J,W)=>(X=X.catch(()=>{}).then(()=>ve(N,J,W)),X),ve=async(N,J,W)=>{if(!W||xt(W))return;if(yt(W)){if(y._layerGraph){let ue=await b(m);Object.assign(y,ue),U.splice(0,U.length,...ne(w,{pagesDir:S,pagesDirs:ue._layerPageDirs?[A,...ue._layerPageDirs.slice(1)]:void 0})),Q()}if(T(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),r&&p)p.reload(W)}else if(M(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),at.clear(),ke();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-
|
|
1010
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(kt.url.toString(),()=>{if(p)st();kt.stop()}),t.native){let T,M=re.join(A,"index.stx");if(me.existsSync(M)){let Q=await Bun.file(M).text();T=gt(Q)}let z=y?.app?.window??{};await Ye(Xe,{title:y?.app?.head?.title||re.basename(m)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??t.titlebarHidden===!0,nativeSidebar:!!T,sidebarConfig:T})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let T=(N)=>N.startsWith("public/")||N.startsWith("public\\"),M=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([m,...y._layerGraph?.layers.map((J)=>J.root)??[],...y._layerGraph?.configDependencies.map((J)=>re.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of y._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let ue=me.realpathSync(W);if(![...N].some((G)=>ue===G||ue.startsWith(`${G}${re.sep}`)))N.add(ue)}for(let[J,W]of z)if(!N.has(J))W.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(W,ue)=>{Re(J,W,ue).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Re=(N,J,W)=>(X=X.catch(()=>{}).then(()=>ve(N,J,W)),X),ve=async(N,J,W)=>{if(!W||xt(W))return;if(yt(W)){if(y._layerGraph){let ue=await b(m);Object.assign(y,ue),U.splice(0,U.length,...ne(w,{pagesDir:S,pagesDirs:ue._layerPageDirs?[A,...ue._layerPageDirs.slice(1)]:void 0})),Q()}if(T(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),r&&p)p.reload(W)}else if(M(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),at.clear(),ke();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-z9x5pn5j.js");ue(re.resolve(N,W)),G.delete(re.resolve(N,W))}catch{}if(P&&W){if(re.resolve(N,W)===P||re.basename(P)===W){let G=await Oo(P,t.stxOptions||{});if(G)k=G}}if(await Be(),await yr(m),r&&p)p.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),at.clear(),ke();try{let{invalidateFileCache:ue,templateCache:G}=await import("./chunk-z9x5pn5j.js");ue(re.resolve(N,W)),G.delete(re.resolve(N,W))}catch{}if(await Be(),r&&p)p.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),r&&p)p.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(p)st();kt.stop(),process.exit(0)})}return!0}import At from"fs";import it from"path";async function Jn(n){try{let o=(await Bun.file(n).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],r=[],p=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=p.exec(d))!==null){let m=u[1],b=u[2]||u[3]||u[4];if(!b)continue;let y={name:b},v=m.match(/@type\s+\{([^}]+)\}/i);if(v)y.type=v[1].trim();if(m.match(/@required/i))y.required=!0;let R=m.match(/@default\s+(.+?)(?:\s+|$)/i);if(R)y.default=R[1].trim();let O=m.split(`
|
|
1011
1011
|
`).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);y.description=O.join(" ").trim(),r.push(y)}if(r.length===0){let m=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(m){let y=m[1].split(",").map((v)=>v.trim()).filter(Boolean);for(let v of y){let[C]=v.split(":").map((R)=>R.trim());if(C)r.push({name:C})}}}return r}catch(t){return console.error(`Error extracting props from ${n}:`,t),[]}}async function Yn(n){try{let t=await Bun.file(n).text(),o=t.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||t.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
|
|
1012
1012
|
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Qn(n,t=!1,o){let d=it.basename(n,".stx"),r=await Jn(n),p=await Yn(n),u="";if(t&&o)u=`<${o}></${o}>`;else{let m=r.map((b)=>{if(b.type==="boolean")return`:${b.name}="true"`;return`${b.name}="value"`}).join(`
|
|
1013
1013
|
`);u=`<${d}
|