@stacksjs/stx 0.2.612 → 0.2.614
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-tawfv519.js → chunk-06bwys2z.js} +1 -1
- package/dist/{chunk-f6pjf3tb.js → chunk-1bqtsjry.js} +1 -1
- package/dist/chunk-1gyrk0qv.js +2 -0
- package/dist/{chunk-jbaedjyk.js → chunk-1q3e1w2y.js} +3 -3
- package/dist/chunk-1v40w4qr.js +2 -0
- package/dist/chunk-1xzxmnsd.js +2 -0
- package/dist/{chunk-1q06tw66.js → chunk-27h4ndsg.js} +2 -2
- package/dist/chunk-2a1sgnxf.js +2 -0
- package/dist/{chunk-kwfwc32d.js → chunk-2bagpncj.js} +2 -2
- package/dist/chunk-37n8rf75.js +2 -0
- package/dist/{chunk-bgcn01mr.js → chunk-3a60b9an.js} +2 -2
- package/dist/{chunk-jskaacqy.js → chunk-3cg5mrtq.js} +6 -6
- package/dist/{chunk-4x5zryhk.js → chunk-3hzr66vn.js} +8 -8
- package/dist/{chunk-6fmcs19t.js → chunk-3vbv4gxx.js} +5 -5
- package/dist/chunk-42er5gwc.js +2 -0
- package/dist/{chunk-1c0zvjt3.js → chunk-5hqkfqne.js} +9 -10
- package/dist/{chunk-t9pnkbg6.js → chunk-5mw7qawr.js} +1 -1
- package/dist/{chunk-zsqfvwwf.js → chunk-5pa5bbzv.js} +2 -2
- package/dist/chunk-6kqmr5z1.js +2 -0
- package/dist/{chunk-d5nxsg1p.js → chunk-71wntraa.js} +1 -1
- package/dist/{chunk-vbzpc1yz.js → chunk-araay35m.js} +4 -4
- package/dist/chunk-awvbp2t4.js +2 -0
- package/dist/chunk-b3g8zzc6.js +2 -0
- package/dist/chunk-bdn21f8c.js +2 -0
- package/dist/chunk-c6vb28zd.js +2 -0
- package/dist/chunk-cjm2d6w1.js +2 -0
- package/dist/{chunk-58s20ceb.js → chunk-ctf9gd40.js} +2 -2
- package/dist/chunk-dcdmr6cp.js +2 -0
- package/dist/{chunk-0s6shhb3.js → chunk-dq58tn5x.js} +1 -1
- package/dist/{chunk-f8kh3s0k.js → chunk-e5t4xhfk.js} +1 -1
- package/dist/{chunk-hw97qw4k.js → chunk-ehq5j4tb.js} +2 -2
- package/dist/{chunk-mfh61qdr.js → chunk-faq9x5kw.js} +15 -15
- package/dist/chunk-fq4xjy4k.js +2 -0
- package/dist/chunk-gv3se08t.js +2 -0
- package/dist/{chunk-qkczk53w.js → chunk-h74p4zay.js} +65 -65
- package/dist/chunk-hx2fc5dt.js +2 -0
- package/dist/{chunk-8n306p92.js → chunk-jpe8pt9m.js} +1 -1
- package/dist/{chunk-g18pwk0t.js → chunk-jrsvbztw.js} +1 -1
- package/dist/{chunk-btcc95hq.js → chunk-jwxppaj3.js} +4 -4
- package/dist/{chunk-qh3b1w7q.js → chunk-k0kajwdw.js} +1 -1
- package/dist/{chunk-adn5r0r4.js → chunk-kt9ksp8w.js} +1 -1
- package/dist/{chunk-t61vdbje.js → chunk-ktvr45qg.js} +6 -6
- package/dist/{chunk-jx1p2eza.js → chunk-m0x9gfx5.js} +1 -1
- package/dist/chunk-m85kmqbn.js +2 -0
- package/dist/chunk-mf6mqs9k.js +2 -0
- package/dist/chunk-mheh85ph.js +2 -0
- package/dist/{chunk-ewmpbxhv.js → chunk-mkss8wbh.js} +5 -5
- package/dist/{chunk-13xvn7vh.js → chunk-mqky9h29.js} +1 -1
- package/dist/chunk-n5acpvq3.js +2 -0
- package/dist/{chunk-zhe35k6k.js → chunk-nk0cn3yq.js} +1 -1
- package/dist/chunk-nvewemvh.js +2 -0
- package/dist/chunk-p1t8mm9b.js +2 -0
- package/dist/{chunk-7ed685cs.js → chunk-pv73vnyj.js} +1 -1
- package/dist/{chunk-970j89r5.js → chunk-pw0b0an6.js} +2 -2
- package/dist/{chunk-s43pj9n6.js → chunk-r9z467kx.js} +5 -5
- package/dist/chunk-rgg6kr7r.js +2 -0
- package/dist/chunk-rw3kgv2q.js +2 -0
- package/dist/{chunk-c9jav70j.js → chunk-s9jgsp0a.js} +3 -3
- package/dist/{chunk-th4x1wbc.js → chunk-t1cbac58.js} +3 -3
- package/dist/{chunk-z83p4bme.js → chunk-t4rxr1zj.js} +3 -3
- package/dist/chunk-t7h714ne.js +2 -0
- package/dist/{chunk-8dq3r6xw.js → chunk-t8akfx99.js} +6 -6
- package/dist/{chunk-ej2ka6g6.js → chunk-temrpzxj.js} +22 -22
- package/dist/chunk-th9t5vks.js +2 -0
- package/dist/{chunk-7yjyzzcp.js → chunk-tkw5mr0k.js} +1 -1
- package/dist/chunk-tq5nzr99.js +2 -0
- package/dist/{chunk-ktg9khmj.js → chunk-trhr4gzz.js} +4 -4
- package/dist/{chunk-j4smj8cr.js → chunk-vxa0h3yy.js} +4 -4
- package/dist/{chunk-xncqjkjm.js → chunk-wq6b8qgz.js} +1 -1
- package/dist/chunk-wr42shpx.js +2 -0
- package/dist/chunk-x81g1v5x.js +2 -0
- package/dist/{chunk-5fa9g7x1.js → chunk-xeqysa9z.js} +62 -62
- package/dist/{chunk-74j18qk0.js → chunk-y8h823cb.js} +28 -28
- package/dist/chunk-yn2d8x8m.js +3 -0
- package/dist/chunk-ywf6pa29.js +2 -0
- package/dist/{chunk-frvn6psn.js → chunk-ywxg3f9s.js} +1 -1
- package/dist/chunk-yxksngda.js +2 -0
- package/dist/chunk-yytfje8a.js +2 -0
- package/dist/{chunk-6w0h6vpd.js → chunk-zb191qdx.js} +3 -3
- package/dist/{chunk-wy93yhce.js → chunk-zde9mef4.js} +3 -3
- package/dist/chunk-zxvqjzr2.js +2 -0
- package/dist/cli.js +42 -42
- package/dist/craft-entry.js +2 -2
- package/dist/craft.js +2 -2
- package/dist/native/compiler/render-screen.js +7 -0
- package/dist/native/runtime/jsc-globals.js +18 -3
- package/dist/pwa.js +3 -3
- package/dist/ssg.js +5 -5
- package/package.json +5 -5
- package/dist/chunk-07rryvyt.js +0 -2
- package/dist/chunk-0dkd5z22.js +0 -2
- package/dist/chunk-0hpng9by.js +0 -2
- package/dist/chunk-0nfysn6e.js +0 -2
- package/dist/chunk-0vmwp37n.js +0 -2
- package/dist/chunk-0x72g1jn.js +0 -2
- package/dist/chunk-15wmzj8j.js +0 -2
- package/dist/chunk-1p7v0ytv.js +0 -2
- package/dist/chunk-32y8adx3.js +0 -2
- package/dist/chunk-5003ncbh.js +0 -2
- package/dist/chunk-514ykzna.js +0 -2
- package/dist/chunk-6yn7pc5s.js +0 -2
- package/dist/chunk-7mee8bte.js +0 -2
- package/dist/chunk-7mgbh13b.js +0 -2
- package/dist/chunk-851cd8sc.js +0 -2
- package/dist/chunk-be89da2e.js +0 -2
- package/dist/chunk-cg8hg6cs.js +0 -3
- package/dist/chunk-cxv6mhky.js +0 -2
- package/dist/chunk-g8hwrejy.js +0 -2
- package/dist/chunk-gmqr7v81.js +0 -2
- package/dist/chunk-h94znyac.js +0 -2
- package/dist/chunk-j9pcvc0z.js +0 -2
- package/dist/chunk-m4k7f63m.js +0 -2
- package/dist/chunk-mtm39290.js +0 -2
- package/dist/chunk-n4z6evey.js +0 -2
- package/dist/chunk-pjh4kftn.js +0 -2
- package/dist/chunk-pjqrcbtt.js +0 -2
- package/dist/chunk-t535swnv.js +0 -2
- package/dist/chunk-trah2z70.js +0 -2
- package/dist/chunk-vrnb2xat.js +0 -2
- package/dist/chunk-xq9f9ftz.js +0 -2
- package/dist/chunk-xv9qre1x.js +0 -2
- package/dist/chunk-zar7fhqr.js +0 -2
- package/dist/chunk-zy266h8p.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,
|
|
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-xeqysa9z.js";import{U,Nn,ie,O,Vt}from"./chunk-k1hpxgzq.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-3hzr66vn.js";import{qt}from"./chunk-mqky9h29.js";import{pe}from"./chunk-5rtatjwq.js";import{a}from"./chunk-6ta850w8.js";import{N}from"./chunk-twmq5m6r.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
|
-
`).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,
|
|
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
|
|
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
|
+
`).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
|
-
`)}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,
|
|
8
|
-
`)}function bt(t,s,i,
|
|
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[H,M]of It(t.slice(p,k)))l[H]=M;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 H=/^(?:readonly\s+)?([A-Za-z_$][\w$]*)\s*\??\s*:\s*([\s\S]+)$/.exec(k);if(H)c[H[1]]=H[2].trim()}if(x.startsWith("{"))for(let[k,H]of It(x)){if(m.push(k),!H.startsWith("{")){let M=Zt(H);if(M)c[k]=M;continue}for(let[M,I]of It(H))if(M==="default")l[k]=I;else if(M==="type"){let E=Zt(I);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 H=yr(k),I=(H===-1?k:k.slice(0,H)).split(":")[0].trim().replace(/^\.\.\./,"");if(!I)continue;if(m.push(I),H!==-1)l[I]=k.slice(H+1).trim()}}else if(m.length===0)m.push(...Object.keys(c));return{text:t.slice(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),H=Ee.relative(i,k);return`${v}${H.startsWith(".")?H:`./${H}`}${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(([M,I])=>[M,en(M,I)])),S=vr(pr(c)),R=wr(S.template),v=xr(c,d,Ee.resolve(i.outputDir)),x=hr(R.template);for(let M of v.propNames){if(w[M])continue;let I=v.defaults[M];w[M]=en(M,{type:ur(v.declared[M])??fr(I),...I===void 0?{}:{default:mr(I)}})}let C=l.methods||{},k=s.methods||{},H=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,...H},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('>', '>')
|
|
@@ -303,22 +303,22 @@ export function defineComponent(Component, definition) {
|
|
|
303
303
|
}
|
|
304
304
|
return Component;
|
|
305
305
|
}
|
|
306
|
-
`}function Er(t){let s=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),i=Object.entries(t.methods).map(([
|
|
306
|
+
`}function Er(t){let s=JSON.stringify({tag:t.tag,template:t.template,styles:t.styles,shadowMode:t.shadowMode,progressive:t.progressive,properties:t.properties,eventTypes:t.eventTypes,bindings:t.bindings},null,2),i=Object.entries(t.methods).map(([p,h])=>{if(on.has(p))throw Error(`${t.sourcePath}: ${rn(p)}`);if(/^(?:async\s+)?[A-Za-z_$][\w$]*\s*\(/.test(h.trim()))return` ${h.trim()}`;return` ${p}($event) {
|
|
307
307
|
${h}
|
|
308
308
|
}`}).join(`
|
|
309
309
|
|
|
310
|
-
`),
|
|
310
|
+
`),d=t.scope,c=[...new Set([...Object.keys(t.properties),...d.propNames])].map((p)=>d.defaults[p]===void 0?p:`${p} = ${d.defaults[p]}`).join(", "),l=(p)=>p.split(`
|
|
311
311
|
`).map((h)=>h.trim()===""?h:` ${h}`).join(`
|
|
312
|
-
`),m="";if(t.render.trim()!==""||
|
|
312
|
+
`),m="";if(t.render.trim()!==""||d.body!==""||c!==""){let p=[c?`const { ${c} } = this._props();`:"",d.body,"let out = '';",t.render,"return out;"].filter(Boolean).join(`
|
|
313
313
|
`),h;try{let g=new Bun.Transpiler({loader:"ts"}).transformSync(`export function __render(__helpers) {
|
|
314
|
-
${
|
|
314
|
+
${p}
|
|
315
315
|
}`),y=g.indexOf("{"),w=g.lastIndexOf("}");h=g.slice(y+1,w).trim()}catch(g){throw Error(`${t.sourcePath}: failed to compile render (${g.message})`)}m=`
|
|
316
316
|
render(__helpers) {
|
|
317
317
|
const { escape: __escape, raw: __raw, values: __values, entries: __entries } = __helpers;
|
|
318
318
|
${l(h.trim())}
|
|
319
319
|
}
|
|
320
320
|
`}return`import { StxElement, defineComponent } from './runtime.js';
|
|
321
|
-
${
|
|
321
|
+
${d.imports.length?`${d.imports.join(`
|
|
322
322
|
`)}
|
|
323
323
|
`:""}
|
|
324
324
|
/** ${t.description||`${t.name} web component generated from ${t.file}.`} */
|
|
@@ -330,14 +330,14 @@ defineComponent(${t.name}, ${s});
|
|
|
330
330
|
export default ${t.name};
|
|
331
331
|
`}function xt(t){switch(t.type){case"boolean":return"boolean";case"number":return"number";case"array":return"unknown[]";case"object":return"Record<string, unknown>";default:return"string"}}function Pr(t){let s=Object.entries(t.properties).map(([l,m])=>` ${l}${m.required?"":"?"}: ${xt(m)}`).join(`
|
|
332
332
|
`),i=Object.entries(t.properties).map(([l,m])=>` ${l}: ${xt(m)}`).join(`
|
|
333
|
-
`),
|
|
333
|
+
`),d=Object.entries(t.events).map(([l,m])=>` ${JSON.stringify(l)}: CustomEvent<${m.detailType||"unknown"}>`).join(`
|
|
334
334
|
`),c=Object.keys(t.methods).map((l)=>` ${l}($event?: Event): unknown`).join(`
|
|
335
335
|
`);return`export interface ${t.name}Props {
|
|
336
336
|
${s}
|
|
337
337
|
}
|
|
338
338
|
|
|
339
339
|
export interface ${t.name}EventMap {
|
|
340
|
-
${
|
|
340
|
+
${d}
|
|
341
341
|
}
|
|
342
342
|
|
|
343
343
|
export declare class ${t.name} extends HTMLElement {
|
|
@@ -358,10 +358,10 @@ export default ${t.name}
|
|
|
358
358
|
`}function Or(t){return`declare global {
|
|
359
359
|
namespace JSX {
|
|
360
360
|
interface IntrinsicElements {
|
|
361
|
-
${t.map((i)=>{let
|
|
362
|
-
`),c=Object.keys(i.events).map((l)=>` ${`on${l.split(/[-:]/).map((
|
|
361
|
+
${t.map((i)=>{let d=Object.entries(i.properties).map(([l,m])=>` ${JSON.stringify(l)}?: ${xt(m)}`).join(`
|
|
362
|
+
`),c=Object.keys(i.events).map((l)=>` ${`on${l.split(/[-:]/).map((p)=>p.charAt(0).toUpperCase()+p.slice(1)).join("")}`}?: (event: CustomEvent<${i.events[l].detailType||"unknown"}>) => void`).join(`
|
|
363
363
|
`);return` ${JSON.stringify(i.tag)}: {
|
|
364
|
-
${
|
|
364
|
+
${d}
|
|
365
365
|
${c}
|
|
366
366
|
children?: unknown
|
|
367
367
|
slot?: string
|
|
@@ -374,9 +374,9 @@ ${c}
|
|
|
374
374
|
}
|
|
375
375
|
|
|
376
376
|
export {}
|
|
377
|
-
`}function Dr(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,
|
|
377
|
+
`}function Dr(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 _r(t){let s=JSON.stringify("\\{!!\\s*([\\w$.]+)\\s*!!\\}"),i=JSON.stringify("\\{\\{\\s*([\\w$.]+)\\s*\\}\\}"),
|
|
379
|
+
}`}function nn(t){return t.replace(/\/\*[\s\S]*?\*\//g,"").replace(/\s+/g," ").replace(/\s*([{}:;,])\s*/g,"$1").replace(/;}/g,"}").trim()}function _r(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('>', '>')
|
|
@@ -391,7 +391,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
|
|
|
391
391
|
let template = definition.template
|
|
392
392
|
.replace(new RegExp(${s}, 'g'), (_match, expression) => String(valueAt(values, expression) ?? ''))
|
|
393
393
|
.replace(new RegExp(${i}, 'g'), (_match, expression) => escapeHTML(valueAt(values, expression)))
|
|
394
|
-
.replace(new RegExp(${
|
|
394
|
+
.replace(new RegExp(${d}, 'gi'), (_match, name) => String(slots[name || 'default'] ?? ''));
|
|
395
395
|
const attributes = Object.entries(definition.properties).flatMap(([name, property]) => {
|
|
396
396
|
if (property.attribute === false || !(name in props)) return [];
|
|
397
397
|
const attribute = property.attribute || name.replace(/[A-Z]/g, letter => '-' + letter.toLowerCase());
|
|
@@ -410,7 +410,7 @@ export function renderComponent(tag, props = {}, slots = {}) {
|
|
|
410
410
|
}
|
|
411
411
|
|
|
412
412
|
${l}
|
|
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
|
|
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
416
|
`);if(await g("index.js",y),await g("ssr.js",_r(l)),t.declarations!==!1)await g("index.d.ts",l.map((x)=>`export * from './${x.tag}.js'`).join(`
|
|
@@ -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 Ir(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 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,"::")})}async function Hr(t){if(!await Ir(t))return!1;return await jr(t)}async function Ge(t,s=20){t=Number(t);for(let i=0;i<s;i++){let
|
|
507
|
+
</div>`}import sn from"net";async function Ir(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 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,"::")})}async function Hr(t){if(!await Ir(t))return!1;return await jr(t)}async function Ge(t,s=20){t=Number(t);for(let i=0;i<s;i++){let d=t+i;if(await Hr(d))return d}throw Error(`Could not find an available port between ${t} and ${t+s-1}`)}var Br={title:"stx Development",width:1400,height:900,darkMode:!0,hotReload:!0,titlebarHidden:!1,nativeSidebar:!1,sidebarWidth:260,sidebarConfig:void 0};async function Fr(){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={...Br,...s},d=await Fr();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
|
-
`,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
|
|
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 zr(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
|
|
512
|
-
`)){let l=
|
|
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 zr(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(),zr(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||[],H=[...new Set([...x,...C])].map((M)=>`<option value="${M}"${M===v?" selected":""}>${M}</option>`).join(`
|
|
513
513
|
`);return l=`
|
|
514
514
|
<!DOCTYPE html>
|
|
515
515
|
<html lang="en">
|
|
@@ -677,14 +677,14 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
677
677
|
${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(`
|
|
678
678
|
${e.bright}\u2192 ${e.cyan}http://localhost:${h}/${e.reset}`),console.log(`
|
|
679
679
|
${e.yellow}Routes:${e.reset}`);let y=ot.relative(process.cwd(),c);if(console.log(` ${e.green}\u2514\u2500 /${e.reset} \u2192 ${e.bright}${y}${e.reset}`),console.log(`
|
|
680
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(g.url.toString(),()=>{if(
|
|
680
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(g.url.toString(),()=>{if(d)Ft.watch(ot.dirname(c),{recursive:!0}).close();g.stop()}),s.native)await rt(h,{title:ot.basename(c,".md")});if(d){let w=ot.dirname(c);console.log(`${e.blue}Watching ${e.bright}${w}${e.reset} for changes...`);let S=Ft.watch(w,{recursive:!0},async(R,v)=>{if(v&&v.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${v}${e.yellow} changed, reprocessing...${e.reset}`),await m()});process.on("SIGINT",()=>{S.close(),g.stop(),process.exit(0)})}return!0}function Kr(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Gr}=globalThis.Bun;import He from"fs";import we from"path";class an{clients=new Set;server=null;options;constructor(t={}){this.options={wsPort:t.wsPort??3001,showOverlay:t.showOverlay??!0,reconnectInterval:t.reconnectInterval??1000,maxReconnectAttempts:t.maxReconnectAttempts??10,verbose:t.verbose??!1}}start(t){let s=t??this.options.wsPort,i=20;for(let d=0;d<i;d++)try{if(this.server=Bun.serve({port:s,fetch(c,l){if(l.upgrade(c,{data:{}}))return;return new Response("stx Hot Reload Server",{headers:{"Content-Type":"text/plain"}})},websocket:{open:(c)=>{if(this.clients.add(c),this.options.verbose)console.log(`[HMR] Client connected (${this.clients.size} total)`);c.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close:(c)=>{if(this.clients.delete(c),this.options.verbose)console.log(`[HMR] Client disconnected (${this.clients.size} total)`)},message:(c,l)=>{let m=typeof l==="string"?l:l.toString();if(m==="ping")return;try{let p=JSON.parse(m);if(p.type==="console"&&Array.isArray(p.args)){let h=p.args.join(" "),y={log:"\x1B[36m",warn:"\x1B[33m",error:"\x1B[31m",info:"\x1B[34m"}[p.level]??"\x1B[36m";console.log(`${y}[browser]${p.level!=="log"?` ${p.level}`:""}\x1B[0m ${h}`)}}catch{}}}}),this.options.verbose)console.log(`[HMR] WebSocket server started on port ${s}`);return s}catch(c){if(c?.code==="EADDRINUSE"){s++;continue}throw c}throw Error(`Could not find an available port after ${i} attempts starting from ${t??this.options.wsPort}`)}stop(){for(let t of this.clients)try{t.close()}catch{}if(this.clients.clear(),this.server)this.server.stop(),this.server=null;if(this.options.verbose)console.log("[HMR] Server stopped")}broadcast(t){let s=JSON.stringify(t),i=0;for(let d of this.clients)try{if(d.readyState===1)d.send(s),i++}catch{this.clients.delete(d)}if(this.options.verbose&&i>0)console.log(`[HMR] Broadcast ${t.type} to ${i} client(s)`)}reload(t){if(this.options.verbose)console.log(`[HMR] Sending reload to ${this.clients.size} client(s) for: ${t||"all"}`);this.broadcast({type:"reload",path:t,timestamp:Date.now()})}updateCss(t,s){this.broadcast({type:"css-update",path:t,content:s,timestamp:Date.now()})}error(t){this.broadcast({type:"error",content:t,timestamp:Date.now()})}get clientCount(){return this.clients.size}get port(){return this.options.wsPort}}function Xr(t,s={}){let{showOverlay:i=!0,reconnectInterval:d=1000,maxReconnectAttempts:c=10}=s;return`
|
|
681
681
|
<script>
|
|
682
682
|
(function() {
|
|
683
683
|
// stx Hot Reload Client
|
|
684
684
|
var wsUrl = 'ws://' + window.location.hostname + ':${t}';
|
|
685
685
|
var reconnectAttempts = 0;
|
|
686
686
|
var maxAttempts = ${c};
|
|
687
|
-
var reconnectInterval = ${
|
|
687
|
+
var reconnectInterval = ${d};
|
|
688
688
|
var socket = null;
|
|
689
689
|
var overlay = null;
|
|
690
690
|
var wasConnected = false; // Track if we ever connected successfully
|
|
@@ -876,10 +876,10 @@ else {
|
|
|
876
876
|
};
|
|
877
877
|
})();
|
|
878
878
|
</script>
|
|
879
|
-
`}function Ve(t,s,i={}){let
|
|
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 Nn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new Nn(`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)||[],H="",M=[];for(let E of k){let _=E.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=E.match(/<script\b([^>]*)>/i),K=B?B[1]:"";if(/\bserver\b/i.test(K))H=_;else M.push(E)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:M}}),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-th9t5vks.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),
|
|
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||N()?`<!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),u.forEach((x)=>p.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,
|
|
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 _={name:"public-assets",setup($e){$e.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ge)=>({path:ge.path,external:!0}))}},B=await Bun.build({entrypoints:[p],outdir:h,plugins:[_,it],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let K=B.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(_){return console.error(`${e.red}Error building stx file:${e.reset}`,_),!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 _=s.hmrPort||R+1;l=Et({wsPort:_,verbose:!1}),m=l.start(_)}let v={},x=null,C;try{let{loadStxConfig:_}=await import("./chunk-bdn21f8c.js"),B=await _();if(C=s.stxOptions?.serverApi??B.serverApi,B?.apiRouter)x=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){v=B.apiRoutes;let K=Object.keys(v).length;if(K>0)console.log(`${e.blue}Loaded ${e.bright}${K} API route${K>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:K,loadChannels:Q}=await import("./chunk-792sscsk.js"),$e=B.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:H}=await import("./chunk-wr42shpx.js"),M=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 I=Gr({port:R,async fetch(_){return qt(_,await(async()=>{let B=new URL(_.url);if([h,we.dirname(p),we.join(process.cwd(),"public")].some((ne)=>H(we.join(ne,B.pathname),process.cwd(),C)))return new Response("Not Found",{status:404});if(x)try{let ne=await x.handleRequest(_);if(ne.status!==404)return ne}catch{}if(v[B.pathname])try{return await v[B.pathname](_)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let K=await M(_);if(K)return K;if(B.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,B.pathname);if(He.existsSync(Q)&&He.statSync(Q).isFile()){let ne=Bun.file(Q),W=we.extname(Q).toLowerCase(),j="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":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":j}})}let $e=we.dirname(p),ge=we.join($e,B.pathname);if(He.existsSync(ge)&&He.statSync(ge).isFile()){let ne=Bun.file(ge),W=we.extname(ge).toLowerCase(),j="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":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":j}})}let Oe=we.join(process.cwd(),"public",B.pathname);if(He.existsSync(Oe)&&He.statSync(Oe).isFile()){let ne=Bun.file(Oe),W=we.extname(Oe).toLowerCase(),j="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":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":j}})}return new Response("Not Found",{status:404})})())},error(_){return new Response(`<pre>${_}
|
|
943
943
|
${_.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
944
944
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
945
945
|
${e.bright}\u2192 ${e.cyan}http://localhost:${R}/${e.reset}`),console.log(`
|
|
946
|
-
${e.yellow}Routes:${e.reset}`);let E=we.relative(process.cwd(),
|
|
947
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(I.url.toString(),()=>{if(
|
|
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(I.url.toString(),()=>{if(d)He.watch(we.dirname(p),{recursive:!0}).close();I.stop()}),s.native){let _=await Bun.file(p).text(),B=Tt(_);await rt(R,{title:we.basename(p,".stx"),titlebarHidden:s.titlebarHidden===!0,nativeSidebar:!!B,sidebarConfig:B})}if(d){let _=we.dirname(p);console.log(`${e.blue}Watching ${e.bright}${_}${e.reset} for changes...`);let B=He.watch(_,{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(B.close(),l)lt();I.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,7 +1255,7 @@ 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((
|
|
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:H}=await he(x,{markdown:{syntaxHighlighting:{serverSide:!0,enabled:!0,defaultTheme:P.markdown?.syntaxHighlighting?.defaultTheme||"github-dark",highlightUnknownLanguages:!0}}}),M=s.markdown?.syntaxHighlighting||P.markdown?.syntaxHighlighting,I=M?.defaultTheme||"github-dark",E=["github-dark"],_=M?.additionalThemes||[],K=[...new Set([...E,..._])].map((Oe)=>`<option value="${Oe}"${Oe===I?" selected":""}>${Oe}</option>`).join(`
|
|
1259
1259
|
`),Q=`
|
|
1260
1260
|
<!DOCTYPE html>
|
|
1261
1261
|
<html lang="en">
|
|
@@ -1419,24 +1419,24 @@ else {
|
|
|
1419
1419
|
</body>
|
|
1420
1420
|
</html>
|
|
1421
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)\//},(_)=>({path:_.path,external:!0}))}},H;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 _=E.outputs.find((B)=>B.path.endsWith(".html"));if(!_){console.error(`${e.red}No HTML output found for ${e.bright}${v}${e.reset}`);continue}H=await Bun.file(_.path).text()}catch(E){console.error(`${e.red}Build failed for ${e.bright}${v}${e.reset}:
|
|
1422
|
-
${pe(E,x)}`);continue}let I=`/${Pe.relative(l,x).replace(/\.stx$/,"")}`;if(I.endsWith("/index"))I=I.slice(0,-6)||"/";if(I.includes("[")){let{regex:E,params:_}=$r(I,{page:!0});
|
|
1422
|
+
${pe(E,x)}`);continue}let I=`/${Pe.relative(l,x).replace(/\.stx$/,"")}`;if(I.endsWith("/index"))I=I.slice(0,-6)||"/";if(I.includes("[")){let{regex:E,params:_}=$r(I,{page:!0});p.push({pattern:E,paramNames:_,filePath:x,routeTemplate:I,fileType:"stx"}),m[I]={filePath:x,content:H,fileType:"stx"}}else m[I||"/"]={filePath:x,content:H,fileType:"stx"}}}if(Object.keys(m).length===0)return console.error(`${e.red}No files were successfully processed${e.reset}`),!1;return!0}catch(v){return console.error(`${e.red}Error processing files:${e.reset}`,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 M=Bun.file(C),I=Pe.extname(C).toLowerCase(),E="application/octet-stream";if(I===".ts"||I===".tsx"){let _=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await M.text(),K=_.transformSync(B);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){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(M,{headers:{"Content-Type":E}})}let k=m[x.pathname];if(!k&&!x.pathname.endsWith("/"))k=m[`${x.pathname}/`];if(!k)for(let M of p){let I=x.pathname.match(M.pattern);if(I){let E=m[M.routeTemplate];if(E){let _={};for(let Q=0;Q<M.paramNames.length;Q++)_[M.paramNames[Q]]=decodeURIComponent(I[Q+1]);let B=E.content,K=`<script>window.__routeParams = ${JSON.stringify(_)};</script>`;if(B.includes("</head>"))B=B.replace("</head>",`${K}
|
|
1423
1423
|
</head>`);else B=K+B;k={...E,content:B}}break}}if(k)return f(k.content).then((M)=>{if(M.includes("</head>"))M=M.replace("</head>",`${cn}
|
|
1424
1424
|
</head>`);return new Response(M,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})});let H=Pe.join(c,x.pathname);if(Ze.existsSync(H)&&Ze.statSync(H).isFile()){let M=Bun.file(H),I=Pe.extname(H).toLowerCase(),E="text/plain";if(I===".ts"||I===".tsx"){let _=new Bun.Transpiler({loader:I===".tsx"?"tsx":"ts"}),B=await M.text(),K=_.transformSync(B);return new Response(K,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(I){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(M,{headers:{"Content-Type":E}})}if(x.pathname!=="/"&&m["/"]){let M=ae(v);return f(m["/"].content).then((I)=>{if(M){let E=I.match(/<main[^>]*>([\s\S]*?)<\/main>/i);if(E){let _=I.match(/<title[^>]*>([\s\S]*?)<\/title>/i),B=_?_[1]:"",K=`<!DOCTYPE html><html><head><title>${ln(B)}</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(I,{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(
|
|
1429
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(w.url.toString(),()=>{if(p)Ze.watch(l,{recursive:!0}).close();w.stop()}),p){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=Ze.watch(l,{recursive:!0},async(x,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(),p={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":p[i]||"application/octet-stream",...l}})}async function Wn(t=".",s={}){let i=s.port||3000,p=s.watch!==!1,c=s.hotReload!==!1&&p,l=null,m=s.hmrPort||i+1,u=te.resolve(t),{loadStxConfig:h}=await import("./chunk-zy266h8p.js"),g=await h(u),{createServerApi:y,isServerApiSource:w}=await import("./chunk-851cd8sc.js"),S=s.stxOptions?.serverApi??g.serverApi,R=await y(u,S),v=g.root&&g.root!=="."?te.join(u,g.root):u,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(u,s.stxOptions?.shell),_){if(E=await Vr(_,s.stxOptions||{}),E)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(u,_)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}ut(),await ft(u);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-zy266h8p.js"),F=await A(u);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(u,"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-zy266h8p.js"),{checkCache:ee,cacheTemplate:Y,readFileCached:q,templateCache:G}=await import("./chunk-7mgbh13b.js"),Se=await ze(u),Ke=(re)=>{if(!re)return re;if(te.isAbsolute(re))return re;return te.resolve(u,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(u,"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-zy266h8p.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(u,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-vrnb2xat.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-7mee8bte.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(u);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(u,z,F.pathname),ve=te.join(u,F.pathname),ze=te.join($e,F.pathname);if([V,ve,ze].some((D)=>w(D,u,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,u,S))return Nt(V);if(ee?.isFile()&&!w(ve,u,S))return Nt(ve);if(Y?.isFile()&&!w(ze,u,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(u,"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(u,z),cacheDir:a(u,"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,u),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,u);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,u),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-7mee8bte.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,u),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,u),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(dt(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,u),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,u),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 ",H=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${H}`)}),console.log(`
|
|
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}
|
|
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,
|
|
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,F=te.join(C,"index.stx");if(be.existsSync(F)){let V=await Bun.file(F).text();A=Tt(V)}let z=g?.app?.window??{};await rt(et,{title:g?.app?.head?.title||te.basename(
|
|
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
|
|
1436
|
-
`).map((
|
|
1437
|
-
`);m=`<${
|
|
1438
|
-
${
|
|
1439
|
-
/>`}return{name:
|
|
1433
|
+
${e.yellow}Routes:${e.reset}`);let Mt=[...Ar(k,p)];for(let{route:A}of M)Mt.push(`${A.pattern}`);if(Mt.forEach((A,F)=>{let V=F===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,F=te.join(C,"index.stx");if(be.existsSync(F)){let V=await Bun.file(F).text();A=Tt(V)}let z=g?.app?.window??{};await rt(et,{title:g?.app?.head?.title||te.basename(p)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.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\\"),F=(ee)=>{let Y=ee.toLowerCase();return Y.endsWith(".stx")||Y.endsWith(".html")||Y.endsWith(".md")},z=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 z)if(!ee.has(Y))q.close(),z.delete(Y);for(let Y of ee)if(!z.has(Y)&&be.existsSync(Y))z.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(F(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),Te.clear(),oe();try{let{invalidateFileCache:G,templateCache:Se}=await import("./chunk-m85kmqbn.js");G(te.resolve(ee,q)),Se.delete(te.resolve(ee,q))}catch{}if(_&&q){if(te.resolve(ee,q)===_||te.basename(_)===q){let Se=await Vr(_,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-m85kmqbn.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 z.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
|
+
`).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
|
+
`).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
|
+
`);m=`<${d}
|
|
1438
|
+
${p}
|
|
1439
|
+
/>`}return{name:d,path:t,description:l,props:c,example:m,isWebComponent:s,tag:i}}async function un(t){try{if(!await r(t))return console.warn(`Components directory does not exist: ${t}`),[];let s=await Ut.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){let c=yt.join(t,d.name);if(d.isDirectory()){let l=await un(c);i.push(...l)}else if(d.isFile()&&d.name.endsWith(".stx"))i.push(c)}return i}catch(s){return console.error(`Error finding component files in ${t}:`,s),[]}}async function to(t,s){try{if(!await r(t))return[];let i=await un(t),d=[],c=new Map;if(s?.components?.length)for(let l of s.components)c.set(l.file,l);for(let l of i){let m=c.get(l),p=!!m,h=m?.tag,g=await eo(l,p,h);d.push(g)}return d}catch(i){return console.error("Error generating component docs:",i),[]}}async function no(t){try{if(!await r(t))return[];let s=await Ut.promises.readdir(t,{withFileTypes:!0}),i=[];for(let d of s){if(!d.isFile()||!d.name.endsWith(".stx"))continue;let c=yt.join(t,d.name),l=await Bun.file(c).text(),m=yt.basename(c,".stx"),p=l.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||l.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//),h=p?p[1].split(`
|
|
1440
1440
|
`).map((x)=>x.trim().replace(/^\*\s*/,"")).join(" ").trim():"",g=/@component\(\s*['"]([^'"]+)['"]/g,y=/<([A-Z][a-zA-Z0-9]*|[a-z]+-[a-z0-9-]+)(?:\s[^>]*)?\/?>|\{\{\s*slot\s*\}\}/g,w=new Set,S;while((S=g.exec(l))!==null)w.add(S[1]);while((S=y.exec(l))!==null)if(S[1]&&S[1]!=="slot")w.add(S[1]);let R=/@([a-z]+)(?:\s*\(|\s+|$)/g,v=new Set;while((S=R.exec(l))!==null)v.add(S[1]);i.push({name:m,path:c,description:h,components:[...w],directives:[...v]})}return i}catch(s){return console.error("Error generating template docs:",s),[]}}async function ro(t=[]){try{let s=[{name:"if",description:"Conditionally render content based on a condition",hasEndTag:!0,example:`@if(user.isLoggedIn)
|
|
1441
1441
|
<p>Welcome, {{ user.name }}!</p>
|
|
1442
1442
|
@endif`},{name:"else",description:"Provides an alternative if a condition is not met",hasEndTag:!1,example:`@if(user.isLoggedIn)
|
|
@@ -1457,9 +1457,9 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Dt.
|
|
|
1457
1457
|
<p>Page {{ page }}</p>
|
|
1458
1458
|
@endwhile`},{name:"component",description:"Include a component in the template",hasEndTag:!1,example:'@component("alert", { type: "warning", title: "Warning", message: "This is a warning" })'},{name:"include",description:"Include a partial template",hasEndTag:!1,example:'@include("partials/header")'},{name:"raw",description:"Display content without processing expressions",hasEndTag:!0,example:`@raw
|
|
1459
1459
|
{{ This will be displayed as-is }}
|
|
1460
|
-
@endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let i of t)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function oo(t=[],s=[],i=[],
|
|
1460
|
+
@endraw`},{name:"translate",description:"Translate a string using the i18n system",hasEndTag:!1,example:'@translate("welcome.message", { name: user.name })'},{name:"t",description:"Short alias for translate directive",hasEndTag:!1,example:'@t("welcome.message", { name: user.name })'}];for(let i of t)s.push({name:i.name,description:i.description||"",hasEndTag:i.hasEndTag||!1,example:""});return s}catch(s){return console.error("Error generating directive docs:",s),[]}}function oo(t=[],s=[],i=[],d){let c=`# stx Documentation
|
|
1461
1461
|
|
|
1462
|
-
`;if(
|
|
1462
|
+
`;if(d)c+=`${d}
|
|
1463
1463
|
|
|
1464
1464
|
`;if(t.length>0){c+=`## Components
|
|
1465
1465
|
|
|
@@ -1499,7 +1499,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Dt.
|
|
|
1499
1499
|
|
|
1500
1500
|
`,c+=`#### Example
|
|
1501
1501
|
|
|
1502
|
-
`,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function so(t=[],s=[],i=[],
|
|
1502
|
+
`,c+="```html\n",c+=l.example,c+="\n```\n\n"}return c}function so(t=[],s=[],i=[],d){let c=`<!DOCTYPE html>
|
|
1503
1503
|
<html lang="en">
|
|
1504
1504
|
<head>
|
|
1505
1505
|
<meta charset="UTF-8">
|
|
@@ -1542,7 +1542,7 @@ Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Qe(Dt.
|
|
|
1542
1542
|
</head>
|
|
1543
1543
|
<body>
|
|
1544
1544
|
<h1>stx Documentation</h1>
|
|
1545
|
-
`;if(
|
|
1545
|
+
`;if(d)c+=`<div>${d}</div>`;if(t.length>0){c+="<h2>Components</h2>";for(let l of t){if(c+=`<h3>${l.name}</h3>`,l.description)c+=`<p>${l.description}</p>`;if(l.isWebComponent)c+=`<p><strong>Web Component Tag:</strong> <code>${l.tag}</code></p>`;if(l.props.length>0){c+="<h4>Properties</h4>",c+=`<table>
|
|
1546
1546
|
<thead>
|
|
1547
1547
|
<tr>
|
|
1548
1548
|
<th>Name</th>
|
|
@@ -1570,23 +1570,23 @@ 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=[],
|
|
1574
|
-
`;let
|
|
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 Nr(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
|
|
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
|
-
`),!
|
|
1577
|
-
`))
|
|
1578
|
-
`;return
|
|
1579
|
-
`;let
|
|
1576
|
+
`),!d.endsWith(`
|
|
1577
|
+
`))d+=`
|
|
1578
|
+
`;return d}function yo(t,s={}){let i={...mn,...s};if(t.trim()==="")return`
|
|
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
1581
|
`),v=Nr(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}
|
|
1585
|
-
${l}\`\`\``}),i.trimTrailingWhitespace)
|
|
1585
|
+
${l}\`\`\``}),i.trimTrailingWhitespace)d=d.replace(/[ \t]+$/gm,"");if(d=d.replace(/\r\n/g,`
|
|
1586
1586
|
`).replace(/\r/g,`
|
|
1587
|
-
`),!
|
|
1588
|
-
`))
|
|
1589
|
-
`;return
|
|
1587
|
+
`),!d.endsWith(`
|
|
1588
|
+
`))d+=`
|
|
1589
|
+
`;return d}function lo(t){let s=t,i=[],d="__PROTECTED_BLOCK_";return s=s.replace(/(<(?:pre|code|textarea)[^>]*>)([\s\S]*?)(<\/(?:pre|code|textarea)>)/gi,(c)=>{let l=i.length;return i.push(c),`${d}${l}__`}),s=s.replace(/(@(?:if|foreach|for|while|unless|section|component|slot|push|prepend|error|auth|guest|can)(?:\((?:[^()'"]|'[^']*'|"[^"]*"|\((?:[^()'"]|'[^']*'|"[^"]*")*\))*\))?)/g,`
|
|
1590
1590
|
$1
|
|
1591
1591
|
`),s=s.replace(/(@end\w+)/g,`
|
|
1592
1592
|
$1
|
|
@@ -1594,16 +1594,16 @@ $1
|
|
|
1594
1594
|
$1
|
|
1595
1595
|
`),s=s.replace(/(@(?:csrf|method|include|extends|yield|stack|vite|asset)(?:\([^)]*\))?)/g,`
|
|
1596
1596
|
$1
|
|
1597
|
-
`),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,
|
|
1598
|
-
${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,
|
|
1599
|
-
${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,
|
|
1600
|
-
`}),s=s.replace(new RegExp(`${
|
|
1597
|
+
`),s=s.replace(/(?<=>)(<(?!\/)[^>]+>)/g,(c,l,m,p)=>{let h=p.substring(m+c.length,Math.min(p.length,m+c.length+20)),g=c.match(/<(\w+)/)?.[1];if(g&&h.match(new RegExp(`^</${g}>`)))return c;return`
|
|
1598
|
+
${c}`}),s=s.replace(/(>)(<\/)/g,(c,l,m,p,h)=>{let g=h.substring(Math.max(0,p-50),p),w=h.substring(p+c.length,Math.min(h.length,p+c.length+20)).match(/^(\w+)>/)?.[1],S=g.match(/<(\w+)[^>]*$/)?.[1];if(S&&w&&S===w)return c;return`${l}
|
|
1599
|
+
${m}`}),s=s.replace(/(<\/[^>]+>)(?=<|$)/g,(c,l,m,p)=>{let h=p.substring(Math.max(0,m-20),m),g=c.match(/<\/(\w+)>/)?.[1],y=new RegExp(`<${g}[^>]*>$`);if(g&&h.match(y))return c;return`${c}
|
|
1600
|
+
`}),s=s.replace(new RegExp(`${d}(\\d+)__`,"g"),(c,l)=>i[Number.parseInt(l,10)]),s=s.replace(/\n{2,}/g,`
|
|
1601
1601
|
`),s=s.split(`
|
|
1602
1602
|
`).map((c)=>c.trim()).join(`
|
|
1603
|
-
`),s=s.replace(/^\n+/,"").replace(/\n+$/,""),s}function po(t,s){let
|
|
1604
|
-
`),c=[],l=0,m=!1,
|
|
1605
|
-
`)}function uo(t,s){if(t=t.replace(/@(if|elseif|foreach|for|while)\s*\(\s*([^)]+)\s*\)/g,(i,
|
|
1606
|
-
`)||c.includes("@"))return i;let l=/(\w+)(?:=("[^"]*"|'[^']*'|[^\s>]+))?/g,m=[],
|
|
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"),H=y.startsWith("<!--"),M=y.startsWith("</"),I=y.startsWith("<")&&!M&&!H&&!k,E=y.includes("/>")||xo(y),_=fn(y);if(M||v)l=Math.max(0,l-1);let B=x?Math.max(0,l-1):l;if(R)c.push(g);else c.push(p.repeat(B)+y);if(I&&!E&&!_&&!R||C)l++;if(w)m=!0;if(S)m=!1}return c.join(`
|
|
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
|
+
`)||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"
|
|
1608
1608
|
const description = "A page built with stx"
|
|
1609
1609
|
const features = [
|
|
@@ -2029,5 +2029,5 @@ const features = [
|
|
|
2029
2029
|
})();
|
|
2030
2030
|
</script>
|
|
2031
2031
|
</body>
|
|
2032
|
-
</html>`}var vo="f9c3713";function
|
|
2033
|
-
`)}export{fo,go,mo,ho,Nr,yo,bo,vo,
|
|
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,Nr,yo,bo,vo,da,pa,Mr,Lr,Vn,Un,Wn};
|