@stacksjs/stx 0.2.534 → 0.2.536
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{chunk-843y0pfg.js → chunk-0yveptr0.js} +2 -2
- package/dist/{chunk-01343ehq.js → chunk-1es2y1jz.js} +1 -1
- package/dist/{chunk-13zbt9py.js → chunk-22ztsen0.js} +1 -1
- package/dist/{chunk-7zgtdap7.js → chunk-2kf4z3e6.js} +1 -1
- package/dist/{chunk-9p6bt089.js → chunk-33vbh6g3.js} +1 -1
- package/dist/{chunk-qqr4rn9p.js → chunk-5zp9wt6m.js} +2 -2
- package/dist/{chunk-pz1mjgsp.js → chunk-672nmsmm.js} +1 -1
- package/dist/{chunk-nmy4x6dx.js → chunk-7g90r41h.js} +1 -1
- package/dist/{chunk-f3q84h7b.js → chunk-8bt1mxny.js} +1 -1
- package/dist/{chunk-d1jxmhph.js → chunk-9e1hftmd.js} +1 -1
- package/dist/{chunk-7v2j9bmc.js → chunk-bgvqcjrg.js} +1 -1
- package/dist/{chunk-8chxczpj.js → chunk-bk5g7qez.js} +1 -1
- package/dist/{chunk-wxy9re1a.js → chunk-c0prbbpe.js} +1 -1
- package/dist/{chunk-kcs7hyep.js → chunk-dr0394tm.js} +1 -1
- package/dist/{chunk-tgc645pa.js → chunk-e6mmvwy9.js} +5 -5
- package/dist/{chunk-bxsehntq.js → chunk-f1cc1z85.js} +1 -1
- package/dist/{chunk-9674w2gm.js → chunk-g9byv420.js} +1 -1
- package/dist/{chunk-4a7v51vh.js → chunk-gx3cs15y.js} +1 -1
- package/dist/{chunk-sqb6gkzf.js → chunk-h51g1ydb.js} +1 -1
- package/dist/{chunk-gsc5t942.js → chunk-hen8zqnp.js} +1 -1
- package/dist/{chunk-tr9bjtqx.js → chunk-hpkrscgk.js} +1 -1
- package/dist/{chunk-z9r3tqyr.js → chunk-jn9e5a4t.js} +1 -1
- package/dist/{chunk-90kzf313.js → chunk-jq3j35a6.js} +1 -1
- package/dist/{chunk-xwrbrg1q.js → chunk-jsa2apk6.js} +1 -1
- package/dist/{chunk-94rg5s6c.js → chunk-jskc4rr7.js} +1 -1
- package/dist/{chunk-jv3jj612.js → chunk-knxqe213.js} +1 -1
- package/dist/chunk-kvn3xsfq.js +2 -0
- package/dist/{chunk-k3v13vfr.js → chunk-mx3rh8zj.js} +1 -1
- package/dist/chunk-n9k24wmf.js +57 -0
- package/dist/{chunk-d871008z.js → chunk-nn66ek7z.js} +1 -1
- package/dist/{chunk-ngma9vzc.js → chunk-pd460250.js} +1 -1
- package/dist/{chunk-v4r8nzf3.js → chunk-pekfkzh7.js} +1 -1
- package/dist/{chunk-gnx0fzne.js → chunk-pwdvc964.js} +19 -19
- package/dist/{chunk-3zs8yxy0.js → chunk-qmd2kvb2.js} +1 -1
- package/dist/{chunk-kvp0at16.js → chunk-s9htq6ef.js} +1 -1
- package/dist/{chunk-2n4je46m.js → chunk-sh8ec2e0.js} +1 -1
- package/dist/chunk-sve2646p.js +2 -0
- package/dist/{chunk-5g498pdp.js → chunk-sye2bjyq.js} +1 -1
- package/dist/{chunk-6rcxtdh3.js → chunk-tr49ckr5.js} +1 -1
- package/dist/{chunk-qk3ptn6h.js → chunk-va61kyky.js} +1 -1
- package/dist/{chunk-93n6yv5x.js → chunk-ve6tn04z.js} +1 -1
- package/dist/{chunk-0e5nasyf.js → chunk-vmq2dd3k.js} +1 -1
- package/dist/{chunk-fqfqyn48.js → chunk-xq7f1yc2.js} +1 -1
- package/dist/chunk-xvjtj1kt.js +2 -0
- package/dist/{chunk-vfnerp7h.js → chunk-xy5sx2z1.js} +1 -1
- package/dist/{chunk-2h4f37kx.js → chunk-xz7dk3yc.js} +1 -1
- package/dist/{chunk-zeve89kw.js → chunk-y5acfh13.js} +1 -1
- package/dist/{chunk-4pxc3r1p.js → chunk-z0h3we7z.js} +2 -2
- package/dist/{chunk-jvqas8y2.js → chunk-zaj09h72.js} +1 -1
- package/dist/{chunk-wjt46tdp.js → chunk-zs5p8jcn.js} +1 -1
- package/dist/cli.js +8 -8
- package/dist/client/signals-loop-conditional-runtime.d.ts +1 -1
- package/dist/client/signals-loop-conditional-runtime.js +1 -1
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/native/bridge/protocol.d.ts +3 -1
- package/dist/native/compiler/browser.d.ts +10 -0
- package/dist/native/compiler/browser.js +31 -0
- package/dist/native/compiler/bundle.d.ts +3 -0
- package/dist/native/compiler/bundle.js +27 -10
- package/dist/native/compiler/html-to-ir.d.ts +2 -0
- package/dist/native/compiler/html-to-ir.js +8 -3
- package/dist/native/compiler/icons.d.ts +2 -0
- package/dist/native/compiler/icons.js +2 -0
- package/dist/native/compiler/render-screen.d.ts +1 -0
- package/dist/native/compiler/render-screen.js +2 -2
- package/dist/native/index.d.ts +1 -0
- package/dist/native/index.js +1 -0
- package/dist/native/runtime/browser-renderer.d.ts +16 -0
- package/dist/native/runtime/browser-renderer.js +537 -0
- package/dist/native/runtime/browser-screen.d.ts +26 -0
- package/dist/native/runtime/browser-screen.js +254 -0
- package/dist/native/runtime/craft-bridge.js +10 -6
- package/dist/native/runtime/craft.d.ts +1 -0
- package/dist/native/runtime/jsc-globals.js +1 -1
- package/dist/native/runtime/native-host.js +9 -4
- package/dist/pwa.js +1 -1
- package/dist/signals-loop-conditional-runtime.d.ts +1 -1
- package/dist/ssg.js +2 -2
- package/dist/variable-extractor.js +5 -1
- package/package.json +5 -5
- package/dist/chunk-40hbpz2b.js +0 -45
- package/dist/chunk-5wx323bm.js +0 -2
- package/dist/chunk-epa1c4q4.js +0 -2
- package/dist/chunk-ydtnskdv.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Fn,Le,Be,ye,ei,Wn,Q,K,ln,d,n,R}from"./chunk-
|
|
2
|
+
import{Fn,Le,Be,ye,ei,Wn,Q,K,ln,d,n,R}from"./chunk-pwdvc964.js";import{dirname as k,resolve as _}from"path";function h(o){return o.endsWith(".md")||o.endsWith(".markdown")}function C(o){let e=[];m(/<pre\b[^>]*>[\s\S]*?<\/pre>/gi);let r=[...e];m(/<code\b[^>]*>[\s\S]*?<\/code>/gi,r);function m(s,p){let u;while((u=s.exec(o))!==null){let t=u.index,i=t+u[0].length;if(p?.some((l)=>t>=l.start&&i<=l.end))continue;e.push({start:t,end:i})}}if(e.length===0)return o;e.sort((s,p)=>s.start-p.start);let a="",c=0;for(let s of e){if(s.start<c)continue;a+=o.slice(c,s.start),a+=`@raw${o.slice(s.start,s.end)}@endraw`,c=s.end}return a+=o.slice(c),a}async function b(o,e={}){let{data:r,content:m}=Fn(o),c=await(e.renderer??((s)=>Le(s)))(m);return{html:C(c),frontmatter:r??{}}}function v(o){let e=o,r=Q(o);if(r)e=r.content.trim();let m=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,a=[],c=[],s=[],p=(i)=>/\b(?:state|derived|effect|batch)\s*(?:<[^<>()]*>)?\s*\(/.test(i),u;while((u=m.exec(o))!==null){let i=u[1],l=u[2],f=u[0],g=i.includes("server");if(p(l))s.push(f);else if(g)c.push(l);else a.push(f)}let t=e;{let i=/<script\b(?![^>]*\b(?:client|type\s*=\s*["']module["']|src\s*=))[^>]*>/gi,l,f=[];while((l=i.exec(t))!==null){let g=l.index+l[0].length,x=t.indexOf("</script>",g);if(x===-1)continue;f.push({start:l.index,end:x+9}),i.lastIndex=x+9}for(let g=f.length-1;g>=0;g--)t=t.substring(0,f[g].start)+t.substring(f[g].end)}for(let i of a)t=t.replace(i,"");return{templateContent:t,serverScripts:c,clientScripts:a,signalsScripts:s}}function M(o,e){return`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="UTF-8">
|
|
@@ -14,5 +14,5 @@ ${c.join(`
|
|
|
14
14
|
`)}`}else{if(r.processClientScripts!==!1&&c.length>0){let i=p.__stx_event_bindings||[],l=Be(p),g=(await Promise.all(c.map(async(w)=>{let y=w.match(/<script\b[^>]*>([\s\S]*?)<\/script>/);if(!y)return w;return await ye(y[1],{eventBindings:i,templateContent:t,serverData:l,filePath:e})}))).join(`
|
|
15
15
|
`);if(t.match(/(<\/body>)/i))t=t.replace(/(<\/body>)/i,`${g}
|
|
16
16
|
$1`);else t+=`
|
|
17
|
-
${g}`}t=await K(t)}if(r.wrapInDocument){if(!t.trim().toLowerCase().startsWith("<!doctype")&&!t.trim().toLowerCase().startsWith("<html"))t=M(t,r.title)}if(r.injectCSS)try{let{injectCss:i}=await import("./chunk-
|
|
17
|
+
${g}`}t=await K(t)}if(r.wrapInDocument){if(!t.trim().toLowerCase().startsWith("<!doctype")&&!t.trim().toLowerCase().startsWith("<html"))t=M(t,r.title)}if(r.injectCSS)try{let{injectCss:i}=await import("./chunk-jq3j35a6.js");t=await i(t)}catch{}return t}
|
|
18
18
|
export{Do};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Rt,C}from"./chunk-v9vvzdag.js";import m from"fs";import e from"path";async function pn(r,o,i){if(r.__stx_runtime_config)return;let n=Rt();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{Rt,C}from"./chunk-v9vvzdag.js";import m from"fs";import e from"path";async function pn(r,o,i){if(r.__stx_runtime_config)return;let n=Rt();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-2kf4z3e6.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 _s(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,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{pn,_s}from"./chunk-
|
|
2
|
+
import{pn,_s}from"./chunk-1es2y1jz.js";import"./chunk-v9vvzdag.js";export{_s as generateRuntimeConfigTypes,pn as prepareRuntimeConfig};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{R,Fc,o,A,tu,nu}from"./chunk-
|
|
2
|
+
import{R,Fc,o,A,tu,nu}from"./chunk-pwdvc964.js";import"./chunk-bczcm7jk.js";import"./chunk-bpr4bkde.js";import"./chunk-x607yxrc.js";import"./chunk-1es2y1jz.js";import"./chunk-v9vvzdag.js";import"./chunk-tkvp3rz0.js";import"./chunk-y18yvcjb.js";import"./chunk-vhfwnvmc.js";import"./chunk-6v1gwdbv.js";import"./chunk-d7zterbp.js";import"./chunk-2bvk0qyd.js";import"./chunk-1xgs9gd5.js";export{A as config,R as defaultConfig,tu as defineStxConfig,o as loadStxConfig,Fc as resolveStxDirectories,nu as validateConfig};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{G,n}from"./chunk-
|
|
2
|
+
import{G,n}from"./chunk-pwdvc964.js";import p from"fs";import g from"path";import*as y from"readline";var e={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m"},u={help:{description:"Show available commands",usage:"help [command]",handler:async(t,o)=>{if(t[0]&&u[t[0]]){let r=u[t[0]];console.log(`
|
|
3
3
|
${e.bold}${t[0]}${e.reset} - ${r.description}`),console.log(` Usage: ${e.cyan}${r.usage}${e.reset}
|
|
4
4
|
`)}else{console.log(`
|
|
5
5
|
${e.bold}Available Commands:${e.reset}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Te,$e,Re}from"./chunk-1c4t7ncb.js";import"./chunk-d7zterbp.js";import"./chunk-6v1gwdbv.js";import{d}from"./chunk-
|
|
2
|
+
import{Te,$e,Re}from"./chunk-1c4t7ncb.js";import"./chunk-d7zterbp.js";import"./chunk-6v1gwdbv.js";import{d}from"./chunk-pwdvc964.js";import"./chunk-vhfwnvmc.js";import"./chunk-bpr4bkde.js";import"./chunk-2bvk0qyd.js";import"./chunk-y18yvcjb.js";import"./chunk-tkvp3rz0.js";import"./chunk-x607yxrc.js";import"./chunk-v9vvzdag.js";import"./chunk-1es2y1jz.js";import"./chunk-1xgs9gd5.js";import{ct,hr,lt,Ws,_e,qs,yr,dt,Ks,ut}from"./chunk-jbfad9cc.js";import"./chunk-bczcm7jk.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()=>{qs("Config file changed, restarting...");try{await e.onChange()}catch(l){_e(`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 nt=".stx/story/analytics.json",st=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,nt),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:st,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:at(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let 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 at(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var it=".stx/story/bookmarks.json",pt=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,it),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:pt,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:mt(),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 mt(){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-g9byv420.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-g9byv420.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 dt(t);$e(t,r);let s=ut(t.config,r);Re(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=Ks(t,async(i,m)=>{console.log(` [${i}] ${m.relativePath}`);let u=await dt(t);$e(t,u);let f=ut(t.config,u);if(Re(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{kl}from"./chunk-
|
|
2
|
+
import{kl}from"./chunk-f1cc1z85.js";import"./chunk-pwdvc964.js";import"./chunk-bczcm7jk.js";import"./chunk-bpr4bkde.js";import"./chunk-x607yxrc.js";import"./chunk-1es2y1jz.js";import"./chunk-v9vvzdag.js";import"./chunk-tkvp3rz0.js";import"./chunk-y18yvcjb.js";import"./chunk-vhfwnvmc.js";import"./chunk-6v1gwdbv.js";import"./chunk-d7zterbp.js";import"./chunk-2bvk0qyd.js";import"./chunk-1xgs9gd5.js";export{kl as buildApp};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{J}from"./chunk-2bvk0qyd.js";import{ue,C}from"./chunk-v9vvzdag.js";import{Ei}from"./chunk-x607yxrc.js";import{a}from"./chunk-4cmqjmqr.js";import v from"fs";import m from"path";import{pathToFileURL as I}from"url";var P=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],R=new Set;function xt(s,l={}){let o=m.resolve(s,l.dir??"server/api"),i=[],f=new Map;if(!v.existsSync(o))return i;let t=Array.from(new Bun.Glob("**/*.{ts,js,mts,mjs}").scanSync({cwd:o})).sort();for(let e of t){if(e.endsWith(".d.ts"))continue;let u=e.replace(/\.(?:ts|js|mts|mjs)$/,"").split("/"),n=u.pop(),c=n.lastIndexOf("."),d=c>=0?n.slice(c+1):"get",g=d.toUpperCase();if(!P.includes(g)||d!==d.toLowerCase())throw Error(`Unsupported API method suffix in ${e}; use ${P.map((A)=>A.toLowerCase()).join(", ")}`);if(c>=0)n=n.slice(0,c);if(n!=="index")u.push(n);let r=new Set,h=u.map((A,j)=>{let y=/^\[(\.\.\.)?([A-Za-z_]\w*)\]$/.exec(A);if(y){if(r.has(y[2])||y[1]&&j!==u.length-1)throw Error(`Invalid API parameter in ${e}`);return r.add(y[2]),`:${y[2]}${y[1]?"*":""}`}if(!/^[\w-]+$/.test(A))throw Error(`Unsupported API path segment ${A} in ${e}`);return A}),w=`/api${h.length?`/${h.join("/")}`:""}`,S=`${g} ${w.replace(/:\w+/g,":param")}`;if(f.has(S))throw Error(`Ambiguous API route ${g} ${w}: ${f.get(S)} and ${e}`);f.set(S,e);let x=m.join(o,e);R.add(m.resolve(x)),R.add(v.realpathSync(x)),i.push({pattern:w,method:g,filePath:x})}return i.sort((e,p)=>{let u=e.pattern.split("/"),n=p.pattern.split("/"),c=(d)=>d?.endsWith("*")?0:d?.startsWith(":")?1:2;for(let d=0;d<Math.max(u.length,n.length);d++){let g=c(n[d])-c(u[d]);if(g)return g}return e.pattern.localeCompare(p.pattern)||e.method.localeCompare(p.method)})}async function Gr(s,l){let o=a(s,"api-types.d.ts"),i=["// Generated by stx. Include this file in tsconfig.json.","declare module '@stacksjs/stx/api-client' {"," interface KnownApiRoutes {"];for(let t of l){let e=`./${m.relative(m.dirname(o),t.filePath).replace(/\\/g,"/")}`,{params:p}=J(t.pattern);i.push(` ${JSON.stringify(`${t.method} ${t.pattern}`)}: { params: { ${p.map((u)=>`${JSON.stringify(u)}: string`).join("; ")} }; response: Awaited<ReturnType<typeof import(${JSON.stringify(e)}).default>> }`)}i.push(" }","}","export {}","");let f=i.join(`
|
|
3
3
|
`);if(!await Bun.file(o).exists()||await Bun.file(o).text()!==f)await Bun.write(o,f);return o}async function Kr(s,l,o={}){let i=xt(s,o);await Gr(s,i);let f=[];for(let t of i){let e=await Bun.build({entrypoints:[t.filePath],target:"bun",format:"esm",minify:!1,splitting:!1});if(!e.success)throw Error(`API build failed for ${t.filePath}: ${e.logs.join(`
|
|
4
|
-
`)}`);let p=e.outputs.find((c)=>c.kind==="entry-point");if(!p)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await p.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(l,n),p),f.push({...t,filePath:n})}return f}function E(s,l){let o=s.map((i)=>({route:i,...J(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,p=(r)=>r.replace(/:\w+/g,":param"),u=t.filter((r)=>p(r.route.pattern)===p(e)),n=i.method,c=u.find((r)=>r.route.method===n)??(n==="HEAD"?u.find((r)=>r.route.method==="GET"):void 0);if(!c){let r=new Set(u.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=c.regex.exec(f),g=Object.create(null);try{c.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await l(c.route);if(typeof r!=="function")throw Error(`API endpoint ${c.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function Xr(s,l){return E(l,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function Id(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=xt(s,o);return await Gr(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=xt(s,o);await Gr(s,t);let{loadStxConfig:e}=await import("./chunk-
|
|
4
|
+
`)}`);let p=e.outputs.find((c)=>c.kind==="entry-point");if(!p)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await p.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(l,n),p),f.push({...t,filePath:n})}return f}function E(s,l){let o=s.map((i)=>({route:i,...J(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,p=(r)=>r.replace(/:\w+/g,":param"),u=t.filter((r)=>p(r.route.pattern)===p(e)),n=i.method,c=u.find((r)=>r.route.method===n)??(n==="HEAD"?u.find((r)=>r.route.method==="GET"):void 0);if(!c){let r=new Set(u.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=c.regex.exec(f),g=Object.create(null);try{c.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await l(c.route);if(typeof r!=="function")throw Error(`API endpoint ${c.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function Xr(s,l){return E(l,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function Id(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=xt(s,o);return await Gr(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=xt(s,o);await Gr(s,t);let{loadStxConfig:e}=await import("./chunk-2kf4z3e6.js"),p=C((await e(s)).runtimeConfig);return await ue(p,()=>E(t,async(u)=>{let n=await Bun.build({entrypoints:[u.filePath],target:"bun",format:"esm",splitting:!1});if(!n.success)throw Error(n.logs.join(`
|
|
5
5
|
`));let c=n.outputs.find((d)=>d.kind==="entry-point");if(!c||n.outputs.length!==1)throw Error(`Unsupported API bundle output: ${u.filePath}`);return(await import(`data:text/javascript;base64,${Buffer.from(await c.text()).toString("base64")}`)).default})(f))}catch(t){return console.error("[stx] API discovery failed:",t),Response.json({error:"API discovery failed; check the server log"},{status:500})}}}function Jr(s,l,o){if(Ei(s))return!0;let i=/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/;if(i.test(m.basename(s)))return!0;try{if(i.test(m.basename(v.realpathSync(s))))return!0}catch{}if(R.has(m.resolve(s)))return!0;if(!o)return!1;let f=m.resolve(l,typeof o==="object"?o.dir??"server/api":"server/api"),t=(p)=>{try{return v.realpathSync(p)}catch{return m.resolve(p)}},e=t(s);return[f,m.resolve(l,"server"),m.resolve(l,".output/server")].some((p)=>{let u=t(p);return e===u||e.startsWith(`${u}${m.sep}`)})}
|
|
6
6
|
export{xt,Gr,Kr,Xr,Id,Jr};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{M,le}from"./chunk-
|
|
2
|
+
import{M,le}from"./chunk-pwdvc964.js";import{ue,C,Je}from"./chunk-v9vvzdag.js";import{tt,J,Ce}from"./chunk-2bvk0qyd.js";import{Pe,re,_,se,mo,Tr,ho,Nt}from"./chunk-z0h3we7z.js";import{Xr}from"./chunk-7g90r41h.js";import{Lt}from"./chunk-7tabykst.js";import F from"zlib";import{promisify as Z}from"util";var ee=Z(F.brotliCompress),te=Z(F.gzip),ne=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],oe=["text/event-stream","multipart/x-mixed-replace"],ae=1024;function ie(t){if(!t)return!1;let e=t.toLowerCase();if(oe.some((o)=>e.startsWith(o)))return!1;return ne.some((o)=>e.startsWith(o))}function ce(t){let e=new Map;for(let o of t.split(",")){let[r,...a]=o.trim().split(";"),f=r.trim().toLowerCase();if(!f)continue;let h=1;for(let g of a){let l=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(g);if(!l)continue;let m=Number.parseFloat(l[1]);if(Number.isFinite(m))h=m}e.set(f,h)}return e}function pe(t){if(!t)return null;let e=ce(t),o=e.get("*"),r=(a)=>e.get(a)??o??0;if(r("br")>0)return"br";if(r("gzip")>0)return"gzip";return null}var Y=33554432,H=new Map,U=0;function me(t,e){if(e.length>Y/8)return;H.set(t,e),U+=e.length;for(let[o,r]of H){if(U<=Y)break;H.delete(o),U-=r.length}}async function Dt(t,e,o={}){if(e.headers.get("content-encoding"))return e;if(e.status===204||e.status===304||!e.body)return e;if(!ie(e.headers.get("content-type")))return e;let r=pe(t.headers.get("accept-encoding"));if(!r)return e;let a;try{a=new Uint8Array(await e.arrayBuffer())}catch{return e}let f=()=>new Response(a,{status:e.status,statusText:e.statusText,headers:Q(e.headers)});if(a.length<(o.threshold??ae))return f();try{let h=o.quality??5,g=`${r}:${h}:${a.length}:${Bun.hash(a)}`,l=H.get(g);if(!l)l=r==="br"?await ee(a,{params:{[F.constants.BROTLI_PARAM_QUALITY]:h,[F.constants.BROTLI_PARAM_SIZE_HINT]:a.length}}):await te(a),me(g,l);if(l.length>=a.length)return f();let m=Q(e.headers);return m.set("Content-Encoding",r),m.set("Content-Length",String(l.length)),new Response(l,{status:e.status,statusText:e.statusText,headers:m})}catch{return f()}}function Q(t){let e=new Headers(t),o=e.get("Vary");if(!o)return e.set("Vary","Accept-Encoding"),e;if(!o.split(",").some((a)=>a.trim().toLowerCase()==="accept-encoding"))e.set("Vary",`${o}, Accept-Encoding`);return e}import K from"fs";import P from"path";var{serve:fe}=globalThis.Bun;class G{now;entries=new M(1000,{maxBytes:33554432,sizeOf:(t)=>t.body.byteLength+JSON.stringify(t.headers).length*2});pending=new Map;generation=0;constructor(t=Date.now){this.now=t}invalidate(t){this.generation++,this.pending.clear();for(let e of Array.from(this.entries.keys()))if(t===void 0||this.entries.get(e)?.path===t)this.entries.delete(e)}async respond(t,e,o){let r,a=async()=>{let s=r??await o();return s.headers.set("Cache-Control","private, no-store"),s.headers.set("Vary",_(s.headers.get("Vary")).Vary),s};if(!e||t.method!=="GET"||t.headers.has("Cookie")||t.headers.has("Authorization")||t.headers.has("Range"))return a();let f=new URL(t.url),h=`${f.origin}${f.pathname}${f.search}|${re(t)?"fragment":"document"}`,g=this.entries.get(h),l=(s)=>{let S=new Headers(s.headers);return S.set("Cache-Control","private, no-store"),S.set("Age",String(Math.max(0,Math.floor((this.now()-s.created)/1000)))),new Response(s.body.slice(0),{headers:S})},m=g?(this.now()-g.created)/1000:1/0;if(g&&m<e.maxAge)return l(g);let b=this.generation,k=async()=>{let s=await o();r=s;let S=(s.headers.get("Vary")??"").toLowerCase().split(",").map((y)=>y.trim()).filter(Boolean);if(s.status!==200||s.headers.has("Set-Cookie")||/(?:private|no-store|no-cache)/i.test(s.headers.get("Cache-Control")??"")||S.some((y)=>y!=="x-stx-router"&&y!=="accept-encoding"))return null;let B=await s.clone().arrayBuffer();if(B.byteLength>1048576)return null;s.headers.set("Vary",_(s.headers.get("Vary")).Vary);let n={body:B,headers:Array.from(s.headers.entries()),created:this.now(),path:f.pathname};if(this.generation===b)this.entries.set(h,n);return n},v=this.pending.get(h);if(!v){if(this.pending.size>=1000)return a();v=k().finally(()=>{if(this.pending.get(h)===v)this.pending.delete(h)}),this.pending.set(h,v)}if(g&&m<e.maxAge+(e.swr??0))return v.catch(()=>{}),l(g);let E=await v;return E?l(E):a()}}var de={".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".html":"text/html",".txt":"text/plain",".xml":"application/xml",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".mp4":"video/mp4",".webm":"video/webm",".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"};async function rl(t={}){let e=P.resolve(t.outputDir||".output"),o=t.port??3000,r=mo(e);if(!r)console.error("[stx] No build manifest found. Run `stx build` first."),process.exit(1);console.log(`[stx] Production server loading ${r.routes.length} routes...`);let a=Lt(r.routeRules),f=new G,h=Xr(e,r.apiRoutes??[]),g=Bun.file(P.join(e,"server/runtime-config.json")),l=t.runtimeConfig??(await g.exists()?await g.json():void 0),m=l?C(l):void 0,b=new Map,k=new Map,v=new Map,E=new Map;for(let n of r.routes)try{let y=P.join(e,n.compiledPath),i=JSON.parse(await Bun.file(y).text());if(m)i.html=Je(i.html,m);b.set(n.pattern,i),v.set(n.pattern,Ce(i.html)),E.set(n.pattern,le(i.html));let X=P.join(e,n.fragmentPath);if(await Bun.file(X).exists()){let A=await Bun.file(X).text();k.set(n.pattern,m?Je(A,m):A)}}catch(y){console.warn(`[stx] Failed to load route ${n.pattern}:`,y)}let s=new Map,S=[];for(let n of r.routes)if(n.hasParams){let{regex:y,params:i}=J(n.pattern,{page:!0});S.push({regex:y,route:n,paramNames:i})}else s.set(n.pattern,n);let B=fe({port:o,async fetch(n){return Dt(n,await ue(m??C(),async()=>{let i=new URL(n.url).pathname;if(t.onRequest){let p=await t.onRequest(n);if(p)return p}if(t.apiRouter){let p=await t.apiRouter.handleRequest(n);if(p.status!==404)return p}if(t.apiRoutes?.[i])return t.apiRoutes[i](n);let X=await h(n);if(X)return X;if((n.method==="GET"||n.method==="HEAD")&&i!=="/"){let p=P.resolve(e,"public"),d;try{d=decodeURIComponent(i)}catch{d=i}if(!d.includes("\x00")){let u=P.resolve(p,`.${d}`);if(u===p||u.startsWith(`${p}${P.sep}`))try{if(K.existsSync(u)&&K.statSync(u).isFile()){let R=P.extname(u).toLowerCase(),L=de[R]||"application/octet-stream",N=i.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(i);return new Response(Bun.file(u),{headers:{"Content-Type":L,"Cache-Control":N?"public, max-age=31536000, immutable":"public, max-age=3600"}})}}catch{}}}let A=re(n),w=null,q={};if(w=s.get(i)||null,!w)for(let{regex:p,route:d,paramNames:u}of S){let c=i.match(p);if(c){w=d,u.forEach((R,L)=>{q[R]=c[L+1]});break}}if(!w){let p=tt(i)?null:s.get("/404")||null;if(p){let d=b.get(p.pattern);if(d)return new Response(d.html,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}})}let O=a(i),W=Object.keys(O).length>0;return f.respond(n,O.cache,async()=>{let p=b.get(w.pattern);if(A&&n.method==="GET"&&p&&!p.hasServerScripts&&Object.keys(p.placeholders).length===0){let c=k.get(w.pattern);if(c){let R=v.get(w.pattern);return new Response(c,{status:p.status??200,headers:{"Content-Type":"text/html","X-STX-Fragment":"true",...E.has(w.pattern)?{"X-STX-Runtime":E.get(w.pattern)?"true":"false"}:{},...R?{"X-STX-Layout":R.layout,"X-STX-Layout-Group":R.group}:{},..._(),...O.cache?{}:{"Cache-Control":Pe}}})}}let d=Tr(n.method),u=b.get(w.pattern);if(!u){let c=s.get("/500")||null;if(c){let R=b.get(c.pattern);if(R)return new Response(R.html,{status:500,headers:{"Content-Type":"text/html"}})}return new Response("Internal Server Error",{status:500})}if(w.prerendered&&d)return new Response("Prerendered pages do not accept actions",{status:405,headers:{Allow:"GET, HEAD"}});if(!d&&!u.hasServerScripts&&Object.keys(u.placeholders).length===0)return new Response(u.html,{status:u.status??200,headers:{"Content-Type":"text/html",..._(),"Cache-Control":"public, max-age=60"}});try{let{html:c,boundaries:R,redirect:L,cookies:N,status:I,headers:D}=await Nt(u,{params:q,request:n,method:n.method,__stx_strict_hydration:W,__stx_runtime_config:m});if(L)return ho(L,N,D);if(R&&R.length>0){let{renderStreamingPage:T,streamToResponse:z}=await import("./chunk-vmq2dd3k.js"),j=new Headers({..._(),...D,"Cache-Control":"private, no-store"});for(let V of N??[])j.append("Set-Cookie",V);if(A&&!d){let V=Ce(c);j.set("X-STX-Fragment","true"),j.set("X-STX-Runtime",le(c)?"true":"false"),j.set("X-STX-Layout",V.layout),j.set("X-STX-Layout-Group",V.group)}return z(T(A&&!d?se(c,r.routerContainer||"main"):c,R,{timeoutMs:30000}),{status:I??u.status??200,headers:j})}let x=new Headers({"Content-Type":"text/html",..._(),...O.cache?{}:{"Cache-Control":"private, no-store"}});for(let T of N??[])x.append("Set-Cookie",T);for(let[T,z]of Object.entries(D??{}))x.set(T,z);if(x.set("Vary",_(x.get("Vary")).Vary),A&&!d){let T=Ce(c);return x.set("X-STX-Fragment","true"),x.set("X-STX-Runtime",le(c)?"true":"false"),x.set("X-STX-Layout",T.layout),x.set("X-STX-Layout-Group",T.group),new Response(se(c,r.routerContainer||"main"),{status:I??u.status??200,headers:x})}return new Response(c,{status:I??u.status??200,headers:x})}catch(c){if(console.error(`[stx] Hydration error for ${i}:`,c),W)return new Response("Internal Server Error",{status:500});return new Response(u.html,{headers:{"Content-Type":"text/html"}})}})}))}});return console.log(`[stx] Production server running at http://localhost:${B.port}`),console.log(`[stx] Serving ${r.routes.length} routes (${b.size} pre-loaded)`),{port:B.port,stop:()=>{f.invalidate(),B.stop()},invalidate:(n)=>f.invalidate(n)}}
|
|
3
3
|
export{Dt,rl};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{De,Xt,cd}from"./chunk-
|
|
2
|
+
import{De,Xt,cd}from"./chunk-h51g1ydb.js";import{U,Mn,Jt,Fr,zr,Nn,ld,dd,ud,Yt,Zt,Hr,Ln,pd}from"./chunk-vb4xxpa6.js";import"./chunk-d7zterbp.js";export{Fr as batch,cd as default,Mn as derived,Jt as effect,De as generateSignalsRuntime,Xt as generateSignalsRuntimeDev,Zt as isDerived,Yt as isSignal,Nn as onDestroy,zr as onMount,Ln as peek,ud as pendingLifecycleCounts,dd as runDestroyCallbacks,ld as runMountCallbacks,U as state,Hr as untrack,pd as useOptimistic};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{sa,ao,al,oa,ia,cl,ll}from"./chunk-
|
|
2
|
+
import{sa,ao,al,oa,ia,cl,ll}from"./chunk-bk5g7qez.js";import"./chunk-xz7dk3yc.js";import"./chunk-nn66ek7z.js";import"./chunk-7g90r41h.js";import"./chunk-azb58ven.js";import{Ve,yc}from"./chunk-pwdvc964.js";import"./chunk-bczcm7jk.js";import"./chunk-bpr4bkde.js";import"./chunk-x607yxrc.js";import"./chunk-1es2y1jz.js";import"./chunk-v9vvzdag.js";import"./chunk-tkvp3rz0.js";import"./chunk-y18yvcjb.js";import"./chunk-vhfwnvmc.js";import"./chunk-6v1gwdbv.js";import"./chunk-d7zterbp.js";import"./chunk-2bvk0qyd.js";import"./chunk-1xgs9gd5.js";export{sa as buildVirtualSource,Ve as extractScriptBlocks,yc as extractTemplateExpressions,oa as findRuntimeTypeDeclarations,ia as findStxModuleDeclarations,ll as formatTypecheckDiagnostics,al as sourcePathFor,cl as typecheckStxFiles,ao as virtualPathFor};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{y}from"./chunk-d7zterbp.js";import{q,Ve,is,as,ti,ni,ri,si,Gn,cs,oi,ii,ai,Tt,o}from"./chunk-
|
|
2
|
+
import{y}from"./chunk-d7zterbp.js";import{q,Ve,is,as,ti,ni,ri,si,Gn,cs,oi,ii,ai,Tt,o}from"./chunk-pwdvc964.js";import{Br}from"./chunk-xz7dk3yc.js";import{a}from"./chunk-4cmqjmqr.js";import{existsSync as M,readFileSync as K}from"fs";import h from"path";var me=new Set(["module","exports","require","$bool","$num","window","document","console","confirm","alert","fetch"]),te=Tt.filter((e)=>!me.has(e)).sort(),ne=[...y].sort(),he=[...new Set([...te,...ne])].sort(),be=new Set(te),ye=new Set(ne),xe=new Set(he),ee=/\bimport\s+(?!type[\s{])\{([^}]*)\}\s*from\s*(['"])stx\2/g;function Se(e,t){if(t==="server")return`'${e}' is not provided by 'stx' in a <script server> block. The engine binds only its own names there (defineProps, state, useHead, ...); any other name becomes \`await import('stx')\`, which does not resolve, so the whole script fails when the page renders. Import it from '@stacksjs/stx' instead.`;return`'${e}' is not provided by 'stx' in a client <script> block. The import is replaced by the window.stx runtime, which has no '${e}', so it is undefined in the browser.`}function ie(e,t){let s=[];for(let u of t){if(u.offset===void 0)continue;let i=u.kind==="server"?be:ye;ee.lastIndex=0;for(let l of u.code.matchAll(ee)){let g=l.index+l[0].indexOf("{")+1;for(let m of l[1].matchAll(/[^,]+/g)){let S=m[0];if(/^\s*type\s/.test(S))continue;let x=/^\s*([A-Za-z_$][\w$]*)/.exec(S);if(!x)continue;let r=x[1];if(!xe.has(r)||i.has(r))continue;let f=u.offset+g+m.index+x[0].length-r.length,p=e.slice(0,f),w=p.split(`
|
|
3
3
|
`).length;s.push({line:w,column:f-(p.lastIndexOf(`
|
|
4
4
|
`)+1)+1,offset:f,length:r.length,name:r,kind:u.kind,message:Se(r,u.kind)})}}}return s}import T from"path";var ke="@stacksjs/stx-typescript-plugin";function we(e,t){let s=T.resolve(e);for(;;){let u=T.join(s,"tsconfig.json");if(t(u))return u;let i=T.dirname(s);if(i===s)return;s=i}}function se(e,t,s){let u=we(e,s);if(!u)return;let i=new Set,l=(g)=>{if(i.has(g))return;i.add(g);let m=t(g);if(!m)return;let S=m.compilerOptions?.plugins;if(Array.isArray(S)){let r=S.find((p)=>p?.name===ke),f=Array.isArray(r?.libs)?r.libs.filter((p)=>typeof p==="string"):[];return r?{configPath:g,libs:f.map((p)=>T.resolve(T.dirname(g),p))}:null}let x=typeof m.extends==="string"?[m.extends]:Array.isArray(m.extends)?m.extends:[];for(let r of[...x].reverse()){if(typeof r!=="string"||!r.startsWith("."))continue;let f=T.resolve(T.dirname(g),r.endsWith(".json")?r:`${r}.json`),p=l(f);if(p!==void 0)return p}return};return l(u)??void 0}function sa(e,t="",s=""){let u=e.startLine>1?`
|
|
5
5
|
`.repeat(e.startLine-1):"",i=cs(e)+as(is(e.code)),l=e.kind==="client"||e.kind==="plain"?ri(t,e.code):"";return Gn(`${u+i}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{je,lc,Bd,Fd,zd,Hd,dc,uc,Ud,Vd,Yo,Wd,sn,on,Un}from"./chunk-
|
|
2
|
+
import{je,lc,Bd,Fd,zd,Hd,dc,uc,Ud,Vd,Yo,Wd,sn,on,Un}from"./chunk-pwdvc964.js";import"./chunk-bczcm7jk.js";import"./chunk-bpr4bkde.js";import"./chunk-x607yxrc.js";import"./chunk-1es2y1jz.js";import"./chunk-v9vvzdag.js";import"./chunk-tkvp3rz0.js";import"./chunk-y18yvcjb.js";import"./chunk-vhfwnvmc.js";import"./chunk-6v1gwdbv.js";import"./chunk-d7zterbp.js";import"./chunk-2bvk0qyd.js";import"./chunk-1xgs9gd5.js";export{Hd as __setSignalsGeneratorsForTest,je as cacheEngineFingerprint,on as cacheTemplate,sn as checkCache,Wd as clearDevCaches,uc as getCachedRouterScript,dc as getCachedSignalsRuntime,Ud as getServeClientAsset,Yo as getServeModuleBundle,Un as hashFilePath,Fd as invalidateFileCache,zd as invalidateFileCacheByDir,Bd as readFileCached,Vd as registerServeModuleBundle,lc as templateCache};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{xt,Gr,Kr,Xr,Id,Jr}from"./chunk-
|
|
2
|
+
import{xt,Gr,Kr,Xr,Id,Jr}from"./chunk-7g90r41h.js";import"./chunk-x607yxrc.js";import"./chunk-v9vvzdag.js";import"./chunk-2bvk0qyd.js";export{Kr as buildServerApi,Id as createServerApi,xt as discoverServerApi,Gr as generateApiTypes,Jr as isServerApiSource,Xr as productionApiDispatcher};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{X,wn,ne,P,Pt}from"./chunk-vhfwnvmc.js";import{tt,kn,ur,pr,fr,nt,rt,st,ot,it,at,Ce}from"./chunk-2bvk0qyd.js";import{W,b,sn,on,e,Et,an,f,ze,_t,He,Ue,Q,N,le,K,d,we,hi,vs,n,r,te,Zn,o,A,de}from"./chunk-
|
|
2
|
+
import{X,wn,ne,P,Pt}from"./chunk-vhfwnvmc.js";import{tt,kn,ur,pr,fr,nt,rt,st,ot,it,at,Ce}from"./chunk-2bvk0qyd.js";import{W,b,sn,on,e,Et,an,f,ze,_t,He,Ue,Q,N,le,K,d,we,hi,vs,n,r,te,Zn,o,A,de}from"./chunk-pwdvc964.js";import{Pe,lo,re,_,uo,_r,In,he,po,se}from"./chunk-z0h3we7z.js";import{Dt}from"./chunk-8bt1mxny.js";import{ce}from"./chunk-azb58ven.js";import{a}from"./chunk-4cmqjmqr.js";import{D}from"./chunk-3nk8cnrm.js";function Xs(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 _e from"fs";import Te from"path";function Pn(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function At(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 On(t,s="stx"){let i=Te.resolve(t);for(let p=0;p<10;p++){let c=Te.join(i,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=Te.dirname(i);if(l===i)break;i=l}return null}var An=["@stacksjs/stx","bun-plugin-stx"];function Pi(t){try{let s=_e.readFileSync(Te.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Oi(t,s=6){let i=Te.resolve(t),p=[],c=new Set;function l(u,h){if(h>s)return;let g;try{g=_e.realpathSync(u)}catch{return}if(c.has(g))return;c.add(g);for(let w of An){let S=Te.join(u,w),C=Pi(S);if(C!==null)p.push({name:w,version:C,dir:Te.relative(i,S)||S,nested:h>0})}let y;try{y=_e.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=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=Te.join(S,x.name,"node_modules");if(_e.existsSync(T))l(T,h+1)}continue}let C=Te.join(S,"node_modules");if(_e.existsSync(C))l(C,h+1)}}let m=Te.join(i,"node_modules");if(_e.existsSync(m))l(m,0);return p}function Ai(t){let s=[];for(let i of An){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 wr(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 Ai(Oi(s)))c.push(h);let u=On(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)=>_e.existsSync(v))||null,y=Pn(h),w=g?Pn(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 (${At(w,p)}) is OLDER than src/signals.ts (${At(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 ${At(y,p)}, dist ${At(w,p)})`});let S=Te.join(s,"node_modules/@stacksjs/stx"),C=null;try{C=_e.lstatSync(S)}catch{C=null}if(!C)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(C.isSymbolicLink()){let v=null;try{v=_e.realpathSync(S)}catch{}let x=(()=>{try{return _e.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 vr(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?`./${Mt.relative(Mt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Zn(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 sn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await ne(()=>Bun.file(m).text(),"",(x)=>{throw new wn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new wn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=W.time("script-extraction",()=>{let x=h,T=Q(h);if(T)x=T.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",M=[];for(let R of k){let L=R.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=R.match(/<script\b([^>]*)>/i),G=B?B[1]:"";if(/\bserver\b/i.test(G))H=L;else M.push(R)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:M}}),S={__filename:m,__dirname:Mt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await ne(()=>d(g,S,m),void 0,(x)=>{let T=new X(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(P.log(T,{filePath:m,scriptContent:g}),i.debug)throw T});let v=await W.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?`./${Mt.relative(Mt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Zn(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 sn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await ne(()=>Bun.file(m).text(),"",(x)=>{throw new wn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new wn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=W.time("script-extraction",()=>{let x=h,T=Q(h);if(T)x=T.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",M=[];for(let R of k){let L=R.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=R.match(/<script\b([^>]*)>/i),G=B?B[1]:"";if(/\bserver\b/i.test(G))H=L;else M.push(R)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:M}}),S={__filename:m,__dirname:Mt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await ne(()=>d(g,S,m),void 0,(x)=>{let T=new X(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(P.log(T,{filePath:m,scriptContent:g}),i.debug)throw T});let v=await W.timeAsync("directive-processing",async()=>await n(y,S,m,i,u));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-jskc4rr7.js"),T=x(w.join(`
|
|
1790
1790
|
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
|
|
1791
1791
|
`+v.slice(k);else v+=`
|
|
1792
1792
|
${T}`}if(v=await K(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await on(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(P.log(h,{filePath:m,buildConfig:t.config}),Pt.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||D()?`<!DOCTYPE html>
|
|
@@ -1849,7 +1849,7 @@ ${T}`}if(v=await K(v),u.forEach((x)=>p.add(x)),i.cache&&i.cachePath){if(await on
|
|
|
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 _n(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(!Fe.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");Fe.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)\//},(ye)=>({path:ye.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 Et(S);let C=i;try{if(C=await Ye(i),C!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||C+1;l=Ct({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,T;try{let{loadStxConfig:L}=await import("./chunk-
|
|
1852
|
+
</html>`,loader:"html"}}})}};async function _n(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(!Fe.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");Fe.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)\//},(ye)=>({path:ye.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 Et(S);let C=i;try{if(C=await Ye(i),C!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||C+1;l=Ct({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,T;try{let{loadStxConfig:L}=await import("./chunk-xvjtj1kt.js"),B=await L();if(T=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:ee}=await import("./chunk-12v4d123.js"),$e=B.broadcasting;await G($e);let ye=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ye}/ws${e.reset}`);let De=Se.join(process.cwd(),"channels.ts");if(Fe.existsSync(De))try{let ae=await ee(De);console.log(`${e.blue}Loaded ${e.bright}${ae} broadcast channel${ae!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ae){console.warn(`${e.yellow}Failed to load channels.ts: ${ae.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-dr0394tm.js"),M=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let I=Fi({port:C,async fetch(L){return Dt(L,await(async()=>{let B=new URL(L.url);if([h,Se.dirname(u),Se.join(process.cwd(),"public")].some((ae)=>H(Se.join(ae,B.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let ae=await x.handleRequest(L);if(ae.status!==404)return ae}catch{}if(v[B.pathname])try{return await v[B.pathname](L)}catch(ae){return new Response(JSON.stringify({error:ae.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await M(L);if(G)return G;if(B.pathname==="/")return(async()=>{let U=await f(g||"");if(c)U=Xe(U,m);if(s.native)if(U.includes("<head>"))U=U.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(U.includes("<html"))U=U.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 U="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+U;if(s.titlebarHidden)if(U.includes("<head>"))U=U.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(U.includes("<html"))U=U.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 U=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${U}`;return U})().then((U)=>new Response(U,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let ee=Se.join(h,B.pathname);if(Fe.existsSync(ee)&&Fe.statSync(ee).isFile()){let ae=Bun.file(ee),U=Se.extname(ee).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let Ne=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),ct=Ne.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(U){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(ae,{headers:{"Content-Type":j}})}let $e=Se.dirname(u),ye=Se.join($e,B.pathname);if(Fe.existsSync(ye)&&Fe.statSync(ye).isFile()){let ae=Bun.file(ye),U=Se.extname(ye).toLowerCase(),j="text/plain";if(U===".ts"||U===".tsx"){let Ne=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),ct=Ne.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(U){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(ae,{headers:{"Content-Type":j}})}let De=Se.join(process.cwd(),"public",B.pathname);if(Fe.existsSync(De)&&Fe.statSync(De).isFile()){let ae=Bun.file(De),U=Se.extname(De).toLowerCase(),j="application/octet-stream";if(U===".ts"||U===".tsx"){let Ne=new Bun.Transpiler({loader:U===".tsx"?"tsx":"ts"}),qe=await ae.text(),ct=Ne.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(U){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(ae,{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:${C}/${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)),C=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Ae.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of u){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Ae.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",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`),Qe(w.url.toString(),()=>{if(p)Ze.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),we.clear(),te(),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:Ni}=globalThis.Bun;import xe from"fs";import ie from"path";async function qn(t){try{return _t(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 $n(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-5wx323bm.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-kcs7hyep.js"),S=s.stxOptions?.serverApi??g.serverApi,C=await y(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",T=ie.join(v,x);if(!xe.existsSync(T)&&!g._layerPageDirs?.some((E)=>xe.existsSync(E)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],M=[];for(let{dir:E,prefix:F}of H)if(xe.existsSync(E)){let z=N(ie.dirname(E),{pagesDir:ie.basename(E)});for(let V of z){let ve=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;M.push({route:{...V,pattern:ve},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,R=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await uo(u,s.stxOptions?.shell),L){if(R=await _r(L,s.stxOptions||{}),R)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}`)}}nt(),await st(u);let B=rt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let G={},ee=null;try{let{loadStxConfig:E}=await import("./chunk-5wx323bm.js"),F=await E(u);if(F?.apiRouter)ee=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-12v4d123.js"),ve=F.broadcasting;await z(ve);let We=ve.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(xe.existsSync(Ge))try{let oe=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${oe} broadcast channel${oe!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(oe){console.warn(`${e.yellow}Failed to load channels.ts: ${oe.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(u,"output");xe.mkdirSync($e,{recursive:!0});let ye=new Map,De=new Set,ae=async(E)=>{let F=pr(T,E);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((ve)=>ve.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},U=new Map,j=async(E,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:ve,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-5wx323bm.js"),{checkCache:oe,cacheTemplate:Z,readFileCached:q,templateCache:J}=await import("./chunk-wxy9re1a.js"),ke=await We(u),Je=(pe)=>{if(!pe)return pe;if(ie.isAbsolute(pe))return pe;return ie.resolve(u,pe)},O={...ve,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=Je(O.partialsDir),O.componentsDir=Je(O.componentsDir),O.layoutsDir=Je(O.layoutsDir),O.storesDir=Je(O.storesDir||"stores"),O.cachePath=Je(O.cachePath)??a(u,"cache");let be=!F&&!s.profile,ue=O.cache!==!1;if(ue&&be){let pe=J.get(E.filePath);if(pe)try{if((await xe.promises.stat(E.filePath)).mtime.getTime()<=pe.mtime){let Be=!0;for(let Ee of pe.dependencies){if(!xe.existsSync(Ee)){Be=!1;break}if((await xe.promises.stat(Ee)).mtime.getTime()>pe.mtime){Be=!1;break}}if(Be){let Ee=pe.output;if(R)Ee=he(Ee,{preserveHead:!0});let gt=U.get(E.filePath);return{route:E,content:Ee,status:gt?.status??await qn(E.filePath),headers:gt?.headers}}}}catch{}let Ie=await oe(E.filePath,O);if(Ie){let je=Ie;if(R)je=he(je,{preserveHead:!0});let Be=U.get(E.filePath);return{route:E,content:je,status:Be?.status??await qn(E.filePath),headers:Be?.headers}}}let ge=ue?await q(E.filePath):await Bun.file(E.filePath).text(),Re=_t(ge),{classifyAllScripts:Y}=await import("./chunk-5wx323bm.js"),Le=Y(ge),Ve=Le.server.map((pe)=>pe.content),fe=ge;for(let pe of Le.server)fe=fe.replace(pe.fullTag,"");let me={__filename:E.filePath,__dirname:ie.dirname(E.filePath),__stx_options:O,params:F??{},__stx_runtime_head:{}};for(let pe of Ve)try{await V(pe,me,E.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",E.filePath,Ie?.message||Ie)}let Ke=new Set,Me;if(s.profile){let pe=performance.now();Me=await z(fe,me,E.filePath,O,Ke);let Ie=performance.now()-pe,je=ie.relative(u,E.filePath)||E.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Me=await z(fe,me,E.filePath,O,Ke);if(!R)Me=await Ge(Me,{router:O.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-94rg5s6c.js");Me=Me.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,Be)=>{if(!/function\s+__stx_setup_/.test(Be))return Ie;return`<script${je}>${pe(Be,me)}</script>`})}if(R)Me=he(Me,{preserveHead:!0});if(ue&&be)await Z(E.filePath,Me,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-0e5nasyf.js"),lt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let pe=me.streamBoundaries||{},Ie={...O,autoShell:!1},je=Object.keys(mt).map((Ee)=>({id:Ee,render:async()=>{let gt=typeof pe[Ee]==="function"?await pe[Ee]():void 0;return z(mt[Ee],{...me,$boundary:gt},E.filePath,Ie,new Set)}})),Be=new Set(je.map((Ee)=>Ee.id));lt=[...(lt||[]).filter((Ee)=>!Be.has(Ee.id)),...je]}if(lt&<.length>0)De.add(E.pattern);else lt=void 0;let Kt=He(me),Xt=Ue(me);if(be)U.set(E.filePath,{status:Kt,headers:Xt});return{route:E,content:Me,status:Kt??Re,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${E.pattern}${e.reset}:`,z),null}},Ne=8,qe=async()=>{ye.clear(),I.clear();for(let E=0;E<k.length;E+=Ne){let F=k.slice(E,E+Ne),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)ye.set(V.route.pattern,V)}for(let E=0;E<M.length;E+=Ne){let F=M.slice(E,E+Ne),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return ye.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 Et(u);let et=i;try{if(et=await Ye(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let E=s.hmrPort||et+1;l=Ct({wsPort:E,verbose:!1}),m=l.start(E)}let Lt=(E,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(E.includes("</head>"))return E.replace("</head>",`${V}</head>`);if(E.includes("<body"))return E.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+E};console.log(`${e.blue}Starting server...${e.reset}`);let It=Ni({port:et,async fetch(E){let F=new URL(E.url),z=g?.publicDir||"public",V=ie.join(u,z,F.pathname),ve=ie.join(u,F.pathname),We=ie.join($e,F.pathname);if([V,ve,We].some((O)=>w(O,u,S)))return new Response("Not Found",{status:404});let[Ge,oe,Z]=await Promise.all([xe.promises.stat(V).catch(()=>null),xe.promises.stat(ve).catch(()=>null),xe.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return qt(V);if(oe?.isFile()&&!w(ve,u,S))return qt(ve);if(Z?.isFile()&&!w(We,u,S))return qt(We);if(F.pathname.startsWith("/_stx/component/")){let O=decodeURIComponent(F.pathname.slice(16));if(O)try{let be=`<${O} />`,ue={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ie.join(u,"components",`${O}.stx`),ue,new Set);return new Response(ge,{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:O}=await import("./chunk-rx4hz615.js"),be=await O(E,{publicDir:ie.join(u,z),cacheDir:a(u,"cache","img")});if(be)return be}if(ee)try{let O=await ee.handleRequest(E);if(O.status!==404)return O}catch{}if(G[F.pathname])try{return await G[F.pathname](E)}catch(O){return new Response(JSON.stringify({error:O.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await C(E);if(q)return q;let J=kn(F.pathname,k);if(J){let O=ye.get(J.route.pattern),be=De.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||be){let ue=await j(J.route,J.params);if(ue)O=ue}if(O){let ue=O.status??200,ge=O.headers??{},Re=(J.route.filePath?ze(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Re.validate){if(!await Re.validate({params:J.params})){let Ve=await ae(404);if(Ve){let fe=Ve;if(fe=await f(fe,u),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Re.middleware){let Le=ot(F.pathname,J.params,Re,F.search),Ve=it(Le,null,E,{isServer:!0}),fe=await at(Re.middleware,Ve);if(fe.redirect){let me=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Me=new Headers(fe.responseHeaders);return Me.set("Location",me),new Response(null,{status:Ke,headers:Me})}if(fe.abort){let{statusCode:me,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${me}</title></head><body><h1>Error ${me}</h1><p>${Ke}</p></body></html>`,{status:me,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let me=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;O.content=O.content.replace("</head>",`${me}</head>`)}}let Y=O.content;if(R&&po(E)){let Le=Ce(Y),Ve=le(Y),fe=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),me=fe?lo(fe[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=se(Y,Ke),new Response(Y,{status:ue,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",...me&&{"X-STX-Title":encodeURIComponent(me)},[hi]:vs(),..._(),"Cache-Control":Pe}})}if(R)Y=In(R,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(O.boundaries&&O.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-0e5nasyf.js");return Ve(Le(Y,O.boundaries,{timeoutMs:30000}),{status:ue,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:ue,headers:{"Content-Type":"text/html",..._(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(M.length>0){let O=M.map((ue)=>ue.route),be=kn(F.pathname,O);if(be){let ue=I.get(be.route.pattern);if(ue){let ge=ue.content;if(R)ge=In(R,ge);if(Object.keys(be.params).length>0)ge=Lt(ge,be.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:ue.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ue}of H)if(ue!=="/"&&F.pathname.startsWith(ue)){let ge=I.get(ue)||I.get(ue+"/");if(ge){let Re=ge.content;if(R)Re=In(R,Re);if(Re=await f(Re,u),c)Re=Xe(Re,m);return new Response(Re,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(tt(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=ye.get("/");if(ke){let O=ke.content;if(O=await f(O,u),c)O=Xe(O,m);if(s.native)if(O.includes("<head>"))O=O.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 O="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+O;return new Response(O,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let O=Je;if(O=await f(O,u),c)O=Xe(O,m);return new Response(O,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(E){let F=await ae(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${E}
|
|
2028
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(p)Ze.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),we.clear(),te(),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:Ni}=globalThis.Bun;import xe from"fs";import ie from"path";async function qn(t){try{return _t(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 $n(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-xvjtj1kt.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-dr0394tm.js"),S=s.stxOptions?.serverApi??g.serverApi,C=await y(u,S),v=g.root&&g.root!=="."?ie.join(u,g.root):u,x=s.pagesDir||g.pagesDir||"pages",T=ie.join(v,x);if(!xe.existsSync(T)&&!g._layerPageDirs?.some((E)=>xe.existsSync(E)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],M=[];for(let{dir:E,prefix:F}of H)if(xe.existsSync(E)){let z=N(ie.dirname(E),{pagesDir:ie.basename(E)});for(let V of z){let ve=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;M.push({route:{...V,pattern:ve},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,R=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await uo(u,s.stxOptions?.shell),L){if(R=await _r(L,s.stxOptions||{}),R)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}`)}}nt(),await st(u);let B=rt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let G={},ee=null;try{let{loadStxConfig:E}=await import("./chunk-xvjtj1kt.js"),F=await E(u);if(F?.apiRouter)ee=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-12v4d123.js"),ve=F.broadcasting;await z(ve);let We=ve.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(xe.existsSync(Ge))try{let oe=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${oe} broadcast channel${oe!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(oe){console.warn(`${e.yellow}Failed to load channels.ts: ${oe.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(u,"output");xe.mkdirSync($e,{recursive:!0});let ye=new Map,De=new Set,ae=async(E)=>{let F=pr(T,E);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((ve)=>ve.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},U=new Map,j=async(E,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:ve,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-xvjtj1kt.js"),{checkCache:oe,cacheTemplate:Z,readFileCached:q,templateCache:J}=await import("./chunk-c0prbbpe.js"),ke=await We(u),Je=(pe)=>{if(!pe)return pe;if(ie.isAbsolute(pe))return pe;return ie.resolve(u,pe)},O={...ve,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=Je(O.partialsDir),O.componentsDir=Je(O.componentsDir),O.layoutsDir=Je(O.layoutsDir),O.storesDir=Je(O.storesDir||"stores"),O.cachePath=Je(O.cachePath)??a(u,"cache");let be=!F&&!s.profile,ue=O.cache!==!1;if(ue&&be){let pe=J.get(E.filePath);if(pe)try{if((await xe.promises.stat(E.filePath)).mtime.getTime()<=pe.mtime){let Be=!0;for(let Ee of pe.dependencies){if(!xe.existsSync(Ee)){Be=!1;break}if((await xe.promises.stat(Ee)).mtime.getTime()>pe.mtime){Be=!1;break}}if(Be){let Ee=pe.output;if(R)Ee=he(Ee,{preserveHead:!0});let gt=U.get(E.filePath);return{route:E,content:Ee,status:gt?.status??await qn(E.filePath),headers:gt?.headers}}}}catch{}let Ie=await oe(E.filePath,O);if(Ie){let je=Ie;if(R)je=he(je,{preserveHead:!0});let Be=U.get(E.filePath);return{route:E,content:je,status:Be?.status??await qn(E.filePath),headers:Be?.headers}}}let ge=ue?await q(E.filePath):await Bun.file(E.filePath).text(),Re=_t(ge),{classifyAllScripts:Y}=await import("./chunk-xvjtj1kt.js"),Le=Y(ge),Ve=Le.server.map((pe)=>pe.content),fe=ge;for(let pe of Le.server)fe=fe.replace(pe.fullTag,"");let me={__filename:E.filePath,__dirname:ie.dirname(E.filePath),__stx_options:O,params:F??{},__stx_runtime_head:{}};for(let pe of Ve)try{await V(pe,me,E.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",E.filePath,Ie?.message||Ie)}let Ke=new Set,Me;if(s.profile){let pe=performance.now();Me=await z(fe,me,E.filePath,O,Ke);let Ie=performance.now()-pe,je=ie.relative(u,E.filePath)||E.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Me=await z(fe,me,E.filePath,O,Ke);if(!R)Me=await Ge(Me,{router:O.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-jskc4rr7.js");Me=Me.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,Be)=>{if(!/function\s+__stx_setup_/.test(Be))return Ie;return`<script${je}>${pe(Be,me)}</script>`})}if(R)Me=he(Me,{preserveHead:!0});if(ue&&be)await Z(E.filePath,Me,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-vmq2dd3k.js"),lt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let pe=me.streamBoundaries||{},Ie={...O,autoShell:!1},je=Object.keys(mt).map((Ee)=>({id:Ee,render:async()=>{let gt=typeof pe[Ee]==="function"?await pe[Ee]():void 0;return z(mt[Ee],{...me,$boundary:gt},E.filePath,Ie,new Set)}})),Be=new Set(je.map((Ee)=>Ee.id));lt=[...(lt||[]).filter((Ee)=>!Be.has(Ee.id)),...je]}if(lt&<.length>0)De.add(E.pattern);else lt=void 0;let Kt=He(me),Xt=Ue(me);if(be)U.set(E.filePath,{status:Kt,headers:Xt});return{route:E,content:Me,status:Kt??Re,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${E.pattern}${e.reset}:`,z),null}},Ne=8,qe=async()=>{ye.clear(),I.clear();for(let E=0;E<k.length;E+=Ne){let F=k.slice(E,E+Ne),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)ye.set(V.route.pattern,V)}for(let E=0;E<M.length;E+=Ne){let F=M.slice(E,E+Ne),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return ye.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 Et(u);let et=i;try{if(et=await Ye(i),et!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${et} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let E=s.hmrPort||et+1;l=Ct({wsPort:E,verbose:!1}),m=l.start(E)}let Lt=(E,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(E.includes("</head>"))return E.replace("</head>",`${V}</head>`);if(E.includes("<body"))return E.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+E};console.log(`${e.blue}Starting server...${e.reset}`);let It=Ni({port:et,async fetch(E){let F=new URL(E.url),z=g?.publicDir||"public",V=ie.join(u,z,F.pathname),ve=ie.join(u,F.pathname),We=ie.join($e,F.pathname);if([V,ve,We].some((O)=>w(O,u,S)))return new Response("Not Found",{status:404});let[Ge,oe,Z]=await Promise.all([xe.promises.stat(V).catch(()=>null),xe.promises.stat(ve).catch(()=>null),xe.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,u,S))return qt(V);if(oe?.isFile()&&!w(ve,u,S))return qt(ve);if(Z?.isFile()&&!w(We,u,S))return qt(We);if(F.pathname.startsWith("/_stx/component/")){let O=decodeURIComponent(F.pathname.slice(16));if(O)try{let be=`<${O} />`,ue={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ie.join(u,"components",`${O}.stx`),ue,new Set);return new Response(ge,{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:O}=await import("./chunk-rx4hz615.js"),be=await O(E,{publicDir:ie.join(u,z),cacheDir:a(u,"cache","img")});if(be)return be}if(ee)try{let O=await ee.handleRequest(E);if(O.status!==404)return O}catch{}if(G[F.pathname])try{return await G[F.pathname](E)}catch(O){return new Response(JSON.stringify({error:O.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await C(E);if(q)return q;let J=kn(F.pathname,k);if(J){let O=ye.get(J.route.pattern),be=De.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||be){let ue=await j(J.route,J.params);if(ue)O=ue}if(O){let ue=O.status??200,ge=O.headers??{},Re=(J.route.filePath?ze(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Re.validate){if(!await Re.validate({params:J.params})){let Ve=await ae(404);if(Ve){let fe=Ve;if(fe=await f(fe,u),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Re.middleware){let Le=ot(F.pathname,J.params,Re,F.search),Ve=it(Le,null,E,{isServer:!0}),fe=await at(Re.middleware,Ve);if(fe.redirect){let me=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Me=new Headers(fe.responseHeaders);return Me.set("Location",me),new Response(null,{status:Ke,headers:Me})}if(fe.abort){let{statusCode:me,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${me}</title></head><body><h1>Error ${me}</h1><p>${Ke}</p></body></html>`,{status:me,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let me=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;O.content=O.content.replace("</head>",`${me}</head>`)}}let Y=O.content;if(R&&po(E)){let Le=Ce(Y),Ve=le(Y),fe=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),me=fe?lo(fe[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=se(Y,Ke),new Response(Y,{status:ue,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",...me&&{"X-STX-Title":encodeURIComponent(me)},[hi]:vs(),..._(),"Cache-Control":Pe}})}if(R)Y=In(R,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(O.boundaries&&O.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-vmq2dd3k.js");return Ve(Le(Y,O.boundaries,{timeoutMs:30000}),{status:ue,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:ue,headers:{"Content-Type":"text/html",..._(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(M.length>0){let O=M.map((ue)=>ue.route),be=kn(F.pathname,O);if(be){let ue=I.get(be.route.pattern);if(ue){let ge=ue.content;if(R)ge=In(R,ge);if(Object.keys(be.params).length>0)ge=Lt(ge,be.params);if(ge=await f(ge,u),c)ge=Xe(ge,m);return new Response(ge,{status:ue.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ue}of H)if(ue!=="/"&&F.pathname.startsWith(ue)){let ge=I.get(ue)||I.get(ue+"/");if(ge){let Re=ge.content;if(R)Re=In(R,Re);if(Re=await f(Re,u),c)Re=Xe(Re,m);return new Response(Re,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(tt(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let ke=ye.get("/");if(ke){let O=ke.content;if(O=await f(O,u),c)O=Xe(O,m);if(s.native)if(O.includes("<head>"))O=O.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 O="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+O;return new Response(O,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let O=Je;if(O=await f(O,u),c)O=Xe(O,m);return new Response(O,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(E){let F=await ae(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${E}
|
|
2029
2029
|
${E.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:${et}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
|
|
2032
2032
|
${e.yellow}Routes:${e.reset}`);let jt=[...fr(k,u)];for(let{route:E}of M)jt.push(`${E.pattern}`);if(jt.forEach((E,F)=>{let V=F===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${E}`)}),console.log(`
|
|
2033
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let E,F=ie.join(T,"index.stx");if(xe.existsSync(F)){let V=await Bun.file(F).text();E=St(V)}let z=g?.app?.window??{};await dt(et,{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:!!E,sidebarConfig:E})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let E=(oe)=>oe.startsWith("public/")||oe.startsWith("public\\"),F=(oe)=>{let Z=oe.toLowerCase();return Z.endsWith(".stx")||Z.endsWith(".html")||Z.endsWith(".md")},z=new Map,V=()=>{let oe=new Set([u,...g._layerGraph?.layers.map((Z)=>Z.root)??[],...g._layerGraph?.configDependencies.map((Z)=>ie.dirname(Z))??[]].filter((Z)=>xe.existsSync(Z)).map((Z)=>xe.realpathSync(Z)));for(let Z of g._layerGraph?.layers??[])for(let q of Object.values(Z.resources)){if(!xe.existsSync(q))continue;let J=xe.realpathSync(q);if(![...oe].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))oe.add(J)}for(let[Z,q]of z)if(!oe.has(Z))q.close(),z.delete(Z);for(let Z of oe)if(!z.has(Z)&&xe.existsSync(Z))z.set(Z,xe.watch(Z,{recursive:!0},(q,J)=>{We(Z,q,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},ve=Promise.resolve(),We=(oe,Z,q)=>(ve=ve.catch(()=>{}).then(()=>Ge(oe,Z,q)),ve),Ge=async(oe,Z,q)=>{if(!q||$t(q))return;if(Tt(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?[T,...J._layerPageDirs.slice(1)]:void 0})),V()}if(E(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}`),we.clear(),te();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-
|
|
2033
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(It.url.toString(),()=>{if(l)ht();It.stop()}),s.native){let E,F=ie.join(T,"index.stx");if(xe.existsSync(F)){let V=await Bun.file(F).text();E=St(V)}let z=g?.app?.window??{};await dt(et,{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:!!E,sidebarConfig:E})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let E=(oe)=>oe.startsWith("public/")||oe.startsWith("public\\"),F=(oe)=>{let Z=oe.toLowerCase();return Z.endsWith(".stx")||Z.endsWith(".html")||Z.endsWith(".md")},z=new Map,V=()=>{let oe=new Set([u,...g._layerGraph?.layers.map((Z)=>Z.root)??[],...g._layerGraph?.configDependencies.map((Z)=>ie.dirname(Z))??[]].filter((Z)=>xe.existsSync(Z)).map((Z)=>xe.realpathSync(Z)));for(let Z of g._layerGraph?.layers??[])for(let q of Object.values(Z.resources)){if(!xe.existsSync(q))continue;let J=xe.realpathSync(q);if(![...oe].some((ke)=>J===ke||J.startsWith(`${ke}${ie.sep}`)))oe.add(J)}for(let[Z,q]of z)if(!oe.has(Z))q.close(),z.delete(Z);for(let Z of oe)if(!z.has(Z)&&xe.existsSync(Z))z.set(Z,xe.watch(Z,{recursive:!0},(q,J)=>{We(Z,q,J).catch((ke)=>console.error("[stx] Layer rebuild failed:",ke))}))},ve=Promise.resolve(),We=(oe,Z,q)=>(ve=ve.catch(()=>{}).then(()=>Ge(oe,Z,q)),ve),Ge=async(oe,Z,q)=>{if(!q||$t(q))return;if(Tt(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?[T,...J._layerPageDirs.slice(1)]:void 0})),V()}if(E(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}`),we.clear(),te();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-c0prbbpe.js");J(ie.resolve(oe,q)),ke.delete(ie.resolve(oe,q))}catch{}if(L&&q){if(ie.resolve(oe,q)===L||ie.basename(L)===q){let ke=await _r(L,s.stxOptions||{});if(ke)R=ke}}if(await qe(),await an(u),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),we.clear(),te();try{let{invalidateFileCache:J,templateCache:ke}=await import("./chunk-c0prbbpe.js");J(ie.resolve(oe,q)),ke.delete(ie.resolve(oe,q))}catch{}if(await qe(),c&&l)l.reload(q)}}else if(kt(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let oe of z.values())oe.close();if(l)ht();It.stop(),process.exit(0)})}return!0}export{Xs,Js,Ys,Zs,br,Qs,eo,to,Ki,Xi,wr,vr,_n,Tn,$n};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{o}from"./chunk-
|
|
2
|
+
import{o}from"./chunk-pwdvc964.js";import{$r}from"./chunk-7tabykst.js";import p from"path";async function kl(t={}){let d=performance.now(),s=t.root||process.cwd(),e=await o(s),u=t.ssr?.routeRules??e.routeRules??{};if($r(u),!e.ssr&&Object.keys(u).length)throw Error("routeRules require ssr: true and the production server; flat SSG output cannot apply request/cache policies");if(!e.ssr&&(t.ssr?.serverApi??e.serverApi))throw Error("serverApi requires ssr: true; flat SSG output cannot execute API endpoints");let r=e.ssr?"ssr":"ssg";console.log(`[stx build] Mode: ${r.toUpperCase()}${e.ssr?" (ssr: true in stx.config.ts)":" (default \u2014 ssr is false)"}`);let n,l;if(r==="ssg"){let{generateStaticSite:i}=await import("./ssg.js");n=await i({pagesDir:p.join(e.root||".",e.pagesDir||e.build?.pagesDir||"pages"),publicDir:e.publicDir||e.build?.publicDir||"public",outputDir:e.build?.outputDir||"dist",generate404:e.build?.generate404??!0,minify:e.build?.minify??!0,cleanOutput:e.build?.cleanOutput??!0,router:e.router,...t.ssg})}else{let{buildForProduction:i}=await import("./chunk-va61kyky.js");l=await i({root:s,outputDir:".output",debug:t.debug,...t.ssr})}let a=Math.round(performance.now()-d);return{mode:r,ssg:n,ssr:l,duration:a}}
|
|
3
3
|
export{kl};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{K,xs,Ss,ks,n}from"./chunk-
|
|
2
|
+
import{K,xs,Ss,ks,n}from"./chunk-pwdvc964.js";import"./chunk-bczcm7jk.js";import"./chunk-bpr4bkde.js";import"./chunk-x607yxrc.js";import"./chunk-1es2y1jz.js";import"./chunk-v9vvzdag.js";import"./chunk-tkvp3rz0.js";import"./chunk-y18yvcjb.js";import"./chunk-vhfwnvmc.js";import"./chunk-6v1gwdbv.js";import"./chunk-d7zterbp.js";import"./chunk-2bvk0qyd.js";import"./chunk-1xgs9gd5.js";export{K as injectRouterScript,n as processDirectives,xs as processJsonDirective,Ss as processOnceDirective,ks as validateClientScript};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{nl}from"./chunk-
|
|
2
|
+
import{nl}from"./chunk-33vbh6g3.js";import"./chunk-pwdvc964.js";import"./chunk-bczcm7jk.js";import"./chunk-bpr4bkde.js";import"./chunk-x607yxrc.js";import"./chunk-1es2y1jz.js";import"./chunk-v9vvzdag.js";import"./chunk-tkvp3rz0.js";import"./chunk-y18yvcjb.js";import"./chunk-vhfwnvmc.js";import"./chunk-6v1gwdbv.js";import"./chunk-d7zterbp.js";import"./chunk-2bvk0qyd.js";import"./chunk-1xgs9gd5.js";export{nl as startInteractive};
|
|
@@ -5052,7 +5052,7 @@ else if (!value && isInserted) {
|
|
|
5052
5052
|
var IF_ATTRS = [':if', 'x-if', '@if'];
|
|
5053
5053
|
var FOR_ATTRS = [':for', 'x-for', '@for'];
|
|
5054
5054
|
function deferRowConditionals(root) {
|
|
5055
|
-
if (!root || !root.querySelectorAll || typeof document === 'undefined' || !document.createElement) return;
|
|
5055
|
+
if (stxHost.isNative || !root || !root.querySelectorAll || typeof document === 'undefined' || !document.createElement) return;
|
|
5056
5056
|
// Inert HTML template content is a DOM allocation optimisation. Native
|
|
5057
5057
|
// hosts already clone recorded descriptors and bind conditions through
|
|
5058
5058
|
// their host operations; their document facade has no template content.
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{rs,ss,os,Xd,qn,Jd}from"./chunk-
|
|
2
|
+
import{rs,ss,os,Xd,qn,Jd}from"./chunk-pwdvc964.js";export{qn as clearImageDeliveryCatalog,Xd as deliveredImage,os as efficientDeliverySources,rs as getImageDelivery,ss as isTransparentImage,Jd as prepareImageDelivery};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{kt,hs,gi,Rc}from"./chunk-
|
|
2
|
+
import{kt,hs,gi,Rc}from"./chunk-pwdvc964.js";import"./chunk-bczcm7jk.js";import"./chunk-bpr4bkde.js";import"./chunk-x607yxrc.js";import"./chunk-1es2y1jz.js";import"./chunk-v9vvzdag.js";import"./chunk-tkvp3rz0.js";import"./chunk-y18yvcjb.js";import"./chunk-vhfwnvmc.js";import"./chunk-6v1gwdbv.js";import"./chunk-d7zterbp.js";import"./chunk-2bvk0qyd.js";import"./chunk-1xgs9gd5.js";export{Rc as declareBareLoopHead,kt as parseLoopBinding,gi as processLoops,hs as reportDeferredLoopWarnings};
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import m from"path";var y=/__stxModules\["((?:[^"\\]|\\.)*)"\]/g;function I(...o){let r=new Set;for(let s of o){if(!s||!s.includes("__stxModules["))continue;for(let e of s.matchAll(y))try{r.add(JSON.parse(`"${e[1]}"`))}catch{}}return[...r].sort()}async function w(o,r={}){if(o.length===0)return null;let s=process.cwd(),e=[],a=[];o.forEach((t,c)=>{let i=t.startsWith("npm:")?t.slice(4):m.resolve(s,t),l=`__stxRegistered${c}`,p=JSON.stringify(t);e.push(`import * as ${l} from ${JSON.stringify(i)};`),a.push(`if (!globalThis.__stxModules[${p}]) globalThis.__stxModules[${p}] = ${l};`)});let d=[...e,"globalThis.__stxModules = globalThis.__stxModules || {};",...a].join(`
|
|
3
|
-
`),n;try{let{bundleClientScript:t}=await import("./chunk-
|
|
3
|
+
`),n;try{let{bundleClientScript:t}=await import("./chunk-zs5p8jcn.js");n=await t(d,m.join(s,".stx-module-registry.ts"),{projectRoot:s,minify:r.minify,externalizeUserModules:!1,collectInputs:r.collectInputs,throwOnFailure:!0})}catch(t){let{formatBuildFailure:c}=await import("./chunk-t94z65ry.js"),i=c(t);console.warn(`[stx] could not build the page module registry (#1957): ${i}`);let l=`[stx] the page module registry did not build, so ${o.join(", ")} cannot load (#1957): ${i}`;return`;console.error(${JSON.stringify(l)});`}let{transformAutoImports:f,generateAutoImportDestructuring:_}=await import("./chunk-tr49ckr5.js"),u=f(n),h=_(u.stxImports,u.browserImports),{transformStoreImports:x}=await import("./chunk-zpftj8s8.js");n=x(u.code);let g=JSON.stringify(new Bun.CryptoHasher("md5").update(d).digest("hex").slice(0,12));return[";(function() {"," var __stxBundles = globalThis.__stxModuleBundles || (globalThis.__stxModuleBundles = {});",` if (__stxBundles[${g}]) return;`,` __stxBundles[${g}] = true;`,h,n,"})();"].join(`
|
|
4
4
|
`)}export{w as buildModuleRegistryScript,I as registeredModuleIdsIn};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{qd,Zo,Gd,Qo,pc,fc,Et,an,Kd,gc,mc,hc,f}from"./chunk-
|
|
2
|
+
import{qd,Zo,Gd,Qo,pc,fc,Et,an,Kd,gc,mc,hc,f}from"./chunk-pwdvc964.js";import"./chunk-bczcm7jk.js";import"./chunk-bpr4bkde.js";import"./chunk-x607yxrc.js";import"./chunk-1es2y1jz.js";import"./chunk-v9vvzdag.js";import"./chunk-tkvp3rz0.js";import"./chunk-y18yvcjb.js";import"./chunk-vhfwnvmc.js";import"./chunk-6v1gwdbv.js";import"./chunk-d7zterbp.js";import"./chunk-2bvk0qyd.js";import"./chunk-1xgs9gd5.js";export{Et as buildCss,gc as extractClassNames,fc as fingerprintConfig,mc as generateCss,Kd as getCachedCSS,qd as getCssServeAsset,f as injectCss,Zo as loadCssEngine,Qo as loadCssEngineConfig,an as rebuildCss,Gd as resetCssCache,pc as resolveUserCssConfig,hc as withLinkedModuleBundles};
|