@stacksjs/stx 0.2.457 → 0.2.458
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/app-service-worker.d.ts +13 -0
- package/dist/{chunk-k84aahz0.js → chunk-0p4kc0xt.js} +1 -1
- package/dist/{chunk-29ynsjfq.js → chunk-1pv77rcj.js} +1 -1
- package/dist/{chunk-kdzjjgne.js → chunk-2a1vnnqn.js} +1 -1
- package/dist/{chunk-td1h2the.js → chunk-381jajp9.js} +1 -1
- package/dist/{chunk-98592x6v.js → chunk-3b6pydsp.js} +1 -1
- package/dist/{chunk-kz1qdjpq.js → chunk-3kffwx9r.js} +1 -1
- package/dist/{chunk-r1v2v4px.js → chunk-3rjv4j1b.js} +1 -1
- package/dist/{chunk-jxwbk5rt.js → chunk-3rpctsyn.js} +1 -1
- package/dist/{chunk-dry642ad.js → chunk-47xf0rzm.js} +1 -1
- package/dist/chunk-48y8nymd.js +2 -0
- package/dist/{chunk-n24v0a8n.js → chunk-4apqdh3f.js} +1 -1
- package/dist/{chunk-ptjjdj21.js → chunk-4s8s4ykn.js} +2 -2
- package/dist/{chunk-141rr8b7.js → chunk-5jaqk3qt.js} +1 -1
- package/dist/{chunk-74g3bm5w.js → chunk-65yzwana.js} +1 -1
- package/dist/{chunk-senqe54c.js → chunk-6rn1k8p8.js} +5 -5
- package/dist/{chunk-w81qh0yy.js → chunk-7cnwxwea.js} +1 -1
- package/dist/{chunk-rrt6h2bs.js → chunk-7yjwssyf.js} +1 -1
- package/dist/{chunk-tkwqpqy2.js → chunk-81207938.js} +1 -1
- package/dist/{chunk-whnpn57z.js → chunk-87zyzvn7.js} +1 -1
- package/dist/{chunk-2mxvwwq8.js → chunk-9446y38z.js} +1 -1
- package/dist/{chunk-qkx3cd5k.js → chunk-9pn8mget.js} +1 -1
- package/dist/{chunk-9pym8csd.js → chunk-bmj0b8wk.js} +1 -1
- package/dist/{chunk-c26tb2ke.js → chunk-ebrwcs9w.js} +1 -1
- package/dist/{chunk-253bkpt7.js → chunk-emf81751.js} +1 -1
- package/dist/{chunk-b77zkf00.js → chunk-esqr3vxx.js} +1 -1
- package/dist/{chunk-j4zt82hj.js → chunk-ey88c81f.js} +1 -1
- package/dist/{chunk-gsh1zkv7.js → chunk-f60g0sq8.js} +1 -1
- package/dist/{chunk-8h0brwv1.js → chunk-f9xe4z1w.js} +1 -1
- package/dist/{chunk-5rhh02zd.js → chunk-fzgv8j3f.js} +2 -2
- package/dist/{chunk-ktnkpk2h.js → chunk-gx6wyk6s.js} +1 -1
- package/dist/{chunk-gr3c9d3a.js → chunk-jww1t4jg.js} +1 -1
- package/dist/{chunk-dmgqax6e.js → chunk-k2ezck5w.js} +1 -1
- package/dist/{chunk-bdyw886t.js → chunk-kpvpxf8b.js} +1 -1
- package/dist/{chunk-ezqjgvbq.js → chunk-mat40nfw.js} +1 -1
- package/dist/{chunk-ztjqtc1q.js → chunk-mq1axbkg.js} +1 -1
- package/dist/{chunk-722t529g.js → chunk-n1099xfe.js} +17 -17
- package/dist/{chunk-y5xez8wj.js → chunk-nnxwd7xs.js} +1 -1
- package/dist/{chunk-rm93zt1y.js → chunk-ph3e93rk.js} +1 -1
- package/dist/{chunk-b053r2ms.js → chunk-q6n9cx76.js} +1 -1
- package/dist/{chunk-qg64y374.js → chunk-rj13se6j.js} +1 -1
- package/dist/{chunk-6sqt3te5.js → chunk-rm932bp5.js} +1 -1
- package/dist/{chunk-z2jp138v.js → chunk-sffew58c.js} +1 -1
- package/dist/{chunk-tm900q42.js → chunk-sxq8amtq.js} +1 -1
- package/dist/{chunk-tpvc09rm.js → chunk-v7ea19ka.js} +1 -1
- package/dist/{chunk-wteftmcw.js → chunk-wze35dza.js} +1 -1
- package/dist/{chunk-s441eqb9.js → chunk-x6zkdeae.js} +1 -1
- package/dist/{chunk-4yp6pm37.js → chunk-xatfan9g.js} +2 -2
- package/dist/{chunk-ddekaar2.js → chunk-ys6ad5qk.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/offline/app-service-worker.d.ts +13 -0
- package/dist/offline/app-service-worker.js +17 -1
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-wf1zbmf2.js +0 -2
|
@@ -78,6 +78,14 @@ export interface OfflineAppConfig {
|
|
|
78
78
|
updateOnColdStart?: boolean;
|
|
79
79
|
/** Where a page that was never cached goes offline (one of `pages`). Default: the first of `pages`. */
|
|
80
80
|
fallback?: string;
|
|
81
|
+
/**
|
|
82
|
+
* The paths the fallback stands in for (a prefix). Default: the fallback's
|
|
83
|
+
* own section, its first path segment, so a `/m` fallback answers only for
|
|
84
|
+
* `/m/...`. Outside it a page that was never kept fails as it would without
|
|
85
|
+
* the worker. A phone app's screen is no answer for a page of the website
|
|
86
|
+
* beside it, and a dev server restarting looks offline for a moment.
|
|
87
|
+
*/
|
|
88
|
+
fallbackScope?: string;
|
|
81
89
|
/**
|
|
82
90
|
* Dynamic screens whose page is the same for every value, drawn on the
|
|
83
91
|
* device from the API: `/m/workout/:id` or `/m/workout/[id]`. One that was
|
|
@@ -131,6 +139,11 @@ export declare function offlineRoute(path: string): OfflineRoute | null;
|
|
|
131
139
|
* `window.stxOffline.applyUpdate()`, which takes over now and reloads.
|
|
132
140
|
*/
|
|
133
141
|
export declare function registerOfflineWorker(path: string): void;
|
|
142
|
+
/**
|
|
143
|
+
* The section a fallback screen stands in for: `scope` when given, else the
|
|
144
|
+
* fallback's first path segment (`/m/today` → `/m`, `/` → `/`).
|
|
145
|
+
*/
|
|
146
|
+
export declare function offlineFallbackScope(fallback: string | null, scope?: string): string | null;
|
|
134
147
|
/** The tag every page carries so the worker is installed. */
|
|
135
148
|
export declare const OFFLINE_REGISTER_SCRIPT: string;
|
|
136
149
|
/** The worker itself, for one build. */
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{bt,Hr,Vr,Ur,yu,Wr}from"./chunk-
|
|
2
|
+
import{bt,Hr,Vr,Ur,yu,Wr}from"./chunk-kpvpxf8b.js";import"./chunk-0trfbqa7.js";import"./chunk-zydg3wgt.js";import"./chunk-w6zz18jt.js";export{Vr as buildServerApi,yu as createServerApi,bt as discoverServerApi,Hr as generateApiTypes,Wr as isServerApiSource,Ur as productionApiDispatcher};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Pe,Wt}from"./chunk-rmcvab7m.js";import{Se}from"./chunk-w6zz18jt.js";import{Bo,Fo,f,St,N,zn,Hn,Vn,n,Q,I,o}from"./chunk-
|
|
2
|
+
import{Pe,Wt}from"./chunk-rmcvab7m.js";import{Se}from"./chunk-w6zz18jt.js";import{Bo,Fo,f,St,N,zn,Hn,Vn,n,Q,I,o}from"./chunk-n1099xfe.js";import{C}from"./chunk-zydg3wgt.js";import{xs}from"./chunk-3b6pydsp.js";import{un,de}from"./chunk-exgyf65a.js";import{bi}from"./chunk-0trfbqa7.js";import{ge,re,io,ao,It}from"./chunk-fzgv8j3f.js";import{bt,Vr}from"./chunk-kpvpxf8b.js";import{Dt}from"./chunk-r80km6mn.js";import{pt,Gt,Jt}from"./chunk-5pjsc9zv.js";import{createHash as ee}from"crypto";function J(i){return ee("sha256").update(i).digest("hex").slice(0,8)}function U(i=!1){let l=i?Wt():Pe(),a=J(l);return{content:l,filename:`runtime.${a}.js`,hash:a}}function V(){let i=Se(),l=J(i);return{content:i,filename:`router.${l}.js`,hash:l}}import m from"fs";import c from"path";import q from"path";import{createHash as te}from"crypto";function se(i={}){let l=new Set;return{context:new Proxy(i,{get(r,e){if(e in r)return r[e];if(typeof e==="string"&&!e.startsWith("__"))l.add(e);return},has(r,e){if(e in r)return!0;if(typeof e==="string"&&!e.startsWith("__"))l.add(e);return!1}}),accessedKeys:l}}async function X(i,l,a={}){let r=q.resolve(i),e=await Bun.file(r).text(),S=te("sha256").update(e).digest("hex").slice(0,16);Bo();let _={};try{_=await o(a.configDir)}catch{}let y=[],d=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,g;while((g=d.exec(e))!==null){let R=g[1];if(/\bserver\b/.test(R))y.push(g[2])}let u=new Set(y.flatMap((R)=>Q(R))),{context:D}=se({__filename:r,__dirname:q.dirname(r),__stx_serverDeclared:u}),A=new Set,j={...I,..._,...a,buildMode:"compile",strict:!1},b=await n(e,D,r,j,A),w=ge(b),P=Fo();return{route:l,sourceFile:i,html:b,fragment:w,placeholders:P,hasServerScripts:y.length>0,serverScriptContent:y,dependencies:Array.from(A),contentHash:S,status:St(e),streamTemplates:D.__streamTemplates}}var ne=new Set([".DS_Store","Thumbs.db","desktop.ini",".gitkeep",".gitignore"]);function Z(i,l){let a=0,r=0;if(!m.existsSync(i))return{copied:a,bytes:r};m.mkdirSync(l,{recursive:!0});function e(S,_){let y=m.readdirSync(S,{withFileTypes:!0});for(let d of y){if(ne.has(d.name))continue;let g=c.join(S,d.name),u=c.join(_,d.name);if(d.isDirectory())m.mkdirSync(u,{recursive:!0}),e(g,u);else if(d.isFile()){if(m.existsSync(u))continue;m.copyFileSync(g,u),a++,r+=m.statSync(u).size}}}return e(i,l),{copied:a,bytes:r}}async function Gc(i={}){let l=Date.now(),a=c.resolve(i.root||process.cwd()),r=c.resolve(a,i.outputDir||".output");console.log("[stx build] Starting production build...");let e=await o(a),S=c.resolve(a,i.componentsDir??e.componentsDir??"components"),_=c.resolve(a,i.partialsDir??e.partialsDir??"partials"),y=c.resolve(a,i.layoutsDir??e.layoutsDir??"layouts"),d=i.publicDir??e.publicDir??"public",g=de(e.app?.head,{known:un,source:"app.head"}),u=e.app?.colorMode,D=e.router?.container||"main",A=i.routeRules??e.routeRules??{},j=Dt(A),b=i.serverApi??e.serverApi,w=typeof b==="object"?b:{};if(b)bt(a,w);if(e.runtimeConfig)C(e.runtimeConfig,{});if(m.existsSync(r))m.rmSync(r,{recursive:!0});let P=[c.join(r,"public","__stx"),c.join(r,"public","assets"),c.join(r,"server","pages"),c.join(r,"server","fragments")];for(let s of P)m.mkdirSync(s,{recursive:!0});console.log("[stx build] Discovering routes...");let R=N(a,{pagesDirs:e._layerPageDirs}),Y=["components","layouts","partials"],B=R.filter((s)=>!Y.some((h)=>s.pattern.startsWith(`/${h}/`)||s.pattern===`/${h}`));console.log(`[stx build] Found ${B.length} page routes (${R.length-B.length} non-page files excluded)`),console.log("[stx build] Generating shared assets...");let v=U(i.debug),x=V();await Bun.write(c.join(r,"public","__stx",v.filename),v.content),await Bun.write(c.join(r,"public","__stx",x.filename),x.content),console.log(`[stx build] Runtime: ${v.filename} (${(v.content.length/1024).toFixed(1)}KB)`),console.log(`[stx build] Router: ${x.filename} (${(x.content.length/1024).toFixed(1)}KB)`),console.log("[stx build] Compiling templates...");let M=[],k=[];for(let s of B){let h=j(s.pattern),O=h.rendering==="prerender";if(O&&(s.pattern.includes(":")||s.pattern.includes("[")))throw Error(`Cannot prerender parameter route ${s.pattern}; use dynamic rendering (explicit path enumeration is not supported here)`);try{let t=await X(s.filePath,s.pattern,{configDir:a,componentsDir:S,partialsDir:_,layoutsDir:y,debug:i.debug});if(M.push(t),t.html=t.html.replace(/runtime\.__STX_HASH__\.js/g,v.filename).replace(/router\.__STX_HASH__\.js/g,x.filename),t.html=Vn(t.html,g,{bodyScripts:[`<script src="/__stx/${x.filename}"></script>`],...u&&{colorMode:u}}),u)t.html=zn(t.html,u);if(g.htmlAttrs)t.html=Hn(t.html,g.htmlAttrs);if(!/<body[^>]*\bdata-stx=/.test(t.html)){let p=t.html.match(/<(?!body\b)[a-zA-Z][a-zA-Z0-9-]*\b[^>]*?\s(data-stx="[^"]+")[^>]*>/);if(p&&p[1]){let W=p[1];t.html=t.html.replace(" "+W,""),t.html=t.html.replace(/<body([^>]*)>/,`<body$1 ${W}>`)}}if(t.html=t.html.replace(/<style data-css="generated">[\s\S]*?<\/style>\s*/g,""),t.html=await f(t.html),O){let p=await It(t,{params:{},request:new Request(`http://stx.build${s.pattern}`),method:"GET",__stx_strict_hydration:!0});if(p.redirect||p.cookies?.length||p.boundaries?.length||p.headers&&Object.keys(p.headers).length)throw Error(`Prerendered route ${s.pattern} cannot set response headers/cookies, redirect or stream`);t.html=p.html,t.status=p.status??t.status,t.hasServerScripts=!1,t.serverScriptContent=[],t.placeholders={}}t.fragment=re(t.html,D);let L=s.pattern==="/"?"index":s.pattern.slice(1).replace(/\//g,"-").replace(/[[\]]/g,"_"),z=c.join("server","pages",`${L}.compiled.json`),G=c.join("server","fragments",`${L}.html`);await Bun.write(c.join(r,z),JSON.stringify(t,null,2)),await Bun.write(c.join(r,G),t.fragment),k.push({pattern:s.pattern,compiledPath:z,fragmentPath:G,isDynamic:t.hasServerScripts,hasParams:s.pattern.includes(":")||s.pattern.includes("["),prerendered:O}),console.log(`[stx build] \u2713 ${s.pattern}`)}catch(t){if(Object.keys(h).length)throw t;console.error(`[stx build] \u2717 ${s.pattern}:`,t instanceof Error?t.message:t)}}let E=c.resolve(a,d);if(m.existsSync(E)){let{copied:s,bytes:h}=Z(E,c.join(r,"public"));if(s>0)console.log(`[stx build] Copied ${s} public asset${s===1?"":"s"} (${(h/1024).toFixed(1)}KB) from ${d}/`)}let H=Jt(a);if(H){let{copied:s,bytes:h}=Z(H,c.join(r,"public",Gt));if(s>0)console.log(`[stx build] Copied ${s} asset${s===1?"":"s"} (${(h/1024).toFixed(1)}KB) from ${pt}/`)}let F={runtime:v.filename,router:x.filename},T=io(k,F,r);if(T.routeRules=A,T.routerContainer=D,b)T.apiRoutes=await Vr(a,r,w);if(e.runtimeConfig)await Bun.write(c.join(r,"server/runtime-config.json"),JSON.stringify(e.runtimeConfig)),await xs(a,e.runtimeConfig);if(e._layerGraph)await Bun.write(c.join(r,"server/layers.json"),JSON.stringify(bi(e._layerGraph),null,2));ao(T,r);let K=Date.now()-l;return console.log(`
|
|
3
3
|
[stx build] Done in ${K}ms \u2014 ${M.length} pages compiled`),{pageCount:M.length,assets:F,outputDir:r,duration:K}}
|
|
4
4
|
export{Gc};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Yi,ul,Zi,Qi,dl,pl}from"./chunk-
|
|
2
|
+
import{Yi,ul,Zi,Qi,dl,pl}from"./chunk-3kffwx9r.js";import"./chunk-n1099xfe.js";import"./chunk-bq2e9qf6.js";import"./chunk-8xz8t9xp.js";import"./chunk-0trfbqa7.js";import"./chunk-3b6pydsp.js";import"./chunk-zydg3wgt.js";import"./chunk-4fa3jec9.js";import"./chunk-exgyf65a.js";import"./chunk-r6pax860.js";import"./chunk-h9e032kq.js";import"./chunk-w1zvh5y7.js";import"./chunk-w6zz18jt.js";import"./chunk-jz7pvh7b.js";export{pl as applySlots,dl as extractSlotContent,ul as parseSlotElement,Yi as parseSlots,Qi as processSlots,Zi as renderSlot};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Or,yl,bl}from"./chunk-
|
|
2
|
+
import{Or,yl,bl}from"./chunk-esqr3vxx.js";import"./chunk-x6zkdeae.js";import"./chunk-kpvpxf8b.js";import"./chunk-n1099xfe.js";import"./chunk-bq2e9qf6.js";import"./chunk-8xz8t9xp.js";import"./chunk-0trfbqa7.js";import"./chunk-3b6pydsp.js";import"./chunk-zydg3wgt.js";import"./chunk-4fa3jec9.js";import"./chunk-exgyf65a.js";import"./chunk-r6pax860.js";import"./chunk-h9e032kq.js";import"./chunk-w1zvh5y7.js";import"./chunk-w6zz18jt.js";import"./chunk-jz7pvh7b.js";export{bl as clearComposableCache,yl as getComposableScript,Or as listComposableModules};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Et,C}from"./chunk-zydg3wgt.js";import m from"fs";import e from"path";async function cn(r,o,i){if(r.__stx_runtime_config)return;let n=Et();if(n||i){r.__stx_runtime_config=n??C(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-
|
|
2
|
+
import{Et,C}from"./chunk-zydg3wgt.js";import m from"fs";import e from"path";async function cn(r,o,i){if(r.__stx_runtime_config)return;let n=Et();if(n||i){r.__stx_runtime_config=n??C(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-v7ea19ka.js"),c=await f(t);if(c.runtimeConfig)r.__stx_runtime_config=C(c.runtimeConfig);return}let s=e.dirname(t);if(s===t)return;t=s}}async function xs(r,o){function i(n){if(n===null)return"null";if(Array.isArray(n))return`Array<${n.length?[...new Set(n.map(i))].join(" | "):"unknown"}>`;if(typeof n==="object")return`{ ${Object.entries(n).map(([t,s])=>`readonly ${JSON.stringify(t)}: ${i(s)}`).join("; ")} }`;return typeof n}await Bun.write(e.join(r,".stx/runtime-config.d.ts"),`import '@stacksjs/stx/runtime-config'
|
|
3
3
|
declare module '@stacksjs/stx/runtime-config' { interface PublicRuntimeConfig ${i(o.public??{})} }
|
|
4
4
|
`),await Bun.write(e.join(r,".stx/runtime-config-server.d.ts"),`import '@stacksjs/stx/runtime-config-server'
|
|
5
5
|
declare module '@stacksjs/stx/runtime-config-server' { interface PrivateRuntimeConfig ${i(o.private??{})} }
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{p,l}from"./chunk-r6pax860.js";import{b}from"./chunk-
|
|
2
|
+
import{p,l}from"./chunk-r6pax860.js";import{b}from"./chunk-n1099xfe.js";function y(t,o){let i=1,r=o,e="<template",n="</template";while(r<t.length&&i>0){let s=t.indexOf("<",r);if(s===-1)break;if(r=s,t.startsWith(e,r)&&(r+e.length>=t.length||/[\s>\/]/.test(t[r+e.length]))){i++,r+=e.length;continue}if(t.startsWith(n,r)){let a=t.indexOf(">",r+n.length);if(a!==-1){if(i--,i===0)return a+1;r=a+1;continue}}r++}return i===0?r:-1}var w=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function x(t,o){let i=null;for(let r=o;r<t.length;r++){let e=t[r];if(i){if(e==="\\"){r++;continue}if(e===i)i=null;continue}if(e==='"'||e==="'"){i=e;continue}if(e===">")return r+1}return-1}function N(t,o,i){let r=o.toLowerCase(),e=1,n=i;while(n<t.length){let s=t.indexOf("<",n);if(s===-1)return-1;if(t.startsWith("<!--",s)){let g=t.indexOf("-->",s+4);n=g===-1?t.length:g+3;continue}let a=x(t,s+1);if(a===-1)return-1;let f=t.slice(s,a),u=f.match(/^<\s*(\/?)\s*([a-zA-Z][\w-]*)/);if(u&&u[2].toLowerCase()===r){if(u[1]==="/"){if(e--,e===0)return a}else if(!/\/\s*>$/.test(f))e++}n=a}return-1}function A(t){let o=[],i=[],r=/\bslot\s*=\s*(?:"([^"]+)"|'([^']+)')/i,e=0;while(e<t.length){let n=t.indexOf("<",e);if(n===-1)break;if(t.startsWith("<!--",n)){let c=t.indexOf("-->",n+4);e=c===-1?t.length:c+3;continue}let s=x(t,n+1);if(s===-1)break;let a=t.slice(n,s),f=a.match(/^<\s*(\/?)\s*([a-zA-Z][\w-]*)/);if(!f){e=s;continue}let u=f[2].toLowerCase();if(f[1]==="/"){let c=i.lastIndexOf(u);if(c!==-1)i.splice(c);e=s;continue}let g=/\/\s*>$/.test(a),d=i.length===0?a.match(r):null;if(d){let c=d[1]||d[2],m=a.replace(r,"").replace(/\s+(?=\/?>$)/,"").replace(/\s{2,}/g," "),h=g||w.has(u)?-1:N(t,u,s);if(h===-1)o.push({start:n,end:s,slotName:c,element:m}),e=s;else o.push({start:n,end:h,slotName:c,element:m+t.slice(s,h)}),e=h;continue}if(!g&&!w.has(u)){if(i.push(u),u==="script"||u==="style"){let c=t.toLowerCase().indexOf(`</${u}>`,s);if(c!==-1){e=c;continue}}}e=s}return o}function O(t){let o=[],i=[],r=/^<template\s+(?:#([a-zA-Z][\w-]*)|v-slot:([a-zA-Z][\w-]*)|slot="([a-zA-Z][\w-]*)")(?:\s*=\s*"([^"]*)")?[^>]*>$/i,e=0;while(e<t.length){let n=t.indexOf("<",e);if(n===-1)break;if(t.startsWith("<!--",n)){let c=t.indexOf("-->",n+4);e=c===-1?t.length:c+3;continue}let s=x(t,n+1);if(s===-1)break;let a=t.slice(n,s),f=a.match(/^<\s*(\/?)\s*([a-zA-Z][\w-]*)/);if(!f){e=s;continue}let u=f[1]==="/",g=f[2].toLowerCase();if(u){let c=i.lastIndexOf(g);if(c!==-1)i.splice(c);e=s;continue}if(g==="template"&&i.length===0){let c=a.match(r);if(c){let m=y(t,s);if(m!==-1){let h=c[1]||c[2]||c[3];o.push({start:n,end:m,slotName:h,content:t.slice(s,m-11).trim(),propsBinding:c[4]||void 0}),e=m;continue}}}if(!/\/\s*>$/.test(a)&&!w.has(g)){if(i.push(g),g==="script"||g==="style"){let c=t.toLowerCase().indexOf(`</${g}>`,s);if(c!==-1){e=c;continue}}}e=s}return o}function Yi(t){let o={default:"",named:new Map},i=t,r=O(t);for(let n of r)o.named.set(n.slotName,{name:n.slotName,content:n.content,propsBinding:n.propsBinding});r.sort((n,s)=>s.start-n.start);for(let n of r)i=i.slice(0,n.start)+i.slice(n.end);let e=A(i);for(let n of e){let s=o.named.get(n.slotName);if(s)s.content+=n.element;else o.named.set(n.slotName,{name:n.slotName,content:n.element})}for(let n=e.length-1;n>=0;n--){let s=e[n];i=i.slice(0,s.start)+i.slice(s.end)}return o.default=i.trim(),o}function ul(t){let o=t.match(/name\s*=\s*["']([^"']+)["']/),i=o?o[1]:"",r={},e=/:([a-zA-Z][\w-]*)\s*=\s*["']([^"']+)["']/g,n;while((n=e.exec(t))!==null)r[n[1]]=n[2];let s=t.match(/<slot[^>]*>([\s\S]*?)<\/slot>/i),a=s?s[1].trim():"";return{name:i,props:r,defaultContent:a}}async function Zi(t,o,i,r){if(!t)return i;let e=t.content;if(t.propsBinding&&Object.keys(o).length>0){let n=t.propsBinding.trim(),s={...r};if(n.startsWith("{")&&n.endsWith("}")){let a=n.slice(1,-1).split(",").map((f)=>f.trim()).filter(Boolean);for(let f of a){let[u,g]=f.split(":").map((c)=>c.trim()),d=g||u;if(o[u]!==void 0)s[d]=o[u]}}else s[n]=o;e=C(e,s)}return e}function C(t,o){return t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,r)=>{try{let e=r.trim(),n=k(e,o);return b(String(n??""))}catch{return`{{ ${r} }}`}})}function k(t,o){if(/^[a-zA-Z_$][\w$]*(\.[a-zA-Z_$][\w$]*)*$/.test(t)){let r=t.split("."),e=o;for(let n of r)if(e&&typeof e==="object"&&n in e)e=e[n];else return;return e}let i=t.match(/^([a-zA-Z_$][\w$]*)\s*([+\-*/])\s*(\d+)$/);if(i){let[,r,e,n]=i,s=o[r],a=parseInt(n,10);if(typeof s==="number")switch(e){case"+":return s+a;case"-":return s-a;case"*":return s*a;case"/":return s/a}}try{if(!p(t))return;return l(t,Object.keys(o))(...Object.values(o))}catch{return}}async function Qi(t,o,i){let r=t;r=await M(r,/<slot\s+name\s*=\s*["']([^"']+)["']([^>]*?)(?:\/>|>([\s\S]*?)<\/slot>)/gi,async(s,a,f,u)=>{let g=o.named.get(a),d=u?.trim()||"",c=f||"",m={},h=/:([a-zA-Z_$][\w$-]*)\s*=\s*["']([^"']+)["']/g,S;while((S=h.exec(c))!==null){let E=S[1],R=S[2];m[E]=k(R,i)}return await Zi(g,m,d,i)});let n=/<slot\b((?:"[^"]*"|'[^']*'|[^>"'])*?)\s*(?:\/>|>([\s\S]*?)<\/slot>)/gi;return r=r.replace(n,(s,a,f)=>{if(/\bname\s*=/.test(a||""))return s;let u=f?.trim()||"";return o.default||u}),r}async function M(t,o,i){let r=[],e=[];t.replace(o,(a,...f)=>{let u=f[f.length-2];return e.push({match:a,index:u}),r.push(i(a,...f.slice(0,-2))),a});let n=await Promise.all(r),s=t;for(let a=e.length-1;a>=0;a--){let{match:f,index:u}=e[a];s=s.slice(0,u)+n[a]+s.slice(u+f.length)}return s}function dl(t){let o=Yi(t);return{defaultSlot:o.default,namedSlots:o.named}}async function pl(t,o,i,r){return await Qi(t,{default:o,named:i},r)}
|
|
3
3
|
export{Yi,ul,Zi,Qi,dl,pl};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{cl}from"./chunk-
|
|
2
|
+
import{cl}from"./chunk-wze35dza.js";import"./chunk-fzgv8j3f.js";import"./chunk-kpvpxf8b.js";import"./chunk-n1099xfe.js";import"./chunk-bq2e9qf6.js";import"./chunk-8xz8t9xp.js";import"./chunk-0trfbqa7.js";import"./chunk-3b6pydsp.js";import"./chunk-zydg3wgt.js";import"./chunk-4fa3jec9.js";import"./chunk-exgyf65a.js";import"./chunk-r6pax860.js";import"./chunk-h9e032kq.js";import"./chunk-w1zvh5y7.js";import"./chunk-w6zz18jt.js";import"./chunk-jz7pvh7b.js";export{cl as startProductionServer};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{nn,rc,ts}from"./chunk-
|
|
2
|
+
import{nn,rc,ts}from"./chunk-n1099xfe.js";import"./chunk-bq2e9qf6.js";import"./chunk-8xz8t9xp.js";import"./chunk-0trfbqa7.js";import"./chunk-3b6pydsp.js";import"./chunk-zydg3wgt.js";import"./chunk-4fa3jec9.js";import"./chunk-exgyf65a.js";import{ve}from"./chunk-r6pax860.js";import"./chunk-h9e032kq.js";import"./chunk-w1zvh5y7.js";import"./chunk-w6zz18jt.js";import"./chunk-jz7pvh7b.js";export{ve as freeIdentifiers,ts as processComponents,rc as processESImports,nn as rendersAsElement};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Oi,Mi}from"./chunk-6rn1k8p8.js";import"./chunk-mhpsz5m0.js";import"./chunk-rcr57c30.js";import"./chunk-sxq8amtq.js";import"./chunk-ree9weje.js";import"./chunk-nnxwd7xs.js";import"./chunk-1pv77rcj.js";import"./chunk-tpeyn7wr.js";import"./chunk-rgwvqmhh.js";import"./chunk-9pn8mget.js";import"./chunk-wze35dza.js";import{no}from"./chunk-fzgv8j3f.js";import"./chunk-tbjyp03h.js";import"./chunk-z80d9dd2.js";import"./chunk-3kffwx9r.js";import"./chunk-ab56jdah.js";import"./chunk-n1dyjhte.js";import"./chunk-462jmw0a.js";import"./chunk-gkqxnetc.js";import"./chunk-5p56w2ke.js";import"./chunk-2bdthb37.js";import"./chunk-esqr3vxx.js";import"./chunk-5qns2sdz.js";import"./chunk-6r2709dj.js";import"./chunk-c491hsm1.js";import"./chunk-n866vbgj.js";import"./chunk-z2daw0th.js";import"./chunk-z3etxty5.js";import"./chunk-ys6ad5qk.js";import"./chunk-rmcvab7m.js";import"./chunk-7cnwxwea.js";import"./chunk-xatfan9g.js";import"./chunk-dxxs52yw.js";import"./chunk-x6zkdeae.js";import"./chunk-kpvpxf8b.js";import{me,Qt,en,K,d,n,Kn,I,o,ce}from"./chunk-n1099xfe.js";import"./chunk-bq2e9qf6.js";import"./chunk-8xz8t9xp.js";import"./chunk-0trfbqa7.js";import"./chunk-3b6pydsp.js";import"./chunk-zydg3wgt.js";import"./chunk-4fa3jec9.js";import"./chunk-exgyf65a.js";import"./chunk-r6pax860.js";import"./chunk-h9e032kq.js";import"./chunk-w1zvh5y7.js";import"./chunk-w6zz18jt.js";import"./chunk-jz7pvh7b.js";export{Kn as buildWebComponents,en as cacheTemplate,Qt as checkCache,no as classifyAllScripts,Oi as createMiddleware,Mi as createRoute,I as defaultConfig,d as extractVariables,K as injectRouterScript,o as loadStxConfig,me as processClientScript,n as processDirectives,ce as readMarkdownFile};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Xc}from"./chunk-
|
|
2
|
+
import{Xc}from"./chunk-nnxwd7xs.js";import"./chunk-n1099xfe.js";import"./chunk-bq2e9qf6.js";import"./chunk-8xz8t9xp.js";import"./chunk-0trfbqa7.js";import"./chunk-3b6pydsp.js";import"./chunk-zydg3wgt.js";import"./chunk-4fa3jec9.js";import"./chunk-exgyf65a.js";import"./chunk-r6pax860.js";import"./chunk-h9e032kq.js";import"./chunk-w1zvh5y7.js";import"./chunk-w6zz18jt.js";import"./chunk-jz7pvh7b.js";export{Xc as startInteractive};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ce,$e,Ee}from"./chunk-qxre7vw6.js";import"./chunk-w1zvh5y7.js";import"./chunk-h9e032kq.js";import{d}from"./chunk-
|
|
2
|
+
import{Ce,$e,Ee}from"./chunk-qxre7vw6.js";import"./chunk-w1zvh5y7.js";import"./chunk-h9e032kq.js";import{d}from"./chunk-n1099xfe.js";import"./chunk-r6pax860.js";import"./chunk-8xz8t9xp.js";import"./chunk-w6zz18jt.js";import"./chunk-exgyf65a.js";import"./chunk-4fa3jec9.js";import"./chunk-0trfbqa7.js";import"./chunk-zydg3wgt.js";import"./chunk-3b6pydsp.js";import"./chunk-jz7pvh7b.js";import{ot,dr,it,js,ke,Bs,pr,at,zs,ct}from"./chunk-1sdtg9np.js";import"./chunk-bq2e9qf6.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(p)=>{if(p==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{Bs("Config file changed, restarting...");try{await e.onChange()}catch(l){ke(`Failed to restart: ${l}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var st=".stx/story/analytics.json",dt=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,st),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:dt,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:pt(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let p=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),l=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),g=l.length>0?l.reduce((i,m)=>i+m,0)/l.length:0,y=Object.entries(c).sort((i,m)=>m[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:p.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:y,variantViews:n,avgTimeSpent:g}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function pt(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var lt=".stx/story/bookmarks.json",mt=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:mt,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:ut(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function ut(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
|
|
3
3
|
<script>
|
|
4
4
|
(function() {
|
|
5
5
|
const ws = new WebSocket('${t}');
|
|
@@ -556,7 +556,7 @@ window.__stxPerformance = {
|
|
|
556
556
|
|
|
557
557
|
window.clearPerformanceMetrics = () => window.__stxPerformance.clear();
|
|
558
558
|
</script>
|
|
559
|
-
`}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:p}=await import("./chunk-
|
|
559
|
+
`}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:p}=await import("./chunk-ph3e93rk.js"),l={},g=h(n);if(g)try{await d(g,l,e)}catch(f){o.push(`Warning: Could not extract script variables: ${f instanceof Error?f.message:String(f)}`)}if(r.props)Object.assign(l,r.props);let i=await p(n,l,e,{},new Set),m=Z(n),u=h(n);return i=Q(i),i=tt(i,l),{html:i,css:m,js:u,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function vt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await d(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await vt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return bt(t,a.source,c);return b(t,e.path,{props:c})}async function bt(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-ph3e93rk.js"),c={...r},n=h(e);if(n)try{await d(n,c,"inline-template.stx")}catch{}let l=await a(e,c,"inline-template.stx",{},new Set);return l=Q(l),l=tt(l,c),{html:l,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
560
560
|
`)}function Q(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/^\s*\n/gm,"").trim()}function h(t){let e=[],r=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
561
561
|
`)}function tt(t,e){let r=`<script>window.__stxProps = ${JSON.stringify(e)};</script>`;return t+r}function et(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function rt(t,e){let r=await at(t);$e(t,r);let s=ct(t.config,r);Ee(t,s),console.log(` Found ${r.length} story files`);let o=typeof e.host==="string"?e.host:e.host===!0?"0.0.0.0":"localhost",a=new I(t.root),c=new P(t.root),n=new k(t.root),p=N(),l=Bun.serve({port:e.port,hostname:o,fetch:async(i,m)=>{let f=new URL(i.url).pathname;if(f==="/__hmr"){if(m.upgrade(i,{data:{isHmr:!0}}))return;return new Response("WebSocket upgrade failed",{status:400})}if(f.startsWith("/api/"))return xt(t,f,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return wt(t,f,e.port)},websocket:{open(i){p.open(i)},close(i){p.close(i)},message(i,m){p.message(i,m)}}}),g=`http://${o}:${e.port}`,y=zs(t,async(i,m)=>{console.log(` [${i}] ${m.relativePath}`);let u=await at(t);$e(t,u);let f=ct(t.config,u);if(Ee(t,f),i==="add")H(m.id,{fileName:m.fileName});else if(i==="unlink")O(m.id);else V(m.id,{fileName:m.fileName})});if(e.open){let i=g;try{let{exec:m}=await import("child_process"),u=process.platform;m(`${u==="darwin"?"open":u==="win32"?"start":"xdg-open"} ${i}`)}catch{}}return{server:l,url:g,close:async()=>{y(),l.stop()}}}async function xt(t,e,r,s){let{presetsManager:o,bookmarksManager:a,analyticsTracker:c}=s;if(e==="/api/stories")return Response.json({files:t.storyFiles.map((n)=>({id:n.id,fileName:n.fileName,relativePath:n.relativePath,treePath:n.treePath})),tree:t.tree});if(e.startsWith("/api/story/")){let n=e.slice(11),p=t.storyFiles.find((l)=>l.id===n);if(!p)return new Response("Story not found",{status:404});try{let l=await Bun.file(p.path).text();return Response.json({id:p.id,fileName:p.fileName,relativePath:p.relativePath,content:l})}catch{return new Response("Error reading story",{status:500})}}if(e==="/api/config")return Response.json({theme:t.config.theme,responsivePresets:t.config.responsivePresets,backgroundPresets:t.config.backgroundPresets});if(e.startsWith("/api/render/")){let n=new URL(r.url),p=e.slice(12).split("/"),l=p[0],g=p[1]||"default",y,i=n.searchParams.get("props");if(i)try{y=JSON.parse(i)}catch{}let m=t.storyFiles.find((u)=>u.id===l);if(!m)return new Response("Story not found",{status:404});try{let u=await Y(t,m,g,y);return Response.json({html:u.html,css:u.css,js:u.js,errors:u.errors,duration:u.duration})}catch(u){return Response.json({html:"",css:"",js:"",errors:[u instanceof Error?u.message:String(u)],duration:0},{status:500})}}if(e==="/api/presets"&&r.method==="GET")return Response.json({presets:o.getAllPresets()});if(e==="/api/presets"&&r.method==="POST")try{let n=await r.json(),p=o.createPreset(n.name,n.props,{componentId:n.componentId,description:n.description});return await o.save(),Response.json(p)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/presets/")&&!e.includes("/use")&&r.method==="GET"){let n=e.slice(13),p=o.getPreset(n);if(!p)return new Response("Preset not found",{status:404});return Response.json(p)}if(e.endsWith("/use")&&r.method==="POST"){let n=e.slice(13,-4),p=o.usePreset(n);if(!p)return new Response("Preset not found",{status:404});return await o.save(),Response.json(p)}if(e.startsWith("/api/presets/")&&r.method==="DELETE"){let n=e.slice(13);if(!o.deletePreset(n))return new Response("Preset not found",{status:404});return await o.save(),Response.json({success:!0})}if(e==="/api/bookmarks"&&r.method==="GET")return Response.json({bookmarks:a.getAllBookmarks()});if(e==="/api/bookmarks"&&r.method==="POST")try{let n=await r.json(),p=a.addBookmark(n.storyId,n.variantId,n.props,{name:n.name,notes:n.notes,color:n.color});return await a.save(),Response.json(p)}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/bookmarks/toggle"&&r.method==="POST")try{let n=await r.json(),p=a.toggleBookmark(n.storyId,n.variantId,n.props);return await a.save(),Response.json(p)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/bookmarks/")&&e!=="/api/bookmarks/toggle"&&r.method==="GET"){let n=e.slice(15),p=a.getBookmark(n);if(!p)return new Response("Bookmark not found",{status:404});return Response.json(p)}if(e.startsWith("/api/bookmarks/")&&r.method==="DELETE"){let n=e.slice(15);if(!a.deleteBookmark(n))return new Response("Bookmark not found",{status:404});return await a.save(),Response.json({success:!0})}if(e==="/api/analytics/track"&&r.method==="POST")try{let n=await r.json();if(n.type==="view"&&n.componentId)c.trackView(n.componentId,n.variantId);else if(n.type==="prop_change"&&n.componentId&&n.propName)c.trackPropChange(n.componentId,n.propName,null);else if(n.type==="variant_switch"&&n.componentId&&n.variantId)c.trackVariantSwitch(n.componentId,n.variantId);else if(n.type==="search"&&n.query)c.trackSearch(n.query,0);return await c.save(),Response.json({success:!0})}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/analytics/summary"&&r.method==="GET")return Response.json({mostViewed:c.getMostViewedComponents(10),mostChangedProps:c.getMostChangedProps(10),searchAnalytics:c.getSearchAnalytics()});if(e.startsWith("/api/analytics/component/")&&r.method==="GET"){let n=e.slice(25),p=t.storyFiles.find((g)=>g.id===n),l=c.getComponentAnalytics(n,p?.fileName||n);return Response.json(l)}return new Response("Not found",{status:404})}function wt(t,e,r){let s=kt(t,r);return new Response(s,{headers:{"Content-Type":"text/html; charset=utf-8"}})}function kt(t,e){let{theme:r}=t.config,s=r.title||"STX Story",o=`ws://localhost:${e}/__hmr`,a=F(o);return`<!DOCTYPE html>
|
|
562
562
|
<html lang="en" class="${r.darkClass||"dark"}">
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Pu,Vo,Iu,Uo,Za,Qa,xt,tn,Du,ec,tc,nc,f}from"./chunk-
|
|
2
|
+
import{Pu,Vo,Iu,Uo,Za,Qa,xt,tn,Du,ec,tc,nc,f}from"./chunk-n1099xfe.js";import"./chunk-bq2e9qf6.js";import"./chunk-8xz8t9xp.js";import"./chunk-0trfbqa7.js";import"./chunk-3b6pydsp.js";import"./chunk-zydg3wgt.js";import"./chunk-4fa3jec9.js";import"./chunk-exgyf65a.js";import"./chunk-r6pax860.js";import"./chunk-h9e032kq.js";import"./chunk-w1zvh5y7.js";import"./chunk-w6zz18jt.js";import"./chunk-jz7pvh7b.js";export{xt as buildCss,ec as extractClassNames,Qa as fingerprintConfig,tc as generateCss,Du as getCachedCSS,Pu as getCssServeAsset,f as injectCss,Vo as loadCssEngine,Uo as loadCssEngineConfig,tn as rebuildCss,Iu as resetCssCache,Za as resolveUserCssConfig,nc as withLinkedModuleBundles};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Nu,sc,ns,rs,qo,Ko,ss,os,Bn,oc,Xo,Go,ic,ze}from"./chunk-
|
|
2
|
+
import{Nu,sc,ns,rs,qo,Ko,ss,os,Bn,oc,Xo,Go,ic,ze}from"./chunk-n1099xfe.js";import"./chunk-bq2e9qf6.js";import"./chunk-8xz8t9xp.js";import"./chunk-0trfbqa7.js";import"./chunk-3b6pydsp.js";import"./chunk-zydg3wgt.js";import"./chunk-4fa3jec9.js";import"./chunk-exgyf65a.js";import"./chunk-r6pax860.js";import"./chunk-h9e032kq.js";import"./chunk-w1zvh5y7.js";import"./chunk-w6zz18jt.js";import"./chunk-jz7pvh7b.js";export{Nu as clearScriptScanCache,ss as convertServerLoopAttributesToDirectives,qo as convertSignalDirectivesToAttributes,os as convertSignalLoopsToAttributes,oc as extractExports,Go as findMarkupIndexOutsideScripts,rs as hasSignalsSyntax,ns as parseLoopExpression,Ko as preEvalLiteralReactiveIfs,Bn as processScriptSetup,Xo as processSignals,ic as rewriteStxImportSpecifiers,sc as scanScriptTags,ze as stripStxRuntimeImports};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{X,dn,te,A,Tt}from"./chunk-r6pax860.js";import{Ze,mn,ir,ar,cr,Qe,et,tt,nt,rt,st,xe}from"./chunk-w6zz18jt.js";import{U,b,Qt,en,e,xt,tn,f,je,St,Be,Fe,Z,N,ae,K,d,ye,ei,ds,n,r,ee,Kn,o,R,ce}from"./chunk-
|
|
2
|
+
import{X,dn,te,A,Tt}from"./chunk-r6pax860.js";import{Ze,mn,ir,ar,cr,Qe,et,tt,nt,rt,st,xe}from"./chunk-w6zz18jt.js";import{U,b,Qt,en,e,xt,tn,f,je,St,Be,Fe,Z,N,ae,K,d,ye,ei,ds,n,r,ee,Kn,o,R,ce}from"./chunk-n1099xfe.js";import{_e,ro,ne,T,so,xr,Cn,ge,oo,re}from"./chunk-fzgv8j3f.js";import{Pt}from"./chunk-wze35dza.js";import{De}from"./chunk-x6zkdeae.js";import{a}from"./chunk-7tt84v1y.js";import{O}from"./chunk-58n62bxb.js";function Hs(t,s){let i=[],p=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(p)){let m=l.slice(p.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}var{serve:rr}=globalThis.Bun;import Bt from"fs";import pt from"path";function bt(){return`
|
|
3
3
|
/* Theme selector for code blocks */
|
|
4
4
|
.theme-selector {
|
|
5
5
|
margin: 1rem 0;
|
|
@@ -1786,7 +1786,7 @@ else {
|
|
|
1786
1786
|
})()
|
|
1787
1787
|
</script>
|
|
1788
1788
|
`;import Me from"fs";import Te from"path";function An(t){try{return Me.statSync(t).mtimeMs}catch{return null}}function Mt(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Ei(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Dn(t,s="stx"){let i=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(i,"pantry","@stacksjs",s);if(Me.existsSync(c))return c;let l=Te.dirname(i);if(l===i)break;i=l}return null}var Mn=["@stacksjs/stx","bun-plugin-stx"];function Pi(t){try{let s=Me.readFileSync(Te.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Ai(t,s=6){let i=Te.resolve(t),p=[],c=new Set;function l(u,h){if(h>s)return;let g;try{g=Me.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of Mn){let S=Te.join(u,w),E=Pi(S);if(E!==null)p.push({name:w,version:E,dir:Te.relative(i,S)||S,nested:h>0})}let y;try{y=Me.readdirSync(u,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=Te.join(u,w.name);if(w.name.startsWith("@")){let v;try{v=Me.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let C=Te.join(S,x.name,"node_modules");if(Me.existsSync(C))l(C,h+1)}continue}let E=Te.join(S,"node_modules");if(Me.existsSync(E))l(E,h+1)}}let m=Te.join(i,"node_modules");if(Me.existsSync(m))l(m,0);return p}function Di(t){let s=[];for(let i of Mn){let p=t.filter((m)=>m.name===i);if(p.length<=1)continue;let c=[...new Set(p.map((m)=>m.version))],l=p.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${p.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function gr(t={}){let s=t.cwd?Te.resolve(t.cwd):process.cwd(),i=t.resolve??Ei,p=Date.now(),c=[],l=i("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of Di(Ai(s)))c.push(h);let u=Dn(s,"stx");if(!u)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=Te.join(u,"src/signals.ts"),g=[Te.join(u,"dist/index.js"),Te.join(u,"dist/signals.js")].find((v)=>Me.existsSync(v))||null,y=An(h),w=g?An(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${u} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${u} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Mt(w,p)}) is OLDER than src/signals.ts (${Mt(y,p)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${u} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Mt(y,p)}, dist ${Mt(w,p)})`});let S=Te.join(s,"node_modules/@stacksjs/stx"),E=null;try{E=Me.lstatSync(S)}catch{E=null}if(!E)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(E.isSymbolicLink()){let v=null;try{v=Me.realpathSync(S)}catch{}let x=(()=>{try{return Me.realpathSync(u)}catch{return u}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function mr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let p of t.checks)if(i.push(` ${s[p.status]} ${p.name}: ${p.detail}`),p.fix)i.push(` \u2192 ${p.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
|
|
1789
|
-
`)}var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},p=new Set,c=i.webComponents?.enabled?`./${_t.relative(_t.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Kn(i,p);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(i.cache&&i.cachePath){let x=await Qt(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await te(()=>Bun.file(m).text(),"",(x)=>{throw new dn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new dn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=U.time("script-extraction",()=>{let x=h,C=Z(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",_=[];for(let P of k){let L=P.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=P.match(/<script\b([^>]*)>/i),G=B?B[1]:"";if(/\bserver\b/i.test(G))H=L;else _.push(P)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:_}}),S={__filename:m,__dirname:_t.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>d(g,S,m),void 0,(x)=>{let C=new X(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(A.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await U.timeAsync("directive-processing",async()=>await n(y,S,m,i,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-
|
|
1789
|
+
`)}var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},p=new Set,c=i.webComponents?.enabled?`./${_t.relative(_t.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Kn(i,p);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let u=new Set;if(i.cache&&i.cachePath){let x=await Qt(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await te(()=>Bun.file(m).text(),"",(x)=>{throw new dn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new dn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=U.time("script-extraction",()=>{let x=h,C=Z(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",_=[];for(let P of k){let L=P.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=P.match(/<script\b([^>]*)>/i),G=B?B[1]:"";if(/\bserver\b/i.test(G))H=L;else _.push(P)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:_}}),S={__filename:m,__dirname:_t.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>d(g,S,m),void 0,(x)=>{let C=new X(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(A.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await U.timeAsync("directive-processing",async()=>await n(y,S,m,i,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-9446y38z.js"),C=x(w.join(`
|
|
1790
1790
|
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+C+`
|
|
1791
1791
|
`+v.slice(k);else v+=`
|
|
1792
1792
|
${C}`}if(v=await K(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await en(m,v,u,i),i.debug)console.log(`Cached template ${m} with ${u.size} dependencies`)}return{contents:v,loader:"html"}}catch(u){let h=u instanceof Error?u:new X(`Plugin processing failed: ${String(u)}`,m);if(A.log(h,{filePath:m,buildConfig:t.config}),Tt.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||O()?`<!DOCTYPE html>
|
|
@@ -1849,7 +1849,7 @@ ${C}`}if(v=await K(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await en
|
|
|
1849
1849
|
<h1>Something went wrong</h1>
|
|
1850
1850
|
<p>An internal error occurred. Please try again later.</p>
|
|
1851
1851
|
</body>
|
|
1852
|
-
</html>`,loader:"html"}}})}};async function bn(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=Se.resolve(t);if(!Ne.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Ne.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let L={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},B=await Bun.build({entrypoints:[u],outdir:h,plugins:[L,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let G=B.outputs.find(($e)=>$e.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(L){return console.error(`${e.red}Error building stx file:${e.reset}`,L),!1}};if(!await y())return!1;let S=Se.dirname(u);await xt(S);let E=i;try{if(E=await Ye(i),E!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${E} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||E+1;l=Ot({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,C;try{let{loadStxConfig:L}=await import("./chunk-
|
|
1852
|
+
</html>`,loader:"html"}}})}};async function bn(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=Se.resolve(t);if(!Ne.existsSync(u))return console.error(`${e.red}Error: File not found: ${e.bright}${u}${e.reset}`),!1;if(u.endsWith(".md"))return Ft(u,s);else if(!u.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${u}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Ne.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let L={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(he)=>({path:he.path,external:!0}))}},B=await Bun.build({entrypoints:[u],outdir:h,plugins:[L,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let G=B.outputs.find(($e)=>$e.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(L){return console.error(`${e.red}Error building stx file:${e.reset}`,L),!1}};if(!await y())return!1;let S=Se.dirname(u);await xt(S);let E=i;try{if(E=await Ye(i),E!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${E} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||E+1;l=Ot({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,C;try{let{loadStxConfig:L}=await import("./chunk-48y8nymd.js"),B=await L();if(C=s.stxOptions?.serverApi??B.serverApi,B?.apiRouter)x=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){v=B.apiRoutes;let G=Object.keys(v).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:oe}=await import("./chunk-vrvnctex.js"),$e=B.broadcasting;await G($e);let he=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${he}/ws${e.reset}`);let Oe=Se.join(process.cwd(),"channels.ts");if(Ne.existsSync(Oe))try{let le=await oe(Oe);console.log(`${e.blue}Loaded ${e.bright}${le} broadcast channel${le!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(le){console.warn(`${e.yellow}Failed to load channels.ts: ${le.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:H}=await import("./chunk-0p4kc0xt.js"),_=await k(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${E}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let I=Ni({port:E,async fetch(L){return Pt(L,await(async()=>{let B=new URL(L.url);if([h,Se.dirname(u),Se.join(process.cwd(),"public")].some((le)=>H(Se.join(le,B.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(x)try{let le=await x.handleRequest(L);if(le.status!==404)return le}catch{}if(v[B.pathname])try{return await v[B.pathname](L)}catch(le){return new Response(JSON.stringify({error:le.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await _(L);if(G)return G;if(B.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Xe(W,m);if(s.native)if(W.includes("<head>"))W=W.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(s.titlebarHidden)if(W.includes("<head>"))W=W.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let oe=Se.join(h,B.pathname);if(Ne.existsSync(oe)&&Ne.statSync(oe).isFile()){let le=Bun.file(oe),W=Se.extname(oe).toLowerCase(),j="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":j}})}let $e=Se.dirname(u),he=Se.join($e,B.pathname);if(Ne.existsSync(he)&&Ne.statSync(he).isFile()){let le=Bun.file(he),W=Se.extname(he).toLowerCase(),j="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":j}})}let Oe=Se.join(process.cwd(),"public",B.pathname);if(Ne.existsSync(Oe)&&Ne.statSync(Oe).isFile()){let le=Bun.file(Oe),W=Se.extname(Oe).toLowerCase(),j="application/octet-stream";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await le.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(le,{headers:{"Content-Type":j}})}return new Response("Not Found",{status:404})})())},error(L){return new Response(`<pre>${L}
|
|
1853
1853
|
${L.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1854
1854
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1855
1855
|
${e.bright}\u2192 ${e.cyan}http://localhost:${E}/${e.reset}`),console.log(`
|
|
@@ -2025,9 +2025,9 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
2025
2025
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
2026
2026
|
${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
|
|
2027
2027
|
${e.yellow}Routes:${e.reset}`);let S=new Set(u.map((v)=>v.routeTemplate)),E=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Pe.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");E.push({route:x,filePath:Pe.relative(process.cwd(),v.filePath),fileType:"stx"})}if(E.sort((v,x)=>v.route.localeCompare(x.route)),E.forEach((v,x)=>{let k=x===E.length-1?"\u2514\u2500 ":"\u251C\u2500 ",H=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${H}`)}),console.log(`
|
|
2028
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(w.url.toString(),()=>{if(p)it.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=it.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Wn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wi}=globalThis.Bun;import ve from"fs";import ie from"path";async function qn(t){try{return St(await Bun.file(t).text())}catch{return}}function qt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function vn(t=".",s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-wf1zbmf2.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-k84aahz0.js"),S=s.stxOptions?.serverApi??g.serverApi,E=await y(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",C=ie.join(v,x);if(!ve.existsSync(C)&&!g._layerPageDirs?.some((D)=>ve.existsSync(D)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],_=[];for(let{dir:D,prefix:F}of H)if(ve.existsSync(D)){let z=N(ie.dirname(D),{pagesDir:ie.basename(D)});for(let V of z){let we=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;_.push({route:{...V,pattern:we},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let I=new Map,P=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await so(u,s.stxOptions?.shell),L){if(P=await xr(L,s.stxOptions||{}),P)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(u,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Qe(),await tt(u);let B=et();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let G={},oe=null;try{let{loadStxConfig:D}=await import("./chunk-wf1zbmf2.js"),F=await D(u);if(F?.apiRouter)oe=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){G=F.apiRoutes;let z=Object.keys(G).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:V}=await import("./chunk-vrvnctex.js"),we=F.broadcasting;await z(we);let We=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let se=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${se} broadcast channel${se!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(se){console.warn(`${e.yellow}Failed to load channels.ts: ${se.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(u,"output");ve.mkdirSync($e,{recursive:!0});let he=new Map,Oe=new Set,le=async(D)=>{let F=ar(C,D);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let V=z.outputs.find((we)=>we.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,j=async(D,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-wf1zbmf2.js"),{checkCache:se,cacheTemplate:Q,readFileCached:q,templateCache:J}=await import("./chunk-9pym8csd.js"),ke=await We(u),Je=(de)=>{if(!de)return de;if(ie.isAbsolute(de))return de;return ie.resolve(u,de)},M={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Je(M.partialsDir),M.componentsDir=Je(M.componentsDir),M.layoutsDir=Je(M.layoutsDir),M.storesDir=Je(M.storesDir||"stores"),M.cachePath=Je(M.cachePath)??a(u,"cache");let be=!F&&!s.profile,pe=M.cache!==!1;if(pe&&be){let de=J.get(D.filePath);if(de)try{if((await ve.promises.stat(D.filePath)).mtime.getTime()<=de.mtime){let ze=!0;for(let Re of de.dependencies){if(!ve.existsSync(Re)){ze=!1;break}if((await ve.promises.stat(Re)).mtime.getTime()>de.mtime){ze=!1;break}}if(ze){let Re=de.output;if(P)Re=ge(Re,{preserveHead:!0});let gt=W.get(D.filePath);return{route:D,content:Re,status:gt?.status??await qn(D.filePath),headers:gt?.headers}}}}catch{}let Ie=await se(D.filePath,M);if(Ie){let He=Ie;if(P)He=ge(He,{preserveHead:!0});let ze=W.get(D.filePath);return{route:D,content:He,status:ze?.status??await qn(D.filePath),headers:ze?.headers}}}let me=pe?await q(D.filePath):await Bun.file(D.filePath).text(),Ce=St(me),{classifyAllScripts:Y}=await import("./chunk-wf1zbmf2.js"),Le=Y(me),Ve=Le.server.map((de)=>de.content),ue=me;for(let de of Le.server)ue=ue.replace(de.fullTag,"");let fe={__filename:D.filePath,__dirname:ie.dirname(D.filePath),__stx_options:M,params:F??{},__stx_runtime_head:{}};for(let de of Ve)try{await V(de,fe,D.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",D.filePath,Ie?.message||Ie)}let Ke=new Set,Ae;if(s.profile){let de=performance.now();Ae=await z(ue,fe,D.filePath,M,Ke);let Ie=performance.now()-de,He=ie.relative(u,D.filePath)||D.filePath;console.log(`[stx:profile] ${He} \u2192 ${Ie.toFixed(2)}ms`)}else Ae=await z(ue,fe,D.filePath,M,Ke);if(!P)Ae=await Ge(Ae,{router:M.router});{let{interpolateScriptExpressions:de}=await import("./chunk-2mxvwwq8.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,He,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return Ie;return`<script${He}>${de(ze,fe)}</script>`})}if(P)Ae=ge(Ae,{preserveHead:!0});if(pe&&be)await Q(D.filePath,Ae,Ke,M);let{extractStreamBoundaries:Xn}=await import("./chunk-ezqjgvbq.js"),lt=Xn(fe),mt=fe.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let de=fe.streamBoundaries||{},Ie={...M,autoShell:!1},He=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof de[Re]==="function"?await de[Re]():void 0;return z(mt[Re],{...fe,$boundary:gt},D.filePath,Ie,new Set)}})),ze=new Set(He.map((Re)=>Re.id));lt=[...(lt||[]).filter((Re)=>!ze.has(Re.id)),...He]}if(lt&<.length>0)Oe.add(D.pattern);else lt=void 0;let Kt=Be(fe),Xt=Fe(fe);if(be)W.set(D.filePath,{status:Kt,headers:Xt});return{route:D,content:Ae,status:Kt??Ce,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${D.pattern}${e.reset}:`,z),null}},Ue=8,qe=async()=>{he.clear(),I.clear();for(let D=0;D<k.length;D+=Ue){let F=k.slice(D,D+Ue),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)he.set(V.route.pattern,V)}for(let D=0;D<_.length;D+=Ue){let F=_.slice(D,D+Ue),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await xt(u);let at=i;try{if(at=await Ye(i),at!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${at} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let D=s.hmrPort||at+1;l=Ot({wsPort:D,verbose:!1}),m=l.start(D)}let Lt=(D,F)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).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(D.includes("</head>"))return D.replace("</head>",`${V}</head>`);if(D.includes("<body"))return D.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+D};console.log(`${e.blue}Starting server...${e.reset}`);let It=Wi({port:at,async fetch(D){let F=new URL(D.url),z=g?.publicDir||"public",V=ie.join(u,z,F.pathname),we=ie.join(u,F.pathname),We=ie.join($e,F.pathname);if([V,we,We].some((M)=>w(M,u,S)))return new Response("Not Found",{status:404});let[Ge,se,Q]=await Promise.all([ve.promises.stat(V).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return qt(V);if(se?.isFile()&&!w(we,u,S))return qt(we);if(Q?.isFile()&&!w(We,u,S))return qt(We);if(F.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(F.pathname.slice(16));if(M)try{let be=`<${M} />`,pe={...buildConfig,autoShell:!1},me=await processDirectives(be,{},ie.join(u,"components",`${M}.stx`),pe,new Set);return new Response(me,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-z990jtmx.js"),be=await M(D,{publicDir:ie.join(u,z),cacheDir:a(u,"cache","img")});if(be)return be}if(oe)try{let M=await oe.handleRequest(D);if(M.status!==404)return M}catch{}if(G[F.pathname])try{return await G[F.pathname](D)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await E(D);if(q)return q;let J=mn(F.pathname,k);if(J){let M=he.get(J.route.pattern),be=Oe.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||be){let pe=await j(J.route,J.params);if(pe)M=pe}if(M){let pe=M.status??200,me=M.headers??{},Ce=(J.route.filePath?je(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:J.params})){let Ve=await le(404);if(Ve){let ue=Ve;if(ue=await f(ue,u),c)ue=Xe(ue,m);return new Response(ue,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Le=nt(F.pathname,J.params,Ce,F.search),Ve=rt(Le,null,D,{isServer:!0}),ue=await st(Ce.middleware,Ve);if(ue.redirect){let fe=ue.redirect.path,Ke=ue.redirect.options.redirectCode||302,Ae=new Headers(ue.responseHeaders);return Ae.set("Location",fe),new Response(null,{status:Ke,headers:Ae})}if(ue.abort){let{statusCode:fe,message:Ke}=ue.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${fe}</title></head><body><h1>Error ${fe}</h1><p>${Ke}</p></body></html>`,{status:fe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ue.state).length>0){let fe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ue.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=M.content.replace("</head>",`${fe}</head>`)}}let Y=M.content;if(P&&oo(D)){let Le=xe(Y),Ve=ae(Y),ue=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=ue?ro(ue[1].trim()):"";if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);Y=await f(Y,u);let Ke=g?.router?.container||"main";return Y=re(Y,Ke),new Response(Y,{status:pe,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...fe&&{"X-STX-Title":encodeURIComponent(fe)},[ei]:ds(),...T(),"Cache-Control":_e}})}if(P)Y=Cn(P,Y);if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);if(Y=await f(Y,u),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-ezqjgvbq.js");return Ve(Le(Y,M.boundaries,{timeoutMs:30000}),{status:pe,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:pe,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...me}})}}if(_.length>0){let M=_.map((pe)=>pe.route),be=mn(F.pathname,M);if(be){let pe=I.get(be.route.pattern);if(pe){let me=pe.content;if(P)me=Cn(P,me);if(Object.keys(be.params).length>0)me=Lt(me,be.params);if(me=await f(me,u),c)me=Xe(me,m);return new Response(me,{status:pe.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:pe}of H)if(pe!=="/"&&F.pathname.startsWith(pe)){let me=I.get(pe)||I.get(pe+"/");if(me){let Ce=me.content;if(P)Ce=Cn(P,Ce);if(Ce=await f(Ce,u),c)Ce=Xe(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ze(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.get("/");if(ke){let M=ke.content;if(M=await f(M,u),c)M=Xe(M,m);if(s.native)if(M.includes("<head>"))M=M.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 M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await le(404);if(Je){let M=Je;if(M=await f(M,u),c)M=Xe(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(D){let F=await le(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${D}
|
|
2028
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(w.url.toString(),()=>{if(p)it.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=it.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),ye.clear(),ee(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Wn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wi}=globalThis.Bun;import ve from"fs";import ie from"path";async function qn(t){try{return St(await Bun.file(t).text())}catch{return}}function qt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function vn(t=".",s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-48y8nymd.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-0p4kc0xt.js"),S=s.stxOptions?.serverApi??g.serverApi,E=await y(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",C=ie.join(v,x);if(!ve.existsSync(C)&&!g._layerPageDirs?.some((D)=>ve.existsSync(D)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],_=[];for(let{dir:D,prefix:F}of H)if(ve.existsSync(D)){let z=N(ie.dirname(D),{pagesDir:ie.basename(D)});for(let V of z){let we=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;_.push({route:{...V,pattern:we},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let I=new Map,P=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await so(u,s.stxOptions?.shell),L){if(P=await xr(L,s.stxOptions||{}),P)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(u,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}Qe(),await tt(u);let B=et();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let G={},oe=null;try{let{loadStxConfig:D}=await import("./chunk-48y8nymd.js"),F=await D(u);if(F?.apiRouter)oe=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){G=F.apiRoutes;let z=Object.keys(G).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:V}=await import("./chunk-vrvnctex.js"),we=F.broadcasting;await z(we);let We=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let se=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${se} broadcast channel${se!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(se){console.warn(`${e.yellow}Failed to load channels.ts: ${se.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(u,"output");ve.mkdirSync($e,{recursive:!0});let he=new Map,Oe=new Set,le=async(D)=>{let F=ar(C,D);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:$e,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let V=z.outputs.find((we)=>we.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,j=async(D,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-48y8nymd.js"),{checkCache:se,cacheTemplate:Q,readFileCached:q,templateCache:J}=await import("./chunk-bmj0b8wk.js"),ke=await We(u),Je=(de)=>{if(!de)return de;if(ie.isAbsolute(de))return de;return ie.resolve(u,de)},M={...we,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Je(M.partialsDir),M.componentsDir=Je(M.componentsDir),M.layoutsDir=Je(M.layoutsDir),M.storesDir=Je(M.storesDir||"stores"),M.cachePath=Je(M.cachePath)??a(u,"cache");let be=!F&&!s.profile,pe=M.cache!==!1;if(pe&&be){let de=J.get(D.filePath);if(de)try{if((await ve.promises.stat(D.filePath)).mtime.getTime()<=de.mtime){let ze=!0;for(let Re of de.dependencies){if(!ve.existsSync(Re)){ze=!1;break}if((await ve.promises.stat(Re)).mtime.getTime()>de.mtime){ze=!1;break}}if(ze){let Re=de.output;if(P)Re=ge(Re,{preserveHead:!0});let gt=W.get(D.filePath);return{route:D,content:Re,status:gt?.status??await qn(D.filePath),headers:gt?.headers}}}}catch{}let Ie=await se(D.filePath,M);if(Ie){let He=Ie;if(P)He=ge(He,{preserveHead:!0});let ze=W.get(D.filePath);return{route:D,content:He,status:ze?.status??await qn(D.filePath),headers:ze?.headers}}}let me=pe?await q(D.filePath):await Bun.file(D.filePath).text(),Ce=St(me),{classifyAllScripts:Y}=await import("./chunk-48y8nymd.js"),Le=Y(me),Ve=Le.server.map((de)=>de.content),ue=me;for(let de of Le.server)ue=ue.replace(de.fullTag,"");let fe={__filename:D.filePath,__dirname:ie.dirname(D.filePath),__stx_options:M,params:F??{},__stx_runtime_head:{}};for(let de of Ve)try{await V(de,fe,D.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",D.filePath,Ie?.message||Ie)}let Ke=new Set,Ae;if(s.profile){let de=performance.now();Ae=await z(ue,fe,D.filePath,M,Ke);let Ie=performance.now()-de,He=ie.relative(u,D.filePath)||D.filePath;console.log(`[stx:profile] ${He} \u2192 ${Ie.toFixed(2)}ms`)}else Ae=await z(ue,fe,D.filePath,M,Ke);if(!P)Ae=await Ge(Ae,{router:M.router});{let{interpolateScriptExpressions:de}=await import("./chunk-9446y38z.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,He,ze)=>{if(!/function\s+__stx_setup_/.test(ze))return Ie;return`<script${He}>${de(ze,fe)}</script>`})}if(P)Ae=ge(Ae,{preserveHead:!0});if(pe&&be)await Q(D.filePath,Ae,Ke,M);let{extractStreamBoundaries:Xn}=await import("./chunk-mat40nfw.js"),lt=Xn(fe),mt=fe.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let de=fe.streamBoundaries||{},Ie={...M,autoShell:!1},He=Object.keys(mt).map((Re)=>({id:Re,render:async()=>{let gt=typeof de[Re]==="function"?await de[Re]():void 0;return z(mt[Re],{...fe,$boundary:gt},D.filePath,Ie,new Set)}})),ze=new Set(He.map((Re)=>Re.id));lt=[...(lt||[]).filter((Re)=>!ze.has(Re.id)),...He]}if(lt&<.length>0)Oe.add(D.pattern);else lt=void 0;let Kt=Be(fe),Xt=Fe(fe);if(be)W.set(D.filePath,{status:Kt,headers:Xt});return{route:D,content:Ae,status:Kt??Ce,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${D.pattern}${e.reset}:`,z),null}},Ue=8,qe=async()=>{he.clear(),I.clear();for(let D=0;D<k.length;D+=Ue){let F=k.slice(D,D+Ue),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)he.set(V.route.pattern,V)}for(let D=0;D<_.length;D+=Ue){let F=_.slice(D,D+Ue),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return he.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await xt(u);let at=i;try{if(at=await Ye(i),at!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${at} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let D=s.hmrPort||at+1;l=Ot({wsPort:D,verbose:!1}),m=l.start(D)}let Lt=(D,F)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).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(D.includes("</head>"))return D.replace("</head>",`${V}</head>`);if(D.includes("<body"))return D.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+D};console.log(`${e.blue}Starting server...${e.reset}`);let It=Wi({port:at,async fetch(D){let F=new URL(D.url),z=g?.publicDir||"public",V=ie.join(u,z,F.pathname),we=ie.join(u,F.pathname),We=ie.join($e,F.pathname);if([V,we,We].some((M)=>w(M,u,S)))return new Response("Not Found",{status:404});let[Ge,se,Q]=await Promise.all([ve.promises.stat(V).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return qt(V);if(se?.isFile()&&!w(we,u,S))return qt(we);if(Q?.isFile()&&!w(We,u,S))return qt(We);if(F.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(F.pathname.slice(16));if(M)try{let be=`<${M} />`,pe={...buildConfig,autoShell:!1},me=await processDirectives(be,{},ie.join(u,"components",`${M}.stx`),pe,new Set);return new Response(me,{headers:{"Content-Type":"text/html"}})}catch(be){return new Response(`<div class="stx-async-error">${be.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-z990jtmx.js"),be=await M(D,{publicDir:ie.join(u,z),cacheDir:a(u,"cache","img")});if(be)return be}if(oe)try{let M=await oe.handleRequest(D);if(M.status!==404)return M}catch{}if(G[F.pathname])try{return await G[F.pathname](D)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await E(D);if(q)return q;let J=mn(F.pathname,k);if(J){let M=he.get(J.route.pattern),be=Oe.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||be){let pe=await j(J.route,J.params);if(pe)M=pe}if(M){let pe=M.status??200,me=M.headers??{},Ce=(J.route.filePath?je(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:J.params})){let Ve=await le(404);if(Ve){let ue=Ve;if(ue=await f(ue,u),c)ue=Xe(ue,m);return new Response(ue,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Le=nt(F.pathname,J.params,Ce,F.search),Ve=rt(Le,null,D,{isServer:!0}),ue=await st(Ce.middleware,Ve);if(ue.redirect){let fe=ue.redirect.path,Ke=ue.redirect.options.redirectCode||302,Ae=new Headers(ue.responseHeaders);return Ae.set("Location",fe),new Response(null,{status:Ke,headers:Ae})}if(ue.abort){let{statusCode:fe,message:Ke}=ue.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${fe}</title></head><body><h1>Error ${fe}</h1><p>${Ke}</p></body></html>`,{status:fe,headers:{"Content-Type":"text/html"}})}if(Object.keys(ue.state).length>0){let fe=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ue.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=M.content.replace("</head>",`${fe}</head>`)}}let Y=M.content;if(P&&oo(D)){let Le=xe(Y),Ve=ae(Y),ue=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),fe=ue?ro(ue[1].trim()):"";if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);Y=await f(Y,u);let Ke=g?.router?.container||"main";return Y=re(Y,Ke),new Response(Y,{status:pe,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...fe&&{"X-STX-Title":encodeURIComponent(fe)},[ei]:ds(),...T(),"Cache-Control":_e}})}if(P)Y=Cn(P,Y);if(Object.keys(J.params).length>0)Y=Lt(Y,J.params);if(Y=await f(Y,u),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-mat40nfw.js");return Ve(Le(Y,M.boundaries,{timeoutMs:30000}),{status:pe,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:pe,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...me}})}}if(_.length>0){let M=_.map((pe)=>pe.route),be=mn(F.pathname,M);if(be){let pe=I.get(be.route.pattern);if(pe){let me=pe.content;if(P)me=Cn(P,me);if(Object.keys(be.params).length>0)me=Lt(me,be.params);if(me=await f(me,u),c)me=Xe(me,m);return new Response(me,{status:pe.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:pe}of H)if(pe!=="/"&&F.pathname.startsWith(pe)){let me=I.get(pe)||I.get(pe+"/");if(me){let Ce=me.content;if(P)Ce=Cn(P,Ce);if(Ce=await f(Ce,u),c)Ce=Xe(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Ze(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=he.get("/");if(ke){let M=ke.content;if(M=await f(M,u),c)M=Xe(M,m);if(s.native)if(M.includes("<head>"))M=M.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 M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await le(404);if(Je){let M=Je;if(M=await f(M,u),c)M=Xe(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(D){let F=await le(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${D}
|
|
2029
2029
|
${D.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
2030
2030
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
2031
2031
|
${e.bright}\u2192 ${e.cyan}http://localhost:${at}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
|
|
2032
2032
|
${e.yellow}Routes:${e.reset}`);let jt=[...cr(k,u)];for(let{route:D}of _)jt.push(`${D.pattern}`);if(jt.forEach((D,F)=>{let V=F===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${D}`)}),console.log(`
|
|
2033
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let D,F=ie.join(C,"index.stx");if(ve.existsSync(F)){let V=await Bun.file(F).text();D=$t(V)}let z=g?.app?.window??{};await dt(at,{title:g?.app?.head?.title||ie.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!D,sidebarConfig:D})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let D=(se)=>se.startsWith("public/")||se.startsWith("public\\"),F=(se)=>{let Q=se.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},z=new Map,V=()=>{let se=new Set([u,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let q of Object.values(Q.resources)){if(!ve.existsSync(q))continue;let J=ve.realpathSync(q);if(![...se].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))se.add(J)}for(let[Q,q]of z)if(!se.has(Q))q.close(),z.delete(Q);for(let Q of se)if(!z.has(Q)&&ve.existsSync(Q))z.set(Q,ve.watch(Q,{recursive:!0},(q,J)=>{We(Q,q,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},we=Promise.resolve(),We=(se,Q,q)=>(we=we.catch(()=>{}).then(()=>Ge(se,Q,q)),we),Ge=async(se,Q,q)=>{if(!q||Et(q))return;if(Rt(q)){if(g._layerGraph){let J=await h(u);Object.assign(g,J),k.splice(0,k.length,...N(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[C,...J._layerPageDirs.slice(1)]:void 0})),V()}if(D(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(F(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-
|
|
2033
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),ot(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let D,F=ie.join(C,"index.stx");if(ve.existsSync(F)){let V=await Bun.file(F).text();D=$t(V)}let z=g?.app?.window??{};await dt(at,{title:g?.app?.head?.title||ie.basename(u)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!D,sidebarConfig:D})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let D=(se)=>se.startsWith("public/")||se.startsWith("public\\"),F=(se)=>{let Q=se.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},z=new Map,V=()=>{let se=new Set([u,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let q of Object.values(Q.resources)){if(!ve.existsSync(q))continue;let J=ve.realpathSync(q);if(![...se].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))se.add(J)}for(let[Q,q]of z)if(!se.has(Q))q.close(),z.delete(Q);for(let Q of se)if(!z.has(Q)&&ve.existsSync(Q))z.set(Q,ve.watch(Q,{recursive:!0},(q,J)=>{We(Q,q,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},we=Promise.resolve(),We=(se,Q,q)=>(we=we.catch(()=>{}).then(()=>Ge(se,Q,q)),we),Ge=async(se,Q,q)=>{if(!q||Et(q))return;if(Rt(q)){if(g._layerGraph){let J=await h(u);Object.assign(g,J),k.splice(0,k.length,...N(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[C,...J._layerPageDirs.slice(1)]:void 0})),V()}if(D(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(F(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-bmj0b8wk.js");J(ie.resolve(se,q)),ke.delete(ie.resolve(se,q))}catch{}if(L&&q){if(ie.resolve(se,q)===L||ie.basename(L)===q){let ke=await xr(L,s.stxOptions||{});if(ke)P=ke}}if(await qe(),await tn(u),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),ye.clear(),ee();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-bmj0b8wk.js");J(ie.resolve(se,q)),ke.delete(ie.resolve(se,q))}catch{}if(await qe(),c&&l)l.reload(q)}}else if(Ct(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let se of z.values())se.close();if(l)ht();It.stop(),process.exit(0)})}return!0}export{Hs,Vs,Us,Ws,fr,qs,Ks,Xs,Oi,Mi,gr,mr,bn,wn,vn};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{b,d,n,g,I}from"./chunk-
|
|
2
|
+
import{b,d,n,g,I}from"./chunk-n1099xfe.js";import q from"path";var M={enabled:!0,bufferSize:16384,strategy:"auto",timeout:30000},T=/<!-- @section:([\w-]+) -->([\s\S]*?)<!-- @endsection:\1 -->/g;var O=/<!-- @suspense:([\w-]+) -->([\s\S]*?)<!-- @endsuspense:\1 -->/g;function z(e){let t=[],o=0,s;O.lastIndex=0;while((s=O.exec(e))!==null){if(s.index>o){let a=e.slice(o,s.index);if(a.trim())t.push({type:t.length===0?"shell":"content",content:a})}let r=s[1],i=s[2];t.push({type:"suspense",name:r,content:i}),o=s.index+s[0].length}if(o<e.length){let r=e.slice(o);if(r.trim())t.push({type:t.length===0?"shell":"content",content:r})}if(t.length===0)t.push({type:"shell",content:e});return t}async function Zl(e,t={},o={}){let s={...I,...o,streaming:{...M,...o.streaming}},r=s.streaming?.bufferSize||16384;return new ReadableStream({async start(i){try{let a=await Bun.file(e).text(),w=a.match(/<script\b[^>]*\bserver\b[^>]*>([\s\S]*?)<\/script>/i),m=w?w[1]:"",c=a.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,""),y={...t,__filename:e,__dirname:q.dirname(e)};if(m.trim())await d(m,y,e);let E=z(c),u=new Set;if(!E.some((h)=>h.type==="suspense")){let h=s.streaming?.strategy||"auto",S=new RegExp(T.source,"g");if(!(h!=="manual"&&S.test(c))){let p=await n(c,y,e,s,u);for(let x=0;x<p.length;x+=r)i.enqueue(p.slice(x,x+r)),await new Promise((f)=>setTimeout(f,0))}else{let p=[],x=new RegExp(T.source,"g"),f;while((f=x.exec(c))!==null)p.push({name:f[1],content:f[2],start:f.index,end:f.index+f[0].length});let v=0;for(let _ of p){if(_.start>v){let k=c.slice(v,_.start);if(k.trim()){let D=await n(k,y,e,s,u);i.enqueue(D),await new Promise((H)=>setTimeout(H,0))}}let C=await n(_.content,y,e,s,u);i.enqueue(C),await new Promise((k)=>setTimeout(k,0)),v=_.end}if(v<c.length){let _=c.slice(v);if(_.trim()){let C=await n(_,y,e,s,u);i.enqueue(C)}}}}else{let h=new Map;for(let l of E)if(l.type==="shell"||l.type==="content"){let p=await n(l.content,y,e,s,u);i.enqueue(p)}else if(l.type==="suspense"&&l.name){let p=`stx-suspense-${l.name}`;i.enqueue(`<div id="${p}" data-suspense="${l.name}" style="display:contents;">
|
|
3
3
|
<template data-suspense-fallback>Loading...</template>
|
|
4
4
|
</div>`),h.set(l.name,n(l.content,y,e,s,u))}i.enqueue(`
|
|
5
5
|
<script>
|