@stacksjs/stx 0.2.616 → 0.2.618
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-3vbv4gxx.js → chunk-06pc67a6.js} +2 -2
- package/dist/{chunk-cjm2d6w1.js → chunk-0v4zcm3s.js} +1 -1
- package/dist/{chunk-m85kmqbn.js → chunk-0vfqp662.js} +1 -1
- package/dist/{chunk-araay35m.js → chunk-1a59snwg.js} +4 -4
- package/dist/{chunk-temrpzxj.js → chunk-1g257jhn.js} +1 -1
- package/dist/chunk-1zq9pht7.js +2 -0
- package/dist/chunk-2a0wr0dm.js +2 -0
- package/dist/chunk-2pvt0edy.js +2 -0
- package/dist/{chunk-h74p4zay.js → chunk-2t49cfd3.js} +33 -33
- package/dist/{chunk-dq58tn5x.js → chunk-35qyy4fx.js} +1 -1
- package/dist/{chunk-twmq5m6r.js → chunk-3jdfzq61.js} +2 -2
- package/dist/{chunk-06bwys2z.js → chunk-3x88c989.js} +1 -1
- package/dist/{chunk-k1hpxgzq.js → chunk-47csgccw.js} +5 -5
- package/dist/{chunk-ekd11w9t.js → chunk-5ek9k7hh.js} +1 -1
- package/dist/{chunk-jpe8pt9m.js → chunk-5md6ejrq.js} +1 -1
- package/dist/{chunk-wq6b8qgz.js → chunk-65b3f0e9.js} +1 -1
- package/dist/{chunk-mqky9h29.js → chunk-6rjm087c.js} +1 -1
- package/dist/{chunk-ywxg3f9s.js → chunk-6tsenq5p.js} +1 -1
- package/dist/chunk-70gchk6z.js +2 -0
- package/dist/{chunk-rw3kgv2q.js → chunk-78jnrn1f.js} +1 -1
- package/dist/{chunk-xeqysa9z.js → chunk-7f0gh0kg.js} +38 -38
- package/dist/{chunk-s9jgsp0a.js → chunk-7fg1hzad.js} +3 -3
- package/dist/chunk-7y4ff3se.js +2 -0
- package/dist/{chunk-e5t4xhfk.js → chunk-86xx6pre.js} +1 -1
- package/dist/chunk-8gy3vz25.js +2 -0
- package/dist/{chunk-kt9ksp8w.js → chunk-8jcrtb7k.js} +1 -1
- package/dist/{chunk-4h62y8dn.js → chunk-8w9w1vv4.js} +1 -1
- package/dist/{chunk-pw0b0an6.js → chunk-8xwgz6jf.js} +1 -1
- package/dist/{chunk-27h4ndsg.js → chunk-93whjefr.js} +1 -1
- package/dist/chunk-9985eshw.js +2 -0
- package/dist/chunk-9k34a7bd.js +2 -0
- package/dist/{chunk-hx2fc5dt.js → chunk-9r4m465q.js} +1 -1
- package/dist/{chunk-q3a13hvc.js → chunk-a0xkvdjr.js} +2 -2
- package/dist/{chunk-k0kajwdw.js → chunk-a3j5sb7g.js} +1 -1
- package/dist/{chunk-97ht3bw3.js → chunk-at430s7q.js} +1 -1
- package/dist/chunk-axt96apz.js +2 -0
- package/dist/chunk-b2shw48x.js +2 -0
- package/dist/{chunk-q4t49t6z.js → chunk-b3v077t7.js} +3 -3
- package/dist/chunk-bah51zv3.js +2 -0
- package/dist/{chunk-jrsvbztw.js → chunk-bbbdfd8q.js} +1 -1
- package/dist/chunk-c091xff6.js +2 -0
- package/dist/chunk-ckts3t2h.js +2 -0
- package/dist/{chunk-71wntraa.js → chunk-cv2t12cc.js} +1 -1
- package/dist/{chunk-tkw5mr0k.js → chunk-d8v0amcr.js} +1 -1
- package/dist/{chunk-th9t5vks.js → chunk-ddx52kk5.js} +1 -1
- package/dist/{chunk-zde9mef4.js → chunk-dz3wh7x0.js} +1 -1
- package/dist/{chunk-qzfq8342.js → chunk-effx3f2n.js} +1 -1
- package/dist/{chunk-trhr4gzz.js → chunk-epbhzaca.js} +1 -1
- package/dist/{chunk-t4rxr1zj.js → chunk-etyjfmza.js} +1 -1
- package/dist/chunk-evqpzzns.js +2 -0
- package/dist/chunk-ey6rjjec.js +2 -0
- package/dist/{chunk-tq5nzr99.js → chunk-gg38as5t.js} +1 -1
- package/dist/chunk-hmdettqm.js +2 -0
- package/dist/{chunk-m0x9gfx5.js → chunk-k1j2aw54.js} +1 -1
- package/dist/{chunk-jwxppaj3.js → chunk-m2c4rx9x.js} +1 -1
- package/dist/{chunk-4rtxkqwh.js → chunk-mktk70gq.js} +2 -2
- package/dist/chunk-mzvggfjn.js +2 -0
- package/dist/chunk-ptgn563n.js +2 -0
- package/dist/{chunk-faq9x5kw.js → chunk-r4n2fve8.js} +17 -17
- package/dist/{chunk-wn3d4gd6.js → chunk-s2n7exsm.js} +2 -2
- package/dist/{chunk-j6nn0c5r.js → chunk-safstptd.js} +1 -1
- package/dist/{chunk-3hzr66vn.js → chunk-samsjcqt.js} +3 -3
- package/dist/chunk-sgnez07y.js +2 -0
- package/dist/{chunk-t8akfx99.js → chunk-sy2nm0z7.js} +1 -1
- package/dist/{chunk-bm632aaj.js → chunk-tk1bkmdq.js} +1 -1
- package/dist/{chunk-wr42shpx.js → chunk-tx1mq72q.js} +1 -1
- package/dist/{chunk-zb191qdx.js → chunk-tyhw0ndz.js} +1 -1
- package/dist/{chunk-3cg5mrtq.js → chunk-vqwszvzt.js} +4 -4
- package/dist/{chunk-b3g8zzc6.js → chunk-x6bh13w3.js} +1 -1
- package/dist/{chunk-gv3se08t.js → chunk-xs01xryj.js} +1 -1
- package/dist/{chunk-792sscsk.js → chunk-xvt6vvg4.js} +1 -1
- package/dist/{chunk-5fxh7fc3.js → chunk-y039e06c.js} +2 -2
- package/dist/chunk-yzpr0fh3.js +2 -0
- package/dist/{chunk-spkwmfbm.js → chunk-z04480ar.js} +1 -1
- package/dist/cli.js +9 -9
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/native/runtime/craft-bridge.js +44 -10
- package/dist/native/runtime/craft.d.ts +19 -0
- package/dist/native/runtime/navigation-chrome.d.ts +24 -0
- package/dist/native/runtime/navigation-chrome.js +49 -0
- package/dist/pwa.js +2 -2
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-1gyrk0qv.js +0 -2
- package/dist/chunk-1xzxmnsd.js +0 -2
- package/dist/chunk-2a1sgnxf.js +0 -2
- package/dist/chunk-3fb3m640.js +0 -2
- package/dist/chunk-awvbp2t4.js +0 -2
- package/dist/chunk-bdn21f8c.js +0 -2
- package/dist/chunk-c6vb28zd.js +0 -2
- package/dist/chunk-dcdmr6cp.js +0 -2
- package/dist/chunk-fq4xjy4k.js +0 -2
- package/dist/chunk-h476qqq9.js +0 -2
- package/dist/chunk-mf6mqs9k.js +0 -2
- package/dist/chunk-n5acpvq3.js +0 -2
- package/dist/chunk-nvewemvh.js +0 -2
- package/dist/chunk-p1t8mm9b.js +0 -2
- package/dist/chunk-pv73vnyj.js +0 -2
- package/dist/chunk-t7h714ne.js +0 -2
- package/dist/chunk-x81g1v5x.js +0 -2
- package/dist/chunk-ywf6pa29.js +0 -2
- package/dist/chunk-yxksngda.js +0 -2
- package/dist/chunk-yytfje8a.js +0 -2
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{X,b,vn,wn,e,Lt,kn,f,Xe,jt,Je,Ye,se,L,me,Z,u,Te,Ii,Ms,n,r,oe,gr,o,P,he}from"./chunk-
|
|
2
|
+
import{X,b,vn,wn,e,Lt,kn,f,Xe,jt,Je,Ye,se,L,me,Z,u,Te,Ii,Ms,n,r,oe,gr,o,P,he}from"./chunk-7f0gh0kg.js";import{U,Dn,ie,O,Vt}from"./chunk-47csgccw.js";import{ut,Fn,$r,Rr,Ar,dt,pt,ft,gt,mt,ht,Ie}from"./chunk-5hqkfqne.js";import{Be,To,ae,T,$o,Vr,Xn,xe,Ro,ce}from"./chunk-samsjcqt.js";import{qt}from"./chunk-6rjm087c.js";import{pe}from"./chunk-5rtatjwq.js";import{a}from"./chunk-6ta850w8.js";import{D}from"./chunk-3jdfzq61.js";async function Gn(t){try{let s=await Bun.file(t).text(),i=Jn(s),d=Yn(s,t),c=Qn(s,i),l=Zn(s,i);return{file:t,metrics:i,issues:d,suggestions:c,performance:l}}catch(s){throw Error(`Failed to analyze template ${t}: ${s instanceof Error?s.message:String(s)}`)}}function Jn(t){let s=t.split(`
|
|
3
3
|
`),i=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),c=(i?i[1]:"").split(`
|
|
4
4
|
`).length,l={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};l.total=l.conditionals+l.loops+l.includes+l.custom;let m=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,p=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,h=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,g=m+p+h,y=(t.match(/<[A-Z][^>]*>/g)||[]).length,w=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,R=0;for(let C of s)if(/@(?:if|unless|foreach|for|while|section)\b/.test(C)&&!/@end/.test(C)&&!/@else/.test(C))R++,S=Math.max(S,R);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(C))R--;let v=S>=4?3:0,x=Math.min(10,Math.ceil(l.total*0.5+g*0.1+y*0.3+(c>10?c*0.05:0)+v));return{lines:s.length,characters:t.length,directives:l,expressions:g,components:y,layouts:w,scriptLines:c,complexity:x}}function Yn(t,s){let i=[],d=Jt(t,"if","endif");if(d>0)i.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let c=Jt(t,"foreach","endforeach");if(c>0)i.push({type:"error",category:"syntax",message:`Found ${c} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let l=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(l&&l.length>0)i.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let m=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(m>0)i.push({type:"warning",category:"security",message:`Found ${m} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let p=t.match(/<img[^>]*>/g);if(p){let y=p.filter((w)=>!w.includes("alt="));if(y.length>0)i.push({type:"warning",category:"accessibility",message:`Found ${y.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let h=t.split(`
|
|
5
5
|
`).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 Qn(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 d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.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 Zn(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 d;if(s.expressions===0&&s.directives.total===0)d="high";else if(s.expressions<5&&s.directives.total<3)d="medium";else d="low";let c=[];if(i>10)c.push("Consider optimizing template complexity");if(d==="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:d,recommendations:c}}function Jt(t,s,i){let d=t.replace(/<!--[\s\S]*?-->/g,""),c=(d.match(new RegExp(`@${s}\\b`,"g"))||[]).length,l=(d.match(new RegExp(`@${i}\\b`,"g"))||[]).length;return Math.abs(c-l)}async function go(t=["**/*.stx"],s){let i=[],d=[];for(let l of t){let m=await Array.fromAsync(new Bun.Glob(l).scan({cwd:s||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...m.filter((p)=>p.endsWith(".stx")))}for(let l of d)try{let m=await Gn(l);i.push(m)}catch(m){console.warn(`Failed to analyze ${l}:`,m)}let c=er(i);return{results:i,summary:c}}function er(t){let s=t.length,i=t.reduce((g,y)=>g+y.metrics.lines,0),d=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,p=Math.max(1,Math.min(10,Math.round(10-m/2-d/2))),h=[];if(d>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(d*100)/100,totalIssues:c,issuesByCategory:l,performanceScore:p,recommendations:h}}import{mkdir as tr,readFile as nr,readdir as rr,stat as Yt,writeFile as or}from"fs/promises";import Ee from"path";function rn(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 on=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 Ht(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function ir(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function ar(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function cr(t){let s=[];async function i(d){let c=await rr(d,{withFileTypes:!0});c.sort((l,m)=>l.name.localeCompare(m.name));for(let l of c){let m=Ee.join(d,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 lr(t,s){let i=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!i)return{};let d=i[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(c){throw Error(`${s}: <script component> must contain JSON metadata (${c.message})`)}}function dr(t,s){let i={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let c of d){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,p;while(p=m.exec(l)){let h=p[1];if(on.has(h))throw Error(`${s}: client ${rn(h)}`);let g=m.lastIndex,y=1,w="",S=!1,R=g;for(;R<l.length&&y>0;R++){let x=l[R];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=p[0].includes("async")?"async ":"";i[h]=`${v}${h}(${p[2]}) {${l.slice(g,R-1)}}`,m.lastIndex=R}}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 Qt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((s)=>s[1].trim()).filter(Boolean).join(`
|
|
6
6
|
|
|
7
7
|
`)}function ur(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 fr(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 mr(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 hr(t){let s=[],i=0,d=t.replace(/\{\{--[\s\S]*?--\}\}/g,""),c=/@(if|elseif|else|endif|foreach|endforeach)\s*/g,l,m=(h)=>{if(d[h]!=="(")return null;let g=0,y="";for(let w=h;w<d.length;w++){let S=d[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:d.slice(h+1,w),end:w+1}}}return null},p=(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(d)){p(d.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,R,v]=w;s.push(R?`for (const [${R}, ${v}] of __entries(${S})) {`:`for (const ${v} of __values(${S})) {`);break}}}return p(d.slice(i)),s.join(`
|
|
8
|
-
`)}function bt(t,s,i,d){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let p=t[m];if(l){if(p==="\\"){m++;continue}if(p===l)l=null;continue}if(p==="'"||p==='"'||p==="`"){l=p;continue}if(p===i)c++;else if(p===d){if(d===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function _t(t,s,i){let d=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,p=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(p){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===p)p=null;continue}if(y==="'"||y==='"'||y==="`"){p=y,h+=y;continue}if(d.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 yr(t){let s=0,i=null;for(let d=0;d<t.length;d++){let c=t[d];if(i){if(c==="\\"){d++;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[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Zt(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 br(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))d=k.index+k[0].indexOf(k[1]);if(d===-1)return null;let c={},l={},m=[],p=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(p<t.length&&/\s/.test(t[p]))p++},g;if(t[p]==="{"){let k=bt(t,p,"{","}");if(k===-1)return null;g=t.slice(p,k),p=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(p));if(!k)return null;g=k[0],p+=k[0].length}if(h(),t[p]!=="=")return null;p++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(p)),w=Boolean(y);if(y)p+=y[0].length;let S=/^defineProps\b/.exec(t.slice(p));if(!S)return null;p+=S[0].length;let R="";if(h(),t[p]==="<"){let k=bt(t,p,"<",">");if(k===-1)return null;R=t.slice(p+1,k-1).trim(),p=k}if(h(),t[p]!=="(")return null;let v=bt(t,p,"(",")");if(v===-1)return null;let x=t.slice(p+1,v-1).trim();if(p=v,w){if(h(),t[p]===",")p++,h();if(t[p]==="{"){let k=bt(t,p,"{","}");if(k===-1)return null;for(let[
|
|
8
|
+
`)}function bt(t,s,i,d){if(t[s]!==i)return-1;let c=0,l=null;for(let m=s;m<t.length;m++){let p=t[m];if(l){if(p==="\\"){m++;continue}if(p===l)l=null;continue}if(p==="'"||p==='"'||p==="`"){l=p;continue}if(p===i)c++;else if(p===d){if(d===">"&&t[m-1]==="=")continue;if(c--,c===0)return m+1}}return-1}function _t(t,s,i){let d=i?"([{<":"([{",c=i?")]}>":")]}",l=[],m=0,p=null,h="";for(let g=0;g<t.length;g++){let y=t[g];if(p){if(h+=y,y==="\\"){h+=t[++g]??"";continue}if(y===p)p=null;continue}if(y==="'"||y==='"'||y==="`"){p=y,h+=y;continue}if(d.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 yr(t){let s=0,i=null;for(let d=0;d<t.length;d++){let c=t[d];if(i){if(c==="\\"){d++;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[d-1];if(t[d+1]==="="||l==="="||l==="!"||l==="<"||l===">")continue;return d}return-1}function Zt(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 br(t){let s=/\bdefineProps\b/.exec(t);if(!s)return null;let i=/(?:^|[\s;{}()])(const|let|var)\s+/g,d=-1;for(let k=i.exec(t);k&&k.index<s.index;k=i.exec(t))d=k.index+k[0].indexOf(k[1]);if(d===-1)return null;let c={},l={},m=[],p=d+(/^(?:const|let|var)\s+/.exec(t.slice(d))?.[0].length??0),h=()=>{while(p<t.length&&/\s/.test(t[p]))p++},g;if(t[p]==="{"){let k=bt(t,p,"{","}");if(k===-1)return null;g=t.slice(p,k),p=k}else{let k=/^[A-Za-z_$][\w$]*/.exec(t.slice(p));if(!k)return null;g=k[0],p+=k[0].length}if(h(),t[p]!=="=")return null;p++,h();let y=/^withDefaults\s*\(\s*/.exec(t.slice(p)),w=Boolean(y);if(y)p+=y[0].length;let S=/^defineProps\b/.exec(t.slice(p));if(!S)return null;p+=S[0].length;let R="";if(h(),t[p]==="<"){let k=bt(t,p,"<",">");if(k===-1)return null;R=t.slice(p+1,k-1).trim(),p=k}if(h(),t[p]!=="(")return null;let v=bt(t,p,"(",")");if(v===-1)return null;let x=t.slice(p+1,v-1).trim();if(p=v,w){if(h(),t[p]===",")p++,h();if(t[p]==="{"){let k=bt(t,p,"{","}");if(k===-1)return null;for(let[B,_]of It(t.slice(p,k)))l[B]=_;p=k}if(h(),t[p]===",")p++,h();if(t[p]===")")p++}if(t[p]===";")p++;let C=/^[A-Za-z_$][\w$]*$/.test(R)?R:void 0;if(R.startsWith("{"))for(let k of _t(R.replace(/^\{/,"").replace(/\}$/,""),",;",!0)){let B=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(B)c[B[1]]=B[2].trim()}if(x.startsWith("{"))for(let[k,B]of It(x)){if(m.push(k),!B.startsWith("{")){let _=Zt(B);if(_)c[k]=_;continue}for(let[_,j]of It(B))if(_==="default")l[k]=j;else if(_==="type"){let E=Zt(j);if(E)c[k]=E}}else if(x.startsWith("["))for(let k of _t(x.slice(1,-1),",",!1))m.push(k.replace(/^['"`]/,"").replace(/['"`]$/,""));if(g.startsWith("{")){m.length=0;for(let k of _t(g.replace(/^\{/,"").replace(/\}$/,""),",",!1)){let B=yr(k),j=(B===-1?k:k.slice(0,B)).split(":")[0].trim().replace(/^\.\.\./,"");if(!j)continue;if(m.push(j),B!==-1)l[j]=k.slice(B+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(d,p),propNames:m,defaults:l,declared:c,typeName:C}}function It(t){let s=t.trim().replace(/^\{/,"").replace(/\}$/,""),i=[],d=0;while(d<s.length){let c=/\s*([A-Za-z_$][\w$]*)\s*:/y;c.lastIndex=d;let l=c.exec(s);if(!l)break;d=c.lastIndex;let m=0,p="",h=d;while(d<s.length){let y=s[d];if(p){if(y==="\\")d++;else if(y===p)p=""}else if(y==="'"||y==='"'||y==="`")p=y;else if(y==="{"||y==="["||y==="(")m++;else if(y==="}"||y==="]"||y===")")m--;else if(y===","&&m===0)break;d++}let g=s.slice(h,d).trim();if(g)i.push([l[1],g]);d++}return i}function xr(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=[],p=[],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*['"])(\.[^'"]*)(['"])/,(R,v,x,C)=>{let k=Ee.resolve(Ee.dirname(s),x),B=Ee.relative(i,k);return`${v}${B.startsWith(".")?B:`./${B}`}${C}`})),""});let y=br(l);if(y)p.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 R=[];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(),R.push(v[1]);w[S[1]]=R}if(y&&y.propNames.length===0&&y.typeName){for(let S of w[y.typeName]??[])if(!p.includes(S))p.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:p,defaults:h,declared:g}}function vr(t){let s=new Set;return{template:t.replace(/\s@([a-z][\w:-]*)(\.[\w.-]+)?\s*=\s*(["'])([A-Za-z_$][\w$]*)\3/gi,(d,c,l,m,p)=>{let h=c.toLowerCase();s.add(h);let g=(l||"").split(".").filter(Boolean).join(" ");return` data-stx-on-${h}="${p}"${g?` data-stx-mod-${h}="${g}"`:""}`}),eventTypes:[...s].sort()}}function wr(t){let s=[];return{template:t.replace(/\s:([a-z][\w:-]*)\s*=\s*(["'])([\w$.]+)\2/gi,(d,c,l,m)=>{let p=s.length;return s.push({id:p,name:c,expression:m}),` data-stx-bind-${p}=""`}),bindings:s}}function Sr(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 kr(t){return[...new Set([...t.matchAll(/(--[a-z0-9_-]+)\s*:/gi)].map((s)=>s[1]))].sort().map((s)=>({name:s}))}function en(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 Tr(t,s,i){let d=Ee.isAbsolute(s.file)?s.file:Ee.resolve(t,s.file),c=await nr(d,"utf8"),l=lr(c,d),m=Ee.basename(d,".stx"),p=s.name||l.name||sr(m),h=`${Ht(i.prefix||"stx")}-${Ht(m)}`,g=s.tag||l.tag||h;if(!p||!/^[A-Za-z_$][\w$]*$/.test(p))throw Error(`${d}: invalid component class name "${p}"`);if(!ir(g))throw Error(`${d}: 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(([_,j])=>[_,en(_,j)])),S=vr(pr(c)),R=wr(S.template),v=xr(c,d,Ee.resolve(i.outputDir)),x=hr(R.template);for(let _ of v.propNames){if(w[_])continue;let j=v.defaults[_];w[_]=en(_,{type:ur(v.declared[_])??fr(j),...j===void 0?{}:{default:mr(j)}})}let C=l.methods||{},k=s.methods||{},B=dr(c,d);return{file:Ee.relative(t,d),sourcePath:d,name:p,tag:g,description:s.description||l.description||"",template:R.template,styles:Qt(c),shadowMode:ar(s.shadowDOM??l.shadowDOM??i.shadowDOM),progressive:s.progressive??l.progressive??i.progressive??!0,properties:w,events:s.events||l.events||{},methods:{...C,...k,...B},eventTypes:S.eventTypes,bindings:R.bindings,slots:Sr(R.template),cssProperties:kr(Qt(c)),scope:v,render:x}}function Cr(){let t=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),s=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}");return`const HTMLElementBase = globalThis.HTMLElement || class {};
|
|
9
9
|
|
|
10
10
|
const escapeHTML = (value) => String(value ?? '')
|
|
11
11
|
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
@@ -374,9 +374,9 @@ ${c}
|
|
|
374
374
|
}
|
|
375
375
|
|
|
376
376
|
export {}
|
|
377
|
-
`}function
|
|
377
|
+
`}function _r(t){return{schemaVersion:"1.0.0",modules:t.map((s)=>({kind:"javascript-module",path:`./${s.tag}.js`,declarations:[{kind:"class",name:s.name,description:s.description||void 0,customElement:!0,tagName:s.tag,members:Object.entries(s.properties).map(([i,d])=>({kind:"field",name:i,description:d.description,type:{text:xt(d)},default:d.default===void 0?void 0:JSON.stringify(d.default),attribute:d.attribute===!1?void 0:d.attribute||Ht(i),reflects:d.reflect})),events:Object.entries(s.events).map(([i,d])=>({name:i,description:d.description,type:{text:`CustomEvent<${d.detailType||"unknown"}>`}})),slots:s.slots,cssProperties:s.cssProperties}],exports:[{kind:"js",name:s.name,declaration:{name:s.name,module:`./${s.tag}.js`}}]}))}}function tn(t){if(!t.styles)return"";let s=t.styles.replace(/:host\b/g,":scope");if(/\@scope\s*\(/.test(s))return s;return`@scope (${t.tag}) {
|
|
378
378
|
${s}
|
|
379
|
-
}`}function nn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function
|
|
379
|
+
}`}function nn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function Ir(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),d=JSON.stringify('<slot(?:\\s+name=["\\\']([^"\\\']+)["\\\'])?\\s*\\/?>(?:<\\/slot>)?'),c=Object.fromEntries(t.map((m)=>[m.tag,{template:m.template,styles:m.styles,shadowMode:m.shadowMode,properties:m.properties}])),l=t.map((m)=>`export const render${m.name} = (props = {}, slots = {}) => renderComponent('${m.tag}', props, slots);`).join(`
|
|
380
380
|
`);return`const definitions = ${JSON.stringify(c,null,2)};
|
|
381
381
|
const escapeHTML = (value) => String(value ?? '')
|
|
382
382
|
.replaceAll('&', '&').replaceAll('<', '<').replaceAll('>', '>')
|
|
@@ -413,16 +413,16 @@ ${l}
|
|
|
413
413
|
`}async function mo(t){let s=Ee.resolve(t.inputDir),i=Ee.resolve(t.outputDir);if(!(await Yt(s).catch(()=>null))?.isDirectory())throw Error(`Component-library input directory does not exist: ${s}`);let c=t.components?.length?t.components:(await cr(s)).map((x)=>({file:x}));if(!c.length)throw Error(`No .stx components found in ${s}`);let l=await Promise.all(c.map((x)=>Tr(s,x,t)));l.sort((x,C)=>x.tag.localeCompare(C.tag));let m=l.filter((x,C)=>l.findIndex((k)=>k.tag===x.tag)!==C);if(m.length)throw Error(`Duplicate custom-element tag: ${m[0].tag}`);let p=l.filter((x,C)=>l.findIndex((k)=>k.name===x.name)!==C);if(p.length)throw Error(`Duplicate component class name: ${p[0].name}`);await tr(i,{recursive:!0});let h=[],g=async(x,C)=>{let k=Ee.join(i,x);return await or(k,C.endsWith(`
|
|
414
414
|
`)?C:`${C}
|
|
415
415
|
`,"utf8"),h.push(k),k};await g("runtime.js",Cr());for(let x of l){if(await g(`${x.tag}.js`,Er(x)),t.declarations!==!1)await g(`${x.tag}.d.ts`,Pr(x));if(t.css!==!1&&x.styles){let C=x.shadowMode?x.styles:tn(x);await g(`${x.tag}.css`,t.minify?nn(C):C)}}let y=l.map((x)=>`export { ${x.name}, default as ${x.name}Element } from './${x.tag}.js';`).join(`
|
|
416
|
-
`);if(await g("index.js",y),await g("ssr.js",
|
|
416
|
+
`);if(await g("index.js",y),await g("ssr.js",Ir(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
|
|
417
417
|
`)),await g("custom-elements.d.ts",Or(l)),await g("ssr.d.ts",`${l.map((x)=>`export declare const render${x.name}: (props?: ${x.name}Props, slots?: Record<string, string>) => string`).join(`
|
|
418
418
|
`)}
|
|
419
419
|
export declare function renderComponent(tag: string, props?: Record<string, unknown>, slots?: Record<string, string>): string
|
|
420
420
|
${l.map((x)=>`import type { ${x.name}Props } from './${x.tag}.js'`).join(`
|
|
421
|
-
`)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(
|
|
421
|
+
`)}`);let w;if(t.manifest!==!1)w=await g("custom-elements.json",JSON.stringify(_r(l),null,2));let S;if(t.css!==!1){let x=l.filter((C)=>!C.shadowMode&&C.styles).map(tn).join(`
|
|
422
422
|
|
|
423
|
-
`);if(x)S=await g("bundle.css",t.minify?nn(x):x)}let R;if(t.bundle!==!1){R=Ee.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(C){let k=C instanceof AggregateError?C.errors:[C],
|
|
424
|
-
`);throw AggregateError(k,`Failed to bundle component library${
|
|
425
|
-
${
|
|
423
|
+
`);if(x)S=await g("bundle.css",t.minify?nn(x):x)}let R;if(t.bundle!==!1){R=Ee.join(i,"bundle.js");let x;try{x=await Bun.build({entrypoints:[Ee.join(i,"index.js")],outdir:i,naming:"bundle.js",target:"browser",format:"esm",minify:t.minify??!0,sourcemap:t.sourcemap||"none"})}catch(C){let k=C instanceof AggregateError?C.errors:[C],B=k.map((_)=>String(_).trim()).filter(Boolean).join(`
|
|
424
|
+
`);throw AggregateError(k,`Failed to bundle component library${B?`
|
|
425
|
+
${B}`:""}`)}if(!x.success){let C=x.logs.map((k)=>String(k).trim()).filter(Boolean).join(`
|
|
426
426
|
`);throw AggregateError(x.logs,`Failed to bundle component library${C?`
|
|
427
427
|
${C}`:""}`)}if(h.push(R),t.sourcemap==="external")h.push(`${R}.map`)}let v=await Promise.all(h.map(async(x)=>(await Yt(x)).size));return{components:l.map((x)=>({name:x.name,tag:x.tag,source:x.sourcePath,module:Ee.join(i,`${x.tag}.js`)})),files:h,manifest:w,bundle:R,cssBundle:S,totalBytes:v.reduce((x,C)=>x+C,0)}}var{serve:qr}=globalThis.Bun;import Ft from"fs";import ot from"path";function vt(){return`
|
|
428
428
|
/* Theme selector for code blocks */
|
|
@@ -504,12 +504,12 @@ else {
|
|
|
504
504
|
<span class="frontmatter-label">${s}:</span>
|
|
505
505
|
<span>${Array.isArray(i)?i.join(", "):String(i)}</span>
|
|
506
506
|
</div>`).join("")}
|
|
507
|
-
</div>`}import sn from"net";async function
|
|
507
|
+
</div>`}import sn from"net";async function jr(t){return new Promise((s)=>{let i=sn.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"0.0.0.0")})}async function Hr(t){return new Promise((s)=>{let i=sn.createServer();i.once("error",()=>s(!1)),i.once("listening",()=>{i.close(()=>s(!0))}),i.listen(t,"::")})}async function Br(t){if(!await jr(t))return!1;return await Hr(t)}async function Ge(t,s=20){t=Number(t);for(let i=0;i<s;i++){let d=t+i;if(await Br(d))return d}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Fr={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function zr(){try{let t=await import("./chunk-y8h823cb.js");if(typeof t.openDevWindow!=="function")return null;return t}catch{return null}}async function rt(t,s={}){let i={...Fr,...s},d=await zr();if(!d)return console.log(`${e.yellow}\u26A0${e.reset} Native window requested, but @stacksjs/desktop is not available.`),console.log(" Install & build the desktop package to enable --native."),!1;try{let c=await d.openDevWindow(t,{title:i.title,width:i.width,height:i.height,darkMode:i.darkMode,hotReload:i.hotReload,titlebarHidden:i.titlebarHidden,nativeSidebar:i.nativeSidebar,sidebarWidth:i.sidebarWidth,sidebarConfig:i.sidebarConfig});if(c&&i.nativeSidebar)console.log(`${e.green}\u2713${e.reset} Native sidebar enabled (macOS Tahoe style)`);return c}catch(c){return console.log(`${e.red}\u2717${e.reset} Could not open native window:`,c),!1}}function Tt(t){if(t.match(/<Sidebar[\s\S]*?variant=["'](?:tahoe|vibrancy|desktop)["'][\s\S]*?\/>/i)){let c=t.match(/<script\s+server[^>]*>([\s\S]*?)<\/script>/i);if(c){let l=c[1];try{let m=`
|
|
508
508
|
${l}
|
|
509
509
|
return typeof sidebarConfig !== 'undefined' ? sidebarConfig : null;
|
|
510
510
|
`,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 d=t.match(/<script\s+native-sidebar[^>]*>([\s\S]*?)<\/script>/i);if(d)try{let c=d[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 Bt(){console.log(`
|
|
511
|
-
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
|
|
512
|
-
`)){let l=d.trim().toLowerCase();d="",Wr(l,t,s,i)}})}function Wr(t,s,i,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else Ur(s);break;case"c":if(d?.onClear)d.onClear();else console.clear(),
|
|
511
|
+
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 Nr(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`),Bt()}function Ur(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(),Bt();let d="";process.stdin.on("data",(c)=>{if(c==="\x03"){if(i?.onQuit)i.onQuit();s(),process.exit(0)}if(d+=c,d.endsWith("\r")||d.endsWith(`
|
|
512
|
+
`)){let l=d.trim().toLowerCase();d="",Wr(l,t,s,i)}})}function Wr(t,s,i,d){switch(t){case"o":if(d?.onOpen)d.onOpen();else Ur(s);break;case"c":if(d?.onClear)d.onClear();else console.clear(),Nr(s);break;case"q":if(d?.onQuit)d.onQuit();console.log(`${e.yellow}Stopping server...${e.reset}`),i(),process.exit(0);break;case"h":if(d?.onHelp)d.onHelp();else Bt();break;default:break}}async function zt(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=ot.resolve(t);if(!Ft.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 he(c,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),R=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,v=R?.defaultTheme||"github-dark",x=["github-dark"],C=R?.additionalThemes||[],B=[...new Set([...x,...C])].map((_)=>`<option value="${_}"${_===v?" selected":""}>${_}</option>`).join(`
|
|
513
513
|
`);return l=`
|
|
514
514
|
<!DOCTYPE html>
|
|
515
515
|
<html lang="en">
|
|
@@ -663,7 +663,7 @@ Keyboard shortcuts:`),console.log(` ${e.cyan}o${e.reset} + Enter - Open in brow
|
|
|
663
663
|
</head>
|
|
664
664
|
<body>
|
|
665
665
|
${kt(S)}
|
|
666
|
-
${wt(
|
|
666
|
+
${wt(B)}
|
|
667
667
|
|
|
668
668
|
${w}
|
|
669
669
|
|
|
@@ -876,10 +876,10 @@ else {
|
|
|
876
876
|
};
|
|
877
877
|
})();
|
|
878
878
|
</script>
|
|
879
|
-
`}function Ve(t,s,i={}){let d=Xr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+d+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function $t(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Ct(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>s.endsWith(d))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var st=null;function Et(t){if(!st)st=new an(t);return st}function lt(){if(st)st.stop(),st=null}import Pt from"path";var it={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Pt.relative(Pt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await gr(i,d);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 p=new Set;if(i.cache&&i.cachePath){let x=await vn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await ie(()=>Bun.file(m).text(),"",(x)=>{throw new
|
|
879
|
+
`}function Ve(t,s,i={}){let d=Xr(s,i),c=t.lastIndexOf("</body>");if(c!==-1)return t.slice(0,c)+d+t.slice(c);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function $t(t){let s=t.toLowerCase();return s.endsWith(".css")||s.endsWith(".scss")||s.endsWith(".sass")||s.endsWith(".less")}function Ct(t){let s=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>s.endsWith(d))}function Rt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((i)=>i.test(t))}var st=null;function Et(t){if(!st)st=new an(t);return st}function lt(){if(st)st.stop(),st=null}import Pt from"path";var it={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Pt.relative(Pt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await gr(i,d);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 p=new Set;if(i.cache&&i.cachePath){let x=await vn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await ie(()=>Bun.file(m).text(),"",(x)=>{throw new Dn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new Dn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=X.time("script-extraction",()=>{let x=h,C=se(h);if(C)x=C.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],B="",_=[];for(let E of k){let I=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",F=E.match(/<script\b([^>]*)>/i),K=F?F[1]:"";if(/\bserver\b/i.test(K))B=I;else _.push(E)}let j=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:B,templateContent:j,allScripts:_}}),S={__filename:m,__dirname:Pt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await ie(()=>u(g,S,m),void 0,(x)=>{let C=new U(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(O.log(C,{filePath:m,scriptContent:g}),i.debug)throw C});let v=await X.timeAsync("directive-processing",async()=>await n(y,S,m,i,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-ddx52kk5.js"),C=x(w.join(`
|
|
880
880
|
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+C+`
|
|
881
881
|
`+v.slice(k);else v+=`
|
|
882
|
-
${C}`}if(v=await Z(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await wn(m,v,p,i),i.debug)console.log(`Cached template ${m} with ${p.size} dependencies`)}return{contents:v,loader:"html"}}catch(p){let h=p instanceof Error?p:new U(`Plugin processing failed: ${String(p)}`,m);if(O.log(h,{filePath:m,buildConfig:t.config}),Vt.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||
|
|
882
|
+
${C}`}if(v=await Z(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await wn(m,v,p,i),i.debug)console.log(`Cached template ${m} with ${p.size} dependencies`)}return{contents:v,loader:"html"}}catch(p){let h=p instanceof Error?p:new U(`Plugin processing failed: ${String(p)}`,m);if(O.log(h,{filePath:m,buildConfig:t.config}),Vt.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>
|
|
883
883
|
<html lang="en">
|
|
884
884
|
<head>
|
|
885
885
|
<meta charset="UTF-8">
|
|
@@ -939,12 +939,12 @@ ${C}`}if(v=await Z(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await wn
|
|
|
939
939
|
<h1>Something went wrong</h1>
|
|
940
940
|
<p>An internal error occurred. Please try again later.</p>
|
|
941
941
|
</body>
|
|
942
|
-
</html>`,loader:"html"}}})}};async function Vn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=we.resolve(t);if(!He.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return zt(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");He.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let
|
|
943
|
-
${
|
|
942
|
+
</html>`,loader:"html"}}})}};async function Vn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=we.resolve(t);if(!He.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return zt(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");He.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let I={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ge)=>({path:ge.path,external:!0}))}},F=await Bun.build({entrypoints:[p],outdir:h,plugins:[I,it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!F.success)return console.error(`${e.red}Build failed:${e.reset}`,F.logs),!1;let K=F.outputs.find(($e)=>$e.path.endsWith(".html"));if(!K)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(K.path).text(),!0}catch(I){return console.error(`${e.red}Error building stx file:${e.reset}`,I),!1}};if(!await y())return!1;let S=we.dirname(p);await Lt(S);let R=i;try{if(R=await Ge(i),R!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${R} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let I=s.hmrPort||R+1;l=Et({wsPort:I,verbose:!1}),m=l.start(I)}let v={},x=null,C;try{let{loadStxConfig:I}=await import("./chunk-9985eshw.js"),F=await I();if(C=s.stxOptions?.serverApi??F.serverApi,F?.apiRouter)x=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){v=F.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Q}=await import("./chunk-xvt6vvg4.js"),$e=F.broadcasting;await K($e);let ge=$e.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ge}/ws${e.reset}`);let Oe=we.join(process.cwd(),"channels.ts");if(He.existsSync(Oe))try{let ne=await Q(Oe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(K){console.warn(`${e.yellow}Broadcasting failed to start: ${K.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:B}=await import("./chunk-tx1mq72q.js"),_=await k(process.cwd(),C);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${R}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let j=Gr({port:R,async fetch(I){return qt(I,await(async()=>{let F=new URL(I.url);if([h,we.dirname(p),we.join(process.cwd(),"public")].some((ne)=>B(we.join(ne,F.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(I);if(ne.status!==404)return ne}catch{}if(v[F.pathname])try{return await v[F.pathname](I)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await _(I);if(K)return K;if(F.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Ve(W,m);if(s.native)if(W.includes("<head>"))W=W.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(s.titlebarHidden)if(W.includes("<head>"))W=W.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Q=we.join(h,F.pathname);if(He.existsSync(Q)&&He.statSync(Q).isFile()){let ne=Bun.file(Q),W=we.extname(Q).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Fe=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),Ue=await ne.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":H}})}let $e=we.dirname(p),ge=we.join($e,F.pathname);if(He.existsSync(ge)&&He.statSync(ge).isFile()){let ne=Bun.file(ge),W=we.extname(ge).toLowerCase(),H="text/plain";if(W===".ts"||W===".tsx"){let Fe=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),Ue=await ne.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":H}})}let Oe=we.join(process.cwd(),"public",F.pathname);if(He.existsSync(Oe)&&He.statSync(Oe).isFile()){let ne=Bun.file(Oe),W=we.extname(Oe).toLowerCase(),H="application/octet-stream";if(W===".ts"||W===".tsx"){let Fe=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),Ue=await ne.text(),tt=Fe.transformSync(Ue);return new Response(tt,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":H="text/html";break;case".css":H="text/css";break;case".js":H="text/javascript";break;case".json":H="application/json";break;case".png":H="image/png";break;case".jpg":case".jpeg":H="image/jpeg";break;case".gif":H="image/gif";break;case".svg":H="image/svg+xml";break;case".ico":H="image/x-icon";break;case".woff":H="font/woff";break;case".woff2":H="font/woff2";break;case".ttf":H="font/ttf";break;case".otf":H="font/otf";break;case".eot":H="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":H}})}return new Response("Not Found",{status:404})})())},error(I){return new Response(`<pre>${I}
|
|
943
|
+
${I.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
944
944
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
945
945
|
${e.bright}\u2192 ${e.cyan}http://localhost:${R}/${e.reset}`),console.log(`
|
|
946
946
|
${e.yellow}Routes:${e.reset}`);let E=we.relative(process.cwd(),p);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${E}${e.reset}`),console.log(`
|
|
947
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(
|
|
947
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(j.url.toString(),()=>{if(d)He.watch(we.dirname(p),{recursive:!0}).close();j.stop()}),s.native){let I=await Bun.file(p).text(),F=Tt(I);await rt(R,{title:we.basename(p,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!F,sidebarConfig:F})}if(d){let I=we.dirname(p);console.log(`${e.blue}Watching ${e.bright}${I}${e.reset} for changes...`);let F=He.watch(I,{recursive:!0},async(K,Q)=>{if(!Q||Rt(Q))return;if(Ct(Q)){console.log(`${e.yellow}File ${e.bright}${Q}${e.yellow} changed, rebuilding...${e.reset}`),Te.clear(),oe();let $e=await y();if(await kn(S),c&&l)if($e)l.reload(Q);else l.error("Build failed - check console for details")}else if($t(Q)){if(console.log(`${e.cyan}CSS ${e.bright}${Q}${e.cyan} changed${e.reset}`),c&&l)l.updateCss(Q)}});process.on("SIGINT",()=>{if(F.close(),l)lt();j.stop(),process.exit(0)})}return!0}var{serve:Jr}=globalThis.Bun;import Ze from"fs";import Pe from"path";var cn=`
|
|
948
948
|
<script data-stx-helpers>
|
|
949
949
|
(function() {
|
|
950
950
|
'use strict'
|
|
@@ -1255,14 +1255,14 @@ else {
|
|
|
1255
1255
|
|
|
1256
1256
|
})()
|
|
1257
1257
|
</script>
|
|
1258
|
-
`;function dn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((d)=>d.split(Pe.sep)),i=[];for(let d=0;d<s[0].length;d++){let c=s[0][d];if(s.every((l)=>l[d]===c))i.push(c);else break}return i.join(Pe.sep)}async function Un(t,s={}){let i=s.port||3000,d=s.watch!==!1;for(let v of t){let x=Pe.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=dn(t.map((v)=>Pe.dirname(Pe.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},p=[],h=async()=>{try{for(let v of t){let x=Pe.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:
|
|
1258
|
+
`;function dn(t){if(t.length===0)return"";if(t.length===1)return t[0];let s=t.map((d)=>d.split(Pe.sep)),i=[];for(let d=0;d<s[0].length;d++){let c=s[0][d];if(s.every((l)=>l[d]===c))i.push(c);else break}return i.join(Pe.sep)}async function Un(t,s={}){let i=s.port||3000,d=s.watch!==!1;for(let v of t){let x=Pe.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=dn(t.map((v)=>Pe.dirname(Pe.resolve(v))));console.log(`${e.blue}Processing ${e.bright}${t.length}${e.reset} files...`);let m={},p=[],h=async()=>{try{for(let v of t){let x=Pe.resolve(v);if(x.endsWith(".md"))try{let{content:k,data:B}=await he(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),_=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,j=_?.defaultTheme||"github-dark",E=["github-dark"],I=_?.additionalThemes||[],K=[...new Set([...E,...I])].map((Oe)=>`<option value="${Oe}"${Oe===j?" selected":""}>${Oe}</option>`).join(`
|
|
1259
1259
|
`),Q=`
|
|
1260
1260
|
<!DOCTYPE html>
|
|
1261
1261
|
<html lang="en">
|
|
1262
1262
|
<head>
|
|
1263
1263
|
<meta charset="UTF-8">
|
|
1264
1264
|
<meta name="viewport" content="width=device-width, initial-scale=1.0">
|
|
1265
|
-
<title>${ln(
|
|
1265
|
+
<title>${ln(B.title||Pe.basename(x))}</title>
|
|
1266
1266
|
<!-- Syntax highlighting styles -->
|
|
1267
1267
|
<style id="syntax-theme">
|
|
1268
1268
|
:root {
|
|
@@ -1408,7 +1408,7 @@ else {
|
|
|
1408
1408
|
</style>
|
|
1409
1409
|
</head>
|
|
1410
1410
|
<body>
|
|
1411
|
-
${kt(
|
|
1411
|
+
${kt(B)}
|
|
1412
1412
|
${wt(K)}
|
|
1413
1413
|
|
|
1414
1414
|
${k}
|
|
@@ -1418,20 +1418,20 @@ else {
|
|
|
1418
1418
|
</script>
|
|
1419
1419
|
</body>
|
|
1420
1420
|
</html>
|
|
1421
|
-
`,ge=`/${Pe.relative(l,x).replace(/\.md$/,"")}`;if(ge.endsWith("/index"))ge=ge.slice(0,-6)||"/";m[ge||"/"]={filePath:x,content:Q,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(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(
|
|
1422
|
-
${pe(E,x)}`);continue}let
|
|
1423
|
-
</head>`);else
|
|
1424
|
-
</head>`);return new Response(
|
|
1421
|
+
`,ge=`/${Pe.relative(l,x).replace(/\.md$/,"")}`;if(ge.endsWith("/index"))ge=ge.slice(0,-6)||"/";m[ge||"/"]={filePath:x,content:Q,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(E){E.onResolve({filter:/^\/(images|fonts|assets|public)\//},(I)=>({path:I.path,external:!0}))}},B;try{let E=await Bun.build({entrypoints:[x],outdir:c,plugins:[k,it],define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!E.success){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:`,pe(E.logs,x));continue}let I=E.outputs.find((F)=>F.path.endsWith(".html"));if(!I){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}B=await Bun.file(I.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
|
|
1422
|
+
${pe(E,x)}`);continue}let j=`/${Pe.relative(l,x).replace(/\.stx$/,"")}`;if(j.endsWith("/index"))j=j.slice(0,-6)||"/";if(j.includes("[")){let{regex:E,params:I}=$r(j,{page:!0});p.push({pattern:E,paramNames:I,filePath:x,routeTemplate:j,fileType:"stx"}),m[j]={filePath:x,content:B,fileType:"stx"}}else m[j||"/"]={filePath:x,content:B,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}`,pe(v)),!1}};if(!await h())return!1;let y=i;try{if(y=await Ge(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=Jr({port:y,async fetch(v){let x=new URL(v.url),C=Pe.join(process.cwd(),"public",x.pathname);if(Ze.existsSync(C)&&Ze.statSync(C).isFile()){let _=Bun.file(C),j=Pe.extname(C).toLowerCase(),E="application/octet-stream";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),F=await _.text(),K=I.transformSync(F);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":E}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let _ of p){let j=x.pathname.match(_.pattern);if(j){let E=m[_.routeTemplate];if(E){let I={};for(let Q=0;Q<_.paramNames.length;Q++)I[_.paramNames[Q]]=decodeURIComponent(j[Q+1]);let F=E.content,K=`<script>window.__routeParams = ${JSON.stringify(I)};</script>`;if(F.includes("</head>"))F=F.replace("</head>",`${K}
|
|
1423
|
+
</head>`);else F=K+F;k={...E,content:F}}break}}if(k)return f(k.content).then((_)=>{if(_.includes("</head>"))_=_.replace("</head>",`${cn}
|
|
1424
|
+
</head>`);return new Response(_,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let B=Pe.join(c,x.pathname);if(Ze.existsSync(B)&&Ze.statSync(B).isFile()){let _=Bun.file(B),j=Pe.extname(B).toLowerCase(),E="text/plain";if(j===".ts"||j===".tsx"){let I=new Bun.Transpiler({loader:j===".tsx"?"tsx":"ts"}),F=await _.text(),K=I.transformSync(F);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(j){case".html":E="text/html";break;case".css":E="text/css";break;case".js":E="text/javascript";break;case".json":E="application/json";break;case".png":E="image/png";break;case".jpg":case".jpeg":E="image/jpeg";break;case".gif":E="image/gif";break;case".svg":E="image/svg+xml";break;case".ico":E="image/x-icon";break;case".woff":E="font/woff";break;case".woff2":E="font/woff2";break;case".ttf":E="font/ttf";break;case".otf":E="font/otf";break;case".eot":E="application/vnd.ms-fontobject";break}return new Response(_,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&m["/"]){let _=ae(v);return f(m["/"].content).then((j)=>{if(_){let E=j.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let I=j.match(/<title[^>]*>([\s\S]*?)<\/title>/i),F=I?I[1]:"",K=`<!DOCTYPE html><html><head><title>${ln(F)}</title></head><body><main>${E[1]}</main></body></html>`;return new Response(K,{headers:{"Content-Type":"text/html","X-STX-Partial":"true",...T(),"Cache-Control":Be,Pragma:"no-cache",Expires:"0"}})}}return new Response(j,{headers:{"Content-Type":"text/html",...T(),"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}
|
|
1425
1425
|
${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1426
1426
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1427
1427
|
${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
|
|
1428
|
-
${e.yellow}Routes:${e.reset}`);let S=new Set(p.map((v)=>v.routeTemplate)),R=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Pe.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of p){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");R.push({route:x,filePath:Pe.relative(process.cwd(),v.filePath),fileType:"stx"})}if(R.sort((v,x)=>v.route.localeCompare(x.route)),R.forEach((v,x)=>{let k=x===R.length-1?"\u2514\u2500 ":"\u251C\u2500 ",
|
|
1429
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(d)Ze.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),Te.clear(),oe(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function ln(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Yr}=globalThis.Bun;import be from"fs";import te from"path";async function pn(t){try{return jt(await Bun.file(t).text())}catch{return}}function Nt(t){let s=Bun.file(t),i=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},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":d[i]||"application/octet-stream",...l}})}async function Wn(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=te.resolve(t),{loadStxConfig:h}=await import("./chunk-bdn21f8c.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-wr42shpx.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(p,S),v=g.root&&g.root!=="."?te.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",C=te.join(v,x);if(!be.existsSync(C)&&!g._layerPageDirs?.some((A)=>be.existsSync(A)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=L(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],M=[];for(let{dir:A,prefix:F}of H)if(be.existsSync(A)){let z=L(te.dirname(A),{pagesDir:te.basename(A)});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,E=null,_=null;if(s.stxOptions?.shell!==!1){if(_=await $o(p,s.stxOptions?.shell),_){if(E=await Vr(_,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(p,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}dt(),await ft(p);let B=pt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let K={},Q=null;try{let{loadStxConfig:A}=await import("./chunk-bdn21f8c.js"),F=await A(p);if(F?.apiRouter)Q=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){K=F.apiRoutes;let z=Object.keys(K).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:V}=await import("./chunk-792sscsk.js"),ve=F.broadcasting;await z(ve);let ze=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ze}/ws${e.reset}`);let qe=te.join(process.cwd(),"channels.ts");if(be.existsSync(qe))try{let ee=await V(qe);console.log(`${e.blue}Loaded ${e.bright}${ee} broadcast channel${ee!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ee){console.warn(`${e.yellow}Failed to load channels.ts: ${ee.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let $e=a(p,"output");be.mkdirSync($e,{recursive:!0});let ge=new Map,Oe=new Set,ne=async(A)=>{let F=Rr(C,A);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:$e,plugins:[it],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}},W=new Map,j=async(A,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:ve,loadStxConfig:ze,injectRouterScript:qe}=await import("./chunk-bdn21f8c.js"),{checkCache:ee,cacheTemplate:Y,readFileCached:q,templateCache:G}=await import("./chunk-m85kmqbn.js"),Se=await ze(p),Ke=(re)=>{if(!re)return re;if(te.isAbsolute(re))return re;return te.resolve(p,re)},D={...ve,...Se,...s.stxOptions,autoShell:!0};if(s.debugDirectives)D.debug=!0;D.partialsDir=Ke(D.partialsDir),D.componentsDir=Ke(D.componentsDir),D.layoutsDir=Ke(D.layoutsDir),D.storesDir=Ke(D.storesDir||"stores"),D.cachePath=Ke(D.cachePath)??a(p,"cache");let ye=!F&&!s.profile,le=D.cache!==!1;if(le&&ye){let re=G.get(A.filePath);if(re)try{if((await be.promises.stat(A.filePath)).mtime.getTime()<=re.mtime){let je=!0;for(let Re of re.dependencies){if(!be.existsSync(Re)){je=!1;break}if((await be.promises.stat(Re)).mtime.getTime()>re.mtime){je=!1;break}}if(je){let Re=re.output;if(E)Re=xe(Re,{preserveHead:!0});let ct=W.get(A.filePath);return{route:A,content:Re,status:ct?.status??await pn(A.filePath),headers:ct?.headers}}}}catch{}let _e=await ee(A.filePath,D);if(_e){let Le=_e;if(E)Le=xe(Le,{preserveHead:!0});let je=W.get(A.filePath);return{route:A,content:Le,status:je?.status??await pn(A.filePath),headers:je?.headers}}}let fe=le?await q(A.filePath):await Bun.file(A.filePath).text(),Ce=jt(fe),{classifyAllScripts:J}=await import("./chunk-bdn21f8c.js"),Me=J(fe),Ne=Me.server.map((re)=>re.content),de=fe;for(let re of Me.server)de=de.replace(re.fullTag,"");let ue={__filename:A.filePath,__dirname:te.dirname(A.filePath),__stx_options:D,params:F??{},__stx_runtime_head:{}};for(let re of Ne)try{await V(re,ue,A.filePath)}catch(_e){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,_e?.message||_e)}let We=new Set,Ae;if(s.profile){let re=performance.now();Ae=await z(de,ue,A.filePath,D,We);let _e=performance.now()-re,Le=te.relative(p,A.filePath)||A.filePath;console.log(`[stx:profile] ${Le} \u2192 ${_e.toFixed(2)}ms`)}else Ae=await z(de,ue,A.filePath,D,We);if(!E)Ae=await qe(Ae,{router:D.router});{let{interpolateScriptExpressions:re}=await import("./chunk-th9t5vks.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(_e,Le,je)=>{if(!/function\s+__stx_setup_/.test(je))return _e;return`<script${Le}>${re(je,ue)}</script>`})}if(E)Ae=xe(Ae,{preserveHead:!0});if(le&&ye)await Y(A.filePath,Ae,We,D);let{extractStreamBoundaries:qn}=await import("./chunk-awvbp2t4.js"),nt=qn(ue),at=ue.__streamTemplates;if(at&&typeof at==="object"&&Object.keys(at).length>0){let re=ue.streamBoundaries||{},_e={...D,autoShell:!1},Le=Object.keys(at).map((Re)=>({id:Re,render:async()=>{let ct=typeof re[Re]==="function"?await re[Re]():void 0;return z(at[Re],{...ue,$boundary:ct},A.filePath,_e,new Set)}})),je=new Set(Le.map((Re)=>Re.id));nt=[...(nt||[]).filter((Re)=>!je.has(Re.id)),...Le]}if(nt&&nt.length>0)Oe.add(A.pattern);else nt=void 0;let Kt=Je(ue),Xt=Ye(ue);if(ye)W.set(A.filePath,{status:Kt,headers:Xt});return{route:A,content:Ae,status:Kt??Ce,headers:Xt,boundaries:nt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,z),null}},Fe=8,Ue=async()=>{ge.clear(),I.clear();for(let A=0;A<k.length;A+=Fe){let F=k.slice(A,A+Fe),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)ge.set(V.route.pattern,V)}for(let A=0;A<M.length;A+=Fe){let F=M.slice(A,A+Fe),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return ge.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await Ue())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Lt(p);let et=i;try{if(et=await Ge(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 A=s.hmrPort||et+1;l=Et({wsPort:A,verbose:!1}),m=l.start(A)}let At=(A,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(A.includes("</head>"))return A.replace("</head>",`${V}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+A};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Yr({port:et,async fetch(A){let F=new URL(A.url),z=g?.publicDir||"public",V=te.join(p,z,F.pathname),ve=te.join(p,F.pathname),ze=te.join($e,F.pathname);if([V,ve,ze].some((D)=>w(D,p,S)))return new Response("Not Found",{status:404});let[qe,ee,Y]=await Promise.all([be.promises.stat(V).catch(()=>null),be.promises.stat(ve).catch(()=>null),be.promises.stat(ze).catch(()=>null)]);if(qe?.isFile()&&!w(V,p,S))return Nt(V);if(ee?.isFile()&&!w(ve,p,S))return Nt(ve);if(Y?.isFile()&&!w(ze,p,S))return Nt(ze);if(F.pathname.startsWith("/_stx/component/")){let D=decodeURIComponent(F.pathname.slice(16));if(D)try{let ye=`<${D} />`,le={...buildConfig,autoShell:!1},fe=await processDirectives(ye,{},te.join(p,"components",`${D}.stx`),le,new Set);return new Response(fe,{headers:{"Content-Type":"text/html"}})}catch(ye){return new Response(`<div class="stx-async-error">${ye.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:D}=await import("./chunk-3fb3m640.js"),ye=await D(A,{publicDir:te.join(p,z),cacheDir:a(p,"cache","img")});if(ye)return ye}if(Q)try{let D=await Q.handleRequest(A);if(D.status!==404)return D}catch{}if(K[F.pathname])try{return await K[F.pathname](A)}catch(D){return new Response(JSON.stringify({error:D.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await R(A);if(q)return q;let G=Fn(F.pathname,k);if(G){let D=ge.get(G.route.pattern),ye=Oe.has(G.route.pattern);if(G.route.isDynamic&&Object.keys(G.params).length>0||ye){let le=await j(G.route,G.params);if(le)D=le}if(D){let le=D.status??200,fe=D.headers??{},Ce=(G.route.filePath?Xe(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:G.params})){let Ne=await ne(404);if(Ne){let de=Ne;if(de=await f(de,p),c)de=Ve(de,m);return new Response(de,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Me=gt(F.pathname,G.params,Ce,F.search),Ne=mt(Me,null,A,{isServer:!0}),de=await ht(Ce.middleware,Ne);if(de.redirect){let ue=de.redirect.path,We=de.redirect.options.redirectCode||302,Ae=new Headers(de.responseHeaders);return Ae.set("Location",ue),new Response(null,{status:We,headers:Ae})}if(de.abort){let{statusCode:ue,message:We}=de.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${ue}</title></head><body><h1>Error ${ue}</h1><p>${We}</p></body></html>`,{status:ue,headers:{"Content-Type":"text/html"}})}if(Object.keys(de.state).length>0){let ue=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(de.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;D.content=D.content.replace("</head>",`${ue}</head>`)}}let J=D.content;if(E&&Ro(A)){let Me=Ie(J),Ne=me(J),de=J.match(/<title[^>]*>([\s\S]*?)<\/title>/i),ue=de?To(de[1].trim()):"";if(Object.keys(G.params).length>0)J=At(J,G.params);J=await f(J,p);let We=g?.router?.container||"main";return J=ce(J,We),new Response(J,{status:le,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Me.layout,"X-STX-Layout-Group":Me.group,"X-STX-Runtime":Ne?"true":"false",...ue&&{"X-STX-Title":encodeURIComponent(ue)},[Ii]:Ms(),...T(),"Cache-Control":Be}})}if(E)J=Xn(E,J);if(Object.keys(G.params).length>0)J=At(J,G.params);if(J=await f(J,p),c)J=Ve(J,m);if(s.native)if(J.includes("<head>"))J=J.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 J="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+J;if(s.titlebarHidden)if(J.includes("<head>"))J=J.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 J=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${J}`;if(D.boundaries&&D.boundaries.length>0){let{renderStreamingPage:Me,streamToResponse:Ne}=await import("./chunk-awvbp2t4.js");return Ne(Me(J,D.boundaries,{timeoutMs:30000}),{status:le,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(J,{status:le,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...fe}})}}if(M.length>0){let D=M.map((le)=>le.route),ye=Fn(F.pathname,D);if(ye){let le=I.get(ye.route.pattern);if(le){let fe=le.content;if(E)fe=Xn(E,fe);if(Object.keys(ye.params).length>0)fe=At(fe,ye.params);if(fe=await f(fe,p),c)fe=Ve(fe,m);return new Response(fe,{status:le.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:le}of H)if(le!=="/"&&F.pathname.startsWith(le)){let fe=I.get(le)||I.get(le+"/");if(fe){let Ce=fe.content;if(E)Ce=Xn(E,Ce);if(Ce=await f(Ce,p),c)Ce=Ve(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(ut(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Se=ge.get("/");if(Se){let D=Se.content;if(D=await f(D,p),c)D=Ve(D,m);if(s.native)if(D.includes("<head>"))D=D.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 D="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+D;return new Response(D,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Ke=await ne(404);if(Ke){let D=Ke;if(D=await f(D,p),c)D=Ve(D,m);return new Response(D,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let F=await ne(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
|
|
1428
|
+
${e.yellow}Routes:${e.reset}`);let S=new Set(p.map((v)=>v.routeTemplate)),R=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Pe.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of p){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");R.push({route:x,filePath:Pe.relative(process.cwd(),v.filePath),fileType:"stx"})}if(R.sort((v,x)=>v.route.localeCompare(x.route)),R.forEach((v,x)=>{let k=x===R.length-1?"\u2514\u2500 ":"\u251C\u2500 ",B=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${B}`)}),console.log(`
|
|
1429
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(d)Ze.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,C)=>{if(!C)return;if(C.endsWith(".stx")||C.endsWith(".js")||C.endsWith(".ts")||C.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${C}${e.yellow} changed, rebuilding...${e.reset}`),Te.clear(),oe(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function ln(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Yr}=globalThis.Bun;import be from"fs";import te from"path";async function pn(t){try{return jt(await Bun.file(t).text())}catch{return}}function Nt(t){let s=Bun.file(t),i=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},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":d[i]||"application/octet-stream",...l}})}async function Wn(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=te.resolve(t),{loadStxConfig:h}=await import("./chunk-9985eshw.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-tx1mq72q.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(p,S),v=g.root&&g.root!=="."?te.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",C=te.join(v,x);if(!be.existsSync(C)&&!g._layerPageDirs?.some((A)=>be.existsSync(A)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${C}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=L(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[C,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${C}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let B=g?._pluginPageDirs||[],_=[];for(let{dir:A,prefix:z}of B)if(be.existsSync(A)){let N=L(te.dirname(A),{pagesDir:te.basename(A)});for(let V of N){let ve=z==="/"?V.pattern:`${z}${V.pattern==="/"?"":V.pattern}`;_.push({route:{...V,pattern:ve},prefix:z})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${z}${e.reset}`)}let j=new Map,E=null,I=null;if(s.stxOptions?.shell!==!1){if(I=await $o(p,s.stxOptions?.shell),I){if(E=await Vr(I,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(p,I)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}dt(),await ft(p);let F=pt();if(F.length>0)console.log(`${e.blue}Loaded ${e.bright}${F.length}${e.blue} middleware: ${e.dim}${F.join(", ")}${e.reset}`);let K={},Q=null;try{let{loadStxConfig:A}=await import("./chunk-9985eshw.js"),z=await A(p);if(z?.apiRouter)Q=z?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(z?.apiRoutes){K=z.apiRoutes;let N=Object.keys(K).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(z?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:V}=await import("./chunk-xvt6vvg4.js"),ve=z.broadcasting;await N(ve);let ze=ve.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ze}/ws${e.reset}`);let qe=te.join(process.cwd(),"channels.ts");if(be.existsSync(qe))try{let ee=await V(qe);console.log(`${e.blue}Loaded ${e.bright}${ee} broadcast channel${ee!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ee){console.warn(`${e.yellow}Failed to load channels.ts: ${ee.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let $e=a(p,"output");be.mkdirSync($e,{recursive:!0});let ge=new Map,Oe=new Set,ne=async(A)=>{let z=Rr(C,A);if(!z)return null;try{let N=await Bun.build({entrypoints:[z],outdir:$e,plugins:[it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!N.success)return null;let V=N.outputs.find((ve)=>ve.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,H=async(A,z)=>{try{let{processDirectives:N,extractVariables:V,defaultConfig:ve,loadStxConfig:ze,injectRouterScript:qe}=await import("./chunk-9985eshw.js"),{checkCache:ee,cacheTemplate:Y,readFileCached:q,templateCache:G}=await import("./chunk-0vfqp662.js"),Se=await ze(p),Ke=(re)=>{if(!re)return re;if(te.isAbsolute(re))return re;return te.resolve(p,re)},M={...ve,...Se,...s.stxOptions,autoShell:!0};if(s.debugDirectives)M.debug=!0;M.partialsDir=Ke(M.partialsDir),M.componentsDir=Ke(M.componentsDir),M.layoutsDir=Ke(M.layoutsDir),M.storesDir=Ke(M.storesDir||"stores"),M.cachePath=Ke(M.cachePath)??a(p,"cache");let ye=!z&&!s.profile,le=M.cache!==!1;if(le&&ye){let re=G.get(A.filePath);if(re)try{if((await be.promises.stat(A.filePath)).mtime.getTime()<=re.mtime){let je=!0;for(let Re of re.dependencies){if(!be.existsSync(Re)){je=!1;break}if((await be.promises.stat(Re)).mtime.getTime()>re.mtime){je=!1;break}}if(je){let Re=re.output;if(E)Re=xe(Re,{preserveHead:!0});let ct=W.get(A.filePath);return{route:A,content:Re,status:ct?.status??await pn(A.filePath),headers:ct?.headers}}}}catch{}let _e=await ee(A.filePath,M);if(_e){let Le=_e;if(E)Le=xe(Le,{preserveHead:!0});let je=W.get(A.filePath);return{route:A,content:Le,status:je?.status??await pn(A.filePath),headers:je?.headers}}}let fe=le?await q(A.filePath):await Bun.file(A.filePath).text(),Ce=jt(fe),{classifyAllScripts:J}=await import("./chunk-9985eshw.js"),Me=J(fe),Ne=Me.server.map((re)=>re.content),de=fe;for(let re of Me.server)de=de.replace(re.fullTag,"");let ue={__filename:A.filePath,__dirname:te.dirname(A.filePath),__stx_options:M,params:z??{},__stx_runtime_head:{}};for(let re of Ne)try{await V(re,ue,A.filePath)}catch(_e){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",A.filePath,_e?.message||_e)}let We=new Set,Ae;if(s.profile){let re=performance.now();Ae=await N(de,ue,A.filePath,M,We);let _e=performance.now()-re,Le=te.relative(p,A.filePath)||A.filePath;console.log(`[stx:profile] ${Le} \u2192 ${_e.toFixed(2)}ms`)}else Ae=await N(de,ue,A.filePath,M,We);if(!E)Ae=await qe(Ae,{router:M.router});{let{interpolateScriptExpressions:re}=await import("./chunk-ddx52kk5.js");Ae=Ae.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(_e,Le,je)=>{if(!/function\s+__stx_setup_/.test(je))return _e;return`<script${Le}>${re(je,ue)}</script>`})}if(E)Ae=xe(Ae,{preserveHead:!0});if(le&&ye)await Y(A.filePath,Ae,We,M);let{extractStreamBoundaries:qn}=await import("./chunk-7y4ff3se.js"),nt=qn(ue),at=ue.__streamTemplates;if(at&&typeof at==="object"&&Object.keys(at).length>0){let re=ue.streamBoundaries||{},_e={...M,autoShell:!1},Le=Object.keys(at).map((Re)=>({id:Re,render:async()=>{let ct=typeof re[Re]==="function"?await re[Re]():void 0;return N(at[Re],{...ue,$boundary:ct},A.filePath,_e,new Set)}})),je=new Set(Le.map((Re)=>Re.id));nt=[...(nt||[]).filter((Re)=>!je.has(Re.id)),...Le]}if(nt&&nt.length>0)Oe.add(A.pattern);else nt=void 0;let Kt=Je(ue),Xt=Ye(ue);if(ye)W.set(A.filePath,{status:Kt,headers:Xt});return{route:A,content:Ae,status:Kt??Ce,headers:Xt,boundaries:nt}}catch(N){return console.error(`${e.red}Error building ${e.bright}${A.pattern}${e.reset}:`,N),null}},Fe=8,Ue=async()=>{ge.clear(),j.clear();for(let A=0;A<k.length;A+=Fe){let z=k.slice(A,A+Fe),N=await Promise.all(z.map((V)=>H(V)));for(let V of N)if(V)ge.set(V.route.pattern,V)}for(let A=0;A<_.length;A+=Fe){let z=_.slice(A,A+Fe),N=await Promise.all(z.map(({route:V})=>H(V)));for(let V of N)if(V)j.set(V.route.pattern,V)}return ge.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await Ue())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await Lt(p);let et=i;try{if(et=await Ge(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 A=s.hmrPort||et+1;l=Et({wsPort:A,verbose:!1}),m=l.start(A)}let At=(A,z)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(z).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(A.includes("</head>"))return A.replace("</head>",`${V}</head>`);if(A.includes("<body"))return A.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+A};console.log(`${e.blue}Starting server...${e.reset}`);let Dt=Yr({port:et,async fetch(A){let z=new URL(A.url),N=g?.publicDir||"public",V=te.join(p,N,z.pathname),ve=te.join(p,z.pathname),ze=te.join($e,z.pathname);if([V,ve,ze].some((M)=>w(M,p,S)))return new Response("Not Found",{status:404});let[qe,ee,Y]=await Promise.all([be.promises.stat(V).catch(()=>null),be.promises.stat(ve).catch(()=>null),be.promises.stat(ze).catch(()=>null)]);if(qe?.isFile()&&!w(V,p,S))return Nt(V);if(ee?.isFile()&&!w(ve,p,S))return Nt(ve);if(Y?.isFile()&&!w(ze,p,S))return Nt(ze);if(z.pathname.startsWith("/_stx/component/")){let M=decodeURIComponent(z.pathname.slice(16));if(M)try{let ye=`<${M} />`,le={...buildConfig,autoShell:!1},fe=await processDirectives(ye,{},te.join(p,"components",`${M}.stx`),le,new Set);return new Response(fe,{headers:{"Content-Type":"text/html"}})}catch(ye){return new Response(`<div class="stx-async-error">${ye.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(z.pathname==="/_stx/img"){let{handleImageRequest:M}=await import("./chunk-c091xff6.js"),ye=await M(A,{publicDir:te.join(p,N),cacheDir:a(p,"cache","img")});if(ye)return ye}if(Q)try{let M=await Q.handleRequest(A);if(M.status!==404)return M}catch{}if(K[z.pathname])try{return await K[z.pathname](A)}catch(M){return new Response(JSON.stringify({error:M.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await R(A);if(q)return q;let G=Fn(z.pathname,k);if(G){let M=ge.get(G.route.pattern),ye=Oe.has(G.route.pattern);if(G.route.isDynamic&&Object.keys(G.params).length>0||ye){let le=await H(G.route,G.params);if(le)M=le}if(M){let le=M.status??200,fe=M.headers??{},Ce=(G.route.filePath?Xe(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(Ce.validate){if(!await Ce.validate({params:G.params})){let Ne=await ne(404);if(Ne){let de=Ne;if(de=await f(de,p),c)de=Ve(de,m);return new Response(de,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Ce.middleware){let Me=gt(z.pathname,G.params,Ce,z.search),Ne=mt(Me,null,A,{isServer:!0}),de=await ht(Ce.middleware,Ne);if(de.redirect){let ue=de.redirect.path,We=de.redirect.options.redirectCode||302,Ae=new Headers(de.responseHeaders);return Ae.set("Location",ue),new Response(null,{status:We,headers:Ae})}if(de.abort){let{statusCode:ue,message:We}=de.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${ue}</title></head><body><h1>Error ${ue}</h1><p>${We}</p></body></html>`,{status:ue,headers:{"Content-Type":"text/html"}})}if(Object.keys(de.state).length>0){let ue=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(de.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;M.content=M.content.replace("</head>",`${ue}</head>`)}}let J=M.content;if(E&&Ro(A)){let Me=Ie(J),Ne=me(J),de=J.match(/<title[^>]*>([\s\S]*?)<\/title>/i),ue=de?To(de[1].trim()):"";if(Object.keys(G.params).length>0)J=At(J,G.params);J=await f(J,p);let We=g?.router?.container||"main";return J=ce(J,We),new Response(J,{status:le,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Me.layout,"X-STX-Layout-Group":Me.group,"X-STX-Runtime":Ne?"true":"false",...ue&&{"X-STX-Title":encodeURIComponent(ue)},[Ii]:Ms(),...T(),"Cache-Control":Be}})}if(E)J=Xn(E,J);if(Object.keys(G.params).length>0)J=At(J,G.params);if(J=await f(J,p),c)J=Ve(J,m);if(s.native)if(J.includes("<head>"))J=J.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 J="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+J;if(s.titlebarHidden)if(J.includes("<head>"))J=J.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 J=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${J}`;if(M.boundaries&&M.boundaries.length>0){let{renderStreamingPage:Me,streamToResponse:Ne}=await import("./chunk-7y4ff3se.js");return Ne(Me(J,M.boundaries,{timeoutMs:30000}),{status:le,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(J,{status:le,headers:{"Content-Type":"text/html",...T(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...fe}})}}if(_.length>0){let M=_.map((le)=>le.route),ye=Fn(z.pathname,M);if(ye){let le=j.get(ye.route.pattern);if(le){let fe=le.content;if(E)fe=Xn(E,fe);if(Object.keys(ye.params).length>0)fe=At(fe,ye.params);if(fe=await f(fe,p),c)fe=Ve(fe,m);return new Response(fe,{status:le.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:le}of B)if(le!=="/"&&z.pathname.startsWith(le)){let fe=j.get(le)||j.get(le+"/");if(fe){let Ce=fe.content;if(E)Ce=Xn(E,Ce);if(Ce=await f(Ce,p),c)Ce=Ve(Ce,m);return new Response(Ce,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(ut(z.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Se=ge.get("/");if(Se){let M=Se.content;if(M=await f(M,p),c)M=Ve(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 Ke=await ne(404);if(Ke){let M=Ke;if(M=await f(M,p),c)M=Ve(M,m);return new Response(M,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(A){let z=await ne(500);if(z)return new Response(z,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${A}
|
|
1430
1430
|
${A.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1431
1431
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1432
1432
|
${e.bright}\u2192 ${e.cyan}http://localhost:${et}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
|
|
1433
|
-
${e.yellow}Routes:${e.reset}`);let Mt=[...Ar(k,p)];for(let{route:A}of
|
|
1434
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Dt.url.toString(),()=>{if(l)lt();Dt.stop()}),s.native){let A,
|
|
1433
|
+
${e.yellow}Routes:${e.reset}`);let Mt=[...Ar(k,p)];for(let{route:A}of _)Mt.push(`${A.pattern}`);if(Mt.forEach((A,z)=>{let V=z===Mt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${A}`)}),console.log(`
|
|
1434
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Dt.url.toString(),()=>{if(l)lt();Dt.stop()}),s.native){let A,z=te.join(C,"index.stx");if(be.existsSync(z)){let V=await Bun.file(z).text();A=Tt(V)}let N=g?.app?.window??{};await rt(et,{title:g?.app?.head?.title||te.basename(p)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!A,sidebarConfig:A})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let A=(ee)=>ee.startsWith("public/")||ee.startsWith("public\\"),z=(ee)=>{let Y=ee.toLowerCase();return Y.endsWith(".stx")||Y.endsWith(".html")||Y.endsWith(".md")},N=new Map,V=()=>{let ee=new Set([p,...g._layerGraph?.layers.map((Y)=>Y.root)??[],...g._layerGraph?.configDependencies.map((Y)=>te.dirname(Y))??[]].filter((Y)=>be.existsSync(Y)).map((Y)=>be.realpathSync(Y)));for(let Y of g._layerGraph?.layers??[])for(let q of Object.values(Y.resources)){if(!be.existsSync(q))continue;let G=be.realpathSync(q);if(![...ee].some((Se)=>G===Se||G.startsWith(`${Se}${te.sep}`)))ee.add(G)}for(let[Y,q]of N)if(!ee.has(Y))q.close(),N.delete(Y);for(let Y of ee)if(!N.has(Y)&&be.existsSync(Y))N.set(Y,be.watch(Y,{recursive:!0},(q,G)=>{ze(Y,q,G).catch((Se)=>console.error("[stx] Layer rebuild failed:",Se))}))},ve=Promise.resolve(),ze=(ee,Y,q)=>(ve=ve.catch(()=>{}).then(()=>qe(ee,Y,q)),ve),qe=async(ee,Y,q)=>{if(!q||Rt(q))return;if(Ct(q)){if(g._layerGraph){let G=await h(p);Object.assign(g,G),k.splice(0,k.length,...L(v,{pagesDir:x,pagesDirs:G._layerPageDirs?[C,...G._layerPageDirs.slice(1)]:void 0})),V()}if(A(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(z(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),Te.clear(),oe();try{let{invalidateFileCache:G,templateCache:Se}=await import("./chunk-0vfqp662.js");G(te.resolve(ee,q)),Se.delete(te.resolve(ee,q))}catch{}if(I&&q){if(te.resolve(ee,q)===I||te.basename(I)===q){let Se=await Vr(I,s.stxOptions||{});if(Se)E=Se}}if(await Ue(),await kn(p),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),Te.clear(),oe();try{let{invalidateFileCache:G,templateCache:Se}=await import("./chunk-0vfqp662.js");G(te.resolve(ee,q)),Se.delete(te.resolve(ee,q))}catch{}if(await Ue(),c&&l)l.reload(q)}}else if($t(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let ee of N.values())ee.close();if(l)lt();Dt.stop(),process.exit(0)})}return!0}import Ut from"fs";import yt from"path";async function Qr(t){try{let i=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!i)return[];let d=i[1],c=[],l=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,m;while((m=l.exec(d))!==null){let p=m[1],h=m[2]||m[3]||m[4];if(!h)continue;let g={name:h},y=p.match(/@type\s+\{([^}]+)\}/i);if(y)g.type=y[1].trim();if(p.match(/@required/i))g.required=!0;let S=p.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)g.default=S[1].trim();let R=p.split(`
|
|
1435
1435
|
`).map((v)=>v.trim().replace(/^\*\s*/,"")).filter((v)=>!v.startsWith("@")&&v.length>0);g.description=R.join(" ").trim(),c.push(g)}if(c.length===0){let p=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(p){let g=p[1].split(",").map((y)=>y.trim()).filter(Boolean);for(let y of g){let[w]=y.split(":").map((S)=>S.trim());if(w)c.push({name:w})}}}return c}catch(s){return console.error(`Error extracting props from ${t}:`,s),[]}}async function Zr(t){try{let s=await Bun.file(t).text(),i=s.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||s.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(i)return i[1].split(`
|
|
1436
1436
|
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function eo(t,s=!1,i){let d=yt.basename(t,".stx"),c=await Qr(t),l=await Zr(t),m="";if(s&&i)m=`<${i}></${i}>`;else{let p=c.map((h)=>{if(h.type==="boolean")return`:${h.name}="true"`;return`${h.name}="value"`}).join(`
|
|
1437
1437
|
`);m=`<${d}
|
|
@@ -1570,7 +1570,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Dt.
|
|
|
1570
1570
|
<td>@${l.name}</td>
|
|
1571
1571
|
<td>${l.description||"-"}</td>
|
|
1572
1572
|
<td>${l.hasEndTag?"Yes":"No"}</td>
|
|
1573
|
-
</tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return c+="</body></html>",c}function io(t=[],s=[],i=[],d){return JSON.stringify({components:t,templates:s,directives:i,extraContent:d||""},null,2)}async function ao(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:d,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Ut.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let p=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),p=await to(s,d),console.log(`Found ${p.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await no(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await ro(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",R="";switch(y){case"markdown":S=oo(p,h,g,w),R="md";break;case"html":S=so(p,h,g,w),R="html";break;case"json":S=io(p,h,g,w),R="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=yt.join(m,`stx-docs.${R}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function ho(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},i=t.componentsDir||P.componentsDir,d=t.templatesDir||".";return ao({componentsDir:i,templatesDir:d,webComponentsConfig:P.webComponents,customDirectives:P.customDirectives,config:s})}var mn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function
|
|
1573
|
+
</tr>`;c+="</tbody></table>";for(let l of i)if(l.example)c+=`<h3>@${l.name}</h3>`,c+=`<p>${l.description||""}</p>`,c+="<h4>Example</h4>",c+=`<pre><code>${l.example.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""").replace(/'/g,"'")}</code></pre>`}return c+="</body></html>",c}function io(t=[],s=[],i=[],d){return JSON.stringify({components:t,templates:s,directives:i,extraContent:d||""},null,2)}async function ao(t){try{let{componentsDir:s,templatesDir:i,webComponentsConfig:d,customDirectives:c,config:l}=t;if(!l.enabled)return!1;let m=l.outputDir||"docs";if(await Ut.promises.mkdir(m,{recursive:!0}),console.log("Generating documentation..."),s)console.log(`Components directory: ${s}`);if(i)console.log(`Templates directory: ${i}`);console.log(`Output directory: ${m}`);let p=[];if(l.components!==!1&&s)console.log("Generating component documentation..."),p=await to(s,d),console.log(`Found ${p.length} components`);let h=[];if(l.templates!==!1&&i)console.log("Generating template documentation..."),h=await no(i),console.log(`Found ${h.length} templates`);let g=[];if(l.directives!==!1)console.log("Generating directive documentation..."),g=await ro(c),console.log(`Found ${g.length} directives`);let y=l.format||"markdown",w=l.extraContent,S="",R="";switch(y){case"markdown":S=oo(p,h,g,w),R="md";break;case"html":S=so(p,h,g,w),R="html";break;case"json":S=io(p,h,g,w),R="json";break;default:throw Error(`Unsupported documentation format: ${y}`)}let v=yt.join(m,`stx-docs.${R}`);return await Bun.write(v,S),console.log(`Documentation generated: ${v}`),!0}catch(s){return console.error("Error generating documentation:",s),!1}}async function ho(t){let s={enabled:!0,outputDir:t.output||"docs",format:t.format||"markdown",components:t.components!==!1,templates:t.templates!==!1,directives:t.directives!==!1,extraContent:t.extraContent},i=t.componentsDir||P.componentsDir,d=t.templatesDir||".";return ao({componentsDir:i,templatesDir:d,webComponentsConfig:P.webComponents,customDirectives:P.customDirectives,config:s})}var mn={indentSize:2,useTabs:!1,maxLineLength:120,normalizeWhitespace:!0,sortAttributes:!1,trimTrailingWhitespace:!0};function Dr(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
|
|
1574
1574
|
`;let d=t;if(i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=po(d,i),d=So(d,i),d=uo(d,i),i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,""),d=d.replace(/(\S)[ \t]+(<\/[^>]+>)/g,"$1$2");if(d=d.replace(/\r\n/g,`
|
|
1575
1575
|
`).replace(/\r/g,`
|
|
1576
1576
|
`),!d.endsWith(`
|
|
@@ -1578,7 +1578,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Dt.
|
|
|
1578
1578
|
`;return d}function yo(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
|
|
1579
1579
|
`;let d=t;if(d=d.replace(/^( *)```(html|stx)\n([\s\S]*?)^( *)```/gm,(c,l,m,p,h)=>{let g=p.split(`
|
|
1580
1580
|
`),y=g.filter((x)=>x.trim().length>0);if(y.length===0)return c;let w=Math.min(...y.map((x)=>{let C=x.match(/^( *)/);return C?C[1].length:0})),S=g.map((x)=>{if(x.trim().length===0)return"";return x.substring(w)}).join(`
|
|
1581
|
-
`),v=
|
|
1581
|
+
`),v=Dr(S,i).trimEnd().split(`
|
|
1582
1582
|
`).map((x)=>{if(x.trim().length===0)return"";return l+x}).join(`
|
|
1583
1583
|
`);return`${l}\`\`\`${m}
|
|
1584
1584
|
${v}
|
|
@@ -1601,7 +1601,7 @@ ${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,p)=>{let h=p.substring(Math.max
|
|
|
1601
1601
|
`),s=s.split(`
|
|
1602
1602
|
`).map((c)=>c.trim()).join(`
|
|
1603
1603
|
`),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function po(t,s){let d=lo(t).split(`
|
|
1604
|
-
`),c=[],l=0,m=!1,p=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<d.length;h++){let g=d[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 R=y===">";if(fn(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(p.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),C=y.startsWith("@")&&wo(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),
|
|
1604
|
+
`),c=[],l=0,m=!1,p=s.useTabs?"\t":" ".repeat(s.indentSize);for(let h=0;h<d.length;h++){let g=d[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 R=y===">";if(fn(y)&&!y.startsWith("<")&&!y.startsWith("@")){c.push(p.repeat(l)+y);continue}let v=y.startsWith("@end"),x=y.startsWith("@else")||y.startsWith("@elseif"),C=y.startsWith("@")&&wo(y),k=y.startsWith("<!DOCTYPE")||y.startsWith("<!doctype"),B=y.startsWith("<!--"),_=y.startsWith("</"),j=y.startsWith("<")&&!_&&!B&&!k,E=y.includes("/>")||xo(y),I=fn(y);if(_||v)l=Math.max(0,l-1);let F=x?Math.max(0,l-1):l;if(R)c.push(g);else c.push(p.repeat(F)+y);if(j&&!E&&!I&&!R||C)l++;if(w)m=!0;if(S)m=!1}return c.join(`
|
|
1605
1605
|
`)}function uo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,d,c)=>{let l=c.trim().replace(/\s+/g," ");return`@${d}(${l})`}),t=t.replace(/@(csrf|method)\s*\(\s*([^)]*)\s*\)/g,(i,d,c)=>{if(c.trim()==="")return`@${d}`;return`@${d}(${c.trim()})`}),s.normalizeWhitespace)t=t.replace(/\{\{\s*([^}]+)\s*\}\}/g,(i,d)=>`{{ ${d.trim()} }}`),t=t.replace(/\{!!\s*([^!]+)\s*!!\}/g,(i,d)=>`{!! ${d.trim()} !!}`);return t}function xo(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 d=i[1];return s.includes(d.toLowerCase())}return!1}function fn(t){return/<(\w+)(?:\s[^>]*)?>[\s\S]*?<\/\1>/.test(t)}function wo(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 So(t,s){if(!s.sortAttributes)return t;return t.replace(/<(\w+)([^>]*)>/g,(i,d,c)=>{if(!c.trim())return i;if(c.includes("<")||c.includes(`
|
|
1606
1606
|
`)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],p;while((p=l.exec(c))!==null)m.push({name:p[1],value:p[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`<${d}${h?` ${h}`:""}>`})}import gn from"fs";import Wt from"path";async function bo(t="index.stx",s={}){try{let i=s.force||!1,d=Wt.resolve(process.cwd(),t);if(await Bun.file(d).exists()){if(!i)throw Error(`File ${t} already exists. Use --force to overwrite.`);console.warn(`File ${t} already exists. Overwriting...`)}let c=Wt.dirname(d);if(!gn.existsSync(c))gn.mkdirSync(c,{recursive:!0});let l;if(s.template){let m=Wt.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=hn(s.preset),console.warn(`Using '${s.preset}' preset template`);else l=hn("basic");return await Bun.write(d,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 hn(t){switch(t){case"basic":return yn();case"component":return ko();case"layout":return Co();case"blog":return Eo();case"api":return Po();case"app":return Oo();default:return yn()}}function yn(){return`<script>
|
|
1607
1607
|
const title = "My stx Page"
|
|
@@ -2030,4 +2030,4 @@ const features = [
|
|
|
2030
2030
|
</script>
|
|
2031
2031
|
</body>
|
|
2032
2032
|
</html>`}var vo="f9c3713";function da(t){return t}function pa(t){return t}function fo(t,s){let i=[],d=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(d)){let m=l.slice(d.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}import De from"fs";import ke from"path";function En(t){try{return De.statSync(t).mtimeMs}catch{return null}}function Ot(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 Ai(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Pn(t,s="stx"){let i=ke.resolve(t);for(let d=0;d<10;d++){let c=ke.join(i,"pantry","@stacksjs",s);if(De.existsSync(c))return c;let l=ke.dirname(i);if(l===i)break;i=l}return null}var On=["@stacksjs/stx","bun-plugin-stx"];function Di(t){try{let s=De.readFileSync(ke.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Mi(t,s=6){let i=ke.resolve(t),d=[],c=new Set;function l(p,h){if(h>s)return;let g;try{g=De.realpathSync(p)}catch{return}if(c.has(g))return;c.add(g);for(let w of On){let S=ke.join(p,w),R=Di(S);if(R!==null)d.push({name:w,version:R,dir:ke.relative(i,S)||S,nested:h>0})}let y;try{y=De.readdirSync(p,{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=ke.join(p,w.name);if(w.name.startsWith("@")){let v;try{v=De.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let C=ke.join(S,x.name,"node_modules");if(De.existsSync(C))l(C,h+1)}continue}let R=ke.join(S,"node_modules");if(De.existsSync(R))l(R,h+1)}}let m=ke.join(i,"node_modules");if(De.existsSync(m))l(m,0);return d}function _i(t){let s=[];for(let i of On){let d=t.filter((m)=>m.name===i);if(d.length<=1)continue;let c=[...new Set(d.map((m)=>m.version))],l=d.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${d.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 Mr(t={}){let s=t.cwd?ke.resolve(t.cwd):process.cwd(),i=t.resolve??Ai,d=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 _i(Mi(s)))c.push(h);let p=Pn(s,"stx");if(!p)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=ke.join(p,"src/signals.ts"),g=[ke.join(p,"dist/index.js"),ke.join(p,"dist/signals.js")].find((v)=>De.existsSync(v))||null,y=En(h),w=g?En(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${p} 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 ${p} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Ot(w,d)}) is OLDER than src/signals.ts (${Ot(y,d)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${p} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Ot(y,d)}, dist ${Ot(w,d)})`});let S=ke.join(s,"node_modules/@stacksjs/stx"),R=null;try{R=De.lstatSync(S)}catch{R=null}if(!R)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(R.isSymbolicLink()){let v=null;try{v=De.realpathSync(S)}catch{}let x=(()=>{try{return De.realpathSync(p)}catch{return p}})();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 Lr(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let d of t.checks)if(i.push(` ${s[d.status]} ${d.name}: ${d.detail}`),d.fix)i.push(` \u2192 ${d.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(`
|
|
2033
|
-
`)}export{fo,go,mo,ho,
|
|
2033
|
+
`)}export{fo,go,mo,ho,Dr,yo,bo,vo,da,pa,Mr,Lr,Vn,Un,Wn};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Y,n}from"./chunk-
|
|
2
|
+
import{Y,n}from"./chunk-7f0gh0kg.js";import p from"fs";import g from"path";import*as y from"readline";var e={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m"},u={help:{description:"Show available commands",usage:"help [command]",handler:async(t,o)=>{if(t[0]&&u[t[0]]){let r=u[t[0]];console.log(`
|
|
3
3
|
${e.bold}${t[0]}${e.reset} - ${r.description}`),console.log(` Usage: ${e.cyan}${r.usage}${e.reset}
|
|
4
4
|
`)}else{console.log(`
|
|
5
5
|
${e.bold}Available Commands:${e.reset}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
function E(){let{NODE_ENV:n}=process.env;return n==="production"}function
|
|
3
|
-
export{E,
|
|
2
|
+
function E(){let{NODE_ENV:n}=process.env;return n==="production"}function D(){let{STX_DEBUG:n}=process.env;return!E()||n==="true"}function Ln(){let{NODE_ENV:n}=process.env;return n==="test"}function to(n){return n==="compile"||E()}function jn(n){if(!n)return n;try{return new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(n).trim()}catch{return n}}
|
|
3
|
+
export{E,D,Ln,to,jn};
|