@stacksjs/stx 0.2.689 → 0.2.690
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-5tkby4j6.js → chunk-063y8kcp.js} +1 -1
- package/dist/{chunk-ys6a6azq.js → chunk-1k7js5nz.js} +1 -1
- package/dist/{chunk-m2vm06rh.js → chunk-1pzshxft.js} +1 -1
- package/dist/chunk-2mf8shg5.js +2 -0
- package/dist/{chunk-3t8aag0q.js → chunk-35cvjgj2.js} +1 -1
- package/dist/{chunk-ys6zjdfc.js → chunk-43h27729.js} +3 -3
- package/dist/{chunk-jdb6qhat.js → chunk-4566drka.js} +1 -1
- package/dist/{chunk-6eazxhpe.js → chunk-4f5bmy7h.js} +6 -6
- package/dist/{chunk-yn9dwq2b.js → chunk-4hbevevz.js} +1 -1
- package/dist/{chunk-2h39d4wz.js → chunk-4mqq6896.js} +5 -5
- package/dist/chunk-5443hz48.js +2 -0
- package/dist/chunk-55eek6b1.js +2 -0
- package/dist/{chunk-m7ce359r.js → chunk-5gh02j5x.js} +1 -1
- package/dist/{chunk-5k013c4h.js → chunk-5m42k74p.js} +1 -1
- package/dist/{chunk-4mnynzf6.js → chunk-5mcwf93c.js} +2 -2
- package/dist/chunk-5y61b94b.js +2 -0
- package/dist/{chunk-3tv5h9xn.js → chunk-67mex2d1.js} +1 -1
- package/dist/{chunk-sbad32da.js → chunk-8485q7dh.js} +1 -1
- package/dist/{chunk-v1qkdg8f.js → chunk-84vsb4v3.js} +1 -1
- package/dist/{chunk-9629wqte.js → chunk-91ytsvhd.js} +1 -1
- package/dist/{chunk-5grcasys.js → chunk-a5agchz8.js} +1 -1
- package/dist/chunk-b6vwy6bd.js +2 -0
- package/dist/chunk-b8v19j69.js +2 -0
- package/dist/{chunk-km9qyqqm.js → chunk-bzxfbh2x.js} +1 -1
- package/dist/{chunk-736bs5xa.js → chunk-c9fs966z.js} +1 -1
- package/dist/{chunk-hyk31r03.js → chunk-cm8ad78x.js} +1 -1
- package/dist/{chunk-89m0kxj9.js → chunk-dsrgestd.js} +5 -5
- package/dist/{chunk-rcr7tncg.js → chunk-e9fmqn0g.js} +1 -1
- package/dist/{chunk-mxpmt6wm.js → chunk-ejafjap5.js} +1 -1
- package/dist/{chunk-ne7rbqw4.js → chunk-fk2m3xdd.js} +1 -1
- package/dist/{chunk-p7j8y51n.js → chunk-g9c284gf.js} +1 -1
- package/dist/{chunk-4cnphtcz.js → chunk-h176dx1q.js} +2 -2
- package/dist/{chunk-j7ktb5se.js → chunk-hqzhej1p.js} +2 -2
- package/dist/{chunk-bsnactb2.js → chunk-hy4gaf8g.js} +1 -1
- package/dist/{chunk-cbbheh2r.js → chunk-j5127cxs.js} +1 -1
- package/dist/{chunk-mm6xx4pm.js → chunk-jk0gba16.js} +2 -2
- package/dist/{chunk-60aezg8h.js → chunk-jkhc0q7g.js} +1 -1
- package/dist/{chunk-623w7x5z.js → chunk-jt9kxnva.js} +2 -2
- package/dist/{chunk-81meeqhp.js → chunk-mwmmmbxj.js} +4 -4
- package/dist/{chunk-a81452y9.js → chunk-n42421az.js} +2 -2
- package/dist/{chunk-rvebwzdj.js → chunk-nc85m4p9.js} +1 -1
- package/dist/{chunk-tbrznnt4.js → chunk-ngd9dsrd.js} +1 -1
- package/dist/chunk-nrw84rpj.js +2 -0
- package/dist/chunk-p7nkw2nr.js +2 -0
- package/dist/chunk-pj1we4mn.js +2 -0
- package/dist/{chunk-qm61depd.js → chunk-ppc64he4.js} +1 -1
- package/dist/{chunk-ryg1ww7v.js → chunk-psprkndv.js} +1 -1
- package/dist/{chunk-qw2skxm6.js → chunk-q3xesyn0.js} +1 -1
- package/dist/{chunk-0s6kqr1h.js → chunk-r86d03dv.js} +1 -1
- package/dist/{chunk-eq9s8dcp.js → chunk-s0226rfp.js} +4 -4
- package/dist/{chunk-9ed0hr7y.js → chunk-s0ntt1cn.js} +1 -1
- package/dist/{chunk-s6vn2w80.js → chunk-s0vs1n7n.js} +1 -1
- package/dist/{chunk-280pa4mp.js → chunk-sj6t3cj2.js} +1 -1
- package/dist/{chunk-b13rac0d.js → chunk-smqgdmc4.js} +1 -1
- package/dist/{chunk-bwcejt6t.js → chunk-tjwv101c.js} +1 -1
- package/dist/chunk-twk9kr73.js +2 -0
- package/dist/{chunk-qa2mkh94.js → chunk-v7xpafs9.js} +1 -1
- package/dist/{chunk-zgwp7pdp.js → chunk-vjt6c16n.js} +1 -1
- package/dist/{chunk-kkxwgx4n.js → chunk-vvezfjt1.js} +1 -1
- package/dist/chunk-ywydtzba.js +2 -0
- package/dist/{chunk-84fn7myr.js → chunk-yxp7jmnz.js} +1 -1
- package/dist/{chunk-q3kg8dde.js → chunk-znhrftsf.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-1w15scke.js +0 -2
- package/dist/chunk-2khba4de.js +0 -2
- package/dist/chunk-98sa3jgn.js +0 -2
- package/dist/chunk-9jwxj1yr.js +0 -2
- package/dist/chunk-a3s7tqsp.js +0 -2
- package/dist/chunk-dr7j2a0t.js +0 -2
- package/dist/chunk-ezj2c0gk.js +0 -2
- package/dist/chunk-gjj8krdx.js +0 -2
- package/dist/chunk-mj3y2dhh.js +0 -2
- package/dist/chunk-xzpwfs7n.js +0 -2
- package/dist/chunk-y4kzqam8.js +0 -2
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{B}from"./chunk-
|
|
2
|
+
import{B}from"./chunk-4f5bmy7h.js";import{Be,A,Nt}from"./chunk-t6m5d64b.js";import{ut,ke,O,_e,Ni,Vs,Di,Cn}from"./chunk-jk0gba16.js";import{vt,le,Ye}from"./chunk-kypwg2ws.js";import{Qs}from"./chunk-cm8ad78x.js";import{En}from"./chunk-pfn70zdr.js";import{he}from"./chunk-s0226rfp.js";import Z from"fs";import T from"path";var{serve:ce}=globalThis.Bun;import F from"zlib";import{promisify as Q}from"util";var K=Q(F.brotliCompress),ee=Q(F.gzip),te=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],ne=["text/event-stream","multipart/x-mixed-replace"],re=1024;function se(t){if(!t)return!1;let e=t.toLowerCase();if(ne.some((o)=>e.startsWith(o)))return!1;return te.some((o)=>e.startsWith(o))}function oe(t){let e=new Map;for(let o of t.split(",")){let[r,...a]=o.trim().split(";"),f=r.trim().toLowerCase();if(!f)continue;let h=1;for(let g of a){let l=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(g);if(!l)continue;let m=Number.parseFloat(l[1]);if(Number.isFinite(m))h=m}e.set(f,h)}return e}function ae(t){if(!t)return null;let e=oe(t),o=e.get("*"),r=(a)=>e.get(a)??o??0;if(r("br")>0)return"br";if(r("gzip")>0)return"gzip";return null}var Y=33554432,H=new Map,U=0;function ie(t,e){if(e.length>Y/8)return;H.set(t,e),U+=e.length;for(let[o,r]of H){if(U<=Y)break;H.delete(o),U-=r.length}}async function kn(t,e,o={}){if(e.headers.get("content-encoding"))return e;if(e.status===204||e.status===304||!e.body)return e;if(!se(e.headers.get("content-type")))return e;let r=ae(t.headers.get("accept-encoding"));if(!r)return e;let a;try{a=new Uint8Array(await e.arrayBuffer())}catch{return e}let f=()=>new Response(a,{status:e.status,statusText:e.statusText,headers:J(e.headers)});if(a.length<(o.threshold??re))return f();try{let h=o.quality??5,g=`${r}:${h}:${a.length}:${Bun.hash(a)}`,l=H.get(g);if(!l)l=r==="br"?await K(a,{params:{[F.constants.BROTLI_PARAM_QUALITY]:h,[F.constants.BROTLI_PARAM_SIZE_HINT]:a.length}}):await ee(a),ie(g,l);if(l.length>=a.length)return f();let m=J(e.headers);return m.set("Content-Encoding",r),m.set("Content-Length",String(l.length)),new Response(l,{status:e.status,statusText:e.statusText,headers:m})}catch{return f()}}function J(t){let e=new Headers(t),o=e.get("Vary");if(!o)return e.set("Vary","Accept-Encoding"),e;if(!o.split(",").some((a)=>a.trim().toLowerCase()==="accept-encoding"))e.set("Vary",`${o}, Accept-Encoding`);return e}class G{now;entries=new B(1000,{maxBytes:33554432,sizeOf:(t)=>t.body.byteLength+JSON.stringify(t.headers).length*2});pending=new Map;generation=0;constructor(t=Date.now){this.now=t}invalidate(t){this.generation++,this.pending.clear();for(let e of Array.from(this.entries.keys()))if(t===void 0||this.entries.get(e)?.path===t)this.entries.delete(e)}async respond(t,e,o){let r,a=async()=>{let s=r??await o();return s.headers.set("Cache-Control","private, no-store"),s.headers.set("Vary",O(s.headers.get("Vary")).Vary),s};if(!e||t.method!=="GET"||t.headers.has("Cookie")||t.headers.has("Authorization")||t.headers.has("Range"))return a();let f=new URL(t.url),h=`${f.origin}${f.pathname}${f.search}|${ke(t)?"fragment":"document"}`,g=this.entries.get(h),l=(s)=>{let b=new Headers(s.headers);return b.set("Cache-Control","private, no-store"),b.set("Age",String(Math.max(0,Math.floor((this.now()-s.created)/1000)))),new Response(s.body.slice(0),{headers:b})},m=g?(this.now()-g.created)/1000:1/0;if(g&&m<e.maxAge)return l(g);let v=this.generation,N=async()=>{let s=await o();r=s;let b=(s.headers.get("Vary")??"").toLowerCase().split(",").map((y)=>y.trim()).filter(Boolean);if(s.status!==200||s.headers.has("Set-Cookie")||/(?:private|no-store|no-cache)/i.test(s.headers.get("Cache-Control")??"")||b.some((y)=>y!=="x-stx-router"&&y!=="accept-encoding"))return null;let E=await s.clone().arrayBuffer();if(E.byteLength>1048576)return null;s.headers.set("Vary",O(s.headers.get("Vary")).Vary);let n={body:E,headers:Array.from(s.headers.entries()),created:this.now(),path:f.pathname};if(this.generation===v)this.entries.set(h,n);return n},x=this.pending.get(h);if(!x){if(this.pending.size>=1000)return a();x=N().finally(()=>{if(this.pending.get(h)===x)this.pending.delete(h)}),this.pending.set(h,x)}if(g&&m<e.maxAge+(e.swr??0))return x.catch(()=>{}),l(g);let M=await x;return M?l(M):a()}}var pe={".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".html":"text/html",".txt":"text/plain",".xml":"application/xml",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".mp4":"video/mp4",".webm":"video/webm",".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"};async function Ou(t={}){let e=T.resolve(t.outputDir||".output"),o=t.port??3000,r=Ni(e);if(!r)console.error("[stx] No build manifest found. Run `stx build` first."),process.exit(1);console.log(`[stx] Production server loading ${r.routes.length} routes...`);let a=En(r.routeRules),f=new G,h=Qs(e,r.apiRoutes??[]),g=Bun.file(T.join(e,"server/runtime-config.json")),l=t.runtimeConfig??(await g.exists()?await g.json():void 0),m=l?A(l):void 0,v=new Map,N=new Map,x=new Map,M=new Map;for(let n of r.routes)try{let y=T.join(e,n.compiledPath),i=JSON.parse(await Bun.file(y).text());if(m)i.html=Nt(i.html,m);v.set(n.pattern,i),x.set(n.pattern,Ye(i.html)),M.set(n.pattern,he(i.html));let X=T.join(e,n.fragmentPath);if(await Bun.file(X).exists()){let P=await Bun.file(X).text();N.set(n.pattern,m?Nt(P,m):P)}}catch(y){console.warn(`[stx] Failed to load route ${n.pattern}:`,y)}let s=new Map,b=[];for(let n of r.routes)if(n.hasParams){let{regex:y,params:i}=le(n.pattern,{page:!0});b.push({regex:y,route:n,paramNames:i})}else s.set(n.pattern,n);let E=ce({port:o,async fetch(n){return kn(n,await Be(m??A(),async()=>{let i=new URL(n.url).pathname;if(t.onRequest){let p=await t.onRequest(n);if(p)return p}if(t.apiRouter){let p=await t.apiRouter.handleRequest(n);if(p.status!==404)return p}if(t.apiRoutes?.[i])return t.apiRoutes[i](n);let X=await h(n);if(X)return X;if((n.method==="GET"||n.method==="HEAD")&&i!=="/"){let p=T.resolve(e,"public"),d;try{d=decodeURIComponent(i)}catch{d=i}if(!d.includes("\x00")){let u=T.resolve(p,`.${d}`);if(u===p||u.startsWith(`${p}${T.sep}`))try{if(Z.existsSync(u)&&Z.statSync(u).isFile()){let R=T.extname(u).toLowerCase(),L=pe[R]||"application/octet-stream",_=i.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(i);return new Response(Bun.file(u),{headers:{"Content-Type":L,"Cache-Control":_?"public, max-age=31536000, immutable":"public, max-age=3600"}})}}catch{}}}let P=ke(n),C=null,q={};if(C=s.get(i)||null,!C)for(let{regex:p,route:d,paramNames:u}of b){let c=i.match(p);if(c){C=d,u.forEach((R,L)=>{q[R]=c[L+1]});break}}if(!C){let p=vt(i)?null:s.get("/404")||null;if(p){let d=v.get(p.pattern);if(d)return new Response(d.html,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}})}let k=a(i),W=Object.keys(k).length>0;return f.respond(n,k.cache,async()=>{let p=v.get(C.pattern);if(P&&n.method==="GET"&&p&&!p.hasServerScripts&&Object.keys(p.placeholders).length===0){let c=N.get(C.pattern);if(c){let R=x.get(C.pattern);return new Response(c,{status:p.status??200,headers:{"Content-Type":"text/html","X-STX-Fragment":"true",...M.has(C.pattern)?{"X-STX-Runtime":M.get(C.pattern)?"true":"false"}:{},...R?{"X-STX-Layout":R.layout,"X-STX-Layout-Group":R.group}:{},...O(),...k.cache?{}:{"Cache-Control":ut}}})}}let d=Vs(n.method),u=v.get(C.pattern);if(!u){let c=s.get("/500")||null;if(c){let R=v.get(c.pattern);if(R)return new Response(R.html,{status:500,headers:{"Content-Type":"text/html"}})}return new Response("Internal Server Error",{status:500})}if(C.prerendered&&d)return new Response("Prerendered pages do not accept actions",{status:405,headers:{Allow:"GET, HEAD"}});if(!d&&!u.hasServerScripts&&Object.keys(u.placeholders).length===0)return new Response(u.html,{status:u.status??200,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"public, max-age=60"}});try{let{html:c,boundaries:R,redirect:L,cookies:_,status:I,headers:D}=await Cn(u,{params:q,request:n,method:n.method,__stx_strict_hydration:W,__stx_runtime_config:m});if(L)return Di(L,_,D);if(R&&R.length>0){let{renderStreamingPage:S,streamToResponse:z}=await import("./chunk-2mf8shg5.js"),j=new Headers({...O(),...D,"Cache-Control":"private, no-store"});for(let V of _??[])j.append("Set-Cookie",V);if(P&&!d){let V=Ye(c);j.set("X-STX-Fragment","true"),j.set("X-STX-Runtime",he(c)?"true":"false"),j.set("X-STX-Layout",V.layout),j.set("X-STX-Layout-Group",V.group)}return z(S(P&&!d?_e(c,r.routerContainer||"main"):c,R,{timeoutMs:30000}),{status:I??u.status??200,headers:j})}let w=new Headers({"Content-Type":"text/html",...O(),...k.cache?{}:{"Cache-Control":"private, no-store"}});for(let S of _??[])w.append("Set-Cookie",S);for(let[S,z]of Object.entries(D??{}))w.set(S,z);if(w.set("Vary",O(w.get("Vary")).Vary),P&&!d){let S=Ye(c);return w.set("X-STX-Fragment","true"),w.set("X-STX-Runtime",he(c)?"true":"false"),w.set("X-STX-Layout",S.layout),w.set("X-STX-Layout-Group",S.group),new Response(_e(c,r.routerContainer||"main"),{status:I??u.status??200,headers:w})}return new Response(c,{status:I??u.status??200,headers:w})}catch(c){if(console.error(`[stx] Hydration error for ${i}:`,c),W)return new Response("Internal Server Error",{status:500});return new Response(u.html,{headers:{"Content-Type":"text/html"}})}})}))}});return console.log(`[stx] Production server running at http://localhost:${E.port}`),console.log(`[stx] Serving ${r.routes.length} routes (${v.size} pre-loaded)`),{port:E.port,stop:()=>{f.invalidate(),E.stop()},invalidate:(n)=>f.invalidate(n)}}
|
|
3
3
|
export{kn,Ou};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import m from"path";var y=/__stxModules\["((?:[^"\\]|\\.)*)"\]/g;function I(...o){let r=new Set;for(let s of o){if(!s||!s.includes("__stxModules["))continue;for(let e of s.matchAll(y))try{r.add(JSON.parse(`"${e[1]}"`))}catch{}}return[...r].sort()}async function w(o,r={}){if(o.length===0)return null;let s=process.cwd(),e=[],a=[];o.forEach((t,c)=>{let i=t.startsWith("npm:")?t.slice(4):m.resolve(s,t),l=`__stxRegistered${c}`,p=JSON.stringify(t);e.push(`import * as ${l} from ${JSON.stringify(i)};`),a.push(`if (!globalThis.__stxModules[${p}]) globalThis.__stxModules[${p}] = ${l};`)});let d=[...e,"globalThis.__stxModules = globalThis.__stxModules || {};",...a].join(`
|
|
3
|
-
`),n;try{let{bundleClientScript:t}=await import("./chunk-
|
|
3
|
+
`),n;try{let{bundleClientScript:t}=await import("./chunk-v7xpafs9.js");n=await t(d,m.join(s,".stx-module-registry.ts"),{projectRoot:s,minify:r.minify,externalizeUserModules:!1,collectInputs:r.collectInputs,throwOnFailure:!0})}catch(t){let{formatBuildFailure:c}=await import("./chunk-6kam8r5y.js"),i=c(t);console.warn(`[stx] could not build the page module registry (#1957): ${i}`);let l=`[stx] the page module registry did not build, so ${o.join(", ")} cannot load (#1957): ${i}`;return`;console.error(${JSON.stringify(l)});`}let{transformAutoImports:f,generateAutoImportDestructuring:_}=await import("./chunk-vjt6c16n.js"),u=f(n),h=_(u.stxImports,u.browserImports),{transformStoreImports:x}=await import("./chunk-9859r1d5.js");n=x(u.code);let g=JSON.stringify(new Bun.CryptoHasher("md5").update(d).digest("hex").slice(0,12));return[";(function() {"," var __stxBundles = globalThis.__stxModuleBundles || (globalThis.__stxModuleBundles = {});",` if (__stxBundles[${g}]) return;`,` __stxBundles[${g}] = true;`,h,n,"})();"].join(`
|
|
4
4
|
`)}export{w as buildModuleRegistryScript,I as registeredModuleIdsIn};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{le}from"./chunk-kypwg2ws.js";import{Be,A}from"./chunk-t6m5d64b.js";import{Sa}from"./chunk-912r15hr.js";import{c}from"./chunk-xvs84gas.js";import S from"fs";import m from"path";import{pathToFileURL as O}from"url";var E=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],P=new Set;function en(s,l={}){let o=m.resolve(s,l.dir??"server/api"),i=[],f=new Map;if(!S.existsSync(o))return i;let t=Array.from(new Bun.Glob("**/*.{ts,js,mts,mjs}").scanSync({cwd:o})).sort();for(let e of t){if(e.endsWith(".d.ts"))continue;let p=e.replace(/\.(?:ts|js|mts|mjs)$/,"").split("/"),n=p.pop(),u=n.lastIndexOf("."),d=u>=0?n.slice(u+1):"get",g=d.toUpperCase();if(!E.includes(g)||d!==d.toLowerCase())throw Error(`Unsupported API method suffix in ${e}; use ${E.map((y)=>y.toLowerCase()).join(", ")}`);if(u>=0)n=n.slice(0,u);if(n!=="index")p.push(n);let r=new Set,h=p.map((y,I)=>{let v=/^\[(\.\.\.)?([A-Za-z_]\w*)\]$/.exec(y);if(v){if(r.has(v[2])||v[1]&&I!==p.length-1)throw Error(`Invalid API parameter in ${e}`);return r.add(v[2]),`:${v[2]}${v[1]?"*":""}`}if(!/^[\w-]+$/.test(y))throw Error(`Unsupported API path segment ${y} in ${e}`);return y}),w=`/api${h.length?`/${h.join("/")}`:""}`,x=`${g} ${w.replace(/:\w+/g,":param")}`;if(f.has(x))throw Error(`Ambiguous API route ${g} ${w}: ${f.get(x)} and ${e}`);f.set(x,e);let R=m.join(o,e);P.add(m.resolve(R)),P.add(S.realpathSync(R)),i.push({pattern:w,method:g,filePath:R})}return i.sort((e,a)=>{let p=e.pattern.split("/"),n=a.pattern.split("/"),u=(d)=>d?.endsWith("*")?0:d?.startsWith(":")?1:2;for(let d=0;d<Math.max(p.length,n.length);d++){let g=u(n[d])-u(p[d]);if(g)return g}return e.pattern.localeCompare(a.pattern)||e.method.localeCompare(a.method)})}async function Ys(s,l){let o=c(s,"api-types.d.ts"),i=["// Generated by stx. Include this file in tsconfig.json.","declare module '@stacksjs/stx/api-client' {"," interface KnownApiRoutes {"];for(let t of l){let e=`./${m.relative(m.dirname(o),t.filePath).replace(/\\/g,"/")}`,{params:a}=le(t.pattern);i.push(` ${JSON.stringify(`${t.method} ${t.pattern}`)}: { params: { ${a.map((p)=>`${JSON.stringify(p)}: string`).join("; ")} }; response: Awaited<ReturnType<typeof import(${JSON.stringify(e)}).default>> }`)}i.push(" }","}","export {}","");let f=i.join(`
|
|
3
3
|
`);if(!await Bun.file(o).exists()||await Bun.file(o).text()!==f)await Bun.write(o,f);return o}async function Zs(s,l,o={}){let i=en(s,o);await Ys(s,i);let f=[];for(let t of i){let e=await Bun.build({entrypoints:[t.filePath],target:"bun",format:"esm",minify:!1,splitting:!1});if(!e.success)throw Error(`API build failed for ${t.filePath}: ${e.logs.join(`
|
|
4
|
-
`)}`);let a=e.outputs.find((u)=>u.kind==="entry-point");if(!a)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await a.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(l,n),a),f.push({...t,filePath:n})}return f}function j(s,l){let o=s.map((i)=>({route:i,...le(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,a=(r)=>r.replace(/:\w+/g,":param"),p=t.filter((r)=>a(r.route.pattern)===a(e)),n=i.method,u=p.find((r)=>r.route.method===n)??(n==="HEAD"?p.find((r)=>r.route.method==="GET"):void 0);if(!u){let r=new Set(p.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=u.regex.exec(f),g=Object.create(null);try{u.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await l(u.route);if(typeof r!=="function")throw Error(`API endpoint ${u.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function Qs(s,l){return j(l,async(o)=>(await import(O(m.resolve(s,o.filePath)).href)).default)}async function lp(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=en(s,o);return await Ys(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=en(s,o);await Ys(s,t);let{loadStxConfig:e}=await import("./chunk-
|
|
4
|
+
`)}`);let a=e.outputs.find((u)=>u.kind==="entry-point");if(!a)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await a.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(l,n),a),f.push({...t,filePath:n})}return f}function j(s,l){let o=s.map((i)=>({route:i,...le(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,a=(r)=>r.replace(/:\w+/g,":param"),p=t.filter((r)=>a(r.route.pattern)===a(e)),n=i.method,u=p.find((r)=>r.route.method===n)??(n==="HEAD"?p.find((r)=>r.route.method==="GET"):void 0);if(!u){let r=new Set(p.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=u.regex.exec(f),g=Object.create(null);try{u.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await l(u.route);if(typeof r!=="function")throw Error(`API endpoint ${u.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function Qs(s,l){return j(l,async(o)=>(await import(O(m.resolve(s,o.filePath)).href)).default)}async function lp(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=en(s,o);return await Ys(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=en(s,o);await Ys(s,t);let{loadStxConfig:e}=await import("./chunk-063y8kcp.js"),a=A((await e(s)).runtimeConfig);return await Be(a,()=>j(t,async(p)=>{let n=await Bun.build({entrypoints:[p.filePath],target:"bun",format:"esm",splitting:!1});if(!n.success)throw Error(n.logs.join(`
|
|
5
5
|
`));let u=n.outputs.find((d)=>d.kind==="entry-point");if(!u||n.outputs.length!==1)throw Error(`Unsupported API bundle output: ${p.filePath}`);return(await import(`data:text/javascript;base64,${Buffer.from(await u.text()).toString("base64")}`)).default})(f))}catch(t){return console.error("[stx] API discovery failed:",t),Response.json({error:"API discovery failed; check the server log"},{status:500})}}}function eo(s,l,o){if(Sa(s))return!0;let i=/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/;if(i.test(m.basename(s)))return!0;try{if(i.test(m.basename(S.realpathSync(s))))return!0}catch{}if(P.has(m.resolve(s)))return!0;if(!o)return!1;let f=m.resolve(l,typeof o==="object"?o.dir??"server/api":"server/api"),t=(a)=>{try{return S.realpathSync(a)}catch{return m.resolve(a)}},e=t(s);return[f,m.resolve(l,"server"),m.resolve(l,".output/server")].some((a)=>{let p=t(a);return e===p||e.startsWith(`${p}${m.sep}`)})}
|
|
6
6
|
export{en,Ys,Zs,Qs,lp,eo};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{se,ue,un,At,Pt,g,n,pe,d}from"./chunk-
|
|
2
|
+
import{se,ue,un,At,Pt,g,n,pe,d}from"./chunk-4f5bmy7h.js";import{gt,$e,oa,Lr,to,no,o}from"./chunk-4mqq6896.js";import{ie,fr,xe,D,bn}from"./chunk-r0ys9aqa.js";import{vt,tr,ns,rs,ss,wt,xt,St,kt,_t,Ct,Ye}from"./chunk-kypwg2ws.js";import{Jr,i,R}from"./chunk-h176dx1q.js";import{ut,Ri,ke,O,Ai,Hs,Pr,Ve,Pi,_e}from"./chunk-jk0gba16.js";import{Zn,Qn}from"./chunk-nc85m4p9.js";import{kn}from"./chunk-bzxfbh2x.js";import{e,nn,Kn,h}from"./chunk-jt9kxnva.js";import{Ke}from"./chunk-mwmmmbxj.js";import{Te}from"./chunk-374nhgyf.js";import{q,he,ye}from"./chunk-s0226rfp.js";import{c}from"./chunk-xvs84gas.js";import{W}from"./chunk-078as147.js";async function Fn(t){try{let r=await Bun.file(t).text(),s=zn(r),p=Nn(r,t),a=Un(r,s),l=Wn(r,s);return{file:t,metrics:s,issues:p,suggestions:a,performance:l}}catch(r){throw Error(`Failed to analyze template ${t}: ${r instanceof Error?r.message:String(r)}`)}}function zn(t){let r=t.split(`
|
|
3
3
|
`),s=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),a=(s?s[1]:"").split(`
|
|
4
4
|
`).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let f=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,y=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,m=f+u+y,b=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,C=0;for(let T of r)if(/@(?:if|unless|foreach|for|while|section)\b/.test(T)&&!/@end/.test(T)&&!/@else/.test(T))C++,S=Math.max(S,C);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(T))C--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+m*0.1+b*0.3+(a>10?a*0.05:0)+v));return{lines:r.length,characters:t.length,directives:l,expressions:m,components:b,layouts:w,scriptLines:a,complexity:x}}function Nn(t,r){let s=[],p=Kt(t,"if","endif");if(p>0)s.push({type:"error",category:"syntax",message:`Found ${p} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let a=Kt(t,"foreach","endforeach");if(a>0)s.push({type:"error",category:"syntax",message:`Found ${a} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)s.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(f>0)s.push({type:"warning",category:"security",message:`Found ${f} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let u=t.match(/<img[^>]*>/g);if(u){let b=u.filter((w)=>!w.includes("alt="));if(b.length>0)s.push({type:"warning",category:"accessibility",message:`Found ${b.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let y=t.split(`
|
|
5
5
|
`).filter((b)=>b.length>120);if(y.length>0)s.push({type:"info",category:"maintainability",message:`Found ${y.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let m=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(m>3)s.push({type:"info",category:"maintainability",message:`Found ${m} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return s}function Un(t,r){let s=[];if(r.complexity>7)s.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(r.complexity>5&&r.directives.total>8)s.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(r.lines>100&&r.components===0)s.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(r.expressions>20)s.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)s.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(r.directives.total===0&&r.expressions<5)s.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(r.scriptLines>50)s.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return s}function Wn(t,r){let s=1;if(s+=r.directives.conditionals*0.1,s+=r.directives.loops*0.5,s+=r.directives.includes*2,s+=r.expressions*0.05,s+=r.components*1,r.scriptLines>10)s+=r.scriptLines*0.1;let p;if(r.expressions===0&&r.directives.total===0)p="high";else if(r.expressions<5&&r.directives.total<3)p="medium";else p="low";let a=[];if(s>10)a.push("Consider optimizing template complexity");if(p==="low"&&r.directives.total>5)a.push("Reduce dynamic content for better caching");if(r.components===0&&r.lines>40)a.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(s*100)/100,complexityScore:r.complexity,cacheability:p,recommendations:a}}function Kt(t,r,s){let p=t.replace(/<!--[\s\S]*?-->/g,""),a=(p.match(new RegExp(`@${r}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length;return Math.abs(a-l)}async function yi(t=["**/*.stx"],r){let s=[],p=[];for(let l of t){let f=await Array.fromAsync(new Bun.Glob(l).scan({cwd:r||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...f.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let f=await Fn(l);s.push(f)}catch(f){console.warn(`Failed to analyze ${l}:`,f)}let a=Vn(s);return{results:s,summary:a}}function Vn(t){let r=t.length,s=t.reduce((m,b)=>m+b.metrics.lines,0),p=r>0?t.reduce((m,b)=>m+b.metrics.complexity,0)/r:0,a=t.reduce((m,b)=>m+b.issues.length,0),l={};t.forEach((m)=>{m.issues.forEach((b)=>{l[b.category]=(l[b.category]||0)+1})});let f=r>0?t.reduce((m,b)=>m+b.performance.estimatedRenderTime,0)/r:0,u=Math.max(1,Math.min(10,Math.round(10-f/2-p/2))),y=[];if(p>6)y.push("Project has high average complexity. Consider refactoring complex templates.");if(a>r*2)y.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)y.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:r,totalLines:s,avgComplexity:Math.round(p*100)/100,totalIssues:a,issuesByCategory:l,performanceScore:u,recommendations:y}}import{mkdir as qn,readFile as Xn,readdir as Gn,stat as Xt,writeFile as Jn}from"fs/promises";import Re from"path";function en(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var tn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Yn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((r)=>r.charAt(0).toUpperCase()+r.slice(1)).join("")}function jt(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function er(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function nr(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function rr(t){let r=[];async function s(p){let a=await Gn(p,{withFileTypes:!0});a.sort((l,f)=>l.name.localeCompare(f.name));for(let l of a){let f=Re.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await s(f)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))r.push(f)}}return await s(t),r}function or(t,r){let s=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!s)return{};let p=s[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(a){throw Error(`${r}: <script component> must contain JSON metadata (${a.message})`)}}function sr(t,r){let s={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let a of p){if(!/\bclient\b/i.test(a[1])||/\bcomponent\b|\bstx:component\b/i.test(a[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(a[2])}catch(y){throw Error(`${r}: failed to transpile <script client> (${y.message})`)}let f=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=f.exec(l)){let y=u[1];if(tn.has(y))throw Error(`${r}: client ${en(y)}`);let m=f.lastIndex,b=1,w="",S=!1,C=m;for(;C<l.length&&b>0;C++){let x=l[C];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")b++;else if(x==="}")b--}if(b!==0)throw Error(`${r}: unterminated client function "${y}"`);let v=u[0].includes("async")?"async ":"";s[y]=`${v}${y}(${u[2]}) {${l.slice(m,C-1)}}`,f.lastIndex=C}}return s}function ir(t){let r=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(r?r[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Gt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((r)=>r[1].trim()).filter(Boolean).join(`
|
|
@@ -876,7 +876,7 @@ else {
|
|
|
876
876
|
};
|
|
877
877
|
})();
|
|
878
878
|
</script>
|
|
879
|
-
`}function Ne(t,r,s={}){let p=zr(r,s),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+p+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function yt(t){let r=t.toLowerCase();return r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".sass")||r.endsWith(".less")}function bt(t){let r=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>r.endsWith(p))}function Tt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((s)=>s.test(t))}var tt=null;function $t(t){if(!tt)tt=new on(t);return tt}function st(){if(tt)tt.stop(),tt=null}import Rt from"path";var nt={name:"bun-plugin-stx",async setup(t){let s={...await i(),...t.config?.stx},p=new Set,a=s.webComponents?.enabled?`./${Rt.relative(Rt.dirname(t.config?.outdir||"dist"),s.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(s.webComponents?.enabled)try{let f=await Jr(s,p);if(l.push(...f),s.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(s.cache&&s.cachePath){let x=await Zn(f,s);if(x){if(s.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let y=await xe(()=>Bun.file(f).text(),"",(x)=>{throw new fr(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new fr(`stx file is empty: ${f}`,f);let{scriptContent:m,templateContent:b,allScripts:w}=se.time("script-extraction",()=>{let x=y,T=ue(y);if(T)x=T.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],I="",A=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",j=E.match(/<script\b([^>]*)>/i),K=j?j[1]:"";if(/\bserver\b/i.test(K))I=_;else A.push(E)}let M=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:I,templateContent:M,allScripts:A}}),S={__filename:f,__dirname:Rt.dirname(f),__stx:{webComponentsPath:a,builtComponents:l}};await xe(()=>g(m,S,f),void 0,(x)=>{let T=new ie(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,m.substring(0,100));if(D.log(T,{filePath:f,scriptContent:m}),s.debug)throw T});let v=await se.timeAsync("directive-processing",async()=>await o(b,S,f,s,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-
|
|
879
|
+
`}function Ne(t,r,s={}){let p=zr(r,s),a=t.lastIndexOf("</body>");if(a!==-1)return t.slice(0,a)+p+t.slice(a);if(t.includes("</html>"))return t.replace("</html>",`${p}</html>`);return t+p}function yt(t){let r=t.toLowerCase();return r.endsWith(".css")||r.endsWith(".scss")||r.endsWith(".sass")||r.endsWith(".less")}function bt(t){let r=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((p)=>r.endsWith(p))}function Tt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((s)=>s.test(t))}var tt=null;function $t(t){if(!tt)tt=new on(t);return tt}function st(){if(tt)tt.stop(),tt=null}import Rt from"path";var nt={name:"bun-plugin-stx",async setup(t){let s={...await i(),...t.config?.stx},p=new Set,a=s.webComponents?.enabled?`./${Rt.relative(Rt.dirname(t.config?.outdir||"dist"),s.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(s.webComponents?.enabled)try{let f=await Jr(s,p);if(l.push(...f),s.debug&&f.length>0)console.log(`Successfully built ${f.length} web components`)}catch(f){console.error("Failed to build web components:",f)}t.onLoad({filter:/\.stx$/},async({path:f})=>{try{let u=new Set;if(s.cache&&s.cachePath){let x=await Zn(f,s);if(x){if(s.debug)console.log(`Using cached version of ${f}`);return{contents:x,loader:"html"}}}let y=await xe(()=>Bun.file(f).text(),"",(x)=>{throw new fr(`Failed to read stx file: ${f}`,f,void 0,void 0,`File read error: ${x.message}`)});if(!y)throw new fr(`stx file is empty: ${f}`,f);let{scriptContent:m,templateContent:b,allScripts:w}=se.time("script-extraction",()=>{let x=y,T=ue(y);if(T)x=T.content.trim();let k=y.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],I="",A=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",j=E.match(/<script\b([^>]*)>/i),K=j?j[1]:"";if(/\bserver\b/i.test(K))I=_;else A.push(E)}let M=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:I,templateContent:M,allScripts:A}}),S={__filename:f,__dirname:Rt.dirname(f),__stx:{webComponentsPath:a,builtComponents:l}};await xe(()=>g(m,S,f),void 0,(x)=>{let T=new ie(`Script execution failed in ${f}: ${x.message}`,f,void 0,void 0,m.substring(0,100));if(D.log(T,{filePath:f,scriptContent:m}),s.debug)throw T});let v=await se.timeAsync("directive-processing",async()=>await o(b,S,f,s,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-a5agchz8.js"),T=x(w.join(`
|
|
880
880
|
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
|
|
881
881
|
`+v.slice(k);else v+=`
|
|
882
882
|
${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await Qn(f,v,u,s),s.debug)console.log(`Cached template ${f} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let y=u instanceof Error?u:new ie(`Plugin processing failed: ${String(u)}`,f);if(D.log(y,{filePath:f,buildConfig:t.config}),bn.logDetailedError(y,{filePath:f,plugin:"bun-plugin-stx"}),s.debug)console.error("stx Plugin Error:",y);let m=y,b=m.line||null,w=m.context||null;return{contents:s.debug||W()?`<!DOCTYPE html>
|
|
@@ -939,7 +939,7 @@ ${T}`}if(v=await ye(v),u.forEach((x)=>p.add(x)),s.cache&&s.cachePath){if(await Q
|
|
|
939
939
|
<h1>Something went wrong</h1>
|
|
940
940
|
<p>An internal error occurred. Please try again later.</p>
|
|
941
941
|
</body>
|
|
942
|
-
</html>`,loader:"html"}}})}};async function Cr(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=ge.resolve(t);if(!Be.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,r);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=c(process.cwd(),"output");Be.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let m=null,b=async()=>{try{let _={name:"public-assets",setup(we){we.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},j=await Bun.build({entrypoints:[u],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!j.success)return console.error(`${e.red}Build failed:${e.reset}`,j.logs),!1;let K=j.outputs.find((we)=>we.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return m=await Bun.file(K.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await b())return!1;let S=ge.dirname(u);await nn(S);let C=s;try{if(C=await We(s),C!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let _=r.hmrPort||C+1;l=$t({wsPort:_,verbose:!1}),f=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-
|
|
942
|
+
</html>`,loader:"html"}}})}};async function Cr(t,r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=ge.resolve(t);if(!Be.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,r);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let y=c(process.cwd(),"output");Be.mkdirSync(y,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let m=null,b=async()=>{try{let _={name:"public-assets",setup(we){we.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},j=await Bun.build({entrypoints:[u],outdir:y,plugins:[_,nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.stxOptions});if(!j.success)return console.error(`${e.red}Build failed:${e.reset}`,j.logs),!1;let K=j.outputs.find((we)=>we.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return m=await Bun.file(K.path).text(),!0}catch(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!1}};if(!await b())return!1;let S=ge.dirname(u);await nn(S);let C=s;try{if(C=await We(s),C!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let _=r.hmrPort||C+1;l=$t({wsPort:_,verbose:!1}),f=l.start(_)}let v={},x=null,T;try{let{loadStxConfig:_}=await import("./chunk-twk9kr73.js"),j=await _();if(T=r.stxOptions?.serverApi??j.serverApi,j?.apiRouter)x=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){v=j.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Y}=await import("./chunk-9rv27cdd.js"),we=j.broadcasting;await K(we);let le=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Pe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Pe))try{let ne=await Y(Pe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:I}=await import("./chunk-1pzshxft.js"),A=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),a)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${f}${e.reset}`);let M=Nr({port:C,async fetch(_){return kn(_,await(async()=>{let j=new URL(_.url);if([y,ge.dirname(u),ge.join(process.cwd(),"public")].some((ne)=>I(ge.join(ne,j.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(_);if(ne.status!==404)return ne}catch{}if(v[j.pathname])try{return await v[j.pathname](_)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await A(_);if(K)return K;if(j.pathname==="/")return(async()=>{let F=await h(m||"");if(a)F=Ne(F,f);if(r.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(r.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(y,j.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),F=ge.extname(Y).toLowerCase(),L="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let we=ge.dirname(u),le=ge.join(we,j.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),F=ge.extname(le).toLowerCase(),L="text/plain";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Pe=ge.join(process.cwd(),"public",j.pathname);if(Be.existsSync(Pe)&&Be.statSync(Pe).isFile()){let ne=Bun.file(Pe),F=ge.extname(Pe).toLowerCase(),L="application/octet-stream";if(F===".ts"||F===".tsx"){let Fe=new Bun.Transpiler({loader:F===".tsx"?"tsx":"ts"}),ze=await ne.text(),Je=Fe.transformSync(ze);return new Response(Je,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(F){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
|
|
943
943
|
${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
944
944
|
${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(`
|
|
945
945
|
${e.bright}\u2192 ${e.cyan}http://localhost:${C}/${e.reset}`),console.log(`
|
|
@@ -1426,12 +1426,12 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1426
1426
|
${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(`
|
|
1427
1427
|
${e.bright}\u2192 ${e.cyan}http://localhost:${b}/${e.reset}`),console.log(`
|
|
1428
1428
|
${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),C=Object.entries(f).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ee.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Ee.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",I=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${I}`)}),console.log(`
|
|
1429
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(p)Xe.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),Ke.clear(),pe(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function ln(t){try{return un(await Bun.file(t).text())}catch{return}}function zt(t){let r=Bun.file(t),s=te.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(s)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(r,{headers:{"Content-Type":p[s]||"application/octet-stream",...l}})}async function Tr(t=".",r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=te.resolve(t),{loadStxConfig:y}=await import("./chunk-gjj8krdx.js"),m=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-m2vm06rh.js"),S=r.stxOptions?.serverApi??m.serverApi,C=await b(u,S),v=m.root&&m.root!=="."?te.join(u,m.root):u,x=r.pagesDir||m.pagesDir||"pages",T=te.join(v,x);if(!me.existsSync(T)&&!m._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=q(v,{pagesDir:x,pagesDirs:m._layerPageDirs?[T,...m._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let I=m?._pluginPageDirs||[],A=[];for(let{dir:P,prefix:H}of I)if(me.existsSync(P)){let z=q(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of z){let X=H==="/"?Q.pattern:`${H}${Q.pattern==="/"?"":Q.pattern}`;A.push({route:{...Q,pattern:X},prefix:H})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${H}${e.reset}`)}let M=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await Ai(u,r.stxOptions?.shell),_){if(E=await Hs(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}wt(),await St(u);let j=xt();if(j.length>0)console.log(`${e.blue}Loaded ${e.bright}${j.length}${e.blue} middleware: ${e.dim}${j.join(", ")}${e.reset}`);let K={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-gjj8krdx.js"),H=await P(u);if(H?.apiRouter)Y=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){K=H.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(H?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-9rv27cdd.js"),X=H.broadcasting;await z(X);let Oe=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let Se=te.join(process.cwd(),"channels.ts");if(me.existsSync(Se))try{let N=await Q(Se);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 we=c(u,"output");me.mkdirSync(we,{recursive:!0});let le=new Map,Pe=new Set,ne=async(P)=>{let H=rs(T,P);if(!H)return null;try{let z=await Bun.build({entrypoints:[H],outdir:we,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.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,L=async(P,H)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Oe,injectRouterScript:Se}=await import("./chunk-gjj8krdx.js"),{checkCache:N,cacheTemplate:J,readFileCached:V,templateCache:de}=await import("./chunk-60aezg8h.js"),G=await Oe(u),Ue=(ae)=>{if(!ae)return ae;if(te.isAbsolute(ae))return ae;return te.resolve(u,ae)},ce={...X,...G,...r.stxOptions,autoShell:!0};if(r.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(u,"cache");let B=!H&&!r.profile,re=ce.cache!==!1;if(re&&B){let ae=de.get(P.filePath);if(ae)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=ae.mtime){let He=!0;for(let Ce of ae.dependencies){if(!me.existsSync(Ce)){He=!1;break}if((await me.promises.stat(Ce)).mtime.getTime()>ae.mtime){He=!1;break}}if(He){let Ce=ae.output;if(E)Ce=Ve(Ce,{preserveHead:!0});let ot=F.get(P.filePath);return{route:P,content:Ce,status:ot?.status??await ln(P.filePath),headers:ot?.headers}}}}catch{}let Ie=await N(P.filePath,ce);if(Ie){let je=Ie;if(E)je=Ve(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await ln(P.filePath),headers:He?.headers}}}let Z=re?await V(P.filePath):await Bun.file(P.filePath).text(),oe=un(Z),{classifyAllScripts:fe}=await import("./chunk-gjj8krdx.js"),U=fe(Z),Le=U.server.map((ae)=>ae.content),De=Z;for(let ae of U.server)De=De.replace(ae.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:H??{},__stx_runtime_head:{}};for(let ae of Le)try{await Q(ae,ee,P.filePath)}catch(Ie){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Ae=new Set,be;if(r.profile){let ae=performance.now();be=await z(De,ee,P.filePath,ce,Ae);let Ie=performance.now()-ae,je=te.relative(u,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else be=await z(De,ee,P.filePath,ce,Ae);if(!E)be=await Se(be,{router:ce.router});{let{interpolateScriptExpressions:ae}=await import("./chunk-5grcasys.js");be=be.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ae(He,ee)}</script>`})}if(E)be=Ve(be,{preserveHead:!0});if(re&&B)await J(P.filePath,be,Ae,ce);let{extractStreamBoundaries:at}=await import("./chunk-2khba4de.js"),Qe=at(ee),rt=ee.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ae=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(rt).map((Ce)=>({id:Ce,render:async()=>{let ot=typeof ae[Ce]==="function"?await ae[Ce]():void 0;return z(rt[Ce],{...ee,$boundary:ot},P.filePath,Ie,new Set)}})),He=new Set(je.map((Ce)=>Ce.id));Qe=[...(Qe||[]).filter((Ce)=>!He.has(Ce.id)),...je]}if(Qe&&Qe.length>0)Pe.add(P.pattern);else Qe=void 0;let Wt=At(ee),Vt=Pt(ee);if(B)F.set(P.filePath,{status:Wt,headers:Vt});return{route:P,content:be,status:Wt??oe,headers:Vt,boundaries:Qe}}catch(z){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,z),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),H=new Set(M.keys());le.clear(),M.clear();let z=r.prebuild===!1?k.filter((X)=>P.has(X.pattern)):k,Q=r.prebuild===!1?A.filter(({route:X})=>H.has(X.pattern)):A;for(let X=0;X<z.length;X+=Fe){let Oe=z.slice(X,X+Fe),Se=await Promise.all(Oe.map((N)=>L(N)));for(let N of Se)if(N)le.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Oe=Q.slice(X,X+Fe),Se=await Promise.all(Oe.map(({route:N})=>L(N)));for(let N of Se)if(N)M.set(N.route.pattern,N)}return le.size>0};if(console.log(`${e.blue}${r.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(r.prebuild===!1?k.length+A.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await nn(u);let Ge=s;try{if(Ge=await We(s),Ge!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Ge+1;l=$t({wsPort:P,verbose:!1}),f=l.start(P)}let Ot=(P,H)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(H).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Wr({port:Ge,hostname:r.hostname,async fetch(P){let H=new URL(P.url),z=r.stxOptions?.offline??m.offline;if(H.pathname===to&&z?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:no(z,Lr()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=m?.publicDir||"public",X=te.join(u,Q,H.pathname),Oe=te.join(u,H.pathname),Se=te.join(we,H.pathname);if([X,Oe,Se].some((B)=>w(B,u,S)))return new Response("Not Found",{status:404});let[N,J,V]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(Se).catch(()=>null)]);if(N?.isFile()&&!w(X,u,S))return zt(X);if(J?.isFile()&&!w(Oe,u,S))return zt(Oe);if(V?.isFile()&&!w(Se,u,S))return zt(Se);if(H.pathname.startsWith("/_stx/component/")){let B=decodeURIComponent(H.pathname.slice(16));if(B)try{let re=`<${B} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(u,"components",`${B}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(H.pathname==="/_stx/img"){let{handleImageRequest:B}=await import("./chunk-ykjzhfyf.js"),re=await B(P,{publicDir:te.join(u,Q),cacheDir:c(u,"cache","img")});if(re)return re}if(Y)try{let B=await Y.handleRequest(P);if(B.status!==404)return B}catch{}if(K[H.pathname])try{return await K[H.pathname](P)}catch(B){return new Response(JSON.stringify({error:B.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await C(P);if(de)return de;let G=tr(H.pathname,k);if(G){let B=le.get(G.route.pattern),re=Pe.has(G.route.pattern);if(!B||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(B=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(B){let Z=B.status??200,oe=B.headers??{},fe=(G.route.filePath?gt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let De=await ne(404);if(De){let ee=De;if(ee=await h(ee,u),a)ee=Ne(ee,f);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Le=kt(H.pathname,G.params,fe,H.search),De=_t(Le,null,P,{isServer:!0}),ee=await Ct(fe.middleware,De);if(ee.redirect){let Ae=ee.redirect.path,be=ee.redirect.options.redirectCode||302,at=new Headers(ee.responseHeaders);return at.set("Location",Ae),new Response(null,{status:be,headers:at})}if(ee.abort){let{statusCode:Ae,message:be}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Ae}</title></head><body><h1>Error ${Ae}</h1><p>${be}</p></body></html>`,{status:Ae,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Ae=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;B.content=B.content.replace("</head>",`${Ae}</head>`)}}let U=B.content;if(E&&Pi(P)){let Le=Ye(U),De=he(U),ee=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Ae=ee?Ri(ee[1].trim()):"";if(Object.keys(G.params).length>0)U=Ot(U,G.params);U=await h(U,u);let be=m?.router?.container||"main";return U=_e(U,be),new Response(U,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Ae&&{"X-STX-Title":encodeURIComponent(Ae)},[oa]:Lr(),...O(),"Cache-Control":ut}})}if(E)U=Pr(E,U);if(Object.keys(G.params).length>0)U=Ot(U,G.params);if(U=await h(U,u),a)U=Ne(U,f);if(r.native)if(U.includes("<head>"))U=U.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 U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(r.titlebarHidden)if(U.includes("<head>"))U=U.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 U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;if(B.boundaries&&B.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-2khba4de.js");return De(Le(U,B.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:Z,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(A.length>0){let B=A.map((Z)=>Z.route),re=tr(H.pathname,B);if(re){let Z=M.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await L(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)M.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(E)oe=Pr(E,oe);if(Object.keys(re.params).length>0)oe=Ot(oe,re.params);if(oe=await h(oe,u),a)oe=Ne(oe,f);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of I)if(Z!=="/"&&H.pathname.startsWith(Z)){let oe=M.get(Z)||M.get(Z+"/");if(!oe){let fe=A.find(({route:U})=>U.pattern===Z||U.pattern===`${Z}/`);if(fe){let U=await L(fe.route);if(U)oe=U,M.set(fe.route.pattern,U)}}if(oe){let fe=oe.content;if(E)fe=Pr(E,fe);if(fe=await h(fe,u),a)fe=Ne(fe,f);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(vt(H.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let B=Ue.content;if(B=await h(B,u),a)B=Ne(B,f);if(r.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;return new Response(B,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let B=ce;if(B=await h(B,u),a)B=Ne(B,f);return new Response(B,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let H=await ne(500);if(H)return new Response(H,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1429
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(w.url.toString(),()=>{if(p)Xe.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Xe.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),Ke.clear(),pe(),await y()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function ln(t){try{return un(await Bun.file(t).text())}catch{return}}function zt(t){let r=Bun.file(t),s=te.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(s)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(r,{headers:{"Content-Type":p[s]||"application/octet-stream",...l}})}async function Tr(t=".",r={}){let s=r.port||3000,p=r.watch!==!1,a=r.hotReload!==!1&&p,l=null,f=r.hmrPort||s+1,u=te.resolve(t),{loadStxConfig:y}=await import("./chunk-twk9kr73.js"),m=await y(u),{createServerApi:b,isServerApiSource:w}=await import("./chunk-1pzshxft.js"),S=r.stxOptions?.serverApi??m.serverApi,C=await b(u,S),v=m.root&&m.root!=="."?te.join(u,m.root):u,x=r.pagesDir||m.pagesDir||"pages",T=te.join(v,x);if(!me.existsSync(T)&&!m._layerPageDirs?.some((P)=>me.existsSync(P)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=q(v,{pagesDir:x,pagesDirs:m._layerPageDirs?[T,...m._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let I=m?._pluginPageDirs||[],A=[];for(let{dir:P,prefix:H}of I)if(me.existsSync(P)){let z=q(te.dirname(P),{pagesDir:te.basename(P)});for(let Q of z){let X=H==="/"?Q.pattern:`${H}${Q.pattern==="/"?"":Q.pattern}`;A.push({route:{...Q,pattern:X},prefix:H})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${H}${e.reset}`)}let M=new Map,E=null,_=null;if(r.stxOptions?.shell!==!1){if(_=await Ai(u,r.stxOptions?.shell),_){if(E=await Hs(_,r.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}wt(),await St(u);let j=xt();if(j.length>0)console.log(`${e.blue}Loaded ${e.bright}${j.length}${e.blue} middleware: ${e.dim}${j.join(", ")}${e.reset}`);let K={},Y=null;try{let{loadStxConfig:P}=await import("./chunk-twk9kr73.js"),H=await P(u);if(H?.apiRouter)Y=H?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(H?.apiRoutes){K=H.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(H?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:Q}=await import("./chunk-9rv27cdd.js"),X=H.broadcasting;await z(X);let Oe=X.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Oe}/ws${e.reset}`);let Se=te.join(process.cwd(),"channels.ts");if(me.existsSync(Se))try{let N=await Q(Se);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 we=c(u,"output");me.mkdirSync(we,{recursive:!0});let le=new Map,Pe=new Set,ne=async(P)=>{let H=rs(T,P);if(!H)return null;try{let z=await Bun.build({entrypoints:[H],outdir:we,plugins:[nt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...r.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,L=async(P,H)=>{try{let{processDirectives:z,extractVariables:Q,defaultConfig:X,loadStxConfig:Oe,injectRouterScript:Se}=await import("./chunk-twk9kr73.js"),{checkCache:N,cacheTemplate:J,readFileCached:V,templateCache:de}=await import("./chunk-jkhc0q7g.js"),G=await Oe(u),Ue=(ae)=>{if(!ae)return ae;if(te.isAbsolute(ae))return ae;return te.resolve(u,ae)},ce={...X,...G,...r.stxOptions,autoShell:!0};if(r.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??c(u,"cache");let B=!H&&!r.profile,re=ce.cache!==!1;if(re&&B){let ae=de.get(P.filePath);if(ae)try{if((await me.promises.stat(P.filePath)).mtime.getTime()<=ae.mtime){let He=!0;for(let Ce of ae.dependencies){if(!me.existsSync(Ce)){He=!1;break}if((await me.promises.stat(Ce)).mtime.getTime()>ae.mtime){He=!1;break}}if(He){let Ce=ae.output;if(E)Ce=Ve(Ce,{preserveHead:!0});let ot=F.get(P.filePath);return{route:P,content:Ce,status:ot?.status??await ln(P.filePath),headers:ot?.headers}}}}catch{}let Ie=await N(P.filePath,ce);if(Ie){let je=Ie;if(E)je=Ve(je,{preserveHead:!0});let He=F.get(P.filePath);return{route:P,content:je,status:He?.status??await ln(P.filePath),headers:He?.headers}}}let Z=re?await V(P.filePath):await Bun.file(P.filePath).text(),oe=un(Z),{classifyAllScripts:fe}=await import("./chunk-twk9kr73.js"),U=fe(Z),Le=U.server.map((ae)=>ae.content),De=Z;for(let ae of U.server)De=De.replace(ae.fullTag,"");let ee={__filename:P.filePath,__dirname:te.dirname(P.filePath),__stx_options:ce,params:H??{},__stx_runtime_head:{}};for(let ae of Le)try{await Q(ae,ee,P.filePath)}catch(Ie){if(r.stxOptions?.debug)console.error("[stx] variable extraction error",P.filePath,Ie?.message||Ie)}let Ae=new Set,be;if(r.profile){let ae=performance.now();be=await z(De,ee,P.filePath,ce,Ae);let Ie=performance.now()-ae,je=te.relative(u,P.filePath)||P.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else be=await z(De,ee,P.filePath,ce,Ae);if(!E)be=await Se(be,{router:ce.router});{let{interpolateScriptExpressions:ae}=await import("./chunk-a5agchz8.js");be=be.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ae(He,ee)}</script>`})}if(E)be=Ve(be,{preserveHead:!0});if(re&&B)await J(P.filePath,be,Ae,ce);let{extractStreamBoundaries:at}=await import("./chunk-2mf8shg5.js"),Qe=at(ee),rt=ee.__streamTemplates;if(rt&&typeof rt==="object"&&Object.keys(rt).length>0){let ae=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(rt).map((Ce)=>({id:Ce,render:async()=>{let ot=typeof ae[Ce]==="function"?await ae[Ce]():void 0;return z(rt[Ce],{...ee,$boundary:ot},P.filePath,Ie,new Set)}})),He=new Set(je.map((Ce)=>Ce.id));Qe=[...(Qe||[]).filter((Ce)=>!He.has(Ce.id)),...je]}if(Qe&&Qe.length>0)Pe.add(P.pattern);else Qe=void 0;let Wt=At(ee),Vt=Pt(ee);if(B)F.set(P.filePath,{status:Wt,headers:Vt});return{route:P,content:be,status:Wt??oe,headers:Vt,boundaries:Qe}}catch(z){return console.error(`${e.red}Error building ${e.bright}${P.pattern}${e.reset}:`,z),null}},Fe=8,ze=async()=>{let P=new Set(le.keys()),H=new Set(M.keys());le.clear(),M.clear();let z=r.prebuild===!1?k.filter((X)=>P.has(X.pattern)):k,Q=r.prebuild===!1?A.filter(({route:X})=>H.has(X.pattern)):A;for(let X=0;X<z.length;X+=Fe){let Oe=z.slice(X,X+Fe),Se=await Promise.all(Oe.map((N)=>L(N)));for(let N of Se)if(N)le.set(N.route.pattern,N)}for(let X=0;X<Q.length;X+=Fe){let Oe=Q.slice(X,X+Fe),Se=await Promise.all(Oe.map(({route:N})=>L(N)));for(let N of Se)if(N)M.set(N.route.pattern,N)}return le.size>0};if(console.log(`${e.blue}${r.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(r.prebuild===!1?k.length+A.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await nn(u);let Ge=s;try{if(Ge=await We(s),Ge!==s)console.log(`${e.yellow}Port ${s} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(a){let P=r.hmrPort||Ge+1;l=$t({wsPort:P,verbose:!1}),f=l.start(P)}let Ot=(P,H)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(H).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(P.includes("</head>"))return P.replace("</head>",`${Q}</head>`);if(P.includes("<body"))return P.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+P};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Wr({port:Ge,hostname:r.hostname,async fetch(P){let H=new URL(P.url),z=r.stxOptions?.offline??m.offline;if(H.pathname===to&&z?.enabled){if(!["GET","HEAD"].includes(P.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(P.method==="HEAD"?null:no(z,Lr()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=m?.publicDir||"public",X=te.join(u,Q,H.pathname),Oe=te.join(u,H.pathname),Se=te.join(we,H.pathname);if([X,Oe,Se].some((B)=>w(B,u,S)))return new Response("Not Found",{status:404});let[N,J,V]=await Promise.all([me.promises.stat(X).catch(()=>null),me.promises.stat(Oe).catch(()=>null),me.promises.stat(Se).catch(()=>null)]);if(N?.isFile()&&!w(X,u,S))return zt(X);if(J?.isFile()&&!w(Oe,u,S))return zt(Oe);if(V?.isFile()&&!w(Se,u,S))return zt(Se);if(H.pathname.startsWith("/_stx/component/")){let B=decodeURIComponent(H.pathname.slice(16));if(B)try{let re=`<${B} />`,Z={...buildConfig,autoShell:!1},oe=await processDirectives(re,{},te.join(u,"components",`${B}.stx`),Z,new Set);return new Response(oe,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(H.pathname==="/_stx/img"){let{handleImageRequest:B}=await import("./chunk-ykjzhfyf.js"),re=await B(P,{publicDir:te.join(u,Q),cacheDir:c(u,"cache","img")});if(re)return re}if(Y)try{let B=await Y.handleRequest(P);if(B.status!==404)return B}catch{}if(K[H.pathname])try{return await K[H.pathname](P)}catch(B){return new Response(JSON.stringify({error:B.message}),{status:500,headers:{"Content-Type":"application/json"}})}let de=await C(P);if(de)return de;let G=tr(H.pathname,k);if(G){let B=le.get(G.route.pattern),re=Pe.has(G.route.pattern);if(!B||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(B=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(B){let Z=B.status??200,oe=B.headers??{},fe=(G.route.filePath?gt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(fe.validate){if(!await fe.validate({params:G.params})){let De=await ne(404);if(De){let ee=De;if(ee=await h(ee,u),a)ee=Ne(ee,f);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(fe.middleware){let Le=kt(H.pathname,G.params,fe,H.search),De=_t(Le,null,P,{isServer:!0}),ee=await Ct(fe.middleware,De);if(ee.redirect){let Ae=ee.redirect.path,be=ee.redirect.options.redirectCode||302,at=new Headers(ee.responseHeaders);return at.set("Location",Ae),new Response(null,{status:be,headers:at})}if(ee.abort){let{statusCode:Ae,message:be}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${Ae}</title></head><body><h1>Error ${Ae}</h1><p>${be}</p></body></html>`,{status:Ae,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let Ae=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;B.content=B.content.replace("</head>",`${Ae}</head>`)}}let U=B.content;if(E&&Pi(P)){let Le=Ye(U),De=he(U),ee=U.match(/<title[^>]*>([\s\S]*?)<\/title>/i),Ae=ee?Ri(ee[1].trim()):"";if(Object.keys(G.params).length>0)U=Ot(U,G.params);U=await h(U,u);let be=m?.router?.container||"main";return U=_e(U,be),new Response(U,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":De?"true":"false",...Ae&&{"X-STX-Title":encodeURIComponent(Ae)},[oa]:Lr(),...O(),"Cache-Control":ut}})}if(E)U=Pr(E,U);if(Object.keys(G.params).length>0)U=Ot(U,G.params);if(U=await h(U,u),a)U=Ne(U,f);if(r.native)if(U.includes("<head>"))U=U.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 U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(r.titlebarHidden)if(U.includes("<head>"))U=U.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 U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;if(B.boundaries&&B.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:De}=await import("./chunk-2mf8shg5.js");return De(Le(U,B.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(U,{status:Z,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...oe}})}}if(A.length>0){let B=A.map((Z)=>Z.route),re=tr(H.pathname,B);if(re){let Z=M.get(re.route.pattern);if(!Z||re.route.isDynamic){let oe=await L(re.route,re.params);if(oe){if(Z=oe,!re.route.isDynamic)M.set(re.route.pattern,oe)}}if(Z){let oe=Z.content;if(E)oe=Pr(E,oe);if(Object.keys(re.params).length>0)oe=Ot(oe,re.params);if(oe=await h(oe,u),a)oe=Ne(oe,f);return new Response(oe,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of I)if(Z!=="/"&&H.pathname.startsWith(Z)){let oe=M.get(Z)||M.get(Z+"/");if(!oe){let fe=A.find(({route:U})=>U.pattern===Z||U.pattern===`${Z}/`);if(fe){let U=await L(fe.route);if(U)oe=U,M.set(fe.route.pattern,U)}}if(oe){let fe=oe.content;if(E)fe=Pr(E,fe);if(fe=await h(fe,u),a)fe=Ne(fe,f);return new Response(fe,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(vt(H.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let B=Ue.content;if(B=await h(B,u),a)B=Ne(B,f);if(r.native)if(B.includes("<head>"))B=B.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else B="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+B;return new Response(B,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let B=ce;if(B=await h(B,u),a)B=Ne(B,f);return new Response(B,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(P){let H=await ne(500);if(H)return new Response(H,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${P}
|
|
1430
1430
|
${P.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1431
1431
|
${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(`
|
|
1432
1432
|
${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),a)console.log(`${e.dim} HMR: ws://localhost:${f}${e.reset}`);console.log(`
|
|
1433
1433
|
${e.yellow}Routes:${e.reset}`);let Mt=[...ss(k,u)];for(let{route:P}of A)Mt.push(`${P.pattern}`);if(Mt.forEach((P,H)=>{let Q=H===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${P}`)}),console.log(`
|
|
1434
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.url.toString(),()=>{if(l)st();Dt.stop()}),r.native){let P,H=te.join(T,"index.stx");if(me.existsSync(H)){let Q=await Bun.file(H).text();P=ht(Q)}let z=m?.app?.window??{};await Ze(Ge,{title:m?.app?.head?.title||te.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(N)=>N.startsWith("public/")||N.startsWith("public\\"),H=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([u,...m._layerGraph?.layers.map((J)=>J.root)??[],...m._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of m._layerGraph?.layers??[])for(let V of Object.values(J.resources)){if(!me.existsSync(V))continue;let de=me.realpathSync(V);if(![...N].some((G)=>de===G||de.startsWith(`${G}${te.sep}`)))N.add(de)}for(let[J,V]of z)if(!N.has(J))V.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(V,de)=>{Oe(J,V,de).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Oe=(N,J,V)=>(X=X.catch(()=>{}).then(()=>Se(N,J,V)),X),Se=async(N,J,V)=>{if(!V||Tt(V))return;if(bt(V)){if(m._layerGraph){let de=await y(u);Object.assign(m,de),k.splice(0,k.length,...q(v,{pagesDir:x,pagesDirs:de._layerPageDirs?[T,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),a&&l)l.reload(V)}else if(H(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-
|
|
1434
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),qe(Dt.url.toString(),()=>{if(l)st();Dt.stop()}),r.native){let P,H=te.join(T,"index.stx");if(me.existsSync(H)){let Q=await Bun.file(H).text();P=ht(Q)}let z=m?.app?.window??{};await Ze(Ge,{title:m?.app?.head?.title||te.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??r.titlebarHidden===!0,nativeSidebar:!!P,sidebarConfig:P})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let P=(N)=>N.startsWith("public/")||N.startsWith("public\\"),H=(N)=>{let J=N.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},z=new Map,Q=()=>{let N=new Set([u,...m._layerGraph?.layers.map((J)=>J.root)??[],...m._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of m._layerGraph?.layers??[])for(let V of Object.values(J.resources)){if(!me.existsSync(V))continue;let de=me.realpathSync(V);if(![...N].some((G)=>de===G||de.startsWith(`${G}${te.sep}`)))N.add(de)}for(let[J,V]of z)if(!N.has(J))V.close(),z.delete(J);for(let J of N)if(!z.has(J)&&me.existsSync(J))z.set(J,me.watch(J,{recursive:!0},(V,de)=>{Oe(J,V,de).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},X=Promise.resolve(),Oe=(N,J,V)=>(X=X.catch(()=>{}).then(()=>Se(N,J,V)),X),Se=async(N,J,V)=>{if(!V||Tt(V))return;if(bt(V)){if(m._layerGraph){let de=await y(u);Object.assign(m,de),k.splice(0,k.length,...q(v,{pagesDir:x,pagesDirs:de._layerPageDirs?[T,...de._layerPageDirs.slice(1)]:void 0})),Q()}if(P(V)){if(console.log(`${e.cyan}${V} changed${e.reset}`),a&&l)l.reload(V)}else if(H(V)){console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-jkhc0q7g.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(_&&V){if(te.resolve(N,V)===_||te.basename(_)===V){let G=await Hs(_,r.stxOptions||{});if(G)E=G}}if(await ze(),await Kn(u),a&&l)l.reload(V)}else{console.log(`${e.yellow}${V} changed, rebuilding...${e.reset}`),Ke.clear(),pe();try{let{invalidateFileCache:de,templateCache:G}=await import("./chunk-jkhc0q7g.js");de(te.resolve(N,V)),G.delete(te.resolve(N,V))}catch{}if(await ze(),a&&l)l.reload(V)}}else if(yt(V)){if(console.log(`${e.cyan}CSS ${V} changed${e.reset}`),a&&l)l.updateCss(V)}};Q(),process.on("SIGINT",()=>{for(let N of z.values())N.close();if(l)st();Dt.stop(),process.exit(0)})}return!0}import Nt from"fs";import it from"path";async function Vr(t){try{let s=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!s)return[];let p=s[1],a=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,f;while((f=l.exec(p))!==null){let u=f[1],y=f[2]||f[3]||f[4];if(!y)continue;let m={name:y},b=u.match(/@type\s+\{([^}]+)\}/i);if(b)m.type=b[1].trim();if(u.match(/@required/i))m.required=!0;let S=u.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)m.default=S[1].trim();let C=u.split(`
|
|
1435
1435
|
`).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);m.description=C.join(" ").trim(),a.push(m)}if(a.length===0){let u=p.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(u){let m=u[1].split(",").map((b)=>b.trim()).filter(Boolean);for(let b of m){let[w]=b.split(":").map((S)=>S.trim());if(w)a.push({name:w})}}}return a}catch(r){return console.error(`Error extracting props from ${t}:`,r),[]}}async function qr(t){try{let r=await Bun.file(t).text(),s=r.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||r.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(s)return s[1].split(`
|
|
1436
1436
|
`).map((p)=>p.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Kr(t,r=!1,s){let p=it.basename(t,".stx"),a=await Vr(t),l=await qr(t),f="";if(r&&s)f=`<${s}></${s}>`;else{let u=a.map((y)=>{if(y.type==="boolean")return`:${y.name}="true"`;return`${y.name}="value"`}).join(`
|
|
1437
1437
|
`);f=`<${p}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{$l,Vr}from"./chunk-
|
|
2
|
+
import{$l,Vr}from"./chunk-vvezfjt1.js";import"./chunk-hx787tfa.js";import"./chunk-jgxzbthg.js";import{ur}from"./chunk-4f5bmy7h.js";import"./chunk-tjwv101c.js";import"./chunk-t6m5d64b.js";import{tt}from"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{tt as freeIdentifiers,Vr as processComponents,$l as processESImports,ur as rendersAsElement};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Vn,Te}from"./chunk-374nhgyf.js";import{L,b,ir,ds,k}from"./chunk-6eazxhpe.js";import{i,R}from"./chunk-4cnphtcz.js";import{eo}from"./chunk-hyk31r03.js";import{Qe}from"./chunk-yn9kvsk1.js";import{c}from"./chunk-xvs84gas.js";import{r,fe}from"./chunk-9tg4995v.js";import d from"path";import v from"fs";import{AsyncLocalStorage as gt}from"async_hooks";var ht=11;function X(t,e,n){return/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(d.basename(t))||eo(t,e,n)}var ot=2;function gl(t){let e=process.env.STX_BUNDLE_CACHE_DIR?.trim();return e?d.resolve(e):c(t,"bundle-cache")}function nt(t,e){let n=t;for(let o of xt(e))if(o!==d.sep)n=n.split(o).join("\x00root");return n}var st=new Map;function xt(t){let e=d.resolve(t),n=st.get(e);if(!n){let o=e;try{o=v.realpathSync(e)}catch{}n=[...new Set([e,o])].sort((u,m)=>m.length-u.length),st.set(e,n)}return n}function $t(t,e){try{let n=v.statSync(t),o=d.resolve(e),u=t.startsWith(`${o}${d.sep}`);return{path:u?d.relative(o,t):t,...u?{inRoot:!0}:{},mtimeMs:n.mtimeMs,size:n.size,hash:Bun.hash(v.readFileSync(t)).toString(36)}}catch{return null}}function at(t,e){return t.inRoot?d.join(d.resolve(e),t.path):t.path}function yt(t,e){for(let n of t){let o=at(n,e);try{let u=v.statSync(o);if(u.size!==n.size)return!1;if(u.mtimeMs!==n.mtimeMs&&Bun.hash(v.readFileSync(o)).toString(36)!==n.hash)return!1}catch{return!1}}return!0}var ct=new Map,bt=100;function ml(t=process.env){let e=Number(t.STX_BUNDLE_CACHE_LIMIT);return Number.isFinite(e)&&e>=1?Math.floor(e):2000}var G=new Map;async function wt(t){let e=G.get(t)??0;if(e>0&&e<bt){G.set(t,e+1);return}G.set(t,1);try{let n=(await v.promises.readdir(t)).filter((l)=>l.endsWith(".js")),o=ml();if(n.length<=o)return;let m=(await Promise.all(n.map(async(l)=>{try{return{name:l,at:(await v.promises.stat(d.join(t,l))).mtimeMs}}catch{return null}}))).filter((l)=>l!==null);m.sort((l,y)=>y.at-l.at);for(let l of m.slice(o)){let y=l.name.slice(0,-3);await v.promises.rm(d.join(t,`${y}.js`),{force:!0}),await v.promises.rm(d.join(t,`${y}.deps.json`),{force:!0})}O("pruned bundle cache to",o,"entries")}catch{}}function Ee(t){return ct.get(t)??[]}function q(t,e){if(t)ct.set(t,e)}function hl(t=process.env){return t.STX_DEBUG==="true"||t.STX_DEBUG==="1"}function O(...t){if(hl())console.log("[stx:bundler]",...t)}var Y=[];function ra(t,e,n){Y.push({filePath:t||"<inline>",message:e,details:n})}function Xt(){return Y.slice()}function Jt(){Y.length=0}var Z;function cp(t){Z=t}function sa(){if(Z)return Z;try{let t=R.strict;return typeof t==="object"&&t!==null?t.bundlerFallback??"warn":"warn"}catch{return"warn"}}var Q=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function Yt(t){let e=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,n;while((n=e.exec(t))!==null){let u=n[1];if(!Q.some((l)=>l.test(u)))return O("detected user import:",u),!0}let o=/^[ \t]*import[ \t]*['"]([^'"]+)['"]/gm;while((n=o.exec(t))!==null){let u=n[1];if(/\.css(?:\?.*)?$/.test(u))continue;if(!Q.some((l)=>l.test(u)))return O("detected side-effect import:",u),!0}return!1}var Hn="stx-module:",St=/\.(?:[cm]?[jt]sx?|json)$/i;function yl(t,e){return d.relative(t,e).split(d.sep).join("/")}function bl(t,e){if(e.size===0)return t;return t.replace(/^([ \t]*import(?:(?:\s+|(?=[{*]))[^;"']*?\s*from\s*|\s*))(["'])([^"']+)\2/gm,(n,o,u,m)=>{let l=e.get(m);return l&&!m.startsWith(Hn)?`${o}${u}${l}${u}`:n})}function vl(t,e){let n=0,o=(m)=>{let l=`__stxMod${n++}`,y=JSON.stringify(m);return e.push(`var ${l} = globalThis.__stxModules && globalThis.__stxModules[${y}];`,`if (${l} === undefined) throw new Error("[stx] module " + ${JSON.stringify(y)} + " is not registered on this page (#1957)");`),l},u=(m,l)=>{for(let y of m.split(",")){let F=y.trim();if(!F)continue;let B=F.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!B)continue;let j=B[1].startsWith('"')?JSON.parse(B[1]):B[1],p=B[2]??j;e.push(`var ${p} = ${l}[${JSON.stringify(j)}];`)}};return t=t.replace(/^[ \t]*import(?:\s+|(?=[{*]))([^;"']+?)\s*from\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(m,l,y)=>{let F=y.slice(Hn.length),B=o(F),j=l.trim(),p=j.match(/^([\w$]+)\s*(?:,\s*|$)/);if(p&&!j.startsWith("{")&&!j.startsWith("*"))e.push(`var ${p[1]} = ${B}.default;`),j=j.slice(p[0].length).trim();let s=j.match(/^\*\s*as\s+([\w$]+)$/);if(s)e.push(`var ${s[1]} = ${B};`);else if(j.startsWith("{"))u(j.replace(/^\{|\}$/g,""),B);return""}),t=t.replace(/^[ \t]*import\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(m,l)=>(o(l.slice(Hn.length)),"")),t}function rt(t){let e=[t,`${t}.ts`,`${t}.tsx`,`${t}.js`,`${t}.mjs`,`${t}.jsx`,d.join(t,"index.ts"),d.join(t,"index.tsx"),d.join(t,"index.js"),d.join(t,"index.mjs")];for(let n of e)try{if(v.existsSync(n)&&v.statSync(n,{throwIfNoEntry:!1})?.isFile())return n}catch{}return}var K=new gt;function Js(t,e){let n=new Bun.CryptoHasher("md5");for(let[o,u]of[...t].sort(([m],[l])=>m<l?-1:m>l?1:0))n.update(`${o}\x00${u}\x00`);return K.run({modules:t,key:n.digest("hex").slice(0,12)},e)}function Zt(){return K.getStore()?.key??""}function vt(t,e,n,o,u,m,l=new Map,y,F){let B=(p,s,a)=>{if(X(s,t,y))return null;if(!m||p!==n||!St.test(s))return null;try{if(!v.statSync(s,{throwIfNoEntry:!1})?.isFile())return null}catch{return null}u.add(s);let w=`${Hn}${yl(process.cwd(),s)}`;return l.set(a,w),{path:w,external:!0}},j=(p,s)=>{let a=p===n?e:d.dirname(p),w=d.resolve(a,s);return rt(w)??w};return{name:"stx-client-bundle",setup(p){if(p.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(s)=>({path:s.path,external:!0})),p.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(s)=>({path:s.path,external:!0})),p.onResolve({filter:/^\//},(s)=>{if(s.path===n)return{path:n};let a=rt(s.path);if(a){let w=B(s.importer,a,s.path);if(w)return w;if(a!==n)u.add(a);return{path:a}}return{path:s.path,external:!0}}),p.onResolve({filter:/^\.\.?\//},(s)=>{let a=j(s.importer,s.path),w=B(s.importer,a,s.path);if(w)return w;return u.add(a),{path:a}}),p.onResolve({filter:/^[@~]\//},(s)=>{let a=d.resolve(t,s.path.slice(2)),w=[a,`${a}.ts`,`${a}.tsx`,`${a}.js`,`${a}.mjs`,`${a}.jsx`,d.join(a,"index.ts"),d.join(a,"index.tsx"),d.join(a,"index.js"),d.join(a,"index.mjs")];for(let x of w)if(v.existsSync(x)&&v.statSync(x,{throwIfNoEntry:!1})?.isFile()){let A=B(s.importer,x,s.path);if(A)return A;return O(`resolved ${s.path[0]}/ import:`,s.path,"\u2192",x),u.add(x),{path:x}}return console.warn(`[stx:bundler] could not resolve ${s.path[0]}/ import:`,s.path),{path:a}}),m)p.onResolve({filter:/^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/},(s)=>{if(s.importer!==n)return;let a=`${Hn}npm:${s.path}`;return l.set(s.path,a),{path:a,external:!0}});p.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(s)=>{if(s.path===n)return{contents:o,loader:"ts"};if(X(s.path,t,y))throw Error(`Server-only API source cannot be imported by a client script: ${s.path}`);let a=d.extname(s.path).toLowerCase(),w=a===".json"?"json":a===".tsx"?"tsx":a===".jsx"?"jsx":a===".ts"||a===".mts"||a===".cts"?"ts":"js";if(s.path!==n)u.add(s.path);let x=F?.get(s.path);if(x!==void 0)return{contents:x,loader:"js"};return{contents:v.readFileSync(s.path,"utf8"),loader:w}})}}}var H=new Map,P=b(64),it=Symbol.for("stx.client-bundle-build-queue");function wl(t){let e=globalThis,o=(e[it]??Promise.resolve()).then(t,t);return e[it]=o.then(()=>{return},()=>{return}),o}async function Qt(t,e,n={}){let o=n.projectRoot||process.cwd(),u=(await i(o)).serverApi,m=n.minify??!1,l=n.externalizeUserModules??!0,y=n.expose?.length?[...new Set(n.expose)].sort():void 0,F=n.cacheDir||gl(o),B=K.getStore(),j=new Bun.CryptoHasher("md5");j.update(`${ht}\x00${Qe()}\x00${JSON.stringify(u??!1)}\x00${l?"registry":"inline"}\x00${y?y.join(","):"*"}\x00${m?"minified":"readable"}\x00${B?.key??""}\x00${nt(t,o)}\x00${nt(e,o)}`);let p=j.digest("hex").slice(0,12),s=d.join(F,`${p}.js`),a=P.get(s);if(a){if(ds(a.files)&&a.files.every((M)=>!X(M.path,o,u))){O("memo hit:",p);let M=a.files.map((C)=>C.path);return q(e,M),n.collectInputs?.push(...M),a.code}P.delete(s),O("memo invalidated by dep change:",p)}let w=d.join(F,`${p}.deps.json`),x=Bun.file(s);if(await x.exists()){let M=Bun.file(w),C=!1,D=null;if(await M.exists())try{let I=JSON.parse(await M.text());if(I.metadataVersion===ot&&Array.isArray(I.files)&&yt(I.files,o))D=ir(I.files.map((g)=>at(g,o))),C=D.length===I.files.length&&!D.some((g)=>X(g.path,o,u))}catch{C=!1}if(C){if(O("cache hit:",p),D)q(e,D.map((T)=>T.path)),n.collectInputs?.push(...D.map((T)=>T.path));let I=await x.text(),g=new Date;if(v.promises.utimes(s,g,g).catch(()=>{}),D)P.set(s,{code:I,files:D});return I}O("cache invalidated by dep change:",p)}let A=H.get(p);if(A){let M=await A;if(n.collectInputs)n.collectInputs.push(...(P.get(s)?.files??[]).map((C)=>C.path));return M}let V=wl(()=>jt(t,e,{projectRoot:o,minify:m,cacheDir:F,hash:p,cachePath:s,depsPath:w,collectInputs:n.collectInputs,externalizeUserModules:l,serverApi:u,expose:y,throwOnFailure:n.throwOnFailure,substitutes:B?.modules}));H.set(p,V);try{return await V}finally{H.delete(p)}}var Bt=0;function xl(t){return`${t}-${process.pid}-${++Bt}`}async function jt(t,e,n){let{projectRoot:o,minify:u,cacheDir:m,hash:l,cachePath:y,depsPath:F,externalizeUserModules:B}=n,j=c(o,"bundle-tmp"),p=xl(l),s=d.join(o,`.stx-client-${p}.ts`),a=d.join(j,"out",p);v.mkdirSync(a,{recursive:!0});let w=d.dirname(e),x=new Set,A=/^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,V=/^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm,M=r(t),{depths:C,balanced:D}=fe(M),I=(_)=>!D||C[_]===0,g;while((g=A.exec(M))!==null){if(g[1])continue;if(!I(g.index))continue;if(g[2])g[2].split(",").forEach((_)=>{let f=_t(_);if(f)x.add(f)});else if(g[3])x.add(g[3])}while((g=V.exec(M))!==null){if(g[1])continue;if(!I(g.index))continue;x.add(g[2])}let T=/^[ \t]*import[ \t]+(?!type\b)(?:(\w+)\s*(?:,\s*)?)?(?:\*\s+as\s+(\w+)|\{([^}]+)\})?\s+from\b/gm;while((g=T.exec(M))!==null){if(!I(g.index))continue;let _=/^\s*['"]([^'"]+)['"]/.exec(t.slice(g.index+g[0].length))?.[1];if(_&&Q.some((f)=>f.test(_)))continue;if(g[1])x.add(g[1]);if(g[2])x.add(g[2]);for(let f of(g[3]??"").split(",")){let S=f.trim();if(!S||/^type\s/.test(S))continue;let U=/\bas\s+(\w+)\s*$/.exec(S)?.[1]??/^\w+$/.exec(S)?.[0];if(U)x.add(U)}}for(let _ of M.matchAll(/\bexport\s*\{([^}]+)\}/g))for(let f of _[1].split(",")){let S=/\bas\s+(\w+)\s*$/.exec(f)?.[1]??/^\s*(\w+)\s*$/.exec(f)?.[1];if(S)x.delete(S)}let lt=x.size>0?`
|
|
2
|
+
import{Vn,Te}from"./chunk-374nhgyf.js";import{L,b,ir,ds,k}from"./chunk-4f5bmy7h.js";import{i,R}from"./chunk-h176dx1q.js";import{eo}from"./chunk-cm8ad78x.js";import{Qe}from"./chunk-yn9kvsk1.js";import{c}from"./chunk-xvs84gas.js";import{r,fe}from"./chunk-9tg4995v.js";import d from"path";import v from"fs";import{AsyncLocalStorage as gt}from"async_hooks";var ht=11;function X(t,e,n){return/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(d.basename(t))||eo(t,e,n)}var ot=2;function gl(t){let e=process.env.STX_BUNDLE_CACHE_DIR?.trim();return e?d.resolve(e):c(t,"bundle-cache")}function nt(t,e){let n=t;for(let o of xt(e))if(o!==d.sep)n=n.split(o).join("\x00root");return n}var st=new Map;function xt(t){let e=d.resolve(t),n=st.get(e);if(!n){let o=e;try{o=v.realpathSync(e)}catch{}n=[...new Set([e,o])].sort((u,m)=>m.length-u.length),st.set(e,n)}return n}function $t(t,e){try{let n=v.statSync(t),o=d.resolve(e),u=t.startsWith(`${o}${d.sep}`);return{path:u?d.relative(o,t):t,...u?{inRoot:!0}:{},mtimeMs:n.mtimeMs,size:n.size,hash:Bun.hash(v.readFileSync(t)).toString(36)}}catch{return null}}function at(t,e){return t.inRoot?d.join(d.resolve(e),t.path):t.path}function yt(t,e){for(let n of t){let o=at(n,e);try{let u=v.statSync(o);if(u.size!==n.size)return!1;if(u.mtimeMs!==n.mtimeMs&&Bun.hash(v.readFileSync(o)).toString(36)!==n.hash)return!1}catch{return!1}}return!0}var ct=new Map,bt=100;function ml(t=process.env){let e=Number(t.STX_BUNDLE_CACHE_LIMIT);return Number.isFinite(e)&&e>=1?Math.floor(e):2000}var G=new Map;async function wt(t){let e=G.get(t)??0;if(e>0&&e<bt){G.set(t,e+1);return}G.set(t,1);try{let n=(await v.promises.readdir(t)).filter((l)=>l.endsWith(".js")),o=ml();if(n.length<=o)return;let m=(await Promise.all(n.map(async(l)=>{try{return{name:l,at:(await v.promises.stat(d.join(t,l))).mtimeMs}}catch{return null}}))).filter((l)=>l!==null);m.sort((l,y)=>y.at-l.at);for(let l of m.slice(o)){let y=l.name.slice(0,-3);await v.promises.rm(d.join(t,`${y}.js`),{force:!0}),await v.promises.rm(d.join(t,`${y}.deps.json`),{force:!0})}O("pruned bundle cache to",o,"entries")}catch{}}function Ee(t){return ct.get(t)??[]}function q(t,e){if(t)ct.set(t,e)}function hl(t=process.env){return t.STX_DEBUG==="true"||t.STX_DEBUG==="1"}function O(...t){if(hl())console.log("[stx:bundler]",...t)}var Y=[];function ra(t,e,n){Y.push({filePath:t||"<inline>",message:e,details:n})}function Xt(){return Y.slice()}function Jt(){Y.length=0}var Z;function cp(t){Z=t}function sa(){if(Z)return Z;try{let t=R.strict;return typeof t==="object"&&t!==null?t.bundlerFallback??"warn":"warn"}catch{return"warn"}}var Q=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function Yt(t){let e=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,n;while((n=e.exec(t))!==null){let u=n[1];if(!Q.some((l)=>l.test(u)))return O("detected user import:",u),!0}let o=/^[ \t]*import[ \t]*['"]([^'"]+)['"]/gm;while((n=o.exec(t))!==null){let u=n[1];if(/\.css(?:\?.*)?$/.test(u))continue;if(!Q.some((l)=>l.test(u)))return O("detected side-effect import:",u),!0}return!1}var Hn="stx-module:",St=/\.(?:[cm]?[jt]sx?|json)$/i;function yl(t,e){return d.relative(t,e).split(d.sep).join("/")}function bl(t,e){if(e.size===0)return t;return t.replace(/^([ \t]*import(?:(?:\s+|(?=[{*]))[^;"']*?\s*from\s*|\s*))(["'])([^"']+)\2/gm,(n,o,u,m)=>{let l=e.get(m);return l&&!m.startsWith(Hn)?`${o}${u}${l}${u}`:n})}function vl(t,e){let n=0,o=(m)=>{let l=`__stxMod${n++}`,y=JSON.stringify(m);return e.push(`var ${l} = globalThis.__stxModules && globalThis.__stxModules[${y}];`,`if (${l} === undefined) throw new Error("[stx] module " + ${JSON.stringify(y)} + " is not registered on this page (#1957)");`),l},u=(m,l)=>{for(let y of m.split(",")){let F=y.trim();if(!F)continue;let B=F.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!B)continue;let j=B[1].startsWith('"')?JSON.parse(B[1]):B[1],p=B[2]??j;e.push(`var ${p} = ${l}[${JSON.stringify(j)}];`)}};return t=t.replace(/^[ \t]*import(?:\s+|(?=[{*]))([^;"']+?)\s*from\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(m,l,y)=>{let F=y.slice(Hn.length),B=o(F),j=l.trim(),p=j.match(/^([\w$]+)\s*(?:,\s*|$)/);if(p&&!j.startsWith("{")&&!j.startsWith("*"))e.push(`var ${p[1]} = ${B}.default;`),j=j.slice(p[0].length).trim();let s=j.match(/^\*\s*as\s+([\w$]+)$/);if(s)e.push(`var ${s[1]} = ${B};`);else if(j.startsWith("{"))u(j.replace(/^\{|\}$/g,""),B);return""}),t=t.replace(/^[ \t]*import\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(m,l)=>(o(l.slice(Hn.length)),"")),t}function rt(t){let e=[t,`${t}.ts`,`${t}.tsx`,`${t}.js`,`${t}.mjs`,`${t}.jsx`,d.join(t,"index.ts"),d.join(t,"index.tsx"),d.join(t,"index.js"),d.join(t,"index.mjs")];for(let n of e)try{if(v.existsSync(n)&&v.statSync(n,{throwIfNoEntry:!1})?.isFile())return n}catch{}return}var K=new gt;function Js(t,e){let n=new Bun.CryptoHasher("md5");for(let[o,u]of[...t].sort(([m],[l])=>m<l?-1:m>l?1:0))n.update(`${o}\x00${u}\x00`);return K.run({modules:t,key:n.digest("hex").slice(0,12)},e)}function Zt(){return K.getStore()?.key??""}function vt(t,e,n,o,u,m,l=new Map,y,F){let B=(p,s,a)=>{if(X(s,t,y))return null;if(!m||p!==n||!St.test(s))return null;try{if(!v.statSync(s,{throwIfNoEntry:!1})?.isFile())return null}catch{return null}u.add(s);let w=`${Hn}${yl(process.cwd(),s)}`;return l.set(a,w),{path:w,external:!0}},j=(p,s)=>{let a=p===n?e:d.dirname(p),w=d.resolve(a,s);return rt(w)??w};return{name:"stx-client-bundle",setup(p){if(p.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(s)=>({path:s.path,external:!0})),p.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(s)=>({path:s.path,external:!0})),p.onResolve({filter:/^\//},(s)=>{if(s.path===n)return{path:n};let a=rt(s.path);if(a){let w=B(s.importer,a,s.path);if(w)return w;if(a!==n)u.add(a);return{path:a}}return{path:s.path,external:!0}}),p.onResolve({filter:/^\.\.?\//},(s)=>{let a=j(s.importer,s.path),w=B(s.importer,a,s.path);if(w)return w;return u.add(a),{path:a}}),p.onResolve({filter:/^[@~]\//},(s)=>{let a=d.resolve(t,s.path.slice(2)),w=[a,`${a}.ts`,`${a}.tsx`,`${a}.js`,`${a}.mjs`,`${a}.jsx`,d.join(a,"index.ts"),d.join(a,"index.tsx"),d.join(a,"index.js"),d.join(a,"index.mjs")];for(let x of w)if(v.existsSync(x)&&v.statSync(x,{throwIfNoEntry:!1})?.isFile()){let A=B(s.importer,x,s.path);if(A)return A;return O(`resolved ${s.path[0]}/ import:`,s.path,"\u2192",x),u.add(x),{path:x}}return console.warn(`[stx:bundler] could not resolve ${s.path[0]}/ import:`,s.path),{path:a}}),m)p.onResolve({filter:/^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/},(s)=>{if(s.importer!==n)return;let a=`${Hn}npm:${s.path}`;return l.set(s.path,a),{path:a,external:!0}});p.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(s)=>{if(s.path===n)return{contents:o,loader:"ts"};if(X(s.path,t,y))throw Error(`Server-only API source cannot be imported by a client script: ${s.path}`);let a=d.extname(s.path).toLowerCase(),w=a===".json"?"json":a===".tsx"?"tsx":a===".jsx"?"jsx":a===".ts"||a===".mts"||a===".cts"?"ts":"js";if(s.path!==n)u.add(s.path);let x=F?.get(s.path);if(x!==void 0)return{contents:x,loader:"js"};return{contents:v.readFileSync(s.path,"utf8"),loader:w}})}}}var H=new Map,P=b(64),it=Symbol.for("stx.client-bundle-build-queue");function wl(t){let e=globalThis,o=(e[it]??Promise.resolve()).then(t,t);return e[it]=o.then(()=>{return},()=>{return}),o}async function Qt(t,e,n={}){let o=n.projectRoot||process.cwd(),u=(await i(o)).serverApi,m=n.minify??!1,l=n.externalizeUserModules??!0,y=n.expose?.length?[...new Set(n.expose)].sort():void 0,F=n.cacheDir||gl(o),B=K.getStore(),j=new Bun.CryptoHasher("md5");j.update(`${ht}\x00${Qe()}\x00${JSON.stringify(u??!1)}\x00${l?"registry":"inline"}\x00${y?y.join(","):"*"}\x00${m?"minified":"readable"}\x00${B?.key??""}\x00${nt(t,o)}\x00${nt(e,o)}`);let p=j.digest("hex").slice(0,12),s=d.join(F,`${p}.js`),a=P.get(s);if(a){if(ds(a.files)&&a.files.every((M)=>!X(M.path,o,u))){O("memo hit:",p);let M=a.files.map((C)=>C.path);return q(e,M),n.collectInputs?.push(...M),a.code}P.delete(s),O("memo invalidated by dep change:",p)}let w=d.join(F,`${p}.deps.json`),x=Bun.file(s);if(await x.exists()){let M=Bun.file(w),C=!1,D=null;if(await M.exists())try{let I=JSON.parse(await M.text());if(I.metadataVersion===ot&&Array.isArray(I.files)&&yt(I.files,o))D=ir(I.files.map((g)=>at(g,o))),C=D.length===I.files.length&&!D.some((g)=>X(g.path,o,u))}catch{C=!1}if(C){if(O("cache hit:",p),D)q(e,D.map((T)=>T.path)),n.collectInputs?.push(...D.map((T)=>T.path));let I=await x.text(),g=new Date;if(v.promises.utimes(s,g,g).catch(()=>{}),D)P.set(s,{code:I,files:D});return I}O("cache invalidated by dep change:",p)}let A=H.get(p);if(A){let M=await A;if(n.collectInputs)n.collectInputs.push(...(P.get(s)?.files??[]).map((C)=>C.path));return M}let V=wl(()=>jt(t,e,{projectRoot:o,minify:m,cacheDir:F,hash:p,cachePath:s,depsPath:w,collectInputs:n.collectInputs,externalizeUserModules:l,serverApi:u,expose:y,throwOnFailure:n.throwOnFailure,substitutes:B?.modules}));H.set(p,V);try{return await V}finally{H.delete(p)}}var Bt=0;function xl(t){return`${t}-${process.pid}-${++Bt}`}async function jt(t,e,n){let{projectRoot:o,minify:u,cacheDir:m,hash:l,cachePath:y,depsPath:F,externalizeUserModules:B}=n,j=c(o,"bundle-tmp"),p=xl(l),s=d.join(o,`.stx-client-${p}.ts`),a=d.join(j,"out",p);v.mkdirSync(a,{recursive:!0});let w=d.dirname(e),x=new Set,A=/^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,V=/^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm,M=r(t),{depths:C,balanced:D}=fe(M),I=(_)=>!D||C[_]===0,g;while((g=A.exec(M))!==null){if(g[1])continue;if(!I(g.index))continue;if(g[2])g[2].split(",").forEach((_)=>{let f=_t(_);if(f)x.add(f)});else if(g[3])x.add(g[3])}while((g=V.exec(M))!==null){if(g[1])continue;if(!I(g.index))continue;x.add(g[2])}let T=/^[ \t]*import[ \t]+(?!type\b)(?:(\w+)\s*(?:,\s*)?)?(?:\*\s+as\s+(\w+)|\{([^}]+)\})?\s+from\b/gm;while((g=T.exec(M))!==null){if(!I(g.index))continue;let _=/^\s*['"]([^'"]+)['"]/.exec(t.slice(g.index+g[0].length))?.[1];if(_&&Q.some((f)=>f.test(_)))continue;if(g[1])x.add(g[1]);if(g[2])x.add(g[2]);for(let f of(g[3]??"").split(",")){let S=f.trim();if(!S||/^type\s/.test(S))continue;let U=/\bas\s+(\w+)\s*$/.exec(S)?.[1]??/^\w+$/.exec(S)?.[0];if(U)x.add(U)}}for(let _ of M.matchAll(/\bexport\s*\{([^}]+)\}/g))for(let f of _[1].split(",")){let S=/\bas\s+(\w+)\s*$/.exec(f)?.[1]??/^\s*(\w+)\s*$/.exec(f)?.[1];if(S)x.delete(S)}let lt=x.size>0?`
|
|
3
3
|
export { ${[...x].join(", ")} }`:"";O("bundling:",l,"from:",d.basename(e));let tt=new Set,et=new Map;try{let _=await Bun.build({entrypoints:[s],outdir:a,target:"browser",format:"esm",minify:u?{whitespace:!1,identifiers:!0,syntax:!0}:!1,plugins:[vt(o,w,s,t+lt,tt,B,et,n.serverApi,n.substitutes)],define:{"process.env.NODE_ENV":u?'"production"':'"development"',...k()},root:o});if(!_.success){let E=_.logs.filter((N)=>N.level==="error").map((N)=>N.message).join(", ")||`Unable to bundle ${d.basename(e)}`,z=Vn(_.logs,e||void 0);if(console.warn("[stx:bundler] build failed:",E),ra(e||"",E,z),n.throwOnFailure||sa()==="error")throw Error(E);return t}let f="";for(let h of _.outputs){f=await h.text();break}let S=[];for(let h of f.matchAll(/^\s*export\s*\{([^}]*)\}\s*;?\s*$/gm))for(let E of h[1].split(",")){let z=E.trim().match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(z){S.push([z[2],z[1]]);continue}let N=E.trim();if(/^[A-Za-z_$][\w$]*$/.test(N))S.push([N,N])}if(n.expose){let h=new Set(n.expose);for(let E=S.length-1;E>=0;E--)if(!h.has(S[E][0]))S.splice(E,1)}let U=[];f=vl(bl(f,et),U);let ut=f.match(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm)||[];if(f=f.replace(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm,"").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm,"").replace(/^\s*export\s+default\s+.*$/gm,"").trim(),u&&f)try{f=new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(f)}catch{}let J=`__stxBundle_${l}`,dt=new Set(L(t,!0).split(",").map((h)=>h.trim())),pt=S.map(([h,E])=>`get ${JSON.stringify(h)}() { return ${E} }${dt.has(h)?`, set ${JSON.stringify(h)}(__stxValue_${E}) { ${E} = __stxValue_${E} }`:""}`).join(", "),ft=S.map(([h])=>`var ${h} = undefined;`).join(`
|
|
4
4
|
`),mt=S.map(([h])=>`${h} = ${J}[${JSON.stringify(h)}];`).join(`
|
|
5
5
|
`);if(f=`${ut.join(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{i}from"./chunk-
|
|
2
|
+
import{i}from"./chunk-h176dx1q.js";import{Ue,ne}from"./chunk-03xn8244.js";import{Zi}from"./chunk-5mcwf93c.js";import{f}from"./chunk-b7e07ybq.js";import{existsSync as A,mkdirSync as x,copyFileSync as T,chmodSync as P,rmSync as ue}from"fs";import{join as c,basename as be,resolve as H}from"path";import{spawn as q}from"child_process";import{platform as ge}from"os";var ep=`
|
|
3
3
|
<script>
|
|
4
4
|
(function() {
|
|
5
5
|
'use strict';
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-r0ys9aqa.js";import"./chunk-gtktv6nn.js";import"./chunk-6beg47t4.js";import"./chunk-
|
|
2
|
+
import"./chunk-r0ys9aqa.js";import"./chunk-gtktv6nn.js";import"./chunk-6beg47t4.js";import"./chunk-4f5bmy7h.js";import"./chunk-t6m5d64b.js";import"./chunk-tjwv101c.js";import"./chunk-tenbwcts.js";import"./chunk-s0ntt1cn.js";import{c}from"./chunk-xvs84gas.js";import u from"fs";import l from"path";async function d(e,t={}){let s=Date.now(),n={total:0,passed:0,failed:0,new:0,failures:[],duration:0},i=t.snapshotDir||c(e.root,"story","snapshots");await u.promises.mkdir(i,{recursive:!0});let r=e.storyFiles;if(t.filter&&t.filter.length>0)r=r.filter((a)=>t.filter.some((o)=>a.fileName.toLowerCase().includes(o.toLowerCase())));for(let a of r)await h(a,i,t,n);return n.duration=Date.now()-s,n}async function h(e,t,s,n){let i=e.story;if(!i)return;for(let r of i.variants){n.total++;let a=l.join(t,`${e.id}-${r.id}.snap`),o=g(r.source||""),f=await w(a);if(s.update||!f){let p={storyId:e.id,variantId:r.id,component:e.fileName,timestamp:Date.now(),hash:o};if(await u.promises.writeFile(a,JSON.stringify(p,null,2)),!f)n.new++;n.passed++}else try{let p=await u.promises.readFile(a,"utf-8"),m=JSON.parse(p);if(m.hash===o)n.passed++;else n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:"Snapshot mismatch",difference:y(m.hash,o)})}catch(p){n.failed++,n.failures.push({storyId:e.id,variantId:r.id,component:e.fileName,message:`Error reading snapshot: ${p}`})}}}async function x(e,t={}){return(await d(e,{...t,update:!0})).total}function g(e){let t=0;for(let s=0;s<e.length;s++){let n=e.charCodeAt(s);t=(t<<5)-t+n,t=t&t}return t.toString(16)}function y(e,t){if(e===t)return 0;let s=Math.abs(Number.parseInt(e,16)-Number.parseInt(t,16));return Math.min(s/1e6,1)}async function w(e){try{return await u.promises.access(e),!0}catch{return!1}}function F(e){let t=[];if(t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(" STX Story Visual Regression Tests"),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),e.failures.length>0){t.push(" \u274C Failures:"),t.push("");for(let s of e.failures){if(t.push(` \u2022 ${s.component} / ${s.variantId}`),t.push(` ${s.message}`),s.difference!==void 0)t.push(` Difference: ${(s.difference*100).toFixed(2)}%`);t.push("")}}if(t.push(" Summary:"),t.push(` Total: ${e.total}`),t.push(` Passed: ${e.passed} \u2713`),t.push(` Failed: ${e.failed} \u2717`),e.new>0)t.push(` New: ${e.new} \u26A1`);return t.push(` Time: ${e.duration}ms`),t.push(""),t.push("\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501\u2501"),t.push(""),t.join(`
|
|
3
3
|
`)}export{F as formatTestResults,d as runVisualTests,x as updateSnapshots};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{t,a}from"./chunk-r0ys9aqa.js";import{n,gn,m}from"./chunk-
|
|
2
|
+
import{t,a}from"./chunk-r0ys9aqa.js";import{n,gn,m}from"./chunk-4f5bmy7h.js";import{Ze}from"./chunk-kypwg2ws.js";import{Qr,es}from"./chunk-ygb33q5w.js";import{ka,vo,Yr,Zr}from"./chunk-912r15hr.js";import{wa,xa}from"./chunk-s0ntt1cn.js";import{bt}from"./chunk-3hxd5td3.js";import{sn,Ra,sr,or}from"./chunk-xvs84gas.js";import{f}from"./chunk-b7e07ybq.js";import{Ps}from"./chunk-vxrhvrr9.js";import Q from"fs";import j from"path";import{loadConfigWithResult as Ht}from"bunfig";var B={duration:300,delay:0,ease:"ease",direction:"both"};function nt(e,r={}){let{duration:o,delay:l,ease:s,direction:c,custom:d}={...B,...r};if(e==="custom"&&d)return d;switch(e){case"fade":return`${c==="in"?"opacity: 0; animation: fadeIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":c==="out"?"opacity: 1; animation: fadeOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"opacity: 1; transition: opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
|
|
3
3
|
@keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
|
|
4
4
|
@keyframes fadeOut { from { opacity: 1; } to { opacity: 0; } }`;case"slide":return`${c==="in"?"transform: translateY(20px); opacity: 0; animation: slideIn var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":c==="out"?"transform: translateY(0); opacity: 1; animation: slideOut var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms) forwards;":"transform: translateY(0); opacity: 1; transition: transform var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms), opacity var(--stx-transition-duration, 300ms) var(--stx-transition-ease, ease) var(--stx-transition-delay, 0ms);"}
|
|
5
5
|
@keyframes slideIn { from { transform: translateY(20px); opacity: 0; } to { transform: translateY(0); opacity: 1; } }
|
|
@@ -1307,6 +1307,6 @@ ${y}
|
|
|
1307
1307
|
customElements.define('${r}', ${d});
|
|
1308
1308
|
`}async function Qe(e,r,o,l){if(r.length<1)return a("WebComponent","@webcomponent directive requires at least the tag name parameter",t.INVALID_DIRECTIVE_SYNTAX);let s=r[0].replace(/['"]/g,""),d=(o.__stx_options||{}).componentsDir||"components",p=q.isAbsolute(d)?[q.join(d,`${s}.stx`),q.join(q.dirname(l),`${s}.stx`)]:[q.join(q.dirname(l),d,`${s}.stx`),q.join(process.cwd(),d,`${s}.stx`),q.join(q.dirname(l),`${s}.stx`)],u=null;for(let h of p)if(await n(h)){u=await Bun.file(h).text();break}if(!u)return a("WebComponent",`Component file not found: ${s}.stx`,t.FILE_NOT_FOUND);let g=Ft(u,s);return`<script type="module">
|
|
1309
1309
|
${qt(g)}
|
|
1310
|
-
</script>`}var N={enabled:!0,ssr:!1,partialsDir:"partials",componentsDir:"components",layoutsDir:"layouts",defaultLayout:"default",debug:!1,cache:!0,stateDir:sn,cachePath:".stx/cache",cacheVersion:"1.0.0",componentRenderCacheBytes:33554432,build:{pagesDir:"pages",outputDir:"dist",baseUrl:"/",sitemap:!0,minify:!0,cache:!0,cacheDir:".stx/ssg-cache",concurrency:10,generate404:!0,publicDir:"public",trailingSlash:!1,cleanOutput:!0},customDirectives:[{name:"markdown",handler:Ie,hasEndTag:!0,description:"Render markdown content to HTML"},{name:"webcomponent",handler:Qe,hasEndTag:!1,description:"Include a web component in the template"},wa,xa,Qr,es,De,ke,Ae,Pe,_e,Oe,Fe,$e,...Ps],middleware:[],i18n:{defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},webComponents:{enabled:!1,outputDir:"dist/web-components",components:[]},docs:{enabled:!1,outputDir:"docs",format:"markdown",components:!0,templates:!0,directives:!0},streaming:{enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},hydration:{enabled:!1,mode:"islands",clientEntry:"src/client.ts",autoMarkers:!0,preload:"lazy"},router:{enabled:!0,container:"main",linkSelector:"a[href]",viewTransitions:!0,scrollToTop:!0,scrollRestoration:!0,prefetch:!0,cache:!0,cacheTTL:300000,skipSelectors:'[data-no-router], [target="_blank"]',viewTransitionCSS:{oldRoot:"fade-out 0.15s ease-in",newRoot:"fade-in 0.2s ease-out",oldContent:"slide-out 0.2s ease-in",newContent:"slide-in 0.25s ease-out"}},a11y:{enabled:!0,addSrOnlyStyles:!0,level:"AA",autoFix:!1,ignoreChecks:[]},seo:{enabled:!0,socialPreview:!0,defaultConfig:{title:"stx Project",description:"A website built with stx templating engine"}},animation:{enabled:!0,defaultDuration:300,defaultEase:"ease",respectMotionPreferences:!0,staggerDelay:50},markdown:{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0,additionalThemes:["light-plus","one-dark-pro","dracula","monokai","solarized-light","nord","github-dark"]}},loops:{maxWhileIterations:1000,useAltLoopVariable:!1},story:{enabled:!0,outDir:".stx/dist/story",storyMatch:["**/*.story.stx"],storyIgnored:["**/node_modules/**","**/dist/**","**/.stx/**"],port:6006},pwa:{enabled:!1,manifest:{name:"stx App",shortName:"stx",description:"A Progressive Web App built with stx",startUrl:"/",display:"standalone",orientation:"any",themeColor:"#000000",backgroundColor:"#ffffff",scope:"/"},icons:{src:"public/icon.png",sizes:[72,96,128,144,152,192,384,512],generateWebP:!0,generateAppleIcons:!0,outputDir:"pwa-icons",purpose:["any","maskable"]},routes:[{pattern:"/",strategy:"network-first"},{pattern:"/static/*",strategy:"cache-first",maxAgeSeconds:2592000},{pattern:"/api/*",strategy:"network-only"},{pattern:"*.js",strategy:"stale-while-revalidate"},{pattern:"*.css",strategy:"stale-while-revalidate"},{pattern:"*.png",strategy:"cache-first"},{pattern:"*.jpg",strategy:"cache-first"},{pattern:"*.webp",strategy:"cache-first"},{pattern:"*.svg",strategy:"cache-first"}],offline:{enabled:!0,fallbackTitle:"You are offline",fallbackMessage:"Please check your internet connection and try again.",precacheAssets:[]},serviceWorker:{fileName:"sw.js",cacheVersion:"1.0.0",skipWaiting:!0,clientsClaim:!0,navigationPreload:!1,excludeRoutes:["/api/auth/*"],cacheFileTypes:["html","css","js","png","jpg","jpeg","webp","svg","woff","woff2"],useWorkbox:!1},autoInject:!0,push:{enabled:!1,defaultOptions:{vibrate:[100,50,100],requireInteraction:!1}},backgroundSync:{enabled:!1,queueName:"stx-sync-queue",maxRetentionMinutes:1440,maxRetries:3,minInterval:1000,forms:[],endpoints:[]},shareTarget:{enabled:!1,action:"/share-target",method:"POST",enctype:"multipart/form-data",params:{title:"title",text:"text",url:"url"}},fileHandlers:{enabled:!1},protocolHandlers:[],cacheStorage:{maxSize:100,maxEntries:500,maxAge:30,purgeStrategy:"lru"},updates:{enabled:!0,promptUser:!0,autoReload:!1,message:"A new version is available. Reload to update?"},precache:{enabled:!0,includeHtml:!0,includeJs:!0,includeCss:!0,includeImages:!0,includeFonts:!0,include:[],exclude:["*.map","*.LICENSE.txt"],maxFileSizeKB:500}},media:{enabled:!0,image:{enabled:!0,defaultWidths:[320,480,640,768,1024,1280,1536,1920],defaultFormats:["avif","webp","jpeg"],defaultQuality:80,placeholderStrategy:"thumbhash",lazyByDefault:!0,enableDpr:!0,defaultDpr:[1,2,3],tsImages:{enabled:!0,outputDir:"dist/images",baseUrl:"/images",formatQuality:{jpeg:{quality:85,mozjpeg:!0,progressive:!0},png:{compressionLevel:9,palette:!1},webp:{quality:82,effort:5,smartSubsample:!0},avif:{quality:75,effort:4,lossless:!1}},breakpoints:[320,480,640,768,1024,1280,1536,1920],batchOptions:{concurrency:4,optimizationPreset:"web"}}},video:{enabled:!0,lazyByDefault:!0,defaultControls:!0,tsVideos:{enabled:!0,outputDir:"dist/videos",baseUrl:"/videos",defaultQuality:"high",streaming:{enabled:!0,format:"hls",segmentDuration:6,defaultQualities:[{label:"1080p",width:1920,height:1080,bitrate:5000000,audioBitrate:192000},{label:"720p",width:1280,height:720,bitrate:2500000,audioBitrate:128000},{label:"480p",width:854,height:480,bitrate:1e6,audioBitrate:96000}]},thumbnails:{enabled:!0,count:10,format:"webp",width:320},transcoding:{defaultCodec:"h264",defaultAudioCodec:"aac",speedPreset:"medium"}}},upload:{enabled:!0,maxSize:10485760,allowedTypes:["image/*","video/*","audio/*","application/pdf"],maxConcurrent:3},protected:{enabled:!0,expirationSeconds:3600,batchSize:10},cache:{enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:500}},broadcasting:{enabled:!1,driver:"bun",host:"0.0.0.0",port:6001,scheme:"ws",verbose:!1}};function Ut(e,r,o){let l=r||"pages";if(e)return{root:e,pagesDir:l};let s=o||process.cwd(),c=j.join(s,"resources","views"),d=j.join(s,"resources","layouts");if(Q.existsSync(c)&&Q.existsSync(d))return{root:"resources",pagesDir:"views"};let p=j.join(s,"resources","views","pages");if(Q.existsSync(p))return{root:"resources/views",pagesDir:l};return{root:".",pagesDir:l}}var et=new Set,ue=["partialsDir","componentsDir","layoutsDir"],Se=new WeakMap;function Bt(e,r){let o=r.replace(/[\\/]+$/,"");if(!o||o===".")return!0;let l=e.replace(/\\/g,"/"),s=o.replace(/\\/g,"/");return l===s||l.startsWith(`${s}/`)}function Nl(e,r){let o=!e.root,l=Ut(e.root,e.pagesDir,r);if(e.root=l.root,e.pagesDir=l.pagesDir,o&&l.root!=="."){let s=`${r}::${l.root}`;if(!et.has(s))et.add(s),console.warn(`[stx] No "root" in config \u2014 inferred "${l.root}" from the project layout. Template directories are resolved under it; set root explicitly to pin this.`)}if(!Se.has(e)){let s={};for(let c of ue){let d=e[c];if(typeof d==="string"&&d)s[c]=d}Se.set(e,s)}if(e.root&&e.root!=="."){let s=e.root;for(let c of ue){let d=e[c];if(typeof d!=="string"||!d)continue;if(j.isAbsolute(d)||Bt(d,s))continue;e[c]=j.join(s,d)}}for(let s of ue){let c=e[s];if(typeof c!=="string"||!c||j.isAbsolute(c))continue;e[s]=j.resolve(r,c)}return e}function Jt(e,r){let o=Se.get(e);for(let l of ue){let s=e[l];if(typeof s!=="string"||!s)continue;let c=j.isAbsolute(s)?s:j.join(r,s);if(Q.existsSync(c))continue;let d=o?.[l]??s,p=e.root,u=!!p&&p!==".";console.warn(`[stx] ${String(l)} resolves to "${c}", which does not exist. Configured as "${d}"`+(u?`, resolved under root "${p}".`:"."))}}function Kt(e){if(e.customDirectives)e.customDirectives=[...e.customDirectives];if(e.middleware)e.middleware=[...e.middleware];if(e.apiRoutes)e.apiRoutes={...e.apiRoutes}}function Gt(e){if(Ra(e.stateDir),e.stateDir=sr(),e.cachePath=or(e.cachePath),e.build)e.build.cacheDir=or(e.build.cacheDir);if(e.media?.cache)e.media.cache.directory=or(e.media.cache.directory);if(e.story)e.story.outDir=or(e.story.outDir)}var K=null,Y=new Map,de=new Map,se=null;async function yo(e,r=Ht){try{return await r(e)}catch(o){if(o instanceof Error&&o.name==="ConfigNotFoundError")return{config:e.defaultConfig};throw o}}async function i(e){let r=e?j.resolve(e):process.cwd(),o=de.get(r);if(o&&o.signature!==Yr(o.graph)){let c=Y.get(r);if(Y.delete(r),de.delete(r),!e)K=null,se=null;let{clearComponentCache:d}=await import("./chunk-84fn7myr.js"),{partialsCache:p}=await import("./chunk-tbrznnt4.js");if(d(),p.clear(),c&&o.configSignature===Zr(o.graph)){let u=c.then(async(g)=>{let y={...o.graph};await vo(y,r),de.set(r,{graph:y,signature:Yr(y),configSignature:Zr(y)});let h={...g,_layerGraph:y};if(!e)K=h;return h});return Y.set(r,u),u}}if(!e){if(K)return K;if(se)return se}let l=Y.get(r);if(l)return l;let s=(async()=>{let c=[".ts",".js",".mjs",".cjs",".json"],d=c.some((v)=>Q.existsSync(j.join(r,`stx.config${v}`))),p=c.some((v)=>Q.existsSync(j.join(r,"config",`ui${v}`))),u;if(d&&p){let v=await yo({name:"ui",cwd:j.join(r,"config"),defaultConfig:N,errorPolicy:"throw",verbose:!1});u=(await yo({name:"stx",alias:"ui",cwd:r,defaultConfig:v.config,errorPolicy:"throw",verbose:!1})).config}else u=(await yo({name:"stx",alias:"ui",cwd:r,defaultConfig:N,errorPolicy:"throw",verbose:!1})).config;if(u.extends!==void 0||o){let v=await ka(r,N);u=v.config,de.set(r,{graph:v.graph,signature:Yr(v.graph),configSignature:Zr(v.graph)})}if(u.runtimeConfig){let{resolveRuntimeConfig:v}=await import("./chunk-wvz7rp5p.js");v(u.runtimeConfig,{});let{generateRuntimeConfigTypes:b}=await import("./chunk-5k013c4h.js");await b(r,u.runtimeConfig)}Kt(u),Gt(u),Nl(u,r),Jt(u,r);let g=[],y=new Set((u.plugins??[]).map((v)=>typeof v==="string"?v:v[0]));for(let v of u.componentPackages??["@stacksjs/components"]){let b=`${v}/stx-plugin`;if(y.has(b)||y.has(v))continue;try{f.resolve(b,{paths:[r]}),g.push(b)}catch{}}let h=[...u.plugins??[],...g];if(h.length>0){let{pluginManager:v}=await import("./chunk-vqv5w6gs.js"),b=[],x=[];for(let P of h){let S=typeof P==="string"?P:P[0],A=typeof P==="string"?{}:P[1]||{};try{let k,E;try{let w=f.resolve(S,{paths:[r]});k=await import(w),E=j.dirname(w)}catch{let w=j.resolve(r,S);k=await import(w),E=j.dirname(w)}let I=k.default||k;if(!v.has(I.name))await v.register(I,u);if(I.components){let w=Array.isArray(I.components)?I.components:[I.components];for(let C of w)b.push(j.resolve(E,C))}if(I.pages){let w=j.resolve(E,I.pages),C=A.path||"/";x.push({dir:w,prefix:C})}if(I.setup){let w={addDirective:(C)=>{u.customDirectives=u.customDirectives||[],u.customDirectives.push(C)},addRoute:(C,D)=>{u.apiRoutes=u.apiRoutes||{},u.apiRoutes[C]=D},addMiddleware:(C)=>{u.middleware=u.middleware||[],u.middleware.push(C)},pluginDir:E,config:u};await I.setup(A,w)}process.stderr.write(`[stx] Plugin loaded: ${I.name||S}
|
|
1310
|
+
</script>`}var N={enabled:!0,ssr:!1,partialsDir:"partials",componentsDir:"components",layoutsDir:"layouts",defaultLayout:"default",debug:!1,cache:!0,stateDir:sn,cachePath:".stx/cache",cacheVersion:"1.0.0",componentRenderCacheBytes:33554432,build:{pagesDir:"pages",outputDir:"dist",baseUrl:"/",sitemap:!0,minify:!0,cache:!0,cacheDir:".stx/ssg-cache",concurrency:10,generate404:!0,publicDir:"public",trailingSlash:!1,cleanOutput:!0},customDirectives:[{name:"markdown",handler:Ie,hasEndTag:!0,description:"Render markdown content to HTML"},{name:"webcomponent",handler:Qe,hasEndTag:!1,description:"Include a web component in the template"},wa,xa,Qr,es,De,ke,Ae,Pe,_e,Oe,Fe,$e,...Ps],middleware:[],i18n:{defaultLocale:"en",locale:"en",translationsDir:"translations",format:"yaml",fallbackToKey:!0,cache:!0},webComponents:{enabled:!1,outputDir:"dist/web-components",components:[]},docs:{enabled:!1,outputDir:"docs",format:"markdown",components:!0,templates:!0,directives:!0},streaming:{enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},hydration:{enabled:!1,mode:"islands",clientEntry:"src/client.ts",autoMarkers:!0,preload:"lazy"},router:{enabled:!0,container:"main",linkSelector:"a[href]",viewTransitions:!0,scrollToTop:!0,scrollRestoration:!0,prefetch:!0,cache:!0,cacheTTL:300000,skipSelectors:'[data-no-router], [target="_blank"]',viewTransitionCSS:{oldRoot:"fade-out 0.15s ease-in",newRoot:"fade-in 0.2s ease-out",oldContent:"slide-out 0.2s ease-in",newContent:"slide-in 0.25s ease-out"}},a11y:{enabled:!0,addSrOnlyStyles:!0,level:"AA",autoFix:!1,ignoreChecks:[]},seo:{enabled:!0,socialPreview:!0,defaultConfig:{title:"stx Project",description:"A website built with stx templating engine"}},animation:{enabled:!0,defaultDuration:300,defaultEase:"ease",respectMotionPreferences:!0,staggerDelay:50},markdown:{enabled:!0,syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0,additionalThemes:["light-plus","one-dark-pro","dracula","monokai","solarized-light","nord","github-dark"]}},loops:{maxWhileIterations:1000,useAltLoopVariable:!1},story:{enabled:!0,outDir:".stx/dist/story",storyMatch:["**/*.story.stx"],storyIgnored:["**/node_modules/**","**/dist/**","**/.stx/**"],port:6006},pwa:{enabled:!1,manifest:{name:"stx App",shortName:"stx",description:"A Progressive Web App built with stx",startUrl:"/",display:"standalone",orientation:"any",themeColor:"#000000",backgroundColor:"#ffffff",scope:"/"},icons:{src:"public/icon.png",sizes:[72,96,128,144,152,192,384,512],generateWebP:!0,generateAppleIcons:!0,outputDir:"pwa-icons",purpose:["any","maskable"]},routes:[{pattern:"/",strategy:"network-first"},{pattern:"/static/*",strategy:"cache-first",maxAgeSeconds:2592000},{pattern:"/api/*",strategy:"network-only"},{pattern:"*.js",strategy:"stale-while-revalidate"},{pattern:"*.css",strategy:"stale-while-revalidate"},{pattern:"*.png",strategy:"cache-first"},{pattern:"*.jpg",strategy:"cache-first"},{pattern:"*.webp",strategy:"cache-first"},{pattern:"*.svg",strategy:"cache-first"}],offline:{enabled:!0,fallbackTitle:"You are offline",fallbackMessage:"Please check your internet connection and try again.",precacheAssets:[]},serviceWorker:{fileName:"sw.js",cacheVersion:"1.0.0",skipWaiting:!0,clientsClaim:!0,navigationPreload:!1,excludeRoutes:["/api/auth/*"],cacheFileTypes:["html","css","js","png","jpg","jpeg","webp","svg","woff","woff2"],useWorkbox:!1},autoInject:!0,push:{enabled:!1,defaultOptions:{vibrate:[100,50,100],requireInteraction:!1}},backgroundSync:{enabled:!1,queueName:"stx-sync-queue",maxRetentionMinutes:1440,maxRetries:3,minInterval:1000,forms:[],endpoints:[]},shareTarget:{enabled:!1,action:"/share-target",method:"POST",enctype:"multipart/form-data",params:{title:"title",text:"text",url:"url"}},fileHandlers:{enabled:!1},protocolHandlers:[],cacheStorage:{maxSize:100,maxEntries:500,maxAge:30,purgeStrategy:"lru"},updates:{enabled:!0,promptUser:!0,autoReload:!1,message:"A new version is available. Reload to update?"},precache:{enabled:!0,includeHtml:!0,includeJs:!0,includeCss:!0,includeImages:!0,includeFonts:!0,include:[],exclude:["*.map","*.LICENSE.txt"],maxFileSizeKB:500}},media:{enabled:!0,image:{enabled:!0,defaultWidths:[320,480,640,768,1024,1280,1536,1920],defaultFormats:["avif","webp","jpeg"],defaultQuality:80,placeholderStrategy:"thumbhash",lazyByDefault:!0,enableDpr:!0,defaultDpr:[1,2,3],tsImages:{enabled:!0,outputDir:"dist/images",baseUrl:"/images",formatQuality:{jpeg:{quality:85,mozjpeg:!0,progressive:!0},png:{compressionLevel:9,palette:!1},webp:{quality:82,effort:5,smartSubsample:!0},avif:{quality:75,effort:4,lossless:!1}},breakpoints:[320,480,640,768,1024,1280,1536,1920],batchOptions:{concurrency:4,optimizationPreset:"web"}}},video:{enabled:!0,lazyByDefault:!0,defaultControls:!0,tsVideos:{enabled:!0,outputDir:"dist/videos",baseUrl:"/videos",defaultQuality:"high",streaming:{enabled:!0,format:"hls",segmentDuration:6,defaultQualities:[{label:"1080p",width:1920,height:1080,bitrate:5000000,audioBitrate:192000},{label:"720p",width:1280,height:720,bitrate:2500000,audioBitrate:128000},{label:"480p",width:854,height:480,bitrate:1e6,audioBitrate:96000}]},thumbnails:{enabled:!0,count:10,format:"webp",width:320},transcoding:{defaultCodec:"h264",defaultAudioCodec:"aac",speedPreset:"medium"}}},upload:{enabled:!0,maxSize:10485760,allowedTypes:["image/*","video/*","audio/*","application/pdf"],maxConcurrent:3},protected:{enabled:!0,expirationSeconds:3600,batchSize:10},cache:{enabled:!0,directory:".stx/media-cache",maxAge:30,maxSize:500}},broadcasting:{enabled:!1,driver:"bun",host:"0.0.0.0",port:6001,scheme:"ws",verbose:!1}};function Ut(e,r,o){let l=r||"pages";if(e)return{root:e,pagesDir:l};let s=o||process.cwd(),c=j.join(s,"resources","views"),d=j.join(s,"resources","layouts");if(Q.existsSync(c)&&Q.existsSync(d))return{root:"resources",pagesDir:"views"};let p=j.join(s,"resources","views","pages");if(Q.existsSync(p))return{root:"resources/views",pagesDir:l};return{root:".",pagesDir:l}}var et=new Set,ue=["partialsDir","componentsDir","layoutsDir"],Se=new WeakMap;function Bt(e,r){let o=r.replace(/[\\/]+$/,"");if(!o||o===".")return!0;let l=e.replace(/\\/g,"/"),s=o.replace(/\\/g,"/");return l===s||l.startsWith(`${s}/`)}function Nl(e,r){let o=!e.root,l=Ut(e.root,e.pagesDir,r);if(e.root=l.root,e.pagesDir=l.pagesDir,o&&l.root!=="."){let s=`${r}::${l.root}`;if(!et.has(s))et.add(s),console.warn(`[stx] No "root" in config \u2014 inferred "${l.root}" from the project layout. Template directories are resolved under it; set root explicitly to pin this.`)}if(!Se.has(e)){let s={};for(let c of ue){let d=e[c];if(typeof d==="string"&&d)s[c]=d}Se.set(e,s)}if(e.root&&e.root!=="."){let s=e.root;for(let c of ue){let d=e[c];if(typeof d!=="string"||!d)continue;if(j.isAbsolute(d)||Bt(d,s))continue;e[c]=j.join(s,d)}}for(let s of ue){let c=e[s];if(typeof c!=="string"||!c||j.isAbsolute(c))continue;e[s]=j.resolve(r,c)}return e}function Jt(e,r){let o=Se.get(e);for(let l of ue){let s=e[l];if(typeof s!=="string"||!s)continue;let c=j.isAbsolute(s)?s:j.join(r,s);if(Q.existsSync(c))continue;let d=o?.[l]??s,p=e.root,u=!!p&&p!==".";console.warn(`[stx] ${String(l)} resolves to "${c}", which does not exist. Configured as "${d}"`+(u?`, resolved under root "${p}".`:"."))}}function Kt(e){if(e.customDirectives)e.customDirectives=[...e.customDirectives];if(e.middleware)e.middleware=[...e.middleware];if(e.apiRoutes)e.apiRoutes={...e.apiRoutes}}function Gt(e){if(Ra(e.stateDir),e.stateDir=sr(),e.cachePath=or(e.cachePath),e.build)e.build.cacheDir=or(e.build.cacheDir);if(e.media?.cache)e.media.cache.directory=or(e.media.cache.directory);if(e.story)e.story.outDir=or(e.story.outDir)}var K=null,Y=new Map,de=new Map,se=null;async function yo(e,r=Ht){try{return await r(e)}catch(o){if(o instanceof Error&&o.name==="ConfigNotFoundError")return{config:e.defaultConfig};throw o}}async function i(e){let r=e?j.resolve(e):process.cwd(),o=de.get(r);if(o&&o.signature!==Yr(o.graph)){let c=Y.get(r);if(Y.delete(r),de.delete(r),!e)K=null,se=null;let{clearComponentCache:d}=await import("./chunk-yxp7jmnz.js"),{partialsCache:p}=await import("./chunk-ngd9dsrd.js");if(d(),p.clear(),c&&o.configSignature===Zr(o.graph)){let u=c.then(async(g)=>{let y={...o.graph};await vo(y,r),de.set(r,{graph:y,signature:Yr(y),configSignature:Zr(y)});let h={...g,_layerGraph:y};if(!e)K=h;return h});return Y.set(r,u),u}}if(!e){if(K)return K;if(se)return se}let l=Y.get(r);if(l)return l;let s=(async()=>{let c=[".ts",".js",".mjs",".cjs",".json"],d=c.some((v)=>Q.existsSync(j.join(r,`stx.config${v}`))),p=c.some((v)=>Q.existsSync(j.join(r,"config",`ui${v}`))),u;if(d&&p){let v=await yo({name:"ui",cwd:j.join(r,"config"),defaultConfig:N,errorPolicy:"throw",verbose:!1});u=(await yo({name:"stx",alias:"ui",cwd:r,defaultConfig:v.config,errorPolicy:"throw",verbose:!1})).config}else u=(await yo({name:"stx",alias:"ui",cwd:r,defaultConfig:N,errorPolicy:"throw",verbose:!1})).config;if(u.extends!==void 0||o){let v=await ka(r,N);u=v.config,de.set(r,{graph:v.graph,signature:Yr(v.graph),configSignature:Zr(v.graph)})}if(u.runtimeConfig){let{resolveRuntimeConfig:v}=await import("./chunk-wvz7rp5p.js");v(u.runtimeConfig,{});let{generateRuntimeConfigTypes:b}=await import("./chunk-5m42k74p.js");await b(r,u.runtimeConfig)}Kt(u),Gt(u),Nl(u,r),Jt(u,r);let g=[],y=new Set((u.plugins??[]).map((v)=>typeof v==="string"?v:v[0]));for(let v of u.componentPackages??["@stacksjs/components"]){let b=`${v}/stx-plugin`;if(y.has(b)||y.has(v))continue;try{f.resolve(b,{paths:[r]}),g.push(b)}catch{}}let h=[...u.plugins??[],...g];if(h.length>0){let{pluginManager:v}=await import("./chunk-vqv5w6gs.js"),b=[],x=[];for(let P of h){let S=typeof P==="string"?P:P[0],A=typeof P==="string"?{}:P[1]||{};try{let k,E;try{let w=f.resolve(S,{paths:[r]});k=await import(w),E=j.dirname(w)}catch{let w=j.resolve(r,S);k=await import(w),E=j.dirname(w)}let I=k.default||k;if(!v.has(I.name))await v.register(I,u);if(I.components){let w=Array.isArray(I.components)?I.components:[I.components];for(let C of w)b.push(j.resolve(E,C))}if(I.pages){let w=j.resolve(E,I.pages),C=A.path||"/";x.push({dir:w,prefix:C})}if(I.setup){let w={addDirective:(C)=>{u.customDirectives=u.customDirectives||[],u.customDirectives.push(C)},addRoute:(C,D)=>{u.apiRoutes=u.apiRoutes||{},u.apiRoutes[C]=D},addMiddleware:(C)=>{u.middleware=u.middleware||[],u.middleware.push(C)},pluginDir:E,config:u};await I.setup(A,w)}process.stderr.write(`[stx] Plugin loaded: ${I.name||S}
|
|
1311
1311
|
`)}catch(k){console.warn(`[stx] Failed to load plugin ${S}:`,k.message)}}u._pluginComponentDirs=b,u._pluginPageDirs=x}return u})();if(Y.set(r,s),s.catch(()=>{if(Y.get(r)===s)Y.delete(r)}),!e)se=s,s.then((c)=>{K=c}).catch(()=>{});return s}var R=new Proxy(N,{get(e,r){if(K&&r in K)return K[r];if(!se)i().catch((o)=>{console.warn("[stx] Failed to load config file:",o?.message||o)});return e[r]}});function Ep(e){return e}function Tp(e){let r=[],o=[];if(e.partialsDir!==void 0&&typeof e.partialsDir!=="string")r.push({path:"partialsDir",message:"partialsDir must be a string",severity:"error"});if(e.componentsDir!==void 0&&typeof e.componentsDir!=="string")r.push({path:"componentsDir",message:"componentsDir must be a string",severity:"error"});if(e.cache!==void 0&&typeof e.cache!=="boolean")r.push({path:"cache",message:"cache must be a boolean",severity:"error"});if(e.debug!==void 0&&typeof e.debug!=="boolean")r.push({path:"debug",message:"debug must be a boolean",severity:"error"});if(e.streaming){if(e.streaming.bufferSize!==void 0){if(typeof e.streaming.bufferSize!=="number"||e.streaming.bufferSize<=0)r.push({path:"streaming.bufferSize",message:"streaming.bufferSize must be a positive number",severity:"error"})}if(e.streaming.timeout!==void 0){if(typeof e.streaming.timeout!=="number"||e.streaming.timeout<=0)r.push({path:"streaming.timeout",message:"streaming.timeout must be a positive number",severity:"error"})}if(e.streaming.strategy!==void 0){let l=["auto","manual","sections"];if(!l.includes(e.streaming.strategy))r.push({path:"streaming.strategy",message:`streaming.strategy must be one of: ${l.join(", ")}`,severity:"error"})}}if(e.i18n){if(e.i18n.format!==void 0){let l=["json","yaml","yml","js"];if(!l.includes(e.i18n.format))r.push({path:"i18n.format",message:`i18n.format must be one of: ${l.join(", ")}`,severity:"error"})}}if(e.animation){if(e.animation.defaultDuration!==void 0){if(typeof e.animation.defaultDuration!=="number"||e.animation.defaultDuration<0)r.push({path:"animation.defaultDuration",message:"animation.defaultDuration must be a non-negative number",severity:"error"})}if(e.animation.staggerDelay!==void 0){if(typeof e.animation.staggerDelay!=="number"||e.animation.staggerDelay<0)r.push({path:"animation.staggerDelay",message:"animation.staggerDelay must be a non-negative number",severity:"error"})}}if(e.a11y){if(e.a11y.level!==void 0){let l=["AA","AAA"];if(!l.includes(e.a11y.level))r.push({path:"a11y.level",message:`a11y.level must be one of: ${l.join(", ")}`,severity:"error"})}}if(e.hydration){if(e.hydration.mode!==void 0){let l=["progressive","islands"];if(!l.includes(e.hydration.mode))r.push({path:"hydration.mode",message:`hydration.mode must be one of: ${l.join(", ")}`,severity:"error"})}if(e.hydration.preload!==void 0){let l=["none","eager","lazy"];if(!l.includes(e.hydration.preload))r.push({path:"hydration.preload",message:`hydration.preload must be one of: ${l.join(", ")}`,severity:"error"})}}if(e.customDirectives)if(!Array.isArray(e.customDirectives))r.push({path:"customDirectives",message:"customDirectives must be an array",severity:"error"});else e.customDirectives.forEach((l,s)=>{if(!l.name||typeof l.name!=="string")r.push({path:`customDirectives[${s}].name`,message:"Custom directive must have a name string",severity:"error"});if(!l.handler||typeof l.handler!=="function")r.push({path:`customDirectives[${s}].handler`,message:"Custom directive must have a handler function",severity:"error"})});if(e.middleware)if(!Array.isArray(e.middleware))r.push({path:"middleware",message:"middleware must be an array",severity:"error"});else e.middleware.forEach((l,s)=>{if(!l.name||typeof l.name!=="string")r.push({path:`middleware[${s}].name`,message:"Middleware must have a name string",severity:"error"});if(!l.handler||typeof l.handler!=="function")r.push({path:`middleware[${s}].handler`,message:"Middleware must have a handler function",severity:"error"});if(!l.timing||!["before","after"].includes(l.timing))r.push({path:`middleware[${s}].timing`,message:'Middleware timing must be "before" or "after"',severity:"error"})});if(e.debug===!0&&e.cache===!0)o.push({path:"debug+cache",message:"Debug mode with caching enabled may show stale content during development",severity:"warning"});if(e.seo?.enabled===!0&&!e.seo?.defaultConfig?.title)o.push({path:"seo.defaultConfig.title",message:"SEO is enabled but no default title is set",severity:"warning"});if(e.pwa){if(e.pwa.enabled===!0&&!e.pwa.manifest?.name)r.push({path:"pwa.manifest.name",message:"PWA manifest name is required when PWA is enabled",severity:"error"});if(e.pwa.manifest?.display!==void 0){let l=["fullscreen","standalone","minimal-ui","browser"];if(!l.includes(e.pwa.manifest.display))r.push({path:"pwa.manifest.display",message:`PWA display must be one of: ${l.join(", ")}`,severity:"error"})}if(e.pwa.manifest?.orientation!==void 0){let l=["portrait","landscape","any","portrait-primary","portrait-secondary","landscape-primary","landscape-secondary"];if(!l.includes(e.pwa.manifest.orientation))r.push({path:"pwa.manifest.orientation",message:`PWA orientation must be one of: ${l.join(", ")}`,severity:"error"})}if(e.pwa.routes){let l=["cache-first","network-first","stale-while-revalidate","network-only","cache-only"];e.pwa.routes.forEach((s,c)=>{if(!s.pattern||typeof s.pattern!=="string")r.push({path:`pwa.routes[${c}].pattern`,message:"PWA route must have a pattern string",severity:"error"});if(!l.includes(s.strategy))r.push({path:`pwa.routes[${c}].strategy`,message:`PWA route strategy must be one of: ${l.join(", ")}`,severity:"error"});if(s.maxAgeSeconds!==void 0&&(typeof s.maxAgeSeconds!=="number"||s.maxAgeSeconds<0))r.push({path:`pwa.routes[${c}].maxAgeSeconds`,message:"PWA route maxAgeSeconds must be a non-negative number",severity:"error"});if(s.maxEntries!==void 0&&(typeof s.maxEntries!=="number"||s.maxEntries<1))r.push({path:`pwa.routes[${c}].maxEntries`,message:"PWA route maxEntries must be a positive number",severity:"error"})})}if(e.pwa.icons?.sizes){if(!Array.isArray(e.pwa.icons.sizes))r.push({path:"pwa.icons.sizes",message:"PWA icon sizes must be an array of numbers",severity:"error"});else if(e.pwa.icons.sizes.filter((s)=>typeof s!=="number"||s<16||s>1024).length>0)r.push({path:"pwa.icons.sizes",message:"PWA icon sizes must be numbers between 16 and 1024",severity:"error"})}if(e.pwa.icons?.purpose){let l=["any","maskable","monochrome"];if(e.pwa.icons.purpose.filter((c)=>!l.includes(c)).length>0)r.push({path:"pwa.icons.purpose",message:`PWA icon purpose must be one of: ${l.join(", ")}`,severity:"error"})}if(e.pwa.enabled===!0&&!e.pwa.icons?.src)o.push({path:"pwa.icons.src",message:"PWA is enabled but no icon source specified. Provide a 512x512 PNG for best results.",severity:"warning"});if(e.pwa.enabled===!0&&!e.pwa.manifest?.themeColor)o.push({path:"pwa.manifest.themeColor",message:"PWA theme color not set, defaulting to black",severity:"warning"})}return{valid:r.length===0,errors:r,warnings:o}}
|
|
1312
1312
|
export{ga,ma,er,Je,ha,Jr,N,Nl,yo,i,R,Ep,Tp};
|