@stacksjs/stx 0.2.556 → 0.2.558
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-pmwzvb3m.js → chunk-05hr7567.js} +5 -5
- package/dist/chunk-12dkj7xn.js +2 -0
- package/dist/{chunk-qx9s066f.js → chunk-29r6af6f.js} +1 -1
- package/dist/{chunk-gmp7apxp.js → chunk-3220kken.js} +1 -1
- package/dist/{chunk-5pdckdhm.js → chunk-3cq4g0t1.js} +1 -1
- package/dist/{chunk-96fpvzm2.js → chunk-49ms9skq.js} +1 -1
- package/dist/chunk-4bdshma4.js +2 -0
- package/dist/{chunk-3bb0tjs3.js → chunk-4kj8a2bn.js} +1 -1
- package/dist/{chunk-ec8k75ep.js → chunk-4zb2ga7p.js} +2 -2
- package/dist/chunk-550whbab.js +2 -0
- package/dist/{chunk-tyrdwvse.js → chunk-59nq020j.js} +2 -2
- package/dist/chunk-5fwphmtr.js +2 -0
- package/dist/{chunk-6wpgxryt.js → chunk-66f3w7rx.js} +1 -1
- package/dist/chunk-6cq0ggmf.js +2 -0
- package/dist/{chunk-tbtg8z35.js → chunk-6kkt5fjx.js} +1 -1
- package/dist/chunk-7qqx3ja8.js +2 -0
- package/dist/{chunk-d0yx9kef.js → chunk-8227vfw0.js} +1 -1
- package/dist/{chunk-avgx6hd9.js → chunk-8jc86h7n.js} +2 -2
- package/dist/{chunk-pz8mf91e.js → chunk-8tpey96f.js} +4 -4
- package/dist/{chunk-vtkfkkzw.js → chunk-9bxwy4f9.js} +1 -1
- package/dist/{chunk-x4d6ndn1.js → chunk-9cc4fdtt.js} +1 -1
- package/dist/chunk-abtgtvs7.js +2 -0
- package/dist/{chunk-qdrvx7vh.js → chunk-ahhav65p.js} +1 -1
- package/dist/{chunk-3enbxxcs.js → chunk-b11qrqzz.js} +1 -1
- package/dist/{chunk-kvmg6r89.js → chunk-b156xw15.js} +2 -2
- package/dist/chunk-b8j7qsct.js +2 -0
- package/dist/{chunk-x8kf5xjf.js → chunk-bj958h8d.js} +3 -3
- package/dist/{chunk-j2erwdgt.js → chunk-cngtf95k.js} +7 -7
- package/dist/{chunk-75hb7wg6.js → chunk-cv1q9fq8.js} +1 -1
- package/dist/{chunk-d7ec8hgm.js → chunk-dp163aad.js} +1 -1
- package/dist/{chunk-1v2vehpc.js → chunk-e4mbr4az.js} +1 -1
- package/dist/chunk-e5vc83gz.js +2 -0
- package/dist/{chunk-x0fhwxhv.js → chunk-ej5w5a5x.js} +1 -1
- package/dist/{chunk-wcbxh9h9.js → chunk-f029nw9a.js} +1 -1
- package/dist/{chunk-dyreg5df.js → chunk-ff61d2wr.js} +3 -3
- package/dist/chunk-fvdm6dta.js +2 -0
- package/dist/{chunk-jmvp99ay.js → chunk-g84ctpqq.js} +5 -5
- package/dist/{chunk-xp879a67.js → chunk-gfqka4zx.js} +1 -1
- package/dist/{chunk-7pk5sqkw.js → chunk-h0e3ps74.js} +3 -3
- package/dist/{chunk-rs9c1meq.js → chunk-hbb208xt.js} +2 -2
- package/dist/chunk-hd47q9s0.js +2 -0
- package/dist/chunk-j1jh32tw.js +2 -0
- package/dist/{chunk-b9jb44kv.js → chunk-km7sb7bj.js} +3 -3
- package/dist/{chunk-cvxc2h58.js → chunk-m5s1wcn9.js} +1 -1
- package/dist/{chunk-66yp3ryj.js → chunk-mdgvzf07.js} +1 -1
- package/dist/{chunk-qdh45a4k.js → chunk-n5swm2mb.js} +3 -3
- package/dist/{chunk-yty18jzq.js → chunk-n6v7nqgb.js} +1 -1
- package/dist/{chunk-fprgww47.js → chunk-n9y4ssn1.js} +1 -1
- package/dist/chunk-nt0j3fm8.js +2 -0
- package/dist/chunk-q0n8vb38.js +2 -0
- package/dist/chunk-q5vzx6gp.js +63 -0
- package/dist/chunk-q8p16y1h.js +2 -0
- package/dist/{chunk-1zyht1bb.js → chunk-q97v1714.js} +1 -1
- package/dist/{chunk-xzcmh5va.js → chunk-qnf9tr0r.js} +1 -1
- package/dist/chunk-qnqb8s28.js +2 -0
- package/dist/{chunk-g3gtxcc3.js → chunk-qrqw667n.js} +51 -51
- package/dist/chunk-qtnqmw1n.js +2 -0
- package/dist/chunk-ry8v73j8.js +2 -0
- package/dist/chunk-shq0hp3a.js +2 -0
- package/dist/{chunk-knkeqpnk.js → chunk-skbbk6va.js} +16 -16
- package/dist/{chunk-6qfrs1pj.js → chunk-srs912da.js} +1 -1
- package/dist/{chunk-afrfcgn4.js → chunk-tkmcyr0k.js} +1 -1
- package/dist/{chunk-nv62tcmb.js → chunk-w5nw5cj6.js} +1 -1
- package/dist/{chunk-8k5sp2t6.js → chunk-whykvbys.js} +1 -1
- package/dist/chunk-xhay04n8.js +2 -0
- package/dist/chunk-y2gaadz3.js +2 -0
- package/dist/{chunk-1b50m7e7.js → chunk-yp1360pq.js} +2 -2
- package/dist/cli.js +10 -10
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/native/compiler/headwind-to-style.js +30 -0
- package/dist/native/compiler/html-to-ir.js +2 -61
- package/dist/native/components/primitives.d.ts +2 -0
- package/dist/native/event-names.d.ts +4 -0
- package/dist/native/event-names.js +61 -0
- package/dist/native/prop-names.js +2 -0
- package/dist/native/runtime/native-host.js +1 -49
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-384xy328.js +0 -2
- package/dist/chunk-3j5bg3xq.js +0 -2
- package/dist/chunk-4c5sxq9p.js +0 -2
- package/dist/chunk-4sbz2y0g.js +0 -2
- package/dist/chunk-7x3az8j6.js +0 -2
- package/dist/chunk-8bqph6jy.js +0 -2
- package/dist/chunk-9wygdzqe.js +0 -2
- package/dist/chunk-a1srrv4w.js +0 -2
- package/dist/chunk-b46ejka8.js +0 -2
- package/dist/chunk-cev76nd8.js +0 -2
- package/dist/chunk-en30fzej.js +0 -2
- package/dist/chunk-hzx0vtw0.js +0 -2
- package/dist/chunk-kvr304zk.js +0 -2
- package/dist/chunk-m2vk8vja.js +0 -2
- package/dist/chunk-n7f2c5vf.js +0 -2
- package/dist/chunk-nd7p8f5p.js +0 -2
- package/dist/chunk-pjbp7axq.js +0 -2
- package/dist/chunk-s98cd7tr.js +0 -63
- package/dist/chunk-se734zc5.js +0 -2
- package/dist/chunk-sn98t7ef.js +0 -2
- package/dist/chunk-wc9344hm.js +0 -2
- package/dist/chunk-zpy0gxqa.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{K,Ss,ks,Cs,n}from"./chunk-qrqw667n.js";import"./chunk-yp1360pq.js";import"./chunk-4zb2ga7p.js";import"./chunk-ff61d2wr.js";import"./chunk-mdgvzf07.js";import"./chunk-e124cgb6.js";import"./chunk-g84ctpqq.js";import"./chunk-cngtf95k.js";import"./chunk-a5kaw8sc.js";import"./chunk-6v1gwdbv.js";import"./chunk-r4199q6x.js";import"./chunk-b156xw15.js";import"./chunk-1xgs9gd5.js";export{K as injectRouterScript,n as processDirectives,Ss as processJsonDirective,ks as processOnceDirective,Cs as validateClientScript};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Qd,Pc,we,mi,eu,bs,ws,vs}from"./chunk-qrqw667n.js";import"./chunk-yp1360pq.js";import"./chunk-4zb2ga7p.js";import"./chunk-ff61d2wr.js";import"./chunk-mdgvzf07.js";import"./chunk-e124cgb6.js";import"./chunk-g84ctpqq.js";import"./chunk-cngtf95k.js";import"./chunk-a5kaw8sc.js";import"./chunk-6v1gwdbv.js";import"./chunk-r4199q6x.js";import"./chunk-b156xw15.js";import"./chunk-1xgs9gd5.js";export{eu as clearOnceStore,mi as onceStore,we as partialsCache,bs as processIncludes,ws as processStackPushDirectives,vs as processStackReplacements,Qd as resetUnscopedSignalWarnings,Pc as topLevelElements};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{X,wn,ne,P,Pt}from"./chunk-a5kaw8sc.js";import{tt,kn,pr,fr,gr,nt,rt,st,ot,it,at,Ce}from"./chunk-
|
|
2
|
+
import{X,wn,ne,P,Pt}from"./chunk-a5kaw8sc.js";import{tt,kn,pr,fr,gr,nt,rt,st,ot,it,at,Ce}from"./chunk-b156xw15.js";import{W,b,sn,on,e,_t,an,f,ze,Et,He,Ue,Q,N,le,K,d,we,hi,xs,n,r,te,Zn,o,A,de}from"./chunk-qrqw667n.js";import{Pe,lo,re,E,uo,Tr,In,he,po,se}from"./chunk-h0e3ps74.js";import{Dt}from"./chunk-whykvbys.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;
|
|
@@ -84,7 +84,7 @@ else {
|
|
|
84
84
|
return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
|
|
85
85
|
`,h=Function(m)();if(h)return h}catch(m){console.warn("Invalid sidebarConfig:",m)}}return{sections:[]}}let i=t.match(/@nativeSidebar\s*\(\s*(\{[\s\S]*?\})\s*\)/m);if(i)try{return JSON.parse(i[1])}catch{console.warn("Invalid @nativeSidebar configuration")}let p=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(p)try{let c=p[1].match(/(?:export\s+(?:default\s+)?|const\s+\w+\s*=\s*)(\{[\s\S]*\})/m);if(c)return Function(`return ${c[1]}`)()}catch(c){console.warn("Invalid native-sidebar script configuration:",c)}return}function Ht(){console.log(`
|
|
86
86
|
Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in browser`),console.log(` ${e.cyan}c${e.reset} + Enter - Clear console`),console.log(` ${e.cyan}q${e.reset} + Enter (or ${e.cyan}Ctrl+C${e.reset}) - Quit server`),console.log(` ${e.cyan}h${e.reset} + Enter - Show this help`)}function er(t){console.log(`${e.green}Server running at ${e.cyan}${t}${e.reset}`),console.log(`Press ${e.cyan}Ctrl+C${e.reset} to stop the server`),Ht()}function tr(t){console.log(`${e.dim}Opening ${e.cyan}${t}${e.dim} in your browser...${e.reset}`),Bun.spawn(["open",t],{stderr:"inherit"})}function Qe(t,s,i){if(!process.stdin.isTTY)return;process.stdin.setRawMode(!0),process.stdin.setEncoding("utf8"),process.stdin.resume(),Ht();let p="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(p+=c,p.endsWith("\r")||p.endsWith(`
|
|
87
|
-
`)){let l=p.trim().toLowerCase();p="",nr(l,t,s,i)}})}function nr(t,s,i,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else tr(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),er(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ht();break;default:break}}async function Ft(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=pt.resolve(t);if(!Bt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await de(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),C=s.markdown?.syntaxHighlighting||A.markdown?.syntaxHighlighting,v=C?.defaultTheme||"github-dark",x=["github-dark"],T=C?.additionalThemes||[],H=[...new Set([...x,...T])].map((
|
|
87
|
+
`)){let l=p.trim().toLowerCase();p="",nr(l,t,s,i)}})}function nr(t,s,i,p){switch(t){case"o":if(p?.onOpen)p.onOpen();else tr(s);break;case"c":if(p?.onClear)p.onClear();else console.clear(),er(s);break;case"q":if(p?.onQuit)p.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(p?.onHelp)p.onHelp();else Ht();break;default:break}}async function Ft(t,s={}){let i=s.port||3000,p=s.watch!==!1,c=pt.resolve(t);if(!Bt.existsSync(c))return console.error(`${e.red}Error: File not found: ${e.bright}${c}${e.reset}`),!1;if(!c.endsWith(".md"))return console.error(`${e.red}Error: File must have .md extension: ${e.bright}${c}${e.reset}`),!1;console.log(`${e.blue}Processing${e.reset} ${e.bright}${t}${e.reset}...`);let l=null,m=async()=>{try{let{content:w,data:S}=await de(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),C=s.markdown?.syntaxHighlighting||A.markdown?.syntaxHighlighting,v=C?.defaultTheme||"github-dark",x=["github-dark"],T=C?.additionalThemes||[],H=[...new Set([...x,...T])].map((_)=>`<option value="${_}"${_===v?" selected":""}>${_}</option>`).join(`
|
|
88
88
|
`);return l=`
|
|
89
89
|
<!DOCTYPE html>
|
|
90
90
|
<html lang="en">
|
|
@@ -457,7 +457,7 @@ else {
|
|
|
457
457
|
`).filter((y)=>y.length>120);if(h.length>0)i.push({type:"info",category:"maintainability",message:`Found ${h.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let g=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(g>3)i.push({type:"info",category:"maintainability",message:`Found ${g} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return i}function lr(t,s){let i=[];if(s.complexity>7)i.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(s.complexity>5&&s.directives.total>8)i.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(s.lines>100&&s.components===0)i.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(s.expressions>20)i.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let p=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(p&&p.length>0)i.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(s.directives.total===0&&s.expressions<5)i.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(s.scriptLines>50)i.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return i}function dr(t,s){let i=1;if(i+=s.directives.conditionals*0.1,i+=s.directives.loops*0.5,i+=s.directives.includes*2,i+=s.expressions*0.05,i+=s.components*1,s.scriptLines>10)i+=s.scriptLines*0.1;let p;if(s.expressions===0&&s.directives.total===0)p="high";else if(s.expressions<5&&s.directives.total<3)p="medium";else p="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(p==="low"&&s.directives.total>5)c.push("Reduce dynamic content for better caching");if(s.components===0&&s.lines>40)c.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(i*100)/100,complexityScore:s.complexity,cacheability:p,recommendations:c}}function Qt(t,s,i){let p=t.replace(/<!--[\s\S]*?-->/g,""),c=(p.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(p.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function Js(t=["**/*.stx"],s){let i=[],p=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));p.push(...m.filter((u)=>u.endsWith(".stx")))}for(let l of p)try{let m=await ir(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=ur(i);return{results:i,summary:c}}function ur(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),p=s>0?t.reduce((g,y)=>g+y.metrics.complexity,0)/s:0,c=t.reduce((g,y)=>g+y.issues.length,0),l={};t.forEach((g)=>{g.issues.forEach((y)=>{l[y.category]=(l[y.category]||0)+1})});let m=s>0?t.reduce((g,y)=>g+y.performance.estimatedRenderTime,0)/s:0,u=Math.max(1,Math.min(10,Math.round(10-m/2-p/2))),h=[];if(p>6)h.push("Project has high average complexity. Consider refactoring complex templates.");if(c>s*2)h.push("High number of issues detected. Run detailed analysis on individual files.");if(l.security>0)h.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:s,totalLines:i,avgComplexity:Math.round(p*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:u,recommendations:h}}import{mkdir as mr,readFile as hr,readdir as yr,stat as Zt,writeFile as br}from"fs/promises";import Oe from"path";function ln(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var dn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Sr(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((s)=>s.charAt(0).toUpperCase()+s.slice(1)).join("")}function Ut(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function kr(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function $r(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function Cr(t){let s=[];async function i(p){let c=await yr(p,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Oe.join(p,l.name);if(l.isDirectory()){if(!l.name.startsWith(".")&&l.name!=="node_modules")await i(m)}else if(l.isFile()&&l.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(l.name))s.push(m)}}return await i(t),s}function Rr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let p=i[1].trim();if(!p)return{};try{return JSON.parse(p)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function Er(t,s){let i={},p=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of p){if(!/\bclient\b/i.test(c[1])||/\bcomponent\b|\bstx:component\b/i.test(c[1]))continue;let l;try{l=new Bun.Transpiler({loader:"ts"}).transformSync(c[2])}catch(h){throw Error(`${s}: failed to transpile <script client> (${h.message})`)}let m=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,u;while(u=m.exec(l)){let h=u[1];if(dn.has(h))throw Error(`${s}: client ${ln(h)}`);let g=m.lastIndex,y=1,w="",S=!1,C=g;for(;C<l.length&&y>0;C++){let x=l[C];if(S){S=!1;continue}if(w){if(x==="\\")S=!0;else if(x===w)w="";continue}if(x==='"'||x==="'"||x==="`")w=x;else if(x==="{")y++;else if(x==="}")y--}if(y!==0)throw Error(`${s}: unterminated client function "${h}"`);let v=u[0].includes("async")?"async ":"";i[h]=`${v}${h}(${u[2]}) {${l.slice(g,C-1)}}`,m.lastIndex=C}}return i}function Pr(t){let s=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(s?s[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function en(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
|
|
458
458
|
|
|
459
459
|
`)}function Or(t){if(!t)return null;let s=t.replace(/\s*\|\s*(?:undefined|null)\b/g,"").trim();if(/^string$/.test(s))return"string";if(/^number$/.test(s))return"number";if(/^boolean$/.test(s))return"boolean";if(/^(?:'[^']*'|"[^"]*")(?:\s*\|\s*(?:'[^']*'|"[^"]*"))*$/.test(s))return"string";return"object"}function Ar(t){if(t===void 0)return"object";if(t==="true"||t==="false")return"boolean";if(/^-?\d+(?:\.\d+)?$/.test(t))return"number";if(/^['"`]/.test(t))return"string";return"object"}function Dr(t){if(t==="true")return!0;if(t==="false")return!1;if(/^-?\d+(?:\.\d+)?$/.test(t))return Number(t);if(/^['"`]/.test(t))return t.slice(1,-1);try{return JSON.parse(t)}catch{return}}function Mr(t){let s=[],i=0,p=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(h)=>{if(p[h]!=="(")return null;let g=0,y="";for(let w=h;w<p.length;w++){let S=p[w];if(y!==""){if(S==="\\")w++;else if(S===y)y="";continue}if(S==="'"||S==='"'||S==="`"){y=S;continue}if(S==="(")g++;else if(S===")"){if(g--,g===0)return{expression:p.slice(h+1,w),end:w+1}}}return null},u=(h)=>{if(h==="")return;let g=0,y=/\{!!\s*([\s\S]*?)\s*!!\}|\{\{\s*([\s\S]*?)\s*\}\}/g,w;while(w=y.exec(h)){if(w.index>g)s.push(`out += ${JSON.stringify(h.slice(g,w.index))};`);s.push(w[1]!==void 0?`out += __raw(${w[1]});`:`out += __escape(${w[2]});`),g=w.index+w[0].length}if(g<h.length)s.push(`out += ${JSON.stringify(h.slice(g))};`)};while(l=c.exec(p)){u(p.slice(i,l.index)),i=l.index+l[0].length;let g=l[1]==="if"||l[1]==="elseif"||l[1]==="foreach"?m(i):null;if(g)i=g.end,c.lastIndex=g.end;let y=g?.expression;switch(l[1]){case"if":s.push(`if (${y}) {`);break;case"elseif":s.push(`} else if (${y}) {`);break;case"else":s.push("} else {");break;case"endif":case"endforeach":s.push("}");break;case"foreach":{let w=/^([\s\S]+?)\s+as\s+(?:([A-Za-z_$][\w$]*)\s*=>\s*)?([A-Za-z_$][\w$]*)$/.exec((y||"").trim());if(!w){s.push(`out += ${JSON.stringify(l[0]+(g?`(${y})`:""))};`);break}let[,S,C,v]=w;s.push(C?`for (const [${C}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return u(p.slice(i)),s.join(`
|
|
460
|
-
`)}function Rt(t,s,i,p){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===i)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function zt(t,s,i){let p=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,u=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(u){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===u)u=null;continue}if(y==="'"||y==='"'||y==="`"){u=y,h+=y;continue}if(p.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function _r(t){let s=0,i=null;for(let p=0;p<t.length;p++){let c=t[p];if(i){if(c==="\\"){p++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function tn(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function Lr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),h=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=Rt(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(h(),t[u]!=="=")return null;u++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(y);if(y)u+=y[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let C="";if(h(),t[u]==="<"){let k=Rt(t,u,"<",">");if(k===-1)return null;C=t.slice(u+1,k-1).trim(),u=k}if(h(),t[u]!=="(")return null;let v=Rt(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(h(),t[u]===",")u++,h();if(t[u]==="{"){let k=Rt(t,u,"{","}");if(k===-1)return null;for(let[H,
|
|
460
|
+
`)}function Rt(t,s,i,p){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let u=t[m];if(l){if(u==="\\"){m++;continue}if(u===l)l=null;continue}if(u==="'"||u==='"'||u==="`"){l=u;continue}if(u===i)c++;else if(u===p){if(p===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function zt(t,s,i){let p=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,u=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(u){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===u)u=null;continue}if(y==="'"||y==='"'||y==="`"){u=y,h+=y;continue}if(p.includes(y))m++;else if(c.includes(y))m--;if(m===0&&s.includes(y)){l.push(h),h="";continue}h+=y}return l.push(h),l.map((g)=>g.trim()).filter(Boolean)}function _r(t){let s=0,i=null;for(let p=0;p<t.length;p++){let c=t[p];if(i){if(c==="\\"){p++;continue}if(c===i)i=null;continue}if(c==="'"||c==='"'||c==="`"){i=c;continue}if("([{".includes(c))s++;else if(")]}".includes(c))s--;if(s!==0||c!=="=")continue;let l=t[p-1];if(t[p+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return p}return-1}function tn(t){switch(t.trim()){case"String":return"string";case"Number":return"number";case"Boolean":return"boolean";case"Array":return"unknown[]";case"Object":return"Record<string, unknown>";default:return}}function Lr(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,p=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))p=k.index+k[0].indexOf(k[1]);if(p===-1)return null;let c={},l={},m=[],u=p+(/^(?:const|let|var)\s+/.exec(t.slice(p))?.[0].length??0),h=()=>{while(u<t.length&&/\s/.test(t[u]))u++},g;if(t[u]==="{"){let k=Rt(t,u,"{","}");if(k===-1)return null;g=t.slice(u,k),u=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(u));if(!k)return null;g=k[0],u+=k[0].length}if(h(),t[u]!=="=")return null;u++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(u)),w=Boolean(y);if(y)u+=y[0].length;let S=/^defineProps\b/.exec(t.slice(u));if(!S)return null;u+=S[0].length;let C="";if(h(),t[u]==="<"){let k=Rt(t,u,"<",">");if(k===-1)return null;C=t.slice(u+1,k-1).trim(),u=k}if(h(),t[u]!=="(")return null;let v=Rt(t,u,"(",")");if(v===-1)return null;let x=t.slice(u+1,v-1).trim();if(u=v,w){if(h(),t[u]===",")u++,h();if(t[u]==="{"){let k=Rt(t,u,"{","}");if(k===-1)return null;for(let[H,_]of Nt(t.slice(u,k)))l[H]=_;u=k}if(h(),t[u]===",")u++,h();if(t[u]===")")u++}if(t[u]===";")u++;let T=/^[A-Za-z_$][\w$]*$/.test(C)?C:void 0;if(C.startsWith("{"))for(let k of zt(C.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let H=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(H)c[H[1]]=H[2].trim()}if(x.startsWith("{"))for(let[k,H]of Nt(x)){if(m.push(k),!H.startsWith("{")){let _=tn(H);if(_)c[k]=_;continue}for(let[_,I]of Nt(H))if(_==="default")l[k]=I;else if(_==="type"){let R=tn(I);if(R)c[k]=R}}else if(x.startsWith("["))for(let k of zt(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of zt(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let H=_r(k),I=(H===-1?k:k.slice(0,H)).split(":")[0].trim().replace(/^\.\.\./,"");if(!I)continue;if(m.push(I),H!==-1)l[I]=k.slice(H+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(p,u),propNames:m,defaults:l,declared:c,typeName:T}}function Nt(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],p=0;while(p<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=p;let l=c.exec(s);if(!l)break;p=c.lastIndex;let m=0,u="",h=p;while(p<s.length){let y=s[p];if(u){if(y==="\\")p++;else if(y===u)u=""}else if(y==="'"||y==='"'||y==="`")u=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;p++}let g=s.slice(h,p).trim();if(g)i.push([l[1],g]);p++}return i}function Ir(t,s,i){let c=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)].find((S)=>!/\bcomponent\b|\bstx:component\b|\bclient\b/i.test(S[1]));if(!c)return{imports:[],body:"",propNames:[],defaults:{},declared:{}};let l=c[2],m=[],u=[],h={},g={};l=l.replace(/^\s*import\s+[\s\S]*?from\s*['"][^'"]+['"];?\s*$/gm,(S)=>{if(/from\s*['"]stx['"]/.test(S))return"";return m.push(S.trim().replace(/(from\s*['"])(\.[^'"]*)(['"])/,(C,v,x,T)=>{let k=Oe.resolve(Oe.dirname(s),x),H=Oe.relative(i,k);return`${v}${H.startsWith(".")?H:`./${H}`}${T}`})),""});let y=Lr(l);if(y)u.push(...y.propNames),Object.assign(h,y.defaults),Object.assign(g,y.declared),l=l.replace(y.text,"");let w={};for(let S of l.matchAll(/(?:export\s+)?interface\s+([A-Za-z_$][\w$]*)\s*\{([\s\S]*?)\n\}/g)){let C=[];for(let v of S[2].matchAll(/^\s*(?:\/\*\*[\s\S]*?\*\/\s*)?([A-Za-z_$][\w$]*)\??\s*:\s*([^\n;]+)/gm))g[v[1]]=v[2].trim(),C.push(v[1]);w[S[1]]=C}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!u.includes(S))u.push(S)}return l=l.replace(/(?:export\s+)?interface\s+[A-Za-z_$][\w$]*\s*\{[\s\S]*?\n\}/g,""),{imports:m,body:l.trim(),propNames:u,defaults:h,declared:g}}function jr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(p,c,l,m,u)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${u}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function Hr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(p,c,l,m)=>{let u=s.length;return s.push({id:u,name:c,expression:m}),` data-stx-bind-${u}=""`}),bindings:s}}function Br(t){let s=new Set;for(let i of t.matchAll(/<slot\b([^>]*)>/gi))s.add(i[1].match(/\bname\s*=\s*["']([^"']+)["']/i)?.[1]||"");return[...s].map((i)=>({name:i}))}function Fr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function nn(t,s){if(!s||!new Set(["string","number","boolean","object","array"]).has(s.type))throw Error(`Property "${t}" must declare one of: string, number, boolean, object, array`);return{...s,reflect:s.reflect??s.attribute!==!1}}async function zr(t,s,i){let p=Oe.isAbsolute(s.file)?s.file:Oe.resolve(t,s.file),c=await hr(p,"utf8"),l=Rr(c,p),m=Oe.basename(p,".stx"),u=s.name||l.name||Sr(m),h=`${Ut(i.prefix||"stx")}-${Ut(m)}`,g=s.tag||l.tag||h;if(!u||!/^[A-Za-z_$][\w$]*$/.test(u))throw Error(`${p}: invalid component class name "${u}"`);if(!kr(g))throw Error(`${p}: invalid custom-element tag "${g}"; tags must be lowercase and contain a hyphen`);let y=s.properties||l.properties||l.props||{},w=Object.fromEntries(Object.entries(y).map(([_,I])=>[_,nn(_,I)])),S=jr(Pr(c)),C=Hr(S.template),v=Ir(c,p,Oe.resolve(i.outputDir)),x=Mr(C.template);for(let _ of v.propNames){if(w[_])continue;let I=v.defaults[_];w[_]=nn(_,{type:Or(v.declared[_])??Ar(I),...I===void 0?{}:{default:Dr(I)}})}let T=l.methods||{},k=s.methods||{},H=Er(c,p);return{file:Oe.relative(t,p),sourcePath:p,name:u,tag:g,description:s.description||l.description||"",template:C.template,styles:en(c),shadowMode:$r(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...T,...k,...H},eventTypes:S.eventTypes,bindings:C.bindings,slots:Br(C.template),cssProperties:Fr(en(c)),scope:v,render:x}}function Nr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
|
|
461
461
|
|
|
462
462
|
const escapeHTML = (value) => String(value ?? '')
|
|
463
463
|
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
@@ -872,7 +872,7 @@ export declare function renderComponent(tag: string, props?: Record<string, unkn
|
|
|
872
872
|
${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
|
|
873
873
|
`)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(qr(l),null,2));let S;if(t.css!==!1){let x=l.filter((T)=>!T.shadowMode&&T.styles).map(rn).join(`
|
|
874
874
|
|
|
875
|
-
`);if(x)S=await g("bundle.css",t.minify?cn(x):x)}let C;if(t.bundle!==!1){C=Oe.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Oe.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(T){let k=T instanceof AggregateError?T.errors:[T],H=k.map((
|
|
875
|
+
`);if(x)S=await g("bundle.css",t.minify?cn(x):x)}let C;if(t.bundle!==!1){C=Oe.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Oe.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(T){let k=T instanceof AggregateError?T.errors:[T],H=k.map((_)=>String(_).trim()).filter(Boolean).join(`
|
|
876
876
|
`);throw AggregateError(k,`Failed to bundle component library${H?`
|
|
877
877
|
${H}`:""}`)}if(!x.success){let T=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
|
|
878
878
|
`);throw AggregateError(x.logs,`Failed to bundle component library${T?`
|
|
@@ -1046,7 +1046,7 @@ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,u)=>{let h=u.substring(Math.max
|
|
|
1046
1046
|
`),s=s.split(`
|
|
1047
1047
|
`).map((c)=>c.trim()).join(`
|
|
1048
1048
|
`),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function co(t,s){let p=ao(t).split(`
|
|
1049
|
-
`),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<p.length;h++){let g=p[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let C=y===">";if(un(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(u.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),T=y.startsWith("@")&&go(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),H=y.startsWith("<!--"),
|
|
1049
|
+
`),c=[],l=0,m=!1,u=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<p.length;h++){let g=p[h],y=g.trim();if(y===""){c.push("");continue}let w=y.match(/<script\b/i),S=y.match(/<\/script>/i);if(m&&!S){c.push(g);continue}let C=y===">";if(un(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(u.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),T=y.startsWith("@")&&go(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),H=y.startsWith("<!--"),_=y.startsWith("</"),I=y.startsWith("<")&&!_&&!H&&!k,R=y.includes("/>")||mo(y),L=un(y);if(_||v)l=Math.max(0,l-1);let B=x?Math.max(0,l-1):l;if(C)c.push(g);else c.push(u.repeat(B)+y);if(I&&!R&&!L&&!C||T)l++;if(w)m=!0;if(S)m=!1}return c.join(`
|
|
1050
1050
|
`)}function fo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,p,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${p}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,p,c)=>{if(c.trim()==="")return`@${p}`;return`@${p}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,p)=>`{{ ${p.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,p)=>`{!! ${p.trim()} !!}`);return t}function mo(t){let s=["br","hr","img","input","meta","link","area","base","col","embed","source","track","wbr"];if(t.includes("/>"))return!0;let i=t.match(/<(\w+)/);if(i){let p=i[1];return s.includes(p.toLowerCase())}return!1}function un(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function go(t){let s=["if","unless","foreach","for","while","section","push","component","slot","markdown","wrap","error"];for(let i of s)if(t.startsWith(`@${i}`))return!t.includes(`@end${i}`);return!1}function ho(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,p,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
|
|
1051
1051
|
`)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],u;while((u=l.exec(c))!==null)m.push({name:u[1],value:u[2]});m.sort((g,y)=>{if(g.name==="id")return-1;if(y.name==="id")return 1;if(g.name==="class")return-1;if(y.name==="class")return 1;return g.name.localeCompare(y.name)});let h=m.map((g)=>g.value?`${g.name}=${g.value}`:g.name).join(" ");return`<${p}${h?` ${h}`:""}>`})}import mn from"fs";import Vt from"path";async function eo(t="index.stx",s={}){try{let i=s.force||!1,p=Vt.resolve(process.cwd(),t);if(await Bun.file(p).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Vt.dirname(p);if(!mn.existsSync(c))mn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=Vt.resolve(process.cwd(),s.template);if(!await Bun.file(m).exists())throw Error(`Template file ${s.template} does not exist.`);if(!m.endsWith(".stx"))console.warn(`Warning: Template file ${s.template} does not have a .stx extension. Using it anyway.`);l=await Bun.file(m).text(),console.warn(`Using template from ${s.template}`)}else if(s.preset)l=gn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=gn("basic");return await Bun.write(p,l),console.warn(`Created new stx file: ${t}`),!0}catch(i){return console.error(`Error creating file: ${i instanceof Error?i.message:String(i)}`),!1}}function gn(t){switch(t){case"basic":return hn();case"component":return yo();case"layout":return bo();case"blog":return xo();case"api":return vo();case"app":return wo();default:return hn()}}function hn(){return`<script>
|
|
1052
1052
|
const title = "My stx Page"
|
|
@@ -1785,8 +1785,8 @@ else {
|
|
|
1785
1785
|
|
|
1786
1786
|
})()
|
|
1787
1787
|
</script>
|
|
1788
|
-
`;import _e from"fs";import Te from"path";function
|
|
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="",
|
|
1788
|
+
`;import _e from"fs";import Te from"path";function On(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 An(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 Dn=["@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 Dn){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 Dn){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 vr(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=An(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=On(h),w=g?On(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 xr(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="",_=[];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 _.push(R)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:_}}),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-3220kken.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,12 +1849,12 @@ ${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
|
|
1852
|
+
</html>`,loader:"html"}}})}};async function En(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 _t(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-j1jh32tw.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-tgfpk4ng.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-550whbab.js"),_=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 _(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(`
|
|
1856
1856
|
${e.yellow}Routes:${e.reset}`);let R=Se.relative(process.cwd(),u);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${R}${e.reset}`),console.log(`
|
|
1857
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(I.url.toString(),()=>{if(p)Fe.watch(Se.dirname(u),{recursive:!0}).close();I.stop()}),s.native){let L=await Bun.file(u).text(),B=St(L);await dt(C,{title:Se.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(p){let L=Se.dirname(u);console.log(`${e.blue}Watching ${e.bright}${L}${e.reset} for changes...`);let B=Fe.watch(L,{recursive:!0},async(G,ee)=>{if(!ee||$t(ee))return;if(Tt(ee)){console.log(`${e.yellow}File ${e.bright}${ee}${e.yellow} changed, rebuilding...${e.reset}`),we.clear(),te();let $e=await y();if(await an(S),c&&l)if($e)l.reload(ee);else l.error("Build failed - check console for details")}else if(kt(ee)){if(console.log(`${e.cyan}CSS ${e.bright}${ee}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(ee)}});process.on("SIGINT",()=>{if(B.close(),l)ht();I.stop(),process.exit(0)})}return!0}var{serve:zi}=globalThis.Bun;import Ze from"fs";import Ae from"path";function Vn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Ae.sep)),i=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))i.push(c);else break}return i.join(Ae.sep)}async function Tn(t,s={}){let i=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Ae.resolve(v);if(!Ze.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");Ze.mkdirSync(c,{recursive:!0});let l=Vn(t.map((v)=>Ae.dirname(Ae.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],h=async()=>{try{for(let v of t){let x=Ae.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:H}=await de(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),
|
|
1857
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(I.url.toString(),()=>{if(p)Fe.watch(Se.dirname(u),{recursive:!0}).close();I.stop()}),s.native){let L=await Bun.file(u).text(),B=St(L);await dt(C,{title:Se.basename(u,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(p){let L=Se.dirname(u);console.log(`${e.blue}Watching ${e.bright}${L}${e.reset} for changes...`);let B=Fe.watch(L,{recursive:!0},async(G,ee)=>{if(!ee||$t(ee))return;if(Tt(ee)){console.log(`${e.yellow}File ${e.bright}${ee}${e.yellow} changed, rebuilding...${e.reset}`),we.clear(),te();let $e=await y();if(await an(S),c&&l)if($e)l.reload(ee);else l.error("Build failed - check console for details")}else if(kt(ee)){if(console.log(`${e.cyan}CSS ${e.bright}${ee}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(ee)}});process.on("SIGINT",()=>{if(B.close(),l)ht();I.stop(),process.exit(0)})}return!0}var{serve:zi}=globalThis.Bun;import Ze from"fs";import Ae from"path";function Vn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((p)=>p.split(Ae.sep)),i=[];for(let p=0;p<s[0].length;p++){let c=s[0][p];if(s.every((l)=>l[p]===c))i.push(c);else break}return i.join(Ae.sep)}async function Tn(t,s={}){let i=s.port||3000,p=s.watch!==!1;for(let v of t){let x=Ae.resolve(v);if(!Ze.existsSync(x))return console.error(`${e.red}Error: File not found: ${e.bright}${x}${e.reset}`),!1;if(!x.endsWith(".stx")&&!x.endsWith(".md"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${x}${e.reset}. Only .stx and .md files are supported.`),!1}let c=a(process.cwd(),"output");Ze.mkdirSync(c,{recursive:!0});let l=Vn(t.map((v)=>Ae.dirname(Ae.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},u=[],h=async()=>{try{for(let v of t){let x=Ae.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:H}=await de(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:A.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),_=s.markdown?.syntaxHighlighting||A.markdown?.syntaxHighlighting,I=_?.defaultTheme||"github-dark",R=["github-dark"],L=_?.additionalThemes||[],G=[...new Set([...R,...L])].map((De)=>`<option value="${De}"${De===I?" selected":""}>${De}</option>`).join(`
|
|
1858
1858
|
`),ee=`
|
|
1859
1859
|
<!DOCTYPE html>
|
|
1860
1860
|
<html lang="en">
|
|
@@ -2018,16 +2018,16 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(I.u
|
|
|
2018
2018
|
</body>
|
|
2019
2019
|
</html>
|
|
2020
2020
|
`,ye=`/${Ae.relative(l,x).replace(/\.md$/,"")}`;if(ye.endsWith("/index"))ye=ye.slice(0,-6)||"/";m[ye||"/"]={filePath:x,content:ee,fileType:"md"}}catch(k){console.error(`${e.red}Error processing Markdown file ${e.bright}${v}${e.reset}:`,k);continue}else{let k={name:"public-assets",setup(R){R.onResolve({filter:/^\/(images|fonts|assets|public)\//},(L)=>({path:L.path,external:!0}))}},H;try{let R=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,ft],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!R.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,ce(R.logs,x));continue}let L=R.outputs.find((B)=>B.path.endsWith(".html"));if(!L){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}H=await Bun.file(L.path).text()}catch(R){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
|
|
2021
|
-
${ce(R,x)}`);continue}let I=`/${Ae.relative(l,x).replace(/\.stx$/,"")}`;if(I.endsWith("/index"))I=I.slice(0,-6)||"/";if(I.includes("[")){let{regex:R,params:L}=pr(I,{page:!0});u.push({pattern:R,paramNames:L,filePath:x,routeTemplate:I,fileType:"stx"}),m[I]={filePath:x,content:H,fileType:"stx"}}else m[I||"/"]={filePath:x,content:H,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,ce(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=zi({port:y,async fetch(v){let x=new URL(v.url),T=Ae.join(process.cwd(),"public",x.pathname);if(Ze.existsSync(T)&&Ze.statSync(T).isFile()){let
|
|
2022
|
-
</head>`);else B=G+B;k={...R,content:B}}break}}if(k)return f(k.content).then((
|
|
2023
|
-
</head>`);return new Response(
|
|
2021
|
+
${ce(R,x)}`);continue}let I=`/${Ae.relative(l,x).replace(/\.stx$/,"")}`;if(I.endsWith("/index"))I=I.slice(0,-6)||"/";if(I.includes("[")){let{regex:R,params:L}=pr(I,{page:!0});u.push({pattern:R,paramNames:L,filePath:x,routeTemplate:I,fileType:"stx"}),m[I]={filePath:x,content:H,fileType:"stx"}}else m[I||"/"]={filePath:x,content:H,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,ce(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ye(i),y!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${y} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${y}/${e.reset}...`);let w=zi({port:y,async fetch(v){let x=new URL(v.url),T=Ae.join(process.cwd(),"public",x.pathname);if(Ze.existsSync(T)&&Ze.statSync(T).isFile()){let _=Bun.file(T),I=Ae.extname(T).toLowerCase(),R="application/octet-stream";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await _.text(),G=L.transformSync(B);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":R}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let _ of u){let I=x.pathname.match(_.pattern);if(I){let R=m[_.routeTemplate];if(R){let L={};for(let ee=0;ee<_.paramNames.length;ee++)L[_.paramNames[ee]]=decodeURIComponent(I[ee+1]);let B=R.content,G=`<script>window.__routeParams = ${JSON.stringify(L)};</script>`;if(B.includes("</head>"))B=B.replace("</head>",`${G}
|
|
2022
|
+
</head>`);else B=G+B;k={...R,content:B}}break}}if(k)return f(k.content).then((_)=>{if(_.includes("</head>"))_=_.replace("</head>",`${yn}
|
|
2023
|
+
</head>`);return new Response(_,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let H=Ae.join(c,x.pathname);if(Ze.existsSync(H)&&Ze.statSync(H).isFile()){let _=Bun.file(H),I=Ae.extname(H).toLowerCase(),R="text/plain";if(I===".ts"||I===".tsx"){let L=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await _.text(),G=L.transformSync(B);return new Response(G,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){case".html":R="text/html";break;case".css":R="text/css";break;case".js":R="text/javascript";break;case".json":R="application/json";break;case".png":R="image/png";break;case".jpg":case".jpeg":R="image/jpeg";break;case".gif":R="image/gif";break;case".svg":R="image/svg+xml";break;case".ico":R="image/x-icon";break;case".woff":R="font/woff";break;case".woff2":R="font/woff2";break;case".ttf":R="font/ttf";break;case".otf":R="font/otf";break;case".eot":R="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":R}})}if(x.pathname!=="/"&&m["/"]){let _=re(v);return f(m["/"].content).then((I)=>{if(_){let R=I.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(R){let L=I.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=L?L[1]:"",G=`<!DOCTYPE html><html><head><title>${Wn(B)}</title></head><body><main>${R[1]}</main></body></html>`;return new Response(G,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...E(),"Cache-Control":Pe,Pragma:"no-cache",Expires:"0"}})}}return new Response(I,{headers:{"Content-Type":"text/html",...E(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})})}return new Response("Not Found",{status:404})},error(v){return new Response(`<pre>${v}
|
|
2024
2024
|
${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
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-n7f2c5vf.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-nd7p8f5p.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 Tr(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-n7f2c5vf.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-tgfpk4ng.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=fr(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-n7f2c5vf.js"),{checkCache:oe,cacheTemplate:Z,readFileCached:q,templateCache:J}=await import("./chunk-96fpvzm2.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-n7f2c5vf.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-gmp7apxp.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-qx9s066f.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-zfypzka2.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]:xs(),..._(),"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-qx9s066f.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
|
-
${
|
|
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 Et(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-j1jh32tw.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-550whbab.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((O)=>xe.existsSync(O)))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||[],_=[];for(let{dir:O,prefix:F}of H)if(xe.existsSync(O)){let z=N(ie.dirname(O),{pagesDir:ie.basename(O)});for(let V of z){let ve=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;_.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 Tr(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:O}=await import("./chunk-j1jh32tw.js"),F=await O(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-tgfpk4ng.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(O)=>{let F=fr(T,O);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(O,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:ve,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-j1jh32tw.js"),{checkCache:oe,cacheTemplate:Z,readFileCached:q,templateCache:J}=await import("./chunk-49ms9skq.js"),ke=await We(u),Je=(pe)=>{if(!pe)return pe;if(ie.isAbsolute(pe))return pe;return ie.resolve(u,pe)},M={...ve,...ke,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Je(M.partialsDir),M.componentsDir=Je(M.componentsDir),M.layoutsDir=Je(M.layoutsDir),M.storesDir=Je(M.storesDir||"stores"),M.cachePath=Je(M.cachePath)??a(u,"cache");let be=!F&&!s.profile,ue=M.cache!==!1;if(ue&&be){let pe=J.get(O.filePath);if(pe)try{if((await xe.promises.stat(O.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(O.filePath);return{route:O,content:Ee,status:gt?.status??await qn(O.filePath),headers:gt?.headers}}}}catch{}let Ie=await oe(O.filePath,M);if(Ie){let je=Ie;if(R)je=he(je,{preserveHead:!0});let Be=U.get(O.filePath);return{route:O,content:je,status:Be?.status??await qn(O.filePath),headers:Be?.headers}}}let ge=ue?await q(O.filePath):await Bun.file(O.filePath).text(),Re=Et(ge),{classifyAllScripts:Y}=await import("./chunk-j1jh32tw.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:O.filePath,__dirname:ie.dirname(O.filePath),__stx_options:M,params:F??{},__stx_runtime_head:{}};for(let pe of Ve)try{await V(pe,me,O.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let Ke=new Set,Me;if(s.profile){let pe=performance.now();Me=await z(fe,me,O.filePath,M,Ke);let Ie=performance.now()-pe,je=ie.relative(u,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Me=await z(fe,me,O.filePath,M,Ke);if(!R)Me=await Ge(Me,{router:M.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-3220kken.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(O.filePath,Me,Ke,M);let{extractStreamBoundaries:Kn}=await import("./chunk-29r6af6f.js"),lt=Kn(me),mt=me.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let pe=me.streamBoundaries||{},Ie={...M,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},O.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(O.pattern);else lt=void 0;let Kt=He(me),Xt=Ue(me);if(be)U.set(O.filePath,{status:Kt,headers:Xt});return{route:O,content:Me,status:Kt??Re,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,z),null}},Ne=8,qe=async()=>{ye.clear(),I.clear();for(let O=0;O<k.length;O+=Ne){let F=k.slice(O,O+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 O=0;O<_.length;O+=Ne){let F=_.slice(O,O+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 _t(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 O=s.hmrPort||et+1;l=Ct({wsPort:O,verbose:!1}),m=l.start(O)}let Lt=(O,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(O.includes("</head>"))return O.replace("</head>",`${V}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+O};console.log(`${e.blue}Starting server...${e.reset}`);let It=Ni({port:et,async fetch(O){let F=new URL(O.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((M)=>w(M,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 M=decodeURIComponent(F.pathname.slice(16));if(M)try{let be=`<${M} />`,ue={...buildConfig,autoShell:!1},ge=await processDirectives(be,{},ie.join(u,"components",`${M}.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:M}=await import("./chunk-zfypzka2.js"),be=await M(O,{publicDir:ie.join(u,z),cacheDir:a(u,"cache","img")});if(be)return be}if(ee)try{let M=await ee.handleRequest(O);if(M.status!==404)return M}catch{}if(G[F.pathname])try{return await G[F.pathname](O)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await C(O);if(q)return q;let J=kn(F.pathname,k);if(J){let M=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)M=ue}if(M){let ue=M.status??200,ge=M.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,O,{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>`;M.content=M.content.replace("</head>",`${me}</head>`)}}let Y=M.content;if(R&&po(O)){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]:xs(),...E(),"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(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-29r6af6f.js");return Ve(Le(Y,M.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",...E(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...ge}})}}if(_.length>0){let M=_.map((ue)=>ue.route),be=kn(F.pathname,M);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 M=ke.content;if(M=await f(M,u),c)M=Xe(M,m);if(s.native)if(M.includes("<head>"))M=M.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else M="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+M;return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await ae(404);if(Je){let M=Je;if(M=await f(M,u),c)M=Xe(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let F=await ae(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
|
|
2029
|
+
${O.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
|
-
${e.yellow}Routes:${e.reset}`);let jt=[...gr(k,u)];for(let{route:
|
|
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
|
|
2032
|
+
${e.yellow}Routes:${e.reset}`);let jt=[...gr(k,u)];for(let{route:O}of _)jt.push(`${O.pattern}`);if(jt.forEach((O,F)=>{let V=F===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${O}`)}),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 O,F=ie.join(T,"index.stx");if(xe.existsSync(F)){let V=await Bun.file(F).text();O=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:!!O,sidebarConfig:O})}if(p){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(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(O(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-49ms9skq.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 Tr(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-49ms9skq.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,wr,Qs,eo,to,Xi,Ji,vr,xr,En,Tn,$n};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{d,hs,pi,fi,Ic,Oc,Dc,Mc,Nc,Lc,qe,L,Ge,jc,Jn,Bc,yi,Fc,Ke,r,Yn,bi,g,te,tu}from"./chunk-
|
|
2
|
+
import{d,hs,pi,fi,Ic,Oc,Dc,Mc,Nc,Lc,qe,L,Ge,jc,Jn,Bc,yi,Fc,Ke,r,Yn,bi,g,te,tu}from"./chunk-qrqw667n.js";import"./chunk-yp1360pq.js";import"./chunk-4zb2ga7p.js";import"./chunk-ff61d2wr.js";import"./chunk-mdgvzf07.js";import"./chunk-e124cgb6.js";import"./chunk-g84ctpqq.js";import"./chunk-cngtf95k.js";import"./chunk-a5kaw8sc.js";import"./chunk-6v1gwdbv.js";import"./chunk-r4199q6x.js";import"./chunk-b156xw15.js";import"./chunk-1xgs9gd5.js";export{te as clearComponentCache,Fc as componentClientSignalNames,hs as convertToCommonJS,g as createDetailedErrorMessage,Nc as extractDirectiveNames,pi as extractScriptFromTemplate,d as extractVariables,r as fileExists,tu as getComponentCacheStats,Oc as getPositionInfo,L as getSharedTranspiler,bi as getSourceLineInfo,Mc as hasDirectives,fi as hasVariables,Bc as isHydrateTrigger,Lc as isJavaScriptScript,Ke as renderComponentWithSlot,Yn as resolveTemplatePath,jc as scopeOnRootElement,qe as shouldTranspileTypeScript,yi as slotContentHasExpressions,Ge as transpileTypeScript,Jn as userComponentFileExists,Dc as validateDirective,Ic as validateTemplate};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{o}from"./chunk-
|
|
2
|
+
import{o}from"./chunk-qrqw667n.js";import{Rr}from"./chunk-n1cqg89v.js";import p from"path";async function Cl(t={}){let d=performance.now(),s=t.root||process.cwd(),e=await o(s),u=t.ssr?.routeRules??e.routeRules??{};if(Rr(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-7qqx3ja8.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{Cl};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{nn,ce}from"./chunk-azb58ven.js";import{m,rn,w,je,o,A}from"./chunk-
|
|
2
|
+
import{nn,ce}from"./chunk-azb58ven.js";import{m,rn,w,je,o,A}from"./chunk-qrqw667n.js";import{Yr}from"./chunk-n5swm2mb.js";import{s,ve}from"./chunk-7wfh2hqy.js";import{a}from"./chunk-4cmqjmqr.js";import h from"path";import v from"fs";var pe=10;function V(e,n,i){return/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(h.basename(e))||Yr(e,n,i)}var ne=1,re=new Map,W=600,fe=100,P=new Map;async function me(e){let n=P.get(e)??0;if(n>0&&n<fe){P.set(e,n+1);return}P.set(e,1);try{let i=(await v.promises.readdir(e)).filter((u)=>u.endsWith(".js"));if(i.length<=W)return;let g=(await Promise.all(i.map(async(u)=>{try{return{name:u,at:(await v.promises.stat(h.join(e,u))).mtimeMs}}catch{return null}}))).filter((u)=>u!==null);g.sort((u,l)=>l.at-u.at);for(let u of g.slice(W)){let l=u.name.slice(0,-3);await v.promises.rm(h.join(e,`${l}.js`),{force:!0}),await v.promises.rm(h.join(e,`${l}.deps.json`),{force:!0})}I("pruned bundle cache to",W,"entries")}catch{}}function ae(e){return re.get(e)??[]}function X(e,n){if(e)re.set(e,n)}function Ya(e=process.env){return e.STX_DEBUG==="true"||e.STX_DEBUG==="1"}function I(...e){if(Ya())console.log("[stx:bundler]",...e)}var Z=[];function Uo(e,n,i){Z.push({filePath:e||"<inline>",message:n,details:i})}function yt(){return Z.slice()}function bt(){Z.length=0}var q;function Id(e){q=e}function Vo(){if(q)return q;try{let e=A.strict;return typeof e==="object"&&e!==null?e.bundlerFallback??"warn":"warn"}catch{return"warn"}}var H=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function wt(e){let n=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,i;while((i=n.exec(e))!==null){let g=i[1];if(!H.some((l)=>l.test(g)))return I("detected user import:",g),!0}let c=/^[ \t]*import[ \t]*['"]([^'"]+)['"]/gm;while((i=c.exec(e))!==null){let g=i[1];if(/\.css(?:\?.*)?$/.test(g))continue;if(!H.some((l)=>l.test(g)))return I("detected side-effect import:",g),!0}return!1}var tn="stx-module:",ge=/\.(?:[cm]?[jt]sx?|json)$/i;function Za(e,n){return h.relative(e,n).split(h.sep).join("/")}function Qa(e,n){if(n.size===0)return e;return e.replace(/^([ \t]*import(?:(?:\s+|(?=[{*]))[^;"']*?\s*from\s*|\s*))(["'])([^"']+)\2/gm,(i,c,g,u)=>{let l=n.get(u);return l&&!u.startsWith(tn)?`${c}${g}${l}${g}`:i})}function ec(e,n){let i=0,c=(u)=>{let l=`__stxMod${i++}`,S=JSON.stringify(u);return n.push(`var ${l} = globalThis.__stxModules && globalThis.__stxModules[${S}];`,`if (${l} === undefined) throw new Error("[stx] module " + ${JSON.stringify(S)} + " is not registered on this page (#1957)");`),l},g=(u,l)=>{for(let S of u.split(",")){let M=S.trim();if(!M)continue;let f=M.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!f)continue;let t=f[1].startsWith('"')?JSON.parse(f[1]):f[1],r=f[2]??t;n.push(`var ${r} = ${l}[${JSON.stringify(t)}];`)}};return e=e.replace(/^[ \t]*import(?:\s+|(?=[{*]))([^;"']+?)\s*from\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(u,l,S)=>{let M=S.slice(tn.length),f=c(M),t=l.trim(),r=t.match(/^([\w$]+)\s*(?:,\s*|$)/);if(r&&!t.startsWith("{")&&!t.startsWith("*"))n.push(`var ${r[1]} = ${f}.default;`),t=t.slice(r[0].length).trim();let d=t.match(/^\*\s*as\s+([\w$]+)$/);if(d)n.push(`var ${d[1]} = ${f};`);else if(t.startsWith("{"))g(t.replace(/^\{|\}$/g,""),f);return""}),e=e.replace(/^[ \t]*import\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(u,l)=>(c(l.slice(tn.length)),"")),e}function ee(e){let n=[e,`${e}.ts`,`${e}.tsx`,`${e}.js`,`${e}.mjs`,`${e}.jsx`,h.join(e,"index.ts"),h.join(e,"index.tsx"),h.join(e,"index.js"),h.join(e,"index.mjs")];for(let i of n)try{if(v.existsSync(i)&&v.statSync(i,{throwIfNoEntry:!1})?.isFile())return i}catch{}return}function he(e,n,i,c,g,u=new Map,l){let S=(f,t,r)=>{if(V(t,e,l))return null;if(!g||f!==i||!ge.test(t))return null;try{if(!v.statSync(t,{throwIfNoEntry:!1})?.isFile())return null}catch{return null}c.add(t);let d=`${tn}${Za(process.cwd(),t)}`;return u.set(r,d),{path:d,external:!0}},M=(f,t)=>{let r=f===i?n:h.dirname(f),d=h.resolve(r,t);return ee(d)??d};return{name:"stx-client-bundle",setup(f){if(f.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(t)=>({path:t.path,external:!0})),f.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(t)=>({path:t.path,external:!0})),f.onResolve({filter:/^\//},(t)=>{let r=ee(t.path);if(r){let d=S(t.importer,r,t.path);if(d)return d;if(r!==i)c.add(r);return{path:r}}return{path:t.path,external:!0}}),f.onResolve({filter:/^\.\.?\//},(t)=>{let r=M(t.importer,t.path),d=S(t.importer,r,t.path);if(d)return d;return c.add(r),{path:r}}),f.onResolve({filter:/^[@~]\//},(t)=>{let r=h.resolve(e,t.path.slice(2)),d=[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.mjs`,`${r}.jsx`,h.join(r,"index.ts"),h.join(r,"index.tsx"),h.join(r,"index.js"),h.join(r,"index.mjs")];for(let E of d)if(v.existsSync(E)&&v.statSync(E,{throwIfNoEntry:!1})?.isFile()){let C=S(t.importer,E,t.path);if(C)return C;return I(`resolved ${t.path[0]}/ import:`,t.path,"\u2192",E),c.add(E),{path:E}}return console.warn(`[stx:bundler] could not resolve ${t.path[0]}/ import:`,t.path),{path:r}}),g)f.onResolve({filter:/^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/},(t)=>{if(t.importer!==i)return;let r=`${tn}npm:${t.path}`;return u.set(t.path,r),{path:r,external:!0}});f.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(t)=>{if(V(t.path,e,l))throw Error(`Server-only API source cannot be imported by a client script: ${t.path}`);let r=h.extname(t.path).toLowerCase(),d=r===".json"?"json":r===".tsx"?"tsx":r===".jsx"?"jsx":r===".ts"||r===".mts"||r===".cts"?"ts":"js";if(t.path!==i)c.add(t.path);return{contents:v.readFileSync(t.path,"utf8"),loader:d}})}}}var G=new Map,L=m(64),te=Symbol.for("stx.client-bundle-build-queue");function tc(e){let n=globalThis,c=(n[te]??Promise.resolve()).then(e,e);return n[te]=c.then(()=>{return},()=>{return}),c}async function vt(e,n,i={}){let c=i.projectRoot||process.cwd(),g=(await o(c)).serverApi,u=i.minify??!1,l=i.externalizeUserModules??!0,S=i.expose?.length?[...new Set(i.expose)].sort():void 0,M=i.cacheDir||a(c,"bundle-cache"),f=new Bun.CryptoHasher("md5");f.update(`${pe}\x00${je()}\x00${JSON.stringify(g??!1)}\x00${l?"registry":"inline"}\x00${S?S.join(","):"*"}\x00${e}\x00${n}`);let t=f.digest("hex").slice(0,12),r=h.join(M,`${t}.js`),d=L.get(r);if(d){if(rn(d.files)&&d.files.every((N)=>!V(N.path,c,g))){I("memo hit:",t);let N=d.files.map((B)=>B.path);return X(n,N),i.collectInputs?.push(...N),d.code}L.delete(r),I("memo invalidated by dep change:",t)}let E=h.join(M,`${t}.deps.json`),C=Bun.file(r);if(await C.exists()){let N=Bun.file(E),B=!1,R=null;if(await N.exists())try{let O=JSON.parse(await N.text());if(O.metadataVersion!==ne||!Array.isArray(O.files))B=!1;else R=O.files,B=!0;if(R&&(!rn(R)||R.some((D)=>V(D.path,c,g))))B=!1}catch{B=!1}if(B){if(I("cache hit:",t),R)X(n,R.map((D)=>D.path)),i.collectInputs?.push(...R.map((D)=>D.path));let O=await C.text();if(R)L.set(r,{code:O,files:R});return O}I("cache invalidated by dep change:",t)}let _=G.get(t);if(_){let N=await _;if(i.collectInputs)i.collectInputs.push(...(L.get(r)?.files??[]).map((B)=>B.path));return N}let z=tc(()=>$e(e,n,{projectRoot:c,minify:u,cacheDir:M,hash:t,cachePath:r,depsPath:E,collectInputs:i.collectInputs,externalizeUserModules:l,serverApi:g,expose:S,throwOnFailure:i.throwOnFailure}));G.set(t,z);try{return await z}finally{G.delete(t)}}var xe=0;function nc(e){return`${e}-${process.pid}-${++xe}`}async function $e(e,n,i){let{projectRoot:c,minify:g,cacheDir:u,hash:l,cachePath:S,depsPath:M,externalizeUserModules:f}=i,t=a(c,"bundle-tmp"),r=nc(l),d=h.join(t,`${r}.ts`),E=h.join(t,"out",r);v.mkdirSync(t,{recursive:!0}),v.mkdirSync(E,{recursive:!0});let C=h.dirname(n),_=new Set,z=/^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,N=/^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm,B=s(e),{depths:R,balanced:O}=ve(B),D=(j)=>!O||R[j]===0,y;while((y=z.exec(B))!==null){if(y[1])continue;if(!D(y.index))continue;if(y[2])y[2].split(",").forEach((j)=>{let p=we(j);if(p)_.add(p)});else if(y[3])_.add(y[3])}while((y=N.exec(B))!==null){if(y[1])continue;if(!D(y.index))continue;_.add(y[2])}let se=/^[ \t]*import[ \t]+(?!type\b)(?:(\w+)\s*(?:,\s*)?)?(?:\*\s+as\s+(\w+)|\{([^}]+)\})?\s+from\b/gm;while((y=se.exec(B))!==null){if(!D(y.index))continue;let j=/^\s*['"]([^'"]+)['"]/.exec(e.slice(y.index+y[0].length))?.[1];if(j&&H.some((p)=>p.test(j)))continue;if(y[1])_.add(y[1]);if(y[2])_.add(y[2]);for(let p of(y[3]??"").split(",")){let b=p.trim();if(!b||/^type\s/.test(b))continue;let U=/\bas\s+(\w+)\s*$/.exec(b)?.[1]??/^\w+$/.exec(b)?.[0];if(U)_.add(U)}}for(let j of B.matchAll(/\bexport\s*\{([^}]+)\}/g))for(let p of j[1].split(",")){let b=/\bas\s+(\w+)\s*$/.exec(p)?.[1]??/^\s*(\w+)\s*$/.exec(p)?.[1];if(b)_.delete(b)}let ie=_.size>0?`
|
|
3
3
|
export { ${[..._].join(", ")} }`:"";await Bun.write(d,e+ie),I("bundling:",l,"from:",h.basename(n));let Y=new Set,Q=new Map;try{let j=await Bun.build({entrypoints:[d],outdir:E,target:"browser",format:"esm",minify:g?{whitespace:!1,identifiers:!0,syntax:!0}:!1,plugins:[he(c,C,d,Y,f,Q,i.serverApi)],define:{"process.env.NODE_ENV":g?'"production"':'"development"',...w()},root:c});if(!j.success){let F=j.logs.filter((T)=>T.level==="error").map((T)=>T.message).join(", ")||`Unable to bundle ${h.basename(n)}`,k=nn(j.logs,n||void 0);if(console.warn("[stx:bundler] build failed:",F),Uo(n||"",F,k),i.throwOnFailure||Vo()==="error")throw Error(F);return e}let p="";for(let x of j.outputs){p=await x.text();break}let b=[];for(let x of p.matchAll(/^\s*export\s*\{([^}]*)\}\s*;?\s*$/gm))for(let F of x[1].split(",")){let k=F.trim().match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(k){b.push([k[2],k[1]]);continue}let T=F.trim();if(/^[A-Za-z_$][\w$]*$/.test(T))b.push([T,T])}if(i.expose){let x=new Set(i.expose);for(let F=b.length-1;F>=0;F--)if(!x.has(b[F][0]))b.splice(F,1)}let U=[];p=ec(Qa(p,Q),U);let oe=p.match(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm)||[];if(p=p.replace(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm,"").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm,"").replace(/^\s*export\s+default\s+.*$/gm,"").trim(),g&&p)try{p=new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(p)}catch{}let K=`__stxBundle_${l}`,le=b.map(([x,F])=>`${JSON.stringify(x)}: ${F}`).join(", "),ue=b.map(([x])=>`var ${x} = undefined;`).join(`
|
|
4
4
|
`),de=b.map(([x])=>`${x} = ${K}[${JSON.stringify(x)}];`).join(`
|
|
5
5
|
`);if(p=`${oe.join(`
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{M,le}from"./chunk-
|
|
2
|
+
import{M,le}from"./chunk-qrqw667n.js";import{ue,C,Je}from"./chunk-e124cgb6.js";import{tt,J,Ce}from"./chunk-b156xw15.js";import{Pe,re,E,se,mo,$r,ho,Nt}from"./chunk-h0e3ps74.js";import{Jr}from"./chunk-n5swm2mb.js";import{Lt}from"./chunk-n1cqg89v.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",E(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 L=await s.clone().arrayBuffer();if(L.byteLength>1048576)return null;s.headers.set("Vary",E(s.headers.get("Vary")).Vary);let n={body:L,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 B=await v;return B?l(B):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 sl(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=Jr(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,B=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)),B.set(n.pattern,le(i.html));let _=P.join(e,n.fragmentPath);if(await Bun.file(_).exists()){let A=await Bun.file(_).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 L=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 _=await h(n);if(_)return _;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(),j=de[R]||"application/octet-stream",N=i.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(i);return new Response(Bun.file(u),{headers:{"Content-Type":j,"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,j)=>{q[R]=c[j+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",...B.has(w.pattern)?{"X-STX-Runtime":B.get(w.pattern)?"true":"false"}:{},...R?{"X-STX-Layout":R.layout,"X-STX-Layout-Group":R.group}:{},...E(),...O.cache?{}:{"Cache-Control":Pe}}})}}let d=$r(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",...E(),"Cache-Control":"public, max-age=60"}});try{let{html:c,boundaries:R,redirect:j,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(j)return ho(j,N,D);if(R&&R.length>0){let{renderStreamingPage:T,streamToResponse:z}=await import("./chunk-29r6af6f.js"),X=new Headers({...E(),...D,"Cache-Control":"private, no-store"});for(let V of N??[])X.append("Set-Cookie",V);if(A&&!d){let V=Ce(c);X.set("X-STX-Fragment","true"),X.set("X-STX-Runtime",le(c)?"true":"false"),X.set("X-STX-Layout",V.layout),X.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:X})}let x=new Headers({"Content-Type":"text/html",...E(),...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",E(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:${L.port}`),console.log(`[stx] Serving ${r.routes.length} routes (${b.size} pre-loaded)`),{port:L.port,stop:()=>{f.invalidate(),L.stop()},invalidate:(n)=>f.invalidate(n)}}
|
|
3
3
|
export{Dt,sl};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{rl}from"./chunk-b11qrqzz.js";import"./chunk-qrqw667n.js";import"./chunk-yp1360pq.js";import"./chunk-4zb2ga7p.js";import"./chunk-ff61d2wr.js";import"./chunk-mdgvzf07.js";import"./chunk-e124cgb6.js";import"./chunk-g84ctpqq.js";import"./chunk-cngtf95k.js";import"./chunk-a5kaw8sc.js";import"./chunk-6v1gwdbv.js";import"./chunk-r4199q6x.js";import"./chunk-b156xw15.js";import"./chunk-1xgs9gd5.js";export{rl as startInteractive};
|