@stacksjs/stx 0.2.551 → 0.2.553
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-5hdby5qp.js → chunk-0fatkxpr.js} +6 -0
- package/dist/{chunk-mvgmz8y8.js → chunk-16g71mm9.js} +1 -1
- package/dist/{chunk-ew038tkx.js → chunk-1hxh2wbw.js} +1 -1
- package/dist/{chunk-tv6ft73q.js → chunk-21v5eee6.js} +5 -5
- package/dist/{chunk-rwx6xg0r.js → chunk-2q624ng4.js} +1 -1
- package/dist/{chunk-a9f7c95b.js → chunk-31gk5b7d.js} +1 -1
- package/dist/{chunk-xng76fpn.js → chunk-45n128za.js} +1 -1
- package/dist/{chunk-qefxscqt.js → chunk-4b7y1p7f.js} +1 -1
- package/dist/chunk-59wnn6gp.js +2 -0
- package/dist/{chunk-vhze2vkc.js → chunk-5y2tgmb6.js} +1 -1
- package/dist/{chunk-whbfh14w.js → chunk-7qf883pk.js} +1 -1
- package/dist/{chunk-1wcy5dwb.js → chunk-81qx2ze8.js} +1 -1
- package/dist/{chunk-1ft901xy.js → chunk-8tsc5hmk.js} +1 -1
- package/dist/{chunk-4xfg4bqd.js → chunk-8wanndhv.js} +1 -1
- package/dist/{chunk-66hrd1ky.js → chunk-93jjxrx9.js} +2 -2
- package/dist/{chunk-vf97p29d.js → chunk-a2c6t7w2.js} +1 -1
- package/dist/{chunk-7y1bszgt.js → chunk-a7tmbbzz.js} +1 -1
- package/dist/{chunk-ecssbjvj.js → chunk-avgwezvb.js} +1 -1
- package/dist/{chunk-0y7wf87h.js → chunk-bh5qgbmv.js} +1 -1
- package/dist/{chunk-7ehqab26.js → chunk-d80mbwyp.js} +1 -1
- package/dist/{chunk-5jnae5f2.js → chunk-da4cj4zb.js} +1 -1
- package/dist/{chunk-eryyt0bm.js → chunk-ecevpzy6.js} +1 -1
- package/dist/{chunk-5vr2aekh.js → chunk-ez5w6a60.js} +1 -1
- package/dist/{chunk-c342fra6.js → chunk-ezrxgtkz.js} +1 -1
- package/dist/{chunk-bf6sav89.js → chunk-g1c3davk.js} +1 -1
- package/dist/{chunk-55n0004d.js → chunk-hh88tvs5.js} +1 -1
- package/dist/{chunk-0zkmzwh2.js → chunk-jb04k0sv.js} +1 -1
- package/dist/{chunk-ersngdzb.js → chunk-jj9356vp.js} +1 -1
- package/dist/{chunk-2g9y4r8p.js → chunk-kbc2bwd5.js} +1 -1
- package/dist/{chunk-4y48zgey.js → chunk-kmvyfwr3.js} +1 -1
- package/dist/{chunk-v40d4bdy.js → chunk-knr41h7p.js} +1 -1
- package/dist/{chunk-0pabd4ax.js → chunk-m24hxk60.js} +1 -1
- package/dist/chunk-mhwf2xrt.js +2 -0
- package/dist/{chunk-xs7g5qaw.js → chunk-mpga9770.js} +1 -1
- package/dist/{chunk-mre8szx6.js → chunk-nvsea9fk.js} +2 -2
- package/dist/{chunk-d38k0ynr.js → chunk-ptj7fwre.js} +1 -1
- package/dist/{chunk-n7wkd877.js → chunk-q28hdn0s.js} +1 -1
- package/dist/{chunk-rfjgv93m.js → chunk-q3sn0xc1.js} +1 -1
- package/dist/{chunk-xneqhbm5.js → chunk-q48nk2gt.js} +1 -1
- package/dist/{chunk-6t59q75z.js → chunk-qmt7t9nt.js} +1 -1
- package/dist/{chunk-dk3yc9k0.js → chunk-sgrwxhgg.js} +1 -1
- package/dist/{chunk-cc204fg5.js → chunk-sjqbd8ga.js} +226 -226
- package/dist/chunk-td7byqwx.js +2 -0
- package/dist/{chunk-90zzfgm2.js → chunk-tfp3exh3.js} +2 -2
- package/dist/{chunk-neegs8ab.js → chunk-tje2mg86.js} +1 -1
- package/dist/{chunk-3b8r08jb.js → chunk-tkwz3ka4.js} +1 -1
- package/dist/{chunk-jsgwt566.js → chunk-tq3bya3n.js} +1 -1
- package/dist/{chunk-7bfwvecv.js → chunk-xvg4nzz6.js} +1 -1
- package/dist/{chunk-85ek2f8h.js → chunk-ynpz7f7p.js} +1 -1
- package/dist/{chunk-exbtztv6.js → chunk-zvptrjt8.js} +1 -1
- package/dist/cli.js +8 -8
- package/dist/client/signals-dom-ready-runtime.d.ts +1 -1
- package/dist/client/signals-dom-ready-runtime.js +6 -0
- package/dist/component-processing.d.ts +1 -16
- package/dist/component-processing.js +3 -4
- package/dist/component-registry.d.ts +1 -6
- package/dist/component-registry.js +1 -3
- package/dist/component-renderer.js +2 -2
- package/dist/component-resolution.d.ts +16 -0
- package/dist/component-resolution.js +5 -2
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/dist/utils.d.ts +3 -1
- package/dist/utils.js +5 -4
- package/package.json +5 -5
- package/dist/chunk-4amn1rxg.js +0 -2
- package/dist/chunk-63d97rg2.js +0 -2
- package/dist/chunk-xb6g3ygh.js +0 -2
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{ad,cd}from"./chunk-q28hdn0s.js";import"./chunk-q48nk2gt.js";import"./chunk-avgwezvb.js";import"./chunk-azb58ven.js";import"./chunk-sjqbd8ga.js";import"./chunk-1b50m7e7.js";import"./chunk-ec8k75ep.js";import"./chunk-dyreg5df.js";import"./chunk-jb04k0sv.js";import"./chunk-e124cgb6.js";import"./chunk-jmvp99ay.js";import"./chunk-j2erwdgt.js";import"./chunk-a5kaw8sc.js";import"./chunk-6v1gwdbv.js";import"./chunk-r4199q6x.js";import"./chunk-kvmg6r89.js";import"./chunk-1xgs9gd5.js";export{cd as clearStoreCache,ad as getStoreScript};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{At}from"./chunk-j2erwdgt.js";import{Jo,ns,Z,Fe,Ct,x,He,Ue,Xn,d}from"./chunk-
|
|
2
|
+
import{At}from"./chunk-j2erwdgt.js";import{Jo,ns,Z,Fe,Ct,x,He,Ue,Xn,d}from"./chunk-sjqbd8ga.js";import{D}from"./chunk-3nk8cnrm.js";import v from"path";var j=/\b(?:state|derived|effect|batch|ref|reactive|computed|watch|watchEffect)\s*(?:<[^>]*>)?\s*\(/;function F(t,n,e){let r={fullTag:e,content:n,attrs:t};if(/\bserver\b/.test(t))return{...r,type:"server"};if(/\bdata-stx-scoped\b/.test(t))return{...r,type:"client"};if(j.test(n))return{...r,type:"signals"};if(/\bclient\b/.test(t)||/\btype\s*=\s*["']module["']/.test(t)||/\bsrc\s*=/.test(t))return{...r,type:"client"};return{...r,type:"server"}}var H=/^<script\b([^>]*)>([\s\S]*)<\/script\s*>$/i;function co(t){let n=[],e=[],r=[],o=0;while(o<t.length){let s=t.indexOf("<",o);if(s===-1)break;let a=Fe(t,s);if(a>s){o=a;continue}let i=Z(t,s);if(i>s){let c=t.slice(s,i),u=H.exec(c);if(u){let l=F(u[1],u[2],c);switch(l.type){case"signals":n.push(l);break;case"client":e.push(l);break;case"server":r.push(l);break}}o=i;continue}o=s+(t.startsWith("<!--",s)?4:1)}return{signals:n,client:e,server:r}}var L=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function V(t){let n=[],e=/<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|template)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,r;while((r=e.exec(t))!==null)n.push({start:r.index,end:r.index+r[0].length});return n}function P(t,n){return n.some((e)=>t>=e.start&&t<e.end)}function B(t){let n=(t||"").trim();if(!n)return null;if(/[\s>+~,:]/.test(n))return null;let e={},r=n,o=r.match(/^[a-z][\w-]*/i);if(o)e.tag=o[0].toLowerCase(),r=r.slice(o[0].length);while(r.length>0){let s=r.match(/^\[([\w-]+)(?:=(["']?)([^\]"']*)\2)?\]/);if(s){if(e.attr=s[1],s[3]!==void 0&&s[3]!=="")e.attrValue=s[3];r=r.slice(s[0].length);continue}let a=r.match(/^#([\w-]+)/);if(a){e.id=a[1],r=r.slice(a[0].length);continue}let i=r.match(/^\.([\w-]+)/);if(i){e.className=i[1],r=r.slice(i[0].length);continue}return null}if(!e.tag&&!e.attr&&!e.id&&!e.className)return null;return e}function q(t,n){if(n.attr){if(!(n.attrValue===void 0?new RegExp(`\\b${n.attr}(?=[\\s=>/]|$)`,"i"):new RegExp(`\\b${n.attr}\\s*=\\s*(["'])\\s*${n.attrValue}\\s*\\1`,"i")).test(t))return!1}if(n.id){if(!new RegExp(`\\bid\\s*=\\s*(["'])\\s*${n.id}\\s*\\1`,"i").test(t))return!1}if(n.className){let e=t.match(/\bclass\s*=\s*(["'])([\s\S]*?)\1/i);if(!e)return!1;if(!e[2].split(/\s+/).includes(n.className))return!1}return!0}function T(t,n="main"){let e=B(n);if(!e)return null;let r=/<([a-z][\w-]*)\b([^>]*)>/gi,o=V(t),s;while((s=r.exec(t))!==null){if(P(s.index,o))continue;let a=s[1].toLowerCase(),i=s[2]||"";if(i.trimEnd().endsWith("/")||L.has(a))continue;if(e.tag&&e.tag!==a)continue;if(!q(i,e))continue;let c=s[0],u=s.index+c.length,l=new RegExp(`<(/?)${a}\\b([^>]*)>`,"gi");l.lastIndex=u;let f=1,p;while((p=l.exec(t))!==null){if(P(p.index,o))continue;let h=p[1]==="/";if(!h&&(p[2]||"").trimEnd().endsWith("/"))continue;if(f+=h?-1:1,f===0)return{openTag:c,openIndex:s.index,start:u,end:p.index,tagName:a}}return null}return null}var Pe="private, no-store";function lo(t){return t.replace(/&#(\d+);/g,(n,e)=>O(Number(e),n)).replace(/&#x([0-9a-f]+);/gi,(n,e)=>O(Number.parseInt(e,16),n)).replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")}function O(t,n){if(!Number.isInteger(t)||t<0||t>1114111)return n;try{return String.fromCodePoint(t)}catch{return n}}function re(t){return t.headers.get("X-STX-Router")==="true"}function z(t,n){if(!t)return n;return t.split(",").some((r)=>r.trim().toLowerCase()===n.toLowerCase())?t:`${t}, ${n}`}function _(t){return{Vary:z(t,"X-STX-Router")}}var G="stx-page-head:",U=/<!--stx-page-head:([A-Za-z0-9+/=]+)-->\n?/,A={dev:null,prod:null};function W(){let t=D()?"dev":"prod",n=A[t];if(n!==null)return n;try{let e=import.meta.require("./chunk-6wpgxryt.js"),r=t==="dev"&&typeof e.getRouterScriptDev==="function"?e.getRouterScriptDev:e.getRouterScript;A[t]=`<script>${r()}</script>`}catch{A[t]=""}return A[t]}async function uo(t,n){if(n===!1)return null;if(n&&typeof n==="string"){let r=v.resolve(t,n);if(await Bun.file(r).exists())return r;return null}let e=v.join(t,"app.stx");if(await Bun.file(e).exists())return e;return null}async function Tr(t,n){try{let e=await Bun.file(t).text(),r=e,o=e.match(/<template\b[^>]*>([\s\S]*?)<\/template>/i);if(o)r=o[1].trim();let s=co(e),a=[...s.client.map((m)=>m.fullTag),...s.signals.map((m)=>m.fullTag)],i=[],c=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,u;while((u=c.exec(e))!==null)i.push(u[0]);let l=r;for(let m of s.server)l=l.replace(m.fullTag,"");for(let m of s.client)l=l.replace(m.fullTag,"");l=l.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"");let f="<!--__STX_PAGE_SLOT__-->";if(l=l.replace(/<slot\s*\/>/gi,f).replace(/<slot\s*>\s*<\/slot>/gi,f),!l.includes(f))return console.warn(`[stx] Shell ${t} has no <slot /> \u2014 pages won't be injected`),null;let{processDirectives:p,extractVariables:h,defaultConfig:S,loadStxConfig:b}=await import("./chunk-mhwf2xrt.js"),R=await b(),g={__filename:t,__dirname:v.dirname(t)};for(let m of a){let C=m.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(C&&!m.includes("client")&&!m.includes('type="module"'))await h(C[1],g,t)}let y=await p(l,g,t,{...S,...R,...n},new Set),w=y.indexOf(f);if(w===-1)return console.warn("[stx] Shell slot placeholder lost during processing"),null;return{beforeSlot:y.substring(0,w),afterSlot:y.substring(w+f.length),filePath:t,shellScripts:a,shellStyles:i}}catch(e){return console.error(`[stx] Error processing shell ${t}:`,e),null}}function In(t,n,e){let r,o="",s=n.match(U);if(s){n=n.replace(s[0],"");try{let l=Buffer.from(s[1],"base64").toString("utf8"),f=l.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(f)r=f[1].trim();o=l.replace(/<title[^>]*>[\s\S]*?<\/title>/i,"").trim()}catch{}}let a=e||r||"stx App",i=W(),c="<script>window.__stxRouterConfig={container:'[data-stx-content]'};</script>";return`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="UTF-8">
|
|
@@ -26,5 +26,5 @@ ${i}
|
|
|
26
26
|
`));if(o.length>0)S.push(o.join(`
|
|
27
27
|
`));if(f.length>0)S.push(f.join(`
|
|
28
28
|
`));return S.push(l),S.join(`
|
|
29
|
-
`)}function E(t,n,e={}){let r=`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(e.maxAge!==void 0)r+=`; Max-Age=${e.maxAge}`;if(e.expires)r+=`; Expires=${e.expires.toUTCString()}`;if(e.path)r+=`; Path=${e.path}`;if(e.domain)r+=`; Domain=${e.domain}`;if(e.secure)r+="; Secure";if(e.httpOnly)r+="; HttpOnly";if(e.sameSite)r+=`; SameSite=${e.sameSite}`;return r}async function J(t){let n=t.headers.get("content-type")||"",e={},r=(o,s)=>{let a=e[o];if(a===void 0)e[o]=s;else if(Array.isArray(a))a.push(s);else e[o]=[a,s]};if(n.includes("multipart/form-data")){let o=await t.formData();for(let[s,a]of o.entries())if(typeof a==="string")r(s,a);return e}if(n.includes("application/x-www-form-urlencoded")){for(let[o,s]of new URLSearchParams(await t.text()).entries())r(o,s);return e}return e}function $r(t){if(!t)return!1;let n=t.toUpperCase();return n!=="GET"&&n!=="HEAD"}async function N(t,n={}){let e=n.request,r=n.method??e?.method;if(!e||!$r(r))return{ran:!1};if(typeof t.action!=="function")return{ran:!1};let o={};try{o=await J(e)}catch{}let s=await t.action({request:e,form:o,params:n.params??{},query:t.query??{},cookies:n.cookies??{}});if(s&&typeof s==="object"){let a=s,i=K(a.cookies),c=a.redirect;if(typeof c==="string"&&c)return{redirect:c,ran:!0,...i.length>0?{cookies:i}:{}};let{cookies:u,redirect:l,...f}=a;if(Object.assign(t,f),i.length>0)return{ran:!0,cookies:i}}return{ran:!0}}function K(t){if(!t||typeof t!=="object"||Array.isArray(t))return[];let n=[];for(let[e,r]of Object.entries(t)){if(!e)continue;if(typeof r==="string"){n.push(E(e,r));continue}if(r&&typeof r==="object"){let o=r;if(typeof o.value!=="string")continue;n.push(E(e,o.value,o))}}return n}function ho(t,n=[],e){let r=new Headers({Location:t,"Cache-Control":"no-store"});for(let o of n)r.append("Set-Cookie",o);for(let[o,s]of Object.entries(e??{}))if(o.toLowerCase()!=="location")r.set(o,s);return new Response(null,{status:303,headers:r})}import k from"fs";import I from"path";function fo(t,n,e){return{version:1,buildTime:new Date().toISOString(),routes:t,assets:n,outputDir:e}}function go(t,n){let e=I.join(n,"manifest.json");k.writeFileSync(e,JSON.stringify(t,null,2))}function mo(t){let n=I.join(t,"manifest.json");if(!k.existsSync(n))return null;try{let e=k.readFileSync(n,"utf-8"),r=JSON.parse(e);if(r.version!==1)return console.warn(`[stx] Manifest version mismatch: expected 1, got ${r.version}`),null;return r}catch(e){return console.warn("[stx] Failed to load manifest:",e),null}}async function Nt(t,n={}){let{html:e,context:r,redirect:o,cookies:s}=await Y(t,n),a=He(r),i=Ue(r);if(o)return{html:e,redirect:o,cookies:s,status:a,headers:i};let{extractStreamBoundaries:c}=await import("./chunk-
|
|
29
|
+
`)}function E(t,n,e={}){let r=`${encodeURIComponent(t)}=${encodeURIComponent(n)}`;if(e.maxAge!==void 0)r+=`; Max-Age=${e.maxAge}`;if(e.expires)r+=`; Expires=${e.expires.toUTCString()}`;if(e.path)r+=`; Path=${e.path}`;if(e.domain)r+=`; Domain=${e.domain}`;if(e.secure)r+="; Secure";if(e.httpOnly)r+="; HttpOnly";if(e.sameSite)r+=`; SameSite=${e.sameSite}`;return r}async function J(t){let n=t.headers.get("content-type")||"",e={},r=(o,s)=>{let a=e[o];if(a===void 0)e[o]=s;else if(Array.isArray(a))a.push(s);else e[o]=[a,s]};if(n.includes("multipart/form-data")){let o=await t.formData();for(let[s,a]of o.entries())if(typeof a==="string")r(s,a);return e}if(n.includes("application/x-www-form-urlencoded")){for(let[o,s]of new URLSearchParams(await t.text()).entries())r(o,s);return e}return e}function $r(t){if(!t)return!1;let n=t.toUpperCase();return n!=="GET"&&n!=="HEAD"}async function N(t,n={}){let e=n.request,r=n.method??e?.method;if(!e||!$r(r))return{ran:!1};if(typeof t.action!=="function")return{ran:!1};let o={};try{o=await J(e)}catch{}let s=await t.action({request:e,form:o,params:n.params??{},query:t.query??{},cookies:n.cookies??{}});if(s&&typeof s==="object"){let a=s,i=K(a.cookies),c=a.redirect;if(typeof c==="string"&&c)return{redirect:c,ran:!0,...i.length>0?{cookies:i}:{}};let{cookies:u,redirect:l,...f}=a;if(Object.assign(t,f),i.length>0)return{ran:!0,cookies:i}}return{ran:!0}}function K(t){if(!t||typeof t!=="object"||Array.isArray(t))return[];let n=[];for(let[e,r]of Object.entries(t)){if(!e)continue;if(typeof r==="string"){n.push(E(e,r));continue}if(r&&typeof r==="object"){let o=r;if(typeof o.value!=="string")continue;n.push(E(e,o.value,o))}}return n}function ho(t,n=[],e){let r=new Headers({Location:t,"Cache-Control":"no-store"});for(let o of n)r.append("Set-Cookie",o);for(let[o,s]of Object.entries(e??{}))if(o.toLowerCase()!=="location")r.set(o,s);return new Response(null,{status:303,headers:r})}import k from"fs";import I from"path";function fo(t,n,e){return{version:1,buildTime:new Date().toISOString(),routes:t,assets:n,outputDir:e}}function go(t,n){let e=I.join(n,"manifest.json");k.writeFileSync(e,JSON.stringify(t,null,2))}function mo(t){let n=I.join(t,"manifest.json");if(!k.existsSync(n))return null;try{let e=k.readFileSync(n,"utf-8"),r=JSON.parse(e);if(r.version!==1)return console.warn(`[stx] Manifest version mismatch: expected 1, got ${r.version}`),null;return r}catch(e){return console.warn("[stx] Failed to load manifest:",e),null}}async function Nt(t,n={}){let{html:e,context:r,redirect:o,cookies:s}=await Y(t,n),a=He(r),i=Ue(r);if(o)return{html:e,redirect:o,cookies:s,status:a,headers:i};let{extractStreamBoundaries:c}=await import("./chunk-hh88tvs5.js"),u=c(r),l=t.streamTemplates;if(l&&Object.keys(l).length>0){let{processDirectives:f}=await import("./chunk-81qx2ze8.js"),{defaultConfig:p}=await import("./chunk-ptj7fwre.js"),h=r.streamBoundaries||{},S={...p,autoShell:!1},b=Object.keys(l).map((g)=>({id:g,render:async()=>{let y=typeof h[g]==="function"?await h[g]():void 0;return f(l[g],{...r,$boundary:y},t.sourceFile,S,new Set)}})),R=new Set(b.map((g)=>g.id));u=[...(u||[]).filter((g)=>!R.has(g.id)),...b]}return{html:e,boundaries:u&&u.length>0?u:void 0,cookies:s,status:a,headers:i}}async function Y(t,n){let e={__filename:t.sourceFile,__dirname:t.sourceFile.replace(/[/\\][^/\\]+$/,""),...n};if(!t.hasServerScripts&&!ns(t.html))return{html:t.html,context:e};for(let a of t.serverScriptContent)try{await d(a,e,t.sourceFile)}catch(i){if(n.__stx_strict_hydration)throw i;console.warn(`[stx] Server script error in ${t.sourceFile}:`,i)}let r=await N(e,{request:n.request,method:n.method,params:n.params??{},cookies:n.cookies??{}}),o=(a)=>{let i=a.replace(/<script\b[^>]*\bdata-stx-server-data\b[^>]*>[\s\S]*?<\/script>/gi,""),c=Xn(e);if(!c)return i;let u=i.indexOf("</head>");return u<0?c+i:i.slice(0,u)+c+i.slice(u)};if(r.redirect)return{html:t.html,context:e,redirect:r.redirect,cookies:r.cookies};if(!ns(t.html))return{html:o(t.html),context:e,cookies:r.cookies};let s=new Map;for(let[a,i]of Object.entries(t.placeholders))if(i.expression)try{let c=x(i.expression,e);if(i.type==="raw")s.set(a,c!==void 0&&c!==null?String(c):"");else s.set(a,c!==void 0&&c!==null?Ct(String(c)):"")}catch(c){if(n.__stx_strict_hydration)throw c;s.set(a,"")}return{html:o(Jo(t.html,s)),context:e,cookies:r.cookies}}
|
|
30
30
|
export{co,Pe,lo,re,_,uo,Tr,In,he,po,se,fo,go,mo,$r,ho,Nt};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{y}from"./chunk-r4199q6x.js";import{q,Ve,as,cs,ti,ni,ri,si,Gn,ls,oi,ii,ai,Tt,o}from"./chunk-
|
|
2
|
+
import{y}from"./chunk-r4199q6x.js";import{q,Ve,as,cs,ti,ni,ri,si,Gn,ls,oi,ii,ai,Tt,o}from"./chunk-sjqbd8ga.js";import{Fr}from"./chunk-16g71mm9.js";import{a}from"./chunk-4cmqjmqr.js";import{existsSync as M,readFileSync as K}from"fs";import h from"path";var me=new Set(["module","exports","require","$bool","$num","window","document","console","confirm","alert","fetch"]),te=Tt.filter((e)=>!me.has(e)).sort(),ne=[...y].sort(),he=[...new Set([...te,...ne])].sort(),be=new Set(te),ye=new Set(ne),xe=new Set(he),ee=/\bimport\s+(?!type[\s{])\{([^}]*)\}\s*from\s*(['"])stx\2/g;function Se(e,t){if(t==="server")return`'${e}' is not provided by 'stx' in a <script server> block. The engine binds only its own names there (defineProps, state, useHead, ...); any other name becomes \`await import('stx')\`, which does not resolve, so the whole script fails when the page renders. Import it from '@stacksjs/stx' instead.`;return`'${e}' is not provided by 'stx' in a client <script> block. The import is replaced by the window.stx runtime, which has no '${e}', so it is undefined in the browser.`}function ie(e,t){let s=[];for(let u of t){if(u.offset===void 0)continue;let i=u.kind==="server"?be:ye;ee.lastIndex=0;for(let l of u.code.matchAll(ee)){let g=l.index+l[0].indexOf("{")+1;for(let m of l[1].matchAll(/[^,]+/g)){let S=m[0];if(/^\s*type\s/.test(S))continue;let x=/^\s*([A-Za-z_$][\w$]*)/.exec(S);if(!x)continue;let r=x[1];if(!xe.has(r)||i.has(r))continue;let f=u.offset+g+m.index+x[0].length-r.length,p=e.slice(0,f),w=p.split(`
|
|
3
3
|
`).length;s.push({line:w,column:f-(p.lastIndexOf(`
|
|
4
4
|
`)+1)+1,offset:f,length:r.length,name:r,kind:u.kind,message:Se(r,u.kind)})}}}return s}import T from"path";var ke="@stacksjs/stx-typescript-plugin";function we(e,t){let s=T.resolve(e);for(;;){let u=T.join(s,"tsconfig.json");if(t(u))return u;let i=T.dirname(s);if(i===s)return;s=i}}function se(e,t,s){let u=we(e,s);if(!u)return;let i=new Set,l=(g)=>{if(i.has(g))return;i.add(g);let m=t(g);if(!m)return;let S=m.compilerOptions?.plugins;if(Array.isArray(S)){let r=S.find((p)=>p?.name===ke),f=Array.isArray(r?.libs)?r.libs.filter((p)=>typeof p==="string"):[];return r?{configPath:g,libs:f.map((p)=>T.resolve(T.dirname(g),p))}:null}let x=typeof m.extends==="string"?[m.extends]:Array.isArray(m.extends)?m.extends:[];for(let r of[...x].reverse()){if(typeof r!=="string"||!r.startsWith("."))continue;let f=T.resolve(T.dirname(g),r.endsWith(".json")?r:`${r}.json`),p=l(f);if(p!==void 0)return p}return};return l(u)??void 0}function oa(e,t="",s=""){let u=e.startLine>1?`
|
|
5
5
|
`.repeat(e.startLine-1):"",i=ls(e)+cs(as(e.code)),l=e.kind==="client"||e.kind==="plain"?ri(t,e.code):"";return Gn(`${u+i}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ss,os,is,Jd,qn,Yd}from"./chunk-
|
|
2
|
+
import{ss,os,is,Jd,qn,Yd}from"./chunk-sjqbd8ga.js";export{qn as clearImageDeliveryCatalog,Jd as deliveredImage,is as efficientDeliverySources,ss as getImageDelivery,os as isTransparentImage,Yd as prepareImageDelivery};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{G,n}from"./chunk-
|
|
2
|
+
import{G,n}from"./chunk-sjqbd8ga.js";import p from"fs";import g from"path";import*as y from"readline";var e={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m"},u={help:{description:"Show available commands",usage:"help [command]",handler:async(t,o)=>{if(t[0]&&u[t[0]]){let r=u[t[0]];console.log(`
|
|
3
3
|
${e.bold}${t[0]}${e.reset} - ${r.description}`),console.log(` Usage: ${e.cyan}${r.usage}${e.reset}
|
|
4
4
|
`)}else{console.log(`
|
|
5
5
|
${e.bold}Available Commands:${e.reset}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{d,hs,pi,fi,Ic,Oc,Dc,Mc,Nc,Lc,qe,L,Ge,jc,Jn,Bc,yi,Fc,Ke,r,Yn,bi,g,te,tu}from"./chunk-
|
|
2
|
+
import{d,hs,pi,fi,Ic,Oc,Dc,Mc,Nc,Lc,qe,L,Ge,jc,Jn,Bc,yi,Fc,Ke,r,Yn,bi,g,te,tu}from"./chunk-sjqbd8ga.js";import"./chunk-1b50m7e7.js";import"./chunk-ec8k75ep.js";import"./chunk-dyreg5df.js";import"./chunk-jb04k0sv.js";import"./chunk-e124cgb6.js";import"./chunk-jmvp99ay.js";import"./chunk-j2erwdgt.js";import"./chunk-a5kaw8sc.js";import"./chunk-6v1gwdbv.js";import"./chunk-r4199q6x.js";import"./chunk-kvmg6r89.js";import"./chunk-1xgs9gd5.js";export{te as clearComponentCache,Fc as componentClientSignalNames,hs as convertToCommonJS,g as createDetailedErrorMessage,Nc as extractDirectiveNames,pi as extractScriptFromTemplate,d as extractVariables,r as fileExists,tu as getComponentCacheStats,Oc as getPositionInfo,L as getSharedTranspiler,bi as getSourceLineInfo,Mc as hasDirectives,fi as hasVariables,Bc as isHydrateTrigger,Lc as isJavaScriptScript,Ke as renderComponentWithSlot,Yn as resolveTemplatePath,jc as scopeOnRootElement,qe as shouldTranspileTypeScript,yi as slotContentHasExpressions,Ge as transpileTypeScript,Jn as userComponentFileExists,Dc as validateDirective,Ic as validateTemplate};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-r4199q6x.js";import"./chunk-6v1gwdbv.js";import{m,h,w,L}from"./chunk-
|
|
2
|
+
import"./chunk-r4199q6x.js";import"./chunk-6v1gwdbv.js";import{m,h,w,L}from"./chunk-sjqbd8ga.js";import"./chunk-a5kaw8sc.js";import"./chunk-ec8k75ep.js";import"./chunk-kvmg6r89.js";import"./chunk-j2erwdgt.js";import"./chunk-jmvp99ay.js";import"./chunk-dyreg5df.js";import"./chunk-e124cgb6.js";import"./chunk-jb04k0sv.js";import"./chunk-1xgs9gd5.js";import"./chunk-1b50m7e7.js";import f from"path";var S=["applyOfflineUpdate","broadcast","cacheMedia","calculateDistance","canNotify","clearCookies","clearFetchCache","clearOfflineData","clearStorage","copyToClipboard","createShareableFile","defineForm","getBatteryLevel","getCookie","getCurrentPosition","getStorageKeys","getStorageSize","getVoices","hasBattery","hasCameraPermission","hasGeolocationPermission","hasMicrophonePermission","hasNotificationPermission","hasResizeObserver","hexToHsl","hexToRgb","isBroadcastChannelSupported","isCharging","isDeviceMotionSupported","isDeviceOrientationSupported","isEventSourceSupported","isEyeDropperSupported","isInFullscreen","isMutationObserverSupported","isPermissionGranted","isSpeechRecognitionSupported","isSpeechSynthesisSupported","isWakeLockSupported","isWebSocketSupported","notify","onOfflineUpdateReady","parseCookies","pickColor","prefetch","removeCookie","requestMediaPermissions","requestMotionPermission","requestNotificationPermission","requestOrientationPermission","setCookie","share","shareCurrentPage","shareFiles","shareText","shareURL","shareWithFallback","speak","stopSpeaking","toggleFullscreen","useAmbientSound","useAsyncData","useAttributeObserver","useAutoLogout","useAutoWakeLock","useBattery","useBreakpoint","useBreathPacer","useBroadcastChannel","useBroadcastStream","useChannel","useChildListObserver","useClipboard","useColorHistory","useConditionalWakeLock","useCookies","useCopySelection","useDeviceMotion","useDeviceOrientation","useElementSize","useElementTextSelection","useElementVisibility","useEventSource","useEyeDropper","useFavicon","useForm","useFullscreen","useGeolocation","useGeolocationWatch","useHotkey","useIdle","useIdleState","useInfiniteScroll","useIntersectionObserver","useIntersectionObserverMultiple","useIsDesktop","useIsMobile","useIsTablet","useKeyPressed","useKeySequence","useKeyboard","useLastActive","useLazyLoad","useMeta","useMouse","useMouseInElement","useMutationObserver","useNetwork","useNotification","useOnline","useOutbox","useParallax","usePermission","usePermissions","usePointer","usePost","useResizeObserver","useResizeObserverMultiple","useSSE","useScroll","useSelectionPopup","useShare","useSpeechRecognition","useSpeechSynthesis","useStorage","useTextObserver","useTextSelection","useTitle","useVisibility","useWakeLock","useWindowSize"],_=new Set(S);var l=new Map,x=m(64),y=new Set,O=0,R=new Set(S);function W(){l.clear(),x.clear()}function P(o){let n=new Map;for(let r of o){let a=f.basename(r);if(a.endsWith(".d.ts"))continue;let t=a.replace(/\.[jt]s$/,"");if(t==="index")continue;if(t===a)continue;let i=n.get(t);if(i&&!i.endsWith(".js"))continue;n.set(t,r)}return[...n.values()].sort()}function I(o,n){let r=n.replace(/[$()*+.?[\\\]^{|}-]/g,"\\$&");return new RegExp(`(?:^|[^\\w$.])(?:const|let|var|function|class)\\s+${r}\\b`).test(o)}function M(o){if(!o)return[];let n=h(o,O),r=x.get(n);if(r)return r.slice();let a=o.replace(/<script\b[^>]*\bdata-stx-runtime\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<script\b[^>]*\bdata-stx-framework-composables\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<script\b[^>]*\bdata-stx-stores\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<script\b[^>]*\bdata-stx-composables\b[^>]*>[\s\S]*?<\/script>/gi,""),t=[];for(let i of R){if(y.has(i))continue;let u=i.replace(/[$()*+.?[\\\]^{|}-]/g,"\\$&");if(new RegExp(`(^|[^\\w$.])${u}\\s*\\(`).test(a))t.push(i)}return t.sort(),x.set(n,t),t.slice()}async function A(o,n){let r=M(o);if(r.length===0)return null;let a=n??f.join(import.meta.dir,"composables"),t=`${a}\x00${r.join(",")}`,i=l.get(t);if(i!==void 0)return i||null;let u=L({loader:"ts",target:"browser",define:w()}),C=new Set(r),d=[],g=new Set,p=[];try{let s=new Bun.Glob("*.{ts,js}");for await(let e of s.scan({cwd:a,absolute:!0}))p.push(e)}catch{return l.set(t,""),null}p=P(p);for(let s of p){let e;try{e=await Bun.file(s).text()}catch{continue}let b=[];try{b=u.scan(e).exports.filter((c)=>c!=="default")}catch{continue}if(!b.some((c)=>C.has(c)))continue;try{e=e.replace(/^import\s+.*from\s+['"][^'"]+['"]\s*;?\s*$/gm,""),e=e.replace(/^import\s+type\s+.*$/gm,""),e=e.replace(/^export\s+\*\s+(?:as\s+\w+\s+)?from\s*['"][^'"]+['"]\s*;?\s*$/gm,""),e=e.replace(/^export\s+(?:type\s+)?\{[\s\S]*?\}\s*(?:from\s*['"][^'"]+['"]\s*)?;?\s*$/gm,""),e=e.replace(/^export\s+default\s+/gm,""),e=e.replace(/^export\s+(?=(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\b)/gm,""),d.push(`// ${f.basename(s).replace(/\.[jt]s$/,"")}
|
|
3
3
|
${u.transformSync(e).trim()}`);for(let c of b)g.add(c)}catch(c){console.warn(`[stx] framework composable ${f.basename(s)} could not be bundled:`,c)}}let v=r.filter((s)=>!g.has(s)&&!I(o,s));if(v.length>0)console.warn(`[stx] could not bundle ${v.join(", ")} from @stacksjs/stx/composables \u2014 `+"calls to them will throw ReferenceError in the browser. Import them explicitly so the bundler inlines them, or use a runtime equivalent from window.stx.");if(d.length===0)return l.set(t,""),null;let E=[...g].map((s)=>` try { if (!(${JSON.stringify(s)} in __s)) { __s[${JSON.stringify(s)}] = ${s}; if (!(${JSON.stringify(s)} in window)) window[${JSON.stringify(s)}] = ${s}; } } catch (e) {}`).join(`
|
|
4
4
|
`),k=`<script data-stx-scoped data-stx-run="always" data-stx-framework-composables>
|
|
5
5
|
;(function(){
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{De,Xt}from"./chunk-
|
|
2
|
+
import{De,Xt}from"./chunk-0fatkxpr.js";import{Ee}from"./chunk-kvmg6r89.js";import{Ko,Xo,f,_t,ee,N,n,R,o}from"./chunk-sjqbd8ga.js";import{C}from"./chunk-e124cgb6.js";import{Ts}from"./chunk-jb04k0sv.js";import{gn,mn,hn,bn,fe}from"./chunk-j2erwdgt.js";import{Ti}from"./chunk-dyreg5df.js";import{he,se,fo,go,Nt}from"./chunk-tfp3exh3.js";import{xt,Xr}from"./chunk-avgwezvb.js";import{Lt}from"./chunk-n1cqg89v.js";import{mt,Qt,en}from"./chunk-hpeg9erh.js";import{createHash as Q}from"crypto";function J(i){return Q("sha256").update(i).digest("hex").slice(0,8)}function U(i=!1){let l=i?Xt():De(),a=J(l);return{content:l,filename:`runtime.${a}.js`,hash:a}}function V(){let i=Ee(),l=J(i);return{content:i,filename:`router.${l}.js`,hash:l}}import m from"fs";import c from"path";import q from"path";import{createHash as te}from"crypto";function re(i={}){let l=new Set;return{context:new Proxy(i,{get(r,e){if(e in r)return r[e];if(typeof e==="string"&&!e.startsWith("__"))l.add(e);return},has(r,e){if(e in r)return!0;if(typeof e==="string"&&!e.startsWith("__"))l.add(e);return!1}}),accessedKeys:l}}async function X(i,l,a={}){let r=q.resolve(i),e=await Bun.file(r).text(),S=te("sha256").update(e).digest("hex").slice(0,16);Ko();let _={};try{_=await o(a.configDir)}catch{}let y=[],d=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,g;while((g=d.exec(e))!==null){let v=g[1];if(/\bserver\b/.test(v))y.push(g[2])}let u=new Set(y.flatMap((v)=>ee(v))),{context:A}=re({__filename:r,__dirname:q.dirname(r),__stx_serverDeclared:u}),w=new Set,P={...R,..._,...a,buildMode:"compile",strict:!1},b=await n(e,A,r,P,w),T=he(b),B=Xo();return{route:l,sourceFile:i,html:b,fragment:T,placeholders:B,hasServerScripts:y.length>0,serverScriptContent:y,dependencies:Array.from(w),contentHash:S,status:_t(e),streamTemplates:A.__streamTemplates}}var ne=new Set([".DS_Store","Thumbs.db","desktop.ini",".gitkeep",".gitignore"]);function Z(i,l){let a=0,r=0;if(!m.existsSync(i))return{copied:a,bytes:r};m.mkdirSync(l,{recursive:!0});function e(S,_){let y=m.readdirSync(S,{withFileTypes:!0});for(let d of y){if(ne.has(d.name))continue;let g=c.join(S,d.name),u=c.join(_,d.name);if(d.isDirectory())m.mkdirSync(u,{recursive:!0}),e(g,u);else if(d.isFile()){if(m.existsSync(u))continue;m.copyFileSync(g,u),a++,r+=m.statSync(u).size}}}return e(i,l),{copied:a,bytes:r}}async function pl(i={}){let l=Date.now(),a=c.resolve(i.root||process.cwd()),r=c.resolve(a,i.outputDir||".output");console.log("[stx build] Starting production build...");let e=await o(a),S=c.resolve(a,i.componentsDir??e.componentsDir??"components"),_=c.resolve(a,i.partialsDir??e.partialsDir??"partials"),y=c.resolve(a,i.layoutsDir??e.layoutsDir??"layouts"),d=i.publicDir??e.publicDir??"public",g=fe(e.app?.head,{known:bn,source:"app.head"}),u=e.app?.colorMode,A=e.router?.container||"main",w=i.routeRules??e.routeRules??{},P=Lt(w),b=i.serverApi??e.serverApi,T=typeof b==="object"?b:{};if(b)xt(a,T);if(e.runtimeConfig)C(e.runtimeConfig,{});if(m.existsSync(r))m.rmSync(r,{recursive:!0});let B=[c.join(r,"public","__stx"),c.join(r,"public","assets"),c.join(r,"server","pages"),c.join(r,"server","fragments")];for(let s of B)m.mkdirSync(s,{recursive:!0});console.log("[stx build] Discovering routes...");let v=N(a,{pagesDirs:e._layerPageDirs}),Y=["components","layouts","partials"],M=v.filter((s)=>!Y.some((h)=>s.pattern.startsWith(`/${h}/`)||s.pattern===`/${h}`));console.log(`[stx build] Found ${M.length} page routes (${v.length-M.length} non-page files excluded)`),console.log("[stx build] Generating shared assets...");let D=U(i.debug),x=V();await Bun.write(c.join(r,"public","__stx",D.filename),D.content),await Bun.write(c.join(r,"public","__stx",x.filename),x.content),console.log(`[stx build] Runtime: ${D.filename} (${(D.content.length/1024).toFixed(1)}KB)`),console.log(`[stx build] Router: ${x.filename} (${(x.content.length/1024).toFixed(1)}KB)`),console.log("[stx build] Compiling templates...");let O=[],E=[];for(let s of M){let h=P(s.pattern),k=h.rendering==="prerender";if(k&&(s.pattern.includes(":")||s.pattern.includes("[")))throw Error(`Cannot prerender parameter route ${s.pattern}; use dynamic rendering (explicit path enumeration is not supported here)`);try{let t=await X(s.filePath,s.pattern,{configDir:a,componentsDir:S,partialsDir:_,layoutsDir:y,debug:i.debug});if(O.push(t),t.html=t.html.replace(/runtime\.__STX_HASH__\.js/g,D.filename).replace(/router\.__STX_HASH__\.js/g,x.filename),t.html=hn(t.html,g,{bodyScripts:[`<script src="/__stx/${x.filename}"></script>`],...u&&{colorMode:u}}),u)t.html=gn(t.html,u);if(g.htmlAttrs)t.html=mn(t.html,g.htmlAttrs);if(!/<body[^>]*\bdata-stx=/.test(t.html)){let p=t.html.match(/<(?!body\b)[a-zA-Z][a-zA-Z0-9-]*\b[^>]*?\s(data-stx="[^"]+")[^>]*>/);if(p&&p[1]){let W=p[1];t.html=t.html.replace(" "+W,""),t.html=t.html.replace(/<body([^>]*)>/,`<body$1 ${W}>`)}}if(t.html=t.html.replace(/<style data-css="generated">[\s\S]*?<\/style>\s*/g,""),t.html=await f(t.html),k){let p=await Nt(t,{params:{},request:new Request(`http://stx.build${s.pattern}`),method:"GET",__stx_strict_hydration:!0});if(p.redirect||p.cookies?.length||p.boundaries?.length||p.headers&&Object.keys(p.headers).length)throw Error(`Prerendered route ${s.pattern} cannot set response headers/cookies, redirect or stream`);t.html=p.html,t.status=p.status??t.status,t.hasServerScripts=!1,t.serverScriptContent=[],t.placeholders={}}t.fragment=se(t.html,A);let z=s.pattern==="/"?"index":s.pattern.slice(1).replace(/\//g,"-").replace(/[[\]]/g,"_"),G=c.join("server","pages",`${z}.compiled.json`),I=c.join("server","fragments",`${z}.html`);await Bun.write(c.join(r,G),JSON.stringify(t,null,2)),await Bun.write(c.join(r,I),t.fragment),E.push({pattern:s.pattern,compiledPath:G,fragmentPath:I,isDynamic:t.hasServerScripts,hasParams:s.pattern.includes(":")||s.pattern.includes("["),prerendered:k}),console.log(`[stx build] \u2713 ${s.pattern}`)}catch(t){if(Object.keys(h).length)throw t;console.error(`[stx build] \u2717 ${s.pattern}:`,t instanceof Error?t.message:t)}}let H=c.resolve(a,d);if(m.existsSync(H)){let{copied:s,bytes:h}=Z(H,c.join(r,"public"));if(s>0)console.log(`[stx build] Copied ${s} public asset${s===1?"":"s"} (${(h/1024).toFixed(1)}KB) from ${d}/`)}let F=en(a);if(F){let{copied:s,bytes:h}=Z(F,c.join(r,"public",Qt));if(s>0)console.log(`[stx build] Copied ${s} asset${s===1?"":"s"} (${(h/1024).toFixed(1)}KB) from ${mt}/`)}let K={runtime:D.filename,router:x.filename},j=fo(E,K,r);if(j.routeRules=w,j.routerContainer=A,b)j.apiRoutes=await Xr(a,r,T);if(e.runtimeConfig)await Bun.write(c.join(r,"server/runtime-config.json"),JSON.stringify(e.runtimeConfig)),await Ts(a,e.runtimeConfig);if(e._layerGraph)await Bun.write(c.join(r,"server/layers.json"),JSON.stringify(Ti(e._layerGraph),null,2));go(j,r);let L=Date.now()-l;return console.log(`
|
|
3
3
|
[stx build] Done in ${L}ms \u2014 ${O.length} pages compiled`),{pageCount:O.length,assets:K,outputDir:r,duration:L}}
|
|
4
4
|
export{pl};
|
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"./chunk-a5kaw8sc.js";import"./chunk-ec8k75ep.js";import"./chunk-kvmg6r89.js";import"./chunk-r4199q6x.js";import"./chunk-6v1gwdbv.js";import{W}from"./chunk-
|
|
3
|
+
import"./chunk-a5kaw8sc.js";import"./chunk-ec8k75ep.js";import"./chunk-kvmg6r89.js";import"./chunk-r4199q6x.js";import"./chunk-6v1gwdbv.js";import{W}from"./chunk-sjqbd8ga.js";import"./chunk-j2erwdgt.js";import"./chunk-jmvp99ay.js";import"./chunk-e124cgb6.js";import"./chunk-jb04k0sv.js";import"./chunk-1xgs9gd5.js";import"./chunk-dyreg5df.js";import"./chunk-d37enreq.js";import"./chunk-b9jb44kv.js";import"./chunk-tqnh98j7.js";import"./chunk-3nc2fr4q.js";import"./chunk-zmq9hwta.js";import"./chunk-ah7h9q0x.js";import"./chunk-frgpx23w.js";import"./chunk-tfp3exh3.js";import"./chunk-m6m19hwd.js";import"./chunk-45n128za.js";import"./chunk-0fatkxpr.js";import"./chunk-vvkfde23.js";import"./chunk-kch9a9v1.js";import"./chunk-31gk5b7d.js";import"./chunk-yq1mvakj.js";import"./chunk-tq3bya3n.js";import"./chunk-gjx5256r.js";import"./chunk-avgwezvb.js";import"./chunk-zvptrjt8.js";import"./chunk-a7tmbbzz.js";import"./chunk-wy4hfmjs.js";import"./chunk-39tkfkp7.js";import"./chunk-7ze47qgv.js";import"./chunk-azb58ven.js";import{yt,bt}from"./chunk-q48nk2gt.js";import"./chunk-16g71mm9.js";import"./chunk-tje2mg86.js";import"./chunk-pz8mf91e.js";import"./chunk-77j26p6r.js";import"./chunk-v79qs0qh.js";import"./chunk-8nwzd6eg.js";import"./chunk-75hb7wg6.js";import"./chunk-q28hdn0s.js";import"./chunk-bh5qgbmv.js";import{Xs,Js,Ys,Zs,wr,Qs,eo,to,vr,xr,_n,Tn,$n}from"./chunk-21v5eee6.js";import"./chunk-nvsea9fk.js";import"./chunk-wk85dz07.js";import{xi}from"./chunk-1b50m7e7.js";import{u}from"./chunk-cg8hg6cs.js";import{spawn as R}from"child_process";import S from"fs";import f from"path";import n from"process";import{CLI as V}from"@stacksjs/clapp";var j="0.2.553";var __dirname="/home/runner/work/stx/stx/packages/stx/bin",y=new V("stx");function B(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Port must be a valid number",suggestion:"Try using a number between 1024 and 65535"};if(p<1024||p>65535)return{isValid:!1,error:"Port must be between 1024 and 65535",suggestion:"Try using a port between 1024 and 65535"};return{isValid:!0}}function A(h){try{if(!S.existsSync(h)){let x=f.dirname(h),t=f.basename(h);if(S.existsSync(x)){let o=S.readdirSync(x).filter((s)=>s.toLowerCase().includes(t.toLowerCase().substring(0,3))||s.endsWith(".stx")||s.endsWith(".md")),i=o.length>0?`File not found. Similar files in ${x}: ${o.slice(0,3).join(", ")}`:`File not found. Directory ${x} exists but doesn't contain the specified file.`;return{isValid:!1,error:`File does not exist: ${h}`,suggestion:i}}return{isValid:!1,error:`File does not exist: ${h}`,suggestion:"Check the file path and try again"}}if(S.statSync(h).isDirectory())return{isValid:!1,error:`Expected file but got directory: ${h}`,suggestion:"Specify a .stx or .md file path"};return{isValid:!0}}catch(p){return{isValid:!1,error:`Cannot access file: ${h}`,suggestion:"Check file permissions and path"}}}function z(h){let p=typeof h==="string"?Number.parseInt(h,10):h;if(Number.isNaN(p))return{isValid:!1,error:"Timeout must be a valid number",suggestion:"Specify timeout in milliseconds (e.g., 5000 for 5 seconds)"};if(p<100)return{isValid:!1,error:"Timeout too short (minimum 100ms)",suggestion:"Use a timeout of at least 100ms"};if(p>300000)return{isValid:!1,error:"Timeout too long (maximum 5 minutes)",suggestion:"Use a timeout of less than 300000ms (5 minutes)"};return{isValid:!0}}var O=(h)=>h.includes("*")||h.includes("?")||h.includes("{")||h.includes("["),U=(h)=>h.endsWith(".stx")||h.endsWith(".md");function F(h,p=1){if(console.error(`\u274C ${h.error}`),h.suggestion)console.error(`\uD83D\uDCA1 suggestion: ${h.suggestion}`);n.exit(p)}function H(h){if(!h)return;let p;try{p=JSON.parse(h)}catch(x){console.error(`\u274C --info-plist is not valid JSON: ${x.message}`),n.exit(1)}if(typeof p!=="object"||p===null||Array.isArray(p))console.error(`\u274C --info-plist must be a JSON object, e.g. '{"NSFocusStatusUsageDescription":"\u2026"}'`),n.exit(1);for(let[x,t]of Object.entries(p))if(typeof t!=="string"&&typeof t!=="number"&&typeof t!=="boolean")console.error(`\u274C --info-plist value for "${x}" must be a string, number or boolean`),n.exit(1);return p}async function L(h,p){try{let x=["test"],t=[];if(h&&h.length>0)for(let c of h)if(O(c))try{let r=await Array.fromAsync(new Bun.Glob(c).scan({onlyFiles:!0,absolute:!0}));if(r.length===0)console.warn(`Warning: No files found matching pattern: ${c}`);else if(t.push(...r),p.verbose)console.log(`Found ${r.length} file(s) matching pattern: ${c}`)}catch(r){return console.error(`Error expanding glob pattern ${c}:`,r),!1}else t.push(c);if(t.length===0)return console.error("Error: No test files found matching the provided patterns."),!1;if(x.push(...t),p.filter)x.push("--pattern",p.filter);if(p.timeout)x.push("--timeout",p.timeout.toString());if(p.reporter&&p.reporter!=="default")if(p.reporter==="junit"){let c=f.resolve("stx-test-report.xml");x.push("--reporter",p.reporter),x.push("--reporter-outfile",c),console.log(`JUnit report: ${c}`)}else console.warn(`Warning: Reporter '${p.reporter}' is not supported. Using default reporter.`);if(p.coverage)x.push("--coverage");if(p.watch)x.push("--watch");x.push("--preload",f.join(__dirname,"../../../test-utils/happy-dom.ts"));let e={...n.env,STX_TEST_MODE:"true",STX_TEST_UI:p.ui?"true":"false",STX_TEST_VERBOSE:p.verbose?"true":"false"},o="bun";if(p.verbose)console.log(`Running: ${o} ${x.join(" ")}`);let i=performance.now(),s=R(o,x,{stdio:"inherit",shell:!1,env:e});return new Promise((c)=>{s.on("close",(r)=>{let d=((performance.now()-i)/1000).toFixed(2);if(r===0)c(!0);else c(!1)}),n.on("SIGINT",()=>{console.log(`
|
|
4
4
|
Test run interrupted`),s.kill("SIGINT"),n.exit(1)})})}catch(x){return console.error("Error running tests:",x instanceof Error?x.message:String(x)),!1}}var J=n.argv.length>=3&&(U(n.argv[2])&&S.existsSync(n.argv[2])||O(n.argv[2]));if(J){let h=n.argv[2],p={port:3000,watch:!0,cache:!0,markdown:{syntaxHighlighting:{enabled:!0,serverSide:!0,defaultTheme:"github-dark",highlightUnknownLanguages:!0}}};for(let x=3;x<n.argv.length;x++){let t=n.argv[x];if(t==="--port"&&x+1<n.argv.length){let e=B(n.argv[++x]);if(!e.isValid)F(e);p.port=Number.parseInt(n.argv[x],10)}else if(t==="--no-watch")p.watch=!1;else if(t==="--highlight-theme"&&x+1<n.argv.length){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.defaultTheme=n.argv[++x]}else if(t==="--no-highlight"){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.enabled=!1}else if(t==="--no-highlight-unknown"){if(!p.markdown)p.markdown={};if(!p.markdown.syntaxHighlighting)p.markdown.syntaxHighlighting={};p.markdown.syntaxHighlighting.highlightUnknownLanguages=!1}else if(t==="--no-cache")p.cache=!1;else if(t==="--native")p.native=!0}if(O(h))try{let x=await Array.fromAsync(new Bun.Glob(h).scan({onlyFiles:!0,absolute:!0})),t=h.endsWith(".stx")?x.filter((s)=>s.endsWith(".stx")):h.endsWith(".md")?x.filter((s)=>s.endsWith(".md")):x.filter((s)=>s.endsWith(".stx")||s.endsWith(".md")),e=h.split("*")[0].replace(/\/$/,"")||".",o=f.resolve(e);try{let s=new Bun.Glob("**/*.stx"),r=(await Array.fromAsync(s.scan({cwd:o,onlyFiles:!0,absolute:!0}))).filter((l)=>/\[.+\]/.test(f.basename(l)));for(let l of r)if(!t.includes(l))t.push(l)}catch{}if(t.length===0)console.error(`Error: No STX or Markdown files found matching pattern: ${h}`),n.exit(1);if(!await Tn(t,p))n.exit(1)}catch(x){console.error("Failed to process files:",x),n.exit(1)}else _n(h,p).catch((x)=>{console.error("Failed to start dev server:",x),n.exit(1)})}else{let h=function(t,e){let o=[];for(let i=0;i<=e.length;i++)o[i]=[i];for(let i=0;i<=t.length;i++)o[0][i]=i;for(let i=1;i<=e.length;i++)for(let s=1;s<=t.length;s++)if(e.charAt(i-1)===t.charAt(s-1))o[i][s]=o[i-1][s-1];else o[i][s]=Math.min(o[i-1][s-1]+1,o[i][s-1]+1,o[i-1][s]+1);return o[e.length][t.length]};y.command("docs","Generate documentation for components, templates, and directives").option("--output <dir>","Output directory for documentation",{default:"docs"}).option("--format <format>","Documentation format (markdown, html, json)",{default:"markdown"}).option("--components-dir <dir>","Components directory",{default:"components"}).option("--templates-dir <dir>","Templates directory",{default:"."}).option("--no-components","Disable components documentation").option("--no-templates","Disable templates documentation").option("--no-directives","Disable directives documentation").option("--extra-content <content>","Extra content to include in documentation").example("stx docs --output docs --format html").action(async(t)=>{try{if(await Zs(t))console.log("Documentation generated successfully."),n.exit(0);else console.error("Documentation generation failed."),n.exit(1)}catch(e){console.error("Error generating documentation:",e),n.exit(1)}}),y.command("iconify <command>","Generate Iconify icon packages").option("--output <dir>","Output directory for generated packages",{default:"packages"}).option("--icons <icons>","Comma-separated list of specific icons to generate").example("stx iconify list").example("stx iconify generate mdi").example("stx iconify generate lucide --icons home,settings,user").action(async(t,e)=>{try{let{fetchCollections:o,generatePackage:i}=await import("./chunk-t61vdbje.js");if(t==="list"){console.log(`
|
|
5
5
|
\uD83D\uDCDA Fetching available icon collections...
|
|
6
6
|
`);let s=await o(),c=Object.entries(s).sort((r,l)=>l[1].total-r[1].total);console.log(`Available collections:
|
|
7
7
|
`);for(let[r,l]of c){let d=l;console.log(` ${r.padEnd(30)} ${d.name} (${d.total} icons)`)}console.log(`
|
|
8
8
|
Total: ${c.length} collections`)}else if(t.startsWith("generate")){let s=t==="generate"?"":t.replace("generate:","").replace("generate-","").replace("generate","").trim();if(!s)console.error("Error: Please specify a collection prefix"),console.error("Usage: stx iconify generate <prefix> [--icons icon1,icon2,...]"),n.exit(1);let c=e.output||f.join(n.cwd(),"packages/collections"),r=e.icons?e.icons.split(",").map((l)=>l.trim()):void 0;await i(s,c,r),console.log(`
|
|
9
9
|
\u2713 Package generated successfully!`),console.log(`
|
|
10
|
-
To use the package:`),console.log(` 1. cd packages/collections/iconify-${s}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${t}`),console.error("Available commands: list, generate"),n.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(t,e)=>{try{if(t==="audit"){let{runPwaAudit:o,formatAuditResult:i}=await import("./chunk-njrakvz7.js"),{loadConfig:s}=await import("./chunk-
|
|
10
|
+
To use the package:`),console.log(` 1. cd packages/collections/iconify-${s}`),console.log(" 2. bun install"),console.log(" 3. bun run build")}else console.error(`Unknown iconify command: ${t}`),console.error("Available commands: list, generate"),n.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("pwa <command>","PWA tools - audit configuration and build output").option("--output <dir>","Build output directory to audit",{default:"dist"}).example("stx pwa audit").example("stx pwa audit --output build").action(async(t,e)=>{try{if(t==="audit"){let{runPwaAudit:o,formatAuditResult:i}=await import("./chunk-njrakvz7.js"),{loadConfig:s}=await import("./chunk-ptj7fwre.js");console.log(`
|
|
11
11
|
\uD83D\uDD0D Running PWA audit...
|
|
12
12
|
`);let c=await s(),r=e.output||"dist",l=o(c,r);if(console.log(i(l)),l.failed>0)n.exit(1)}else console.error(`Unknown pwa command: ${t}`),console.error("Available commands: audit"),n.exit(1)}catch(o){console.error("Error:",o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("dev [file]","Start a development server for an STX app or file").option("--port <port>","Port to use for the dev server",{default:3000}).option("--pages <dir>",'Directory containing page templates (default: pagesDir from stx.config.ts, else "pages")').option("--no-watch","Disable file watching and auto-reload").option("--native","Open in a native desktop window using Zyte").option("--titlebar-hidden","Hide the native titlebar but keep the traffic-light buttons (web content draws under a transparent full-size titlebar). Implies --native.").option("--highlight-theme <theme>","Syntax highlighting theme for Markdown code blocks",{default:"github-dark"}).option("--no-highlight","Disable syntax highlighting for Markdown code blocks").option("--no-highlight-unknown","Disable syntax highlighting for unknown languages in Markdown").option("--no-cache","Disable caching of parsed files").option("--no-hmr","Disable HMR / live-reload script injection (useful for clean network traces)").option("--profile","Print per-directive timing for every page render via performanceMonitor").option("--debug-directives","Log directive ordering and intermediate template state during rendering").example("stx dev").example("stx dev --port 8080").example("stx dev --pages src/pages").example("stx dev template.stx").example("stx dev components/hero.stx --port 8080").example("stx dev **/*.stx").example("stx dev docs/guide.md").example("stx dev template.stx --native").action(async(t,e)=>{try{if(e.port!==void 0){let i=B(e.port);if(!i.isValid)F(i);e.port=Number.parseInt(String(e.port),10)}if(e.timeout!==void 0){let i=z(e.timeout);if(!i.isValid)F(i)}let o={syntaxHighlighting:{enabled:e.highlight!==!1,serverSide:!0,defaultTheme:e.highlightTheme||"github-dark",highlightUnknownLanguages:e.highlightUnknown!==!1}};if(!t){if(!await $n(".",{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,cache:e.cache!==!1,hotReload:e.hmr!==!1,profile:e.profile===!0,debugDirectives:e.debugDirectives===!0,...e.pages&&{pagesDir:e.pages}}))n.exit(1);return}if(!O(t))try{let i=await import("fs");if(i.existsSync(t)&&i.statSync(t).isDirectory()){if(!await $n(t,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,cache:e.cache!==!1,hotReload:e.hmr!==!1,profile:e.profile===!0,debugDirectives:e.debugDirectives===!0,...e.pages&&{pagesDir:e.pages}}))n.exit(1);return}}catch{}if(O(t)){console.log(`Expanding glob pattern: ${t}`);let i=await W.timeAsync("glob-expansion",async()=>Array.fromAsync(new Bun.Glob(t).scan({onlyFiles:!0,absolute:!0}))),s=t.endsWith(".stx")?i.filter((d)=>d.endsWith(".stx")):t.endsWith(".md")?i.filter((d)=>d.endsWith(".md")):i.filter((d)=>d.endsWith(".stx")||d.endsWith(".md"));if(s.length===0)console.error(`No STX or Markdown files found matching pattern: ${t}`),console.error("Try using patterns like '*.stx' or 'components/**/*.stx'"),n.exit(1);let c=t.split("*")[0].replace(/\/$/,"")||".",r=f.resolve(c);try{let d=new Bun.Glob("**/*.stx"),m=(await Array.fromAsync(d.scan({cwd:r,onlyFiles:!0,absolute:!0}))).filter((g)=>/\[.+\]/.test(f.basename(g)));for(let g of m)if(!s.includes(g))s.push(g)}catch{}if(console.log(`Found ${s.length} ${s.length===1?"file":"files"} matching ${t}`),!await Tn(s,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,markdown:o,cache:e.cache!==!1}))n.exit(1)}else{if(!O(t)){let s=A(t);if(!s.isValid)F(s)}if(!await _n(t,{port:e.port,watch:e.watch!==!1,native:e.native||e.titlebarHidden||!1,titlebarHidden:e.titlebarHidden===!0,markdown:o,cache:e.cache!==!1}))n.exit(1)}}catch(o){console.error("Error starting dev server:",o),n.exit(1)}}),y.command("a11y [target]","Scan .stx files for accessibility issues (directory, file, or glob)").option("--no-recursive","Disable recursive scanning of directories").option("--ignore <paths>","Comma-separated paths to ignore",{default:""}).option("--json","Output results as JSON").option("--output <file>","Write results to a file instead of stdout").option("--fix","Automatically fix common accessibility issues").example("stx a11y ./templates").example('stx a11y "resources/**/*.stx"').example("stx a11y resources/emails/welcome.stx").example("stx a11y --json --output a11y-report.json").action(async(t=".",e)=>{try{console.log(`Scanning ${t} for accessibility issues...`);let o=e.ignore?e.ignore.split(",").map((l)=>l.trim()):[],{results:i,scannedFiles:s}=await xi(t,{recursive:e.recursive!==!1,ignorePaths:o});if(s.length===0)console.log(`
|
|
13
13
|
No .stx files matched ${t}
|
|
@@ -69,7 +69,7 @@ Total: ${r} issues in ${c} files`),e.output){let l=`
|
|
|
69
69
|
File not found: ${t}`),n.exit(1);if(!t.endsWith(".stx"))console.error(`
|
|
70
70
|
File must have .stx extension: ${t}`),n.exit(1)}let i=f.resolve(e.pages),s=f.resolve(e.out);if(!t&&!S.existsSync(i))console.error(`
|
|
71
71
|
Pages directory not found: ${i}`),console.log(`
|
|
72
|
-
Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),n.exit(1);let{buildApp:c}=await import("./chunk-
|
|
72
|
+
Create a 'pages' directory with .stx files, or use --pages to specify a different directory.`),n.exit(1);let{buildApp:c}=await import("./chunk-sgrwxhgg.js");bt();let r=await c({root:t?f.dirname(t):void 0,debug:e.verbose,ssg:{pagesDir:e.pages,outputDir:e.out,domain:e.domain,baseUrl:e.base,sitemap:e.sitemap,rss:e.rss,minify:e.minify,cache:e.cache!==!1,cleanOutput:e.clean,concurrency:Number.parseInt(e.concurrency,10)||10,publicDir:e.public,trailingSlash:e.trailingSlash,generate404:!0,hooks:e.verbose?{onPageStart:(d)=>console.log(` Generating: ${d}`),onPageEnd:(d,a)=>console.log(` Generated: ${d} (${a.length} bytes)`),onError:(d,a)=>console.error(` Error in ${a}: ${d.message}`)}:void 0},ssr:{outputDir:e.out==="dist"?".output":e.out,debug:e.verbose}}),l=((performance.now()-o)/1000).toFixed(2);if(r.mode==="ssr"&&r.ssr)console.log(`
|
|
73
73
|
Build complete! (SSR)
|
|
74
74
|
`),console.log(` Pages compiled: ${r.ssr.pageCount}`),console.log(` Output: ${r.ssr.outputDir}`),console.log(` Duration: ${l}s
|
|
75
75
|
`);else if(r.ssg){if(console.log(`
|
|
@@ -84,7 +84,7 @@ Total: ${r} issues in ${c} files`),e.output){let l=`
|
|
|
84
84
|
Build completed with ${r.ssg.failedCount} error(s). Fix the issues above and try again.
|
|
85
85
|
`),n.exit(1);console.log(" To preview locally:"),console.log(` cd ${e.out||"dist"} && npx serve
|
|
86
86
|
`)}}catch(o){console.error(`
|
|
87
|
-
Build failed:`,o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(t)=>{try{let e=f.resolve(t.output);if(!S.existsSync(f.join(e,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),n.exit(1);let{startProductionServer:o}=await import("./chunk-
|
|
87
|
+
Build failed:`,o instanceof Error?o.message:String(o)),n.exit(1)}}),y.command("start","Start the production server (serves pre-built .output/)").option("--port <number>","Server port",{default:"3000"}).option("--output <dir>","Output directory from stx build",{default:".output"}).example("stx start").example("stx start --port 8080").action(async(t)=>{try{let e=f.resolve(t.output);if(!S.existsSync(f.join(e,"manifest.json")))console.error("\n No production build found. Run `stx build --out .output` first.\n"),n.exit(1);let{startProductionServer:o}=await import("./chunk-da4cj4zb.js");await o({outputDir:e,port:Number.parseInt(t.port,10)||3000})}catch(e){console.error(`
|
|
88
88
|
Failed to start production server:`,e instanceof Error?e.message:String(e)),n.exit(1)}}),y.command("deploy [directory]","Deploy built site to Netlify").option("--site-id <id>","Netlify site ID (or set NETLIFY_SITE_ID env var)").option("--token <token>","Auth token (or set NETLIFY_AUTH_TOKEN env var)").option("--production","Deploy to production (default: draft preview)").option("--message <msg>","Deploy message/title").option("--no-build","Skip build step before deploy").option("--open","Open deployed URL in browser").option("--dry-run","Preview deployment without uploading").option("--init","Initialize Netlify configuration for this project").example("stx deploy").example("stx deploy --production").example("stx deploy dist --site-id my-site-abc123").example("stx deploy --init").example("stx deploy --dry-run").action(async(t,e)=>{try{let{deploy:o,initNetlify:i,DeployError:s}=await import("./chunk-3j5bg3xq.js");if(console.log(`\x1B[1mstx deploy\x1B[0m \x1B[2mv${j}\x1B[0m`),e.init){console.log(`
|
|
89
89
|
\uD83D\uDCDD Initializing Netlify configuration...
|
|
90
90
|
`);let r=await i({directory:t||n.cwd(),siteId:e.siteId});if(console.log(`\u2713 Created ${r.configPath}`),r.siteId)console.log("\u2713 Saved site ID to .env.local");console.log(`
|
|
@@ -124,7 +124,7 @@ To view it in the development server:`),console.log(` stx dev ${t}
|
|
|
124
124
|
\uD83D\uDCDD ${f.relative(n.cwd(),a)}:`),console.log("--- Original"),console.log("+++ Formatted"),console.log(`@@ Changes in ${f.basename(a)} @@`),console.log("+ Formatted content would be applied");else await Bun.write(a,b),console.log(`\u2705 Formatted ${f.relative(n.cwd(),a)}`),l++}catch(m){console.error(`\u274C Error formatting ${f.relative(n.cwd(),a)}:`,m),d++}if(e.check&&d>0)console.log(`
|
|
125
125
|
${d} files need formatting. Run 'stx format' to fix.`),n.exit(1);else if(!e.check&&!e.diff)console.log(`\u2728 Formatted ${l} files successfully`)}catch(o){console.error("Error formatting files:",o),n.exit(1)}}),y.command("perf [command...]","Show performance statistics for STX operations").option("--clear","Clear performance statistics").option("--json","Output as JSON").example("stx perf").example("stx perf --clear").example("stx perf --json").action(async(t,e)=>{try{if(e.clear){W.clear(),console.log("\u2705 Performance statistics cleared");return}let o=W.getStats();if(Object.keys(o).length===0){if(e.json){console.log(JSON.stringify({},null,2));return}console.log("No performance data available. Run some STX commands first.");return}if(e.json)console.log(JSON.stringify(o,null,2));else{console.log(`
|
|
126
126
|
\uD83D\uDCCA STX Performance Statistics
|
|
127
|
-
`);for(let[i,s]of Object.entries(o))console.log(`\uD83D\uDD27 ${i}:`),console.log(` Count: ${s.count}`),console.log(` Average: ${s.avgTime.toFixed(2)}ms`),console.log(` Total: ${s.totalTime.toFixed(2)}ms`),console.log(` Min: ${s.minTime.toFixed(2)}ms`),console.log(` Max: ${s.maxTime.toFixed(2)}ms`),console.log("")}}catch(o){console.error("Error showing performance stats:",o),n.exit(1)}}),y.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(t,e)=>{let{formatTypecheckDiagnostics:o,typecheckStxFiles:i}=await import("./chunk-
|
|
127
|
+
`);for(let[i,s]of Object.entries(o))console.log(`\uD83D\uDD27 ${i}:`),console.log(` Count: ${s.count}`),console.log(` Average: ${s.avgTime.toFixed(2)}ms`),console.log(` Total: ${s.totalTime.toFixed(2)}ms`),console.log(` Min: ${s.minTime.toFixed(2)}ms`),console.log(` Max: ${s.maxTime.toFixed(2)}ms`),console.log("")}}catch(o){console.error("Error showing performance stats:",o),n.exit(1)}}),y.command("typecheck [patterns...]","Type-check the TypeScript inside .stx script blocks").option("--no-client","Skip <script client> and bare <script> blocks").option("--no-server","Skip <script server> blocks").option("--no-templates","Skip {{ }} and directive expressions in the markup").option("--lib <path>","Extra ambient declaration file (repeatable)").example("stx typecheck").example('stx typecheck "resources/views/**/*.stx"').action(async(t,e)=>{let{formatTypecheckDiagnostics:o,typecheckStxFiles:i}=await import("./chunk-8tsc5hmk.js"),{resolveStxTargets:s}=await import("./chunk-sn98t7ef.js"),c=Array.isArray(t)?t:t?[t]:[],r=c.length?c:["**/*.stx"],l=await s(r);if(l.length===0){console.log(`
|
|
128
128
|
No .stx files matched ${r.join(", ")}
|
|
129
129
|
`);return}let d=Xs(n.argv,"--lib"),a=d.length>0?d:e.lib?Array.isArray(e.lib)?e.lib:[e.lib]:[],m=await i(l,{client:e.client!==!1,server:e.server!==!1,templates:e.templates!==!1,extraLibs:a});if(m.failure)console.error(`
|
|
130
130
|
Type-check did not run.
|
|
@@ -136,7 +136,7 @@ ${d} files need formatting. Run 'stx format' to fix.`),n.exit(1);else if(!e.chec
|
|
|
136
136
|
${o(m.diagnostics)}
|
|
137
137
|
`);if(console.log(` Checked ${m.blockCount} script block(s) and ${m.expressionCount} template expression(s) in ${m.checkedFiles.length} file(s) \u2014 `+`${g.length} error(s), ${m.diagnostics.length-g.length} warning(s)
|
|
138
138
|
`),g.length>0)n.exit(1)}),y.command("codemod [patterns...]","Find hand-rolled code that an stx primitive already covers").option("--fix","Write the safe rewrites (default is report-only)").option("--rule <rule>","Run one rule only: confirm | tooltip (rewritable) \xB7 alert | route-params | search-params | navigate | "+"fetch | polling | debounce | click-outside | focus | clipboard | watch (report-only)").example("stx codemod").example("stx codemod --rule route-params").example('stx codemod --fix "resources/views/**/*.stx"').action(async(t,e)=>{let{codemodSource:o,formatCodemodFindings:i}=await import("./chunk-v1m9nrn9.js"),s=globalThis.Bun.Glob,c=Array.isArray(t)?t:t?[t]:[],r=c.length?c:["**/*.stx","**/*.ts"],l=e.rule?[e.rule]:void 0;if(e.rule&&e.rule!=="confirm"&&e.rule!=="tooltip")console.error(`Unknown rule "${e.rule}". Expected: confirm | tooltip`),n.exit(1);let d=new Set,a=[],m=0,g=new Set;try{let b=Bun.spawnSync(["git","ls-files","--others","--ignored","--exclude-standard","-z"],{cwd:n.cwd(),stdout:"pipe",stderr:"pipe"});for(let w of new TextDecoder().decode(b.stdout).split("\x00"))if(w)g.add(f.resolve(n.cwd(),w))}catch{}for(let b of r)for await(let w of new s(b).scan({cwd:n.cwd(),absolute:!0})){if(w.includes("/node_modules/")||w.includes("/dist/")||d.has(w)||g.has(w))continue;d.add(w);let k=await Bun.file(w).text(),v=o(k,{file:w,rules:l});if(a.push(...v.findings),e.fix&&v.code!==k)await Bun.write(w,v.code),m++}if(console.error(i(a,Boolean(e.fix))),e.fix)console.error(`
|
|
139
|
-
${m} file(s) written.`)}),y.command("doctor","Diagnose the stx framework-runtime resolution + staleness chain").option("--json","Output the report as JSON").example("stx doctor").example("stx doctor --json").action(async(t)=>{try{let e;try{let i=await import("./chunk-
|
|
139
|
+
${m} file(s) written.`)}),y.command("doctor","Diagnose the stx framework-runtime resolution + staleness chain").option("--json","Output the report as JSON").example("stx doctor").example("stx doctor --json").action(async(t)=>{try{let e;try{let i=await import("./chunk-knr41h7p.js");e=i.generateSignalsRuntime}catch{e=void 0}let o=await vr({generateRuntime:e});if(t.json)console.log(JSON.stringify(o,null,2));else console.log(xr(o));if(!o.ok)n.exit(1)}catch(e){console.error("Error running doctor:",e),n.exit(1)}}),y.command("debug <file>","Debug STX template processing step by step").option("--step","Step through processing stages interactively").option("--verbose","Show detailed processing information").option("--context <data>","JSON string of context data to use").option("--save-report <file>","Save debug report to file").example("stx debug template.stx").example("stx debug template.stx --step").example(`stx debug template.stx --context '{"name": "John", "items": [1,2,3]}'`).action(async(t,e)=>{try{let o=A(t);if(!o.isValid)F(o);console.log(`\uD83D\uDD0D Debugging stx template: ${t}
|
|
140
140
|
`);let i={};if(e.context)try{i=JSON.parse(e.context)}catch(r){console.error("\u274C Invalid JSON in --context option"),n.exit(1)}let s=await Bun.file(t).text();console.log(`\uD83D\uDCC4 Template Content (${s.length} chars):`),console.log("\u2500".repeat(50)),console.log(s.substring(0,500)+(s.length>500?`
|
|
141
141
|
...
|
|
142
142
|
`:"")),console.log("\u2500".repeat(50));let c=s.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(c)console.log(`
|
|
@@ -160,11 +160,11 @@ Press Ctrl+C to stop watching...
|
|
|
160
160
|
\uD83D\uDCC4 Files with issues:`),d.forEach((a)=>{let m=a.issues.filter((g)=>s[g.type]>=c).length;if(m>0)console.log(` ${f.relative(n.cwd(),a.file)} (${m} issues)`)});if(e.saveReport){let a={summary:l,results:d,generatedAt:new Date().toISOString(),commandOptions:e};await Bun.write(e.saveReport,JSON.stringify(a,null,2)),console.log(`
|
|
161
161
|
\uD83D\uDCCB Analysis report saved to: ${e.saveReport}`)}console.log(`
|
|
162
162
|
\u2728 Analysis complete! Use --detailed for more information.`)}catch(o){console.error("Error analyzing templates:",o),n.exit(1)}}),y.command("screenshot [input]","Capture PNG screenshot(s) of page(s) via Bun WebView \u2014 a file, URL, or dist directory").option("--out <dir>","Output directory",{default:"screenshots"}).option("--width <px>","Viewport width",{default:"1440"}).option("--height <px>","Viewport height",{default:"2200"}).option("--wait <ms>","Settle time after navigation before capture",{default:"800"}).option("--timeout <ms>","Hard cap on waiting for navigation",{default:"15000"}).option("--full-page","Capture the entire scrollable page, not just the viewport").option("--wait-selector <sel>","Wait until a CSS selector exists before capturing").option("--format <fmt>","Image format: png | jpeg | webp",{default:"png"}).option("--backend <name>","WebView backend: webkit (macOS, default) | chrome").action(async(t,e)=>{let{captureScreenshots:o}=await import("./chunk-13xhvx68.js"),i=t||"dist";try{let s=await o(i,e.out,{width:Number.parseInt(e.width,10),height:Number.parseInt(e.height,10),waitMs:Number.parseInt(e.wait,10),timeoutMs:Number.parseInt(e.timeout,10),fullPage:Boolean(e.fullPage),waitSelector:e.waitSelector,format:e.format,backend:e.backend});for(let c of s)console.log(`\uD83D\uDCF8 ${c.output} (${(c.bytes/1024).toFixed(0)} KB)`);console.log(`
|
|
163
|
-
\u2728 Captured ${s.length} screenshot(s) to ${e.out}/ via Bun WebView`)}catch(s){console.error(`Screenshot failed: ${s.message}`),n.exit(1)}}),y.command("version","Show the version of the CLI").action(()=>{console.log(j)}),y.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(t)=>{let{startInteractive:e}=await import("./chunk-
|
|
163
|
+
\u2728 Captured ${s.length} screenshot(s) to ${e.out}/ via Bun WebView`)}catch(s){console.error(`Screenshot failed: ${s.message}`),n.exit(1)}}),y.command("version","Show the version of the CLI").action(()=>{console.log(j)}),y.command("interactive","Start interactive REPL mode for template development").alias("i").option("--context <file>","Load initial context from JSON file").option("--cwd <directory>","Set working directory").option("--verbose","Show verbose output").action(async(t)=>{let{startInteractive:e}=await import("./chunk-8wanndhv.js"),o={};if(t.context){let i=f.resolve(t.context);if(S.existsSync(i))try{let s=S.readFileSync(i,"utf-8");o=JSON.parse(s)}catch(s){console.error("Error loading context file:",s),n.exit(1)}else console.error(`Context file not found: ${i}`),n.exit(1)}await e({context:o,cwd:t.cwd?f.resolve(t.cwd):n.cwd(),verbose:t.verbose})}),y.command("build:native <input>","Build stx template into a native desktop/mobile app").option("--output <dir>","Output directory",{default:"dist/native"}).option("--target <platform>","Target platform: macos, windows, linux, ios, android").option("--format <format>","Output format: app, dmg, pkg, msi, zip, deb, rpm, appimage, ipa, apk").option("--name <name>","Application name (defaults to filename)").option("--version <version>","Application version",{default:"1.0.0"}).option("--description <desc>","Application description").option("--author <author>","Author/Maintainer name").option("--bundle-id <id>","Bundle identifier (macOS/iOS)").option("--icon <path>","Path to application icon").option("--width <width>","Window width",{default:"1200"}).option("--height <height>","Window height",{default:"800"}).option("--title <title>","Window title").option("--system-tray","Enable system tray/menubar mode").option("--menubar-only","Run without a dock icon (implied by --system-tray)").option("--category <type>","LSApplicationCategoryType (macOS)").option("--copyright <text>","NSHumanReadableCopyright (macOS)").option("--min-system-version <v>","LSMinimumSystemVersion (macOS)").option("--info-plist <json>","Extra Info.plist keys as a JSON object (macOS)").option("--dev-tools","Enable developer tools").option("--frameless","Create frameless window").option("--always-on-top","Keep window always on top").option("--craft-path <path>","Path to Craft binary").option("--verbose","Show verbose output").example("stx build:native app.stx --target macos").example("stx build:native app.stx --target macos --format dmg").example("stx build:native app.stx --target linux --format appimage").example('stx build:native app.stx --name "My App" --icon icon.png').action(async(t,e)=>{try{let{buildNative:o,getAvailableTargets:i,getAvailableFormats:s}=await import("./chunk-1hxh2wbw.js"),c=f.resolve(t);if(!S.existsSync(c))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let r=i();if(e.target&&!["macos","windows","linux","ios","android"].includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error("\uD83D\uDCA1 Available targets: macos, windows, linux, ios, android"),console.error(`\uD83D\uDCA1 Targets available on this machine: ${r.join(", ")}`),n.exit(1);let l=e.target||r[0],d=s(l);if(e.format&&!d.includes(e.format))console.error(`\u274C Invalid format for ${l}: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${d.join(", ")}`),n.exit(1);console.log(`
|
|
164
164
|
\uD83D\uDD28 Building native app...`),console.log(` Input: ${t}`),console.log(` Target: ${l}`),console.log(` Format: ${e.format||"default"}`),console.log(` Output: ${e.output}
|
|
165
165
|
`);let a=await o({input:c,output:f.resolve(e.output),target:l,format:e.format,name:e.name,version:e.version,description:e.description,author:e.author,bundleId:e.bundleId,icon:e.icon?f.resolve(e.icon):void 0,window:{title:e.title,width:Number.parseInt(e.width,10),height:Number.parseInt(e.height,10),frameless:e.frameless,alwaysOnTop:e.alwaysOnTop},systemTray:e.systemTray,menubarOnly:e.menubarOnly,category:e.category,copyright:e.copyright,minimumSystemVersion:e.minSystemVersion,infoPlist:H(e.infoPlist),devTools:e.devTools,craftPath:e.craftPath,verbose:e.verbose});if(a.success){if(console.log("\u2705 Build successful!"),console.log(` Output: ${a.outputPath}`),a.duration)console.log(` Duration: ${(a.duration/1000).toFixed(2)}s`);if(l==="macos"&&a.format==="app")console.log(`
|
|
166
166
|
\uD83D\uDCA1 To run: open "${a.outputPath}"`);else if(l==="linux"&&a.format==="appimage")console.log(`
|
|
167
|
-
\uD83D\uDCA1 To run: chmod +x "${a.outputPath}" && "${a.outputPath}"`)}else console.error(`\u274C Build failed: ${a.error}`),n.exit(1)}catch(o){console.error(`\u274C Build error: ${o.message}`),n.exit(1)}}),y.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(t)=>{try{let{devCommand:e}=await import("./chunk-
|
|
167
|
+
\uD83D\uDCA1 To run: chmod +x "${a.outputPath}" && "${a.outputPath}"`)}else console.error(`\u274C Build failed: ${a.error}`),n.exit(1)}catch(o){console.error(`\u274C Build error: ${o.message}`),n.exit(1)}}),y.command("story","Start component showcase and testing server").option("-p, --port <port>","Server port",{default:"6006"}).option("-o, --open","Open browser automatically",{default:!1}).option("--host <host>","Host to bind to",{default:"localhost"}).example("stx story").example("stx story --port 3000 --open").action(async(t)=>{try{let{devCommand:e}=await import("./chunk-93jjxrx9.js");await e({port:t.port?Number.parseInt(t.port,10):6006,open:t.open,host:t.host})}catch(e){console.error(`\u274C Story error: ${e.message}`),n.exit(1)}}),y.command("story:build","Build static story site").option("-o, --outDir <dir>","Output directory",{default:".stx/dist/story"}).example("stx story:build").example("stx story:build --outDir ./docs/components").action(async(t)=>{try{let{buildCommand:e}=await import("./chunk-d0yx9kef.js");await e({outDir:t.outDir})}catch(e){console.error(`\u274C Story build error: ${e.message}`),n.exit(1)}}),y.command("story:test","Run visual regression tests").option("-u, --update","Update snapshots",{default:!1}).option("-f, --filter <name>","Filter components by name").example("stx story:test").example("stx story:test --update").example("stx story:test --filter Button").action(async(t)=>{try{let{createContext:e}=await import("./chunk-hp8g2q2n.js"),{runVisualTests:o,updateSnapshots:i,formatTestResults:s}=await import("./chunk-xzcmh5va.js"),c=await e({mode:"build"});if(t.update){let r=await i(c,{filter:t.filter?[t.filter]:void 0});console.log(`Updated ${r} snapshots`)}else{let r=await o(c,{filter:t.filter?[t.filter]:void 0});if(console.log(s(r)),r.failed>0)n.exit(1)}}catch(e){console.error(`\u274C Story test error: ${e.message}`),n.exit(1)}}),y.command("native <action> [file]","Compile .stx screens into the JavaScriptCore bundle Craft renders natively").option("--format <format>","bundle (the JavaScriptCore bundle) or ir (the template as JSON)",{default:"ir"}).option("--output <path>","Write to this file instead of stdout").option("--minify","Minify the bundle",{default:!1}).option("--config <file>","Screens config (default: native.config.json in the working directory)").example("stx native compile Screen.stx --format bundle --output native-screen.js").example("stx native compile --format bundle --output native-screen.js --minify").example("stx native compile Screen.stx").action(async(t,e,o)=>{if(t!=="compile")console.error(`Unknown native command: ${t}`),console.error("Usage: stx native compile [file.stx] --format bundle|ir [--output <file>] [--minify] [--config <file>]"),n.exit(1);try{let{runNativeCompile:i}=await import("./chunk-d80mbwyp.js"),s=await i(e,{format:o.format,output:o.output,minify:Boolean(o.minify),config:o.config});for(let c of s.diagnostics)console.warn(`${c.level}: ${c.message}`);if(s.written)console.log(`Compiled: ${e??"screens"} \u2192 ${f.relative(n.cwd(),s.written)||s.written}`);else console.log(s.output)}catch(i){console.error(i instanceof Error?i.message:String(i)),n.exit(1)}}),y.command("compile <input>","Compile stx template to native Craft component code").option("--target <platform>","Target platform: macos, windows, linux, ios, android, universal",{default:"universal"}).option("--format <format>","Output format: zig, typescript, json",{default:"zig"}).option("--output <path>","Output directory for compiled files",{default:"./dist"}).option("--optimize","Enable optimizations",{default:!0}).option("--tree-shake","Enable tree shaking",{default:!0}).option("--hot-reload","Enable hot reload support",{default:!1}).option("--sourcemaps","Generate source maps",{default:!1}).option("--bundle","Bundle all dependencies",{default:!0}).option("--minify","Minify output",{default:!1}).option("--verbose","Show detailed output",{default:!1}).example("stx compile app.stx").example("stx compile app.stx --target macos --format zig").example("stx compile app.stx --format typescript --output ./native").example("stx compile app.stx --optimize --tree-shake --minify").action(async(t,e)=>{try{let{compileToNative:o}=await import("./chunk-qyj6zygv.js"),i=f.resolve(t);if(!S.existsSync(i))console.error(`\u274C Input file not found: ${t}`),n.exit(1);let s=["macos","windows","linux","ios","android","universal"];if(!s.includes(e.target))console.error(`\u274C Invalid target: ${e.target}`),console.error(`\uD83D\uDCA1 Available targets: ${s.join(", ")}`),n.exit(1);let c=["zig","typescript","json"];if(!c.includes(e.format))console.error(`\u274C Invalid format: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${c.join(", ")}`),n.exit(1);console.log(`
|
|
168
168
|
\uD83D\uDD27 Compiling stx template to native code...`),console.log(` Input: ${t}`),console.log(` Target: ${e.target}`),console.log(` Format: ${e.format}`),console.log(` Output: ${e.output}
|
|
169
169
|
`);let r=S.readFileSync(i,"utf-8"),l=await o(r,{target:e.target,format:e.format,optimize:e.optimize,treeShake:e.treeShake,hotReload:e.hotReload,debug:e.verbose,sourceMaps:e.sourcemaps,bundle:e.bundle,minify:e.minify}),d=f.resolve(e.output);if(!S.existsSync(d))S.mkdirSync(d,{recursive:!0});let a=f.basename(t,f.extname(t)),m=e.format==="typescript"?"ts":e.format==="json"?"json":"zig",g=f.join(d,`${a}.${m}`);S.writeFileSync(g,l.code);let b=f.join(d,`${a}.manifest.json`);if(S.writeFileSync(b,JSON.stringify(l.manifest,null,2)),e.sourcemaps&&l.sourceMaps){let w=f.join(d,`${a}.${m}.map`);S.writeFileSync(w,l.sourceMaps)}if(e.target==="universal"&&l.platformCode.size>0)for(let[w,k]of l.platformCode){let v=f.join(d,`${a}.${w}.${m}`);S.writeFileSync(v,k)}if(console.log("\u2705 Compilation successful!"),console.log(` Output: ${g}`),console.log(` Manifest: ${b}`),console.log(`
|
|
170
170
|
\uD83D\uDCCA Statistics:`),console.log(` Compilation time: ${l.stats.compilationTime.toFixed(2)}ms`),console.log(` Total components: ${l.stats.totalComponents}`),console.log(` Native components: ${l.stats.nativeComponents}`),console.log(` Web fallback components: ${l.stats.webComponents}`),console.log(` Bundle size: ${(l.stats.bundleSize/1024).toFixed(2)}KB`),l.stats.warnings.length>0){console.log(`
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
/** DOM-ready initialization used by the generated client runtime. */
|
|
2
|
-
export declare const SIGNALS_DOM_READY_RUNTIME = " // ==========================================================================\n // Auto-initialization\n // ==========================================================================\n\n // A dev runtime may be evaluated again by HMR, an embed, or a test harness.\n // Replace the previous listener so only the latest runtime closure can own\n // componentScope and reactive subscriptions.\n if (window.__stxDomReadyHandler) {\n document.removeEventListener('DOMContentLoaded', window.__stxDomReadyHandler);\n }\n const stxDomReadyHandler = () => {\n console.log('[stx] DOMContentLoaded fired \u2014 processing scopes');\n // Track which scoped elements have been processed\n const processedScopes = new Set();\n\n // Layout expansion can remove the data-stx marker from a page's first\n // element while leaving markers owned by the layout itself. The generated\n // page setup is still queued explicitly, so adopt it when its own marker\n // did not survive.\n const latestSetup = window.stx._latestSetup;\n const latestSetupName = typeof latestSetup === 'function' ? latestSetup.name : '';\n const hasLatestSetupMarker = latestSetupName && Array.from(document.querySelectorAll('[data-stx]'))\n .some(el => el.getAttribute('data-stx') === latestSetupName);\n if (latestSetup && !hasLatestSetupMarker) {\n try {\n const result = latestSetup();\n if (typeof result === 'object' && result !== null)\n Object.assign(componentScope, result);\n }\n catch (e) {\n console.error('[stx] initial setup error:', e);\n }\n }\n\n // Register page setup before mounting child components. Projected slot\n // content belongs to the caller, so child mounts need the caller's signals\n // available when they walk their own rendered roots.\n document.querySelectorAll('[data-stx]').forEach(el => {\n const setupName = el.getAttribute('data-stx');\n console.log('[DOMContentLoaded] data-stx:', setupName, 'el:', el.tagName, 'fn exists:', !!(setupName && window[setupName]));\n if (setupName && window[setupName]) {\n // Contained, like the two sibling setup call sites. An uncaught throw\n // here aborted the whole forEach and everything after it in this\n // handler, so ONE bad name in ONE page's setup left every root on the\n // page unhydrated \u2014 the user sees raw {{ }}, and the console names the\n // identifier without saying it cost them the document (#1805).\n try {\n const result = window[setupName]();\n console.log('[DOMContentLoaded] setup returned:', result ? Object.keys(result).slice(0, 10) : 'null');\n if (typeof result === 'object' && result !== null) {\n Object.assign(componentScope, result);\n }\n }\n catch (e) {\n console.error('[stx] page setup \"' + setupName + '\" threw; this root will not hydrate:', e);\n }\n }\n });\n var pageScopeSnapshot = { ...componentScope };\n\n /*\n * Any x-data scope the reactive bridge did not reach, initialized here.\n *\n * The bridge script addresses each scope by a selector it generated, and\n * that numbering restarts per render - so a page carrying three component\n * islands emits three scripts all looking for the same scope id, and two of\n * the three scopes are never initialized at all. The symptom is the\n * quietest one available: the markup is there, every binding shows its\n * initial value, and whatever x-init was meant to start never starts.\n *\n * Registered scopes are skipped, so the bridge stays authoritative where it\n * did run and this only picks up what it missed. The init expression is\n * read from data-stx-xinit, which the server preserves for exactly this.\n *\n * No backticks in this comment, deliberately: it lives inside the runtime\n * source that is embedded as a template literal, and one would end the\n * literal and take the whole file's syntax with it.\n */\n if (window.__stx_reactive && window.__stx_reactive.initScope) {\n document.querySelectorAll('[data-stx-xdata]').forEach(function(el) {\n var scopeId = el.getAttribute('data-stx-scope');\n if (scopeId && window.stx._scopes && window.stx._scopes[scopeId]) return;\n if (el.__stx_scope_initialized) return;\n\n var xdata = el.getAttribute('data-stx-xdata');\n if (!xdata) return;\n\n if (!scopeId) {\n scopeId = '__stx_scope_island_' + (++window.stx._scopeCounter);\n el.setAttribute('data-stx-scope', scopeId);\n }\n\n el.__stx_scope_initialized = true;\n\n try {\n window.__stx_reactive.initScope(el, xdata, [], {}, el.getAttribute('data-stx-xinit') || null);\n }\n catch (e) {\n console.error('[stx] island scope init error:', e);\n }\n });\n }\n\n // Process mount queue (from stx.mount() calls during loading) only after\n // caller setup is available for Vue-style projected slot ownership.\n mountQueue.forEach(function(fn) { fn(); });\n mountQueue = [];\n\n // Bind page roots after child components have registered their local scope.\n document.querySelectorAll('[data-stx]').forEach(el => {\n console.log('[DOMContentLoaded] processElement on:', el.tagName, 'scope keys:', Object.keys(componentScope).slice(0, 10));\n var disposeEffects = trackEffects(function() {\n // The server's list when the page shipped one, the walk otherwise.\n if (!processFromManifest(el, componentScope, window.__stx_bindings)) processElement(el);\n });\n el.__stx_disposers = disposeEffects;\n\n // Remove x-cloak after bindings are applied (prevents FOUC)\n el.removeAttribute('x-cloak');\n el.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n\n runMountCallbacks(mountCallbacks, destroyCallbacks);\n });\n\n // Multi-root fragment fix: a no-body> setup page tags only the FIRST\n // top-level element with data-stx (signal-processing.ts marks one element),\n // so sibling root elements were orphaned \u2014 their :if / :for / {{ }} / x-text\n // never hydrated, which read as \"{{ }} doesn't work under :if/:for\". The\n // setup(s) above already populated the shared global componentScope, so\n // process each un-hydrated sibling root under that same scope \u2014 same signals,\n // so cross-root state stays coupled.\n var stxRoots = document.querySelectorAll('[data-stx]');\n if (stxRoots.length && Object.keys(componentScope).length) {\n var rootParent = stxRoots[0].parentNode;\n if (rootParent && rootParent.children) {\n Array.prototype.slice.call(rootParent.children).forEach(function(sib) {\n if (sib.nodeType !== 1) return;\n if (sib.hasAttribute('data-stx') || sib.hasAttribute('data-stx-scope')) return;\n if (sib.tagName === 'SCRIPT' || sib.tagName === 'STYLE') return;\n if (sib.__stx_disposers) return; // already processed\n var disposeSib = trackEffects(function() { processElement(sib); });\n sib.__stx_disposers = disposeSib;\n sib.removeAttribute('x-cloak');\n sib.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n });\n }\n }\n\n // Process scoped components FIRST (their scripts have already registered scope variables)\n var allScopes = document.querySelectorAll('[data-stx-scope]');\n console.log('[stx] found', allScopes.length, 'data-stx-scope elements');\n allScopes.forEach(el => {\n const scopeId = el.getAttribute('data-stx-scope');\n console.log('[stx] scope:', scopeId, 'registered:', !!(window.stx._scopes && window.stx._scopes[scopeId]), 'el:', el.tagName);\n processedScopes.add(el);\n\n const scopeVars = window.stx._scopes && window.stx._scopes[scopeId];\n // Record the element this scope is bound to so cleanupContainer can tell a\n // dead registry entry (element replaced by an SPA swap) from a live one.\n // See sweepOrphanedScopes / #1775.\n if (scopeVars) scopeVars.__el = el;\n\n // Deferred island (#1746): its setup script (type=\"stx/island\") hasn't run\n // yet, so the scope isn't registered. Arm the hydration trigger anyway \u2014\n // processElement sees stx-hydrate and defers; deferHydration's run()\n // executes the script (registering the scope + running side-effectful\n // setup like fetches) and binds on the trigger. Reveal the HTML now.\n var isDeferredIsland = !scopeVars && el.hasAttribute && el.hasAttribute('stx-hydrate')\n && !!document.querySelector('script[data-stx-island=\"' + scopeId + '\"]');\n if (isDeferredIsland) {\n processElement(el);\n el.removeAttribute('x-cloak');\n el.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n return;\n }\n\n if (!scopeVars) return;\n\n // Forwarded props and events belong to the caller. Capture its scope\n // before this component's locals are merged, so identical child names\n // cannot shadow expressions such as :total-items=\"totalItems\".\n el.__stx_parent_scope = el.__stx_parent_scope\n || resolveComponentCallerScope(el, pageScopeSnapshot);\n bindParentComponentProps(el, el.__stx_parent_scope);\n\n // Merge component scope vars into componentScope (don't restore - keep for head elements)\n // This ensures expressions can access component variables even for elements\n // where findElementScope might not work (e.g., cloned elements not yet in DOM)\n if (scopeVars) {\n componentScope = { ...componentScope, ...scopeVars };\n }\n\n console.log('[stx] calling processElement on scope:', scopeId, 'componentScope keys:', Object.keys(componentScope).length, 'scopeVars keys:', Object.keys(scopeVars).length);\n var disposeEffects = trackEffects(function() { processElement(el); });\n el.__stx_disposers = disposeEffects;\n console.log('[stx] scope processed OK:', scopeId);\n\n // Remove x-cloak after bindings are applied\n el.removeAttribute('x-cloak');\n el.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n\n // Run scope-specific mount callbacks (mark mounted so _handleStxLoad\n // doesn't re-fire onMount on persistent layout scopes \u2014 see #1697).\n // EXCEPT when this scope's hydration is deferred (stx-hydrate, e.g. a\n // client=visible|idle island, #1746): processElement above only SCHEDULED\n // the work, so onMount must fire when the trigger actually hydrates the\n // scope, not now. deferHydration's run() flushes it then.\n var scopeDeferred = el.hasAttribute && el.hasAttribute('stx-hydrate') && !el.__stx_hydrated;\n // A component behind a false :if is in the document's MARKUP but not in\n // the document: bindIf detached the subtree before this walk reached it,\n // while the component's own setup script already ran and queued its\n // onMount. Mounting it from here anyway is what made being mounted\n // unusable as an open state (stacksjs/stx#2036) -- three gated modal\n // shells each locked body scroll and registered an Escape handler before\n // anything had been opened, so the page could not be scrolled and Escape\n // reached whichever instance registered last.\n //\n // Left unmounted rather than mounted-and-torn-down, so hydrateComponentScopes\n // flushes it when bindIf shows the subtree -- the same deferral\n // stx-hydrate uses above, and the same flush an island gets.\n var scopeDetached = el.isConnected === false;\n if (scopeVars && scopeVars.__mountCallbacks && !scopeVars.__mounted && !scopeDeferred && !scopeDetached) {\n scopeVars.__mounted = true;\n runMountCallbacks(scopeVars.__mountCallbacks, scopeDestroySink(scopeVars));\n }\n });\n\n // Run global mount callbacks (from partial <script client> blocks that call onMount)\n // These are pushed during script execution, before DOMContentLoaded\n console.log('[stx] running global mountCallbacks:', mountCallbacks.length);\n runMountCallbacks(mountCallbacks, destroyCallbacks);\n mountCallbacks.length = 0;\n\n // Auto-process elements with data-stx-auto (skip already processed scoped elements)\n document.querySelectorAll('[data-stx-auto]').forEach(el => {\n // Process element but skip children that are in scoped containers\n processElementSkipScopes(el, processedScopes);\n\n // Remove x-cloak after bindings are applied\n el.removeAttribute('x-cloak');\n el.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n });\n\n // Process head> elements (title, meta) that may contain {{ }} expressions\n // Use componentScope which now contains variables from processed components\n const headElements = document.querySelectorAll('head title, head meta[content]');\n headElements.forEach(el => {\n if (el.tagName === 'TITLE') {\n const text = el.textContent;\n if (text && text.includes('{{')) {\n effect(() => {\n try {\n let result = text;\n const matches = text.match(/\\{\\{\\s*(.+?)\\s*\\}\\}/g);\n if (matches) {\n matches.forEach(match => {\n const expr = match.replace(/^\\{\\{\\s*|\\s*\\}\\}$/g, '');\n const fn = __stxCompileScoped(componentScope, [], 'return ' + expr);\n const value = fn(...__stxArgs(fn, componentScope));\n result = result.replace(match, value != null ? value : '');\n });\n }\n el.textContent = result;\n }\ncatch (e) {\n if (!(e instanceof ReferenceError) && !(e instanceof TypeError)) console.warn('[STX] Title expression error:', e);\n }\n });\n }\n }\nelse if (el.tagName === 'META') {\n const content = el.getAttribute('content');\n if (content && content.includes('{{')) {\n // Skip build-time placeholders like {{__TITLE__}}\n const hasOnlyPlaceholders = !content.replace(/\\{\\{\\s*__[A-Z_]+__\\s*\\}\\}/g, '').includes('{{');\n if (hasOnlyPlaceholders) return;\n effect(() => {\n try {\n let result = content;\n const matches = content.match(/\\{\\{\\s*(.+?)\\s*\\}\\}/g);\n if (matches) {\n matches.forEach(match => {\n const expr = match.replace(/^\\{\\{\\s*|\\s*\\}\\}$/g, '');\n if (/^__[A-Z_]+__$/.test(expr.trim())) return;\n const fn = __stxCompileScoped(componentScope, [], 'return ' + expr);\n const value = fn(...__stxArgs(fn, componentScope));\n result = result.replace(match, value != null ? value : '');\n });\n }\n el.setAttribute('content', result);\n }\ncatch (e) {\n if (!(e instanceof ReferenceError) && !(e instanceof TypeError)) console.warn('[STX] Meta expression error:', e);\n }\n });\n }\n }\n });\n\n // Everything that should have hydrated has now had its chance (#1773).\n auditHydration(document.body, 'DOMContentLoaded');\n };\n window.__stxDomReadyHandler = stxDomReadyHandler;\n console.log('[stx] registering DOMContentLoaded handler');\n document.addEventListener('DOMContentLoaded', stxDomReadyHandler);\n";
|
|
2
|
+
export declare const SIGNALS_DOM_READY_RUNTIME = " // ==========================================================================\n // Auto-initialization\n // ==========================================================================\n\n // A dev runtime may be evaluated again by HMR, an embed, or a test harness.\n // Replace the previous listener so only the latest runtime closure can own\n // componentScope and reactive subscriptions.\n if (window.__stxDomReadyHandler) {\n document.removeEventListener('DOMContentLoaded', window.__stxDomReadyHandler);\n }\n const stxDomReadyHandler = () => {\n console.log('[stx] DOMContentLoaded fired \u2014 processing scopes');\n // Track which scoped elements have been processed\n const processedScopes = new Set();\n\n // Layout expansion can remove the data-stx marker from a page's first\n // element while leaving markers owned by the layout itself. The generated\n // page setup is still queued explicitly, so adopt it when its own marker\n // did not survive.\n const latestSetup = window.stx._latestSetup;\n const latestSetupName = typeof latestSetup === 'function' ? latestSetup.name : '';\n const hasLatestSetupMarker = latestSetupName && Array.from(document.querySelectorAll('[data-stx]'))\n .some(el => el.getAttribute('data-stx') === latestSetupName);\n if (latestSetup && !hasLatestSetupMarker) {\n try {\n const result = latestSetup();\n if (typeof result === 'object' && result !== null)\n Object.assign(componentScope, result);\n }\n catch (e) {\n console.error('[stx] initial setup error:', e);\n }\n }\n\n // Register page setup before mounting child components. Projected slot\n // content belongs to the caller, so child mounts need the caller's signals\n // available when they walk their own rendered roots.\n document.querySelectorAll('[data-stx]').forEach(el => {\n const setupName = el.getAttribute('data-stx');\n console.log('[DOMContentLoaded] data-stx:', setupName, 'el:', el.tagName, 'fn exists:', !!(setupName && window[setupName]));\n if (setupName && window[setupName]) {\n // Contained, like the two sibling setup call sites. An uncaught throw\n // here aborted the whole forEach and everything after it in this\n // handler, so ONE bad name in ONE page's setup left every root on the\n // page unhydrated \u2014 the user sees raw {{ }}, and the console names the\n // identifier without saying it cost them the document (#1805).\n try {\n const result = window[setupName]();\n console.log('[DOMContentLoaded] setup returned:', result ? Object.keys(result).slice(0, 10) : 'null');\n if (typeof result === 'object' && result !== null) {\n Object.assign(componentScope, result);\n }\n }\n catch (e) {\n console.error('[stx] page setup \"' + setupName + '\" threw; this root will not hydrate:', e);\n }\n }\n });\n var pageScopeSnapshot = { ...componentScope };\n\n /*\n * Any x-data scope the reactive bridge did not reach, initialized here.\n *\n * The bridge script addresses each scope by a selector it generated, and\n * that numbering restarts per render - so a page carrying three component\n * islands emits three scripts all looking for the same scope id, and two of\n * the three scopes are never initialized at all. The symptom is the\n * quietest one available: the markup is there, every binding shows its\n * initial value, and whatever x-init was meant to start never starts.\n *\n * Registered scopes are skipped, so the bridge stays authoritative where it\n * did run and this only picks up what it missed. The init expression is\n * read from data-stx-xinit, which the server preserves for exactly this.\n *\n * No backticks in this comment, deliberately: it lives inside the runtime\n * source that is embedded as a template literal, and one would end the\n * literal and take the whole file's syntax with it.\n */\n if (window.__stx_reactive && window.__stx_reactive.initScope) {\n document.querySelectorAll('[data-stx-xdata]').forEach(function(el) {\n var scopeId = el.getAttribute('data-stx-scope');\n if (scopeId && window.stx._scopes && window.stx._scopes[scopeId]) return;\n if (el.__stx_scope_initialized) return;\n\n var xdata = el.getAttribute('data-stx-xdata');\n if (!xdata) return;\n\n if (!scopeId) {\n scopeId = '__stx_scope_island_' + (++window.stx._scopeCounter);\n el.setAttribute('data-stx-scope', scopeId);\n }\n\n el.__stx_scope_initialized = true;\n\n try {\n window.__stx_reactive.initScope(el, xdata, [], {}, el.getAttribute('data-stx-xinit') || null);\n }\n catch (e) {\n console.error('[stx] island scope init error:', e);\n }\n });\n }\n\n // Process mount queue (from stx.mount() calls during loading) only after\n // caller setup is available for Vue-style projected slot ownership.\n mountQueue.forEach(function(fn) { fn(); });\n mountQueue = [];\n\n // A queued layout mount owns a separate $refs map and merges it into the\n // compatibility scope. Page useRef accessors already captured the page's\n // map during setup; bind its DOM back into that same map before onMount.\n // Keep the layout's other exposed names available for legacy bindings.\n componentScope.$refs = pageScopeSnapshot.$refs;\n\n // Bind page roots after child components have registered their local scope.\n document.querySelectorAll('[data-stx]').forEach(el => {\n console.log('[DOMContentLoaded] processElement on:', el.tagName, 'scope keys:', Object.keys(componentScope).slice(0, 10));\n var disposeEffects = trackEffects(function() {\n // The server's list when the page shipped one, the walk otherwise.\n if (!processFromManifest(el, componentScope, window.__stx_bindings)) processElement(el);\n });\n el.__stx_disposers = disposeEffects;\n\n // Remove x-cloak after bindings are applied (prevents FOUC)\n el.removeAttribute('x-cloak');\n el.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n\n runMountCallbacks(mountCallbacks, destroyCallbacks);\n });\n\n // Multi-root fragment fix: a no-body> setup page tags only the FIRST\n // top-level element with data-stx (signal-processing.ts marks one element),\n // so sibling root elements were orphaned \u2014 their :if / :for / {{ }} / x-text\n // never hydrated, which read as \"{{ }} doesn't work under :if/:for\". The\n // setup(s) above already populated the shared global componentScope, so\n // process each un-hydrated sibling root under that same scope \u2014 same signals,\n // so cross-root state stays coupled.\n var stxRoots = document.querySelectorAll('[data-stx]');\n if (stxRoots.length && Object.keys(componentScope).length) {\n var rootParent = stxRoots[0].parentNode;\n if (rootParent && rootParent.children) {\n Array.prototype.slice.call(rootParent.children).forEach(function(sib) {\n if (sib.nodeType !== 1) return;\n if (sib.hasAttribute('data-stx') || sib.hasAttribute('data-stx-scope')) return;\n if (sib.tagName === 'SCRIPT' || sib.tagName === 'STYLE') return;\n if (sib.__stx_disposers) return; // already processed\n var disposeSib = trackEffects(function() { processElement(sib); });\n sib.__stx_disposers = disposeSib;\n sib.removeAttribute('x-cloak');\n sib.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n });\n }\n }\n\n // Process scoped components FIRST (their scripts have already registered scope variables)\n var allScopes = document.querySelectorAll('[data-stx-scope]');\n console.log('[stx] found', allScopes.length, 'data-stx-scope elements');\n allScopes.forEach(el => {\n const scopeId = el.getAttribute('data-stx-scope');\n console.log('[stx] scope:', scopeId, 'registered:', !!(window.stx._scopes && window.stx._scopes[scopeId]), 'el:', el.tagName);\n processedScopes.add(el);\n\n const scopeVars = window.stx._scopes && window.stx._scopes[scopeId];\n // Record the element this scope is bound to so cleanupContainer can tell a\n // dead registry entry (element replaced by an SPA swap) from a live one.\n // See sweepOrphanedScopes / #1775.\n if (scopeVars) scopeVars.__el = el;\n\n // Deferred island (#1746): its setup script (type=\"stx/island\") hasn't run\n // yet, so the scope isn't registered. Arm the hydration trigger anyway \u2014\n // processElement sees stx-hydrate and defers; deferHydration's run()\n // executes the script (registering the scope + running side-effectful\n // setup like fetches) and binds on the trigger. Reveal the HTML now.\n var isDeferredIsland = !scopeVars && el.hasAttribute && el.hasAttribute('stx-hydrate')\n && !!document.querySelector('script[data-stx-island=\"' + scopeId + '\"]');\n if (isDeferredIsland) {\n processElement(el);\n el.removeAttribute('x-cloak');\n el.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n return;\n }\n\n if (!scopeVars) return;\n\n // Forwarded props and events belong to the caller. Capture its scope\n // before this component's locals are merged, so identical child names\n // cannot shadow expressions such as :total-items=\"totalItems\".\n el.__stx_parent_scope = el.__stx_parent_scope\n || resolveComponentCallerScope(el, pageScopeSnapshot);\n bindParentComponentProps(el, el.__stx_parent_scope);\n\n // Merge component scope vars into componentScope (don't restore - keep for head elements)\n // This ensures expressions can access component variables even for elements\n // where findElementScope might not work (e.g., cloned elements not yet in DOM)\n if (scopeVars) {\n componentScope = { ...componentScope, ...scopeVars };\n }\n\n console.log('[stx] calling processElement on scope:', scopeId, 'componentScope keys:', Object.keys(componentScope).length, 'scopeVars keys:', Object.keys(scopeVars).length);\n var disposeEffects = trackEffects(function() { processElement(el); });\n el.__stx_disposers = disposeEffects;\n console.log('[stx] scope processed OK:', scopeId);\n\n // Remove x-cloak after bindings are applied\n el.removeAttribute('x-cloak');\n el.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n\n // Run scope-specific mount callbacks (mark mounted so _handleStxLoad\n // doesn't re-fire onMount on persistent layout scopes \u2014 see #1697).\n // EXCEPT when this scope's hydration is deferred (stx-hydrate, e.g. a\n // client=visible|idle island, #1746): processElement above only SCHEDULED\n // the work, so onMount must fire when the trigger actually hydrates the\n // scope, not now. deferHydration's run() flushes it then.\n var scopeDeferred = el.hasAttribute && el.hasAttribute('stx-hydrate') && !el.__stx_hydrated;\n // A component behind a false :if is in the document's MARKUP but not in\n // the document: bindIf detached the subtree before this walk reached it,\n // while the component's own setup script already ran and queued its\n // onMount. Mounting it from here anyway is what made being mounted\n // unusable as an open state (stacksjs/stx#2036) -- three gated modal\n // shells each locked body scroll and registered an Escape handler before\n // anything had been opened, so the page could not be scrolled and Escape\n // reached whichever instance registered last.\n //\n // Left unmounted rather than mounted-and-torn-down, so hydrateComponentScopes\n // flushes it when bindIf shows the subtree -- the same deferral\n // stx-hydrate uses above, and the same flush an island gets.\n var scopeDetached = el.isConnected === false;\n if (scopeVars && scopeVars.__mountCallbacks && !scopeVars.__mounted && !scopeDeferred && !scopeDetached) {\n scopeVars.__mounted = true;\n runMountCallbacks(scopeVars.__mountCallbacks, scopeDestroySink(scopeVars));\n }\n });\n\n // Run global mount callbacks (from partial <script client> blocks that call onMount)\n // These are pushed during script execution, before DOMContentLoaded\n console.log('[stx] running global mountCallbacks:', mountCallbacks.length);\n runMountCallbacks(mountCallbacks, destroyCallbacks);\n mountCallbacks.length = 0;\n\n // Auto-process elements with data-stx-auto (skip already processed scoped elements)\n document.querySelectorAll('[data-stx-auto]').forEach(el => {\n // Process element but skip children that are in scoped containers\n processElementSkipScopes(el, processedScopes);\n\n // Remove x-cloak after bindings are applied\n el.removeAttribute('x-cloak');\n el.querySelectorAll('[x-cloak]').forEach(function(c) { c.removeAttribute('x-cloak'); });\n });\n\n // Process head> elements (title, meta) that may contain {{ }} expressions\n // Use componentScope which now contains variables from processed components\n const headElements = document.querySelectorAll('head title, head meta[content]');\n headElements.forEach(el => {\n if (el.tagName === 'TITLE') {\n const text = el.textContent;\n if (text && text.includes('{{')) {\n effect(() => {\n try {\n let result = text;\n const matches = text.match(/\\{\\{\\s*(.+?)\\s*\\}\\}/g);\n if (matches) {\n matches.forEach(match => {\n const expr = match.replace(/^\\{\\{\\s*|\\s*\\}\\}$/g, '');\n const fn = __stxCompileScoped(componentScope, [], 'return ' + expr);\n const value = fn(...__stxArgs(fn, componentScope));\n result = result.replace(match, value != null ? value : '');\n });\n }\n el.textContent = result;\n }\ncatch (e) {\n if (!(e instanceof ReferenceError) && !(e instanceof TypeError)) console.warn('[STX] Title expression error:', e);\n }\n });\n }\n }\nelse if (el.tagName === 'META') {\n const content = el.getAttribute('content');\n if (content && content.includes('{{')) {\n // Skip build-time placeholders like {{__TITLE__}}\n const hasOnlyPlaceholders = !content.replace(/\\{\\{\\s*__[A-Z_]+__\\s*\\}\\}/g, '').includes('{{');\n if (hasOnlyPlaceholders) return;\n effect(() => {\n try {\n let result = content;\n const matches = content.match(/\\{\\{\\s*(.+?)\\s*\\}\\}/g);\n if (matches) {\n matches.forEach(match => {\n const expr = match.replace(/^\\{\\{\\s*|\\s*\\}\\}$/g, '');\n if (/^__[A-Z_]+__$/.test(expr.trim())) return;\n const fn = __stxCompileScoped(componentScope, [], 'return ' + expr);\n const value = fn(...__stxArgs(fn, componentScope));\n result = result.replace(match, value != null ? value : '');\n });\n }\n el.setAttribute('content', result);\n }\ncatch (e) {\n if (!(e instanceof ReferenceError) && !(e instanceof TypeError)) console.warn('[STX] Meta expression error:', e);\n }\n });\n }\n }\n });\n\n // Everything that should have hydrated has now had its chance (#1773).\n auditHydration(document.body, 'DOMContentLoaded');\n };\n window.__stxDomReadyHandler = stxDomReadyHandler;\n console.log('[stx] registering DOMContentLoaded handler');\n document.addEventListener('DOMContentLoaded', stxDomReadyHandler);\n";
|
|
@@ -106,6 +106,12 @@ export const SIGNALS_DOM_READY_RUNTIME = ` // =================================
|
|
|
106
106
|
mountQueue.forEach(function(fn) { fn(); });
|
|
107
107
|
mountQueue = [];
|
|
108
108
|
|
|
109
|
+
// A queued layout mount owns a separate $refs map and merges it into the
|
|
110
|
+
// compatibility scope. Page useRef accessors already captured the page's
|
|
111
|
+
// map during setup; bind its DOM back into that same map before onMount.
|
|
112
|
+
// Keep the layout's other exposed names available for legacy bindings.
|
|
113
|
+
componentScope.$refs = pageScopeSnapshot.$refs;
|
|
114
|
+
|
|
109
115
|
// Bind page roots after child components have registered their local scope.
|
|
110
116
|
document.querySelectorAll('[data-stx]').forEach(el => {
|
|
111
117
|
console.log('[DOMContentLoaded] processElement on:', el.tagName, 'scope keys:', Object.keys(componentScope).slice(0, 10));
|
|
@@ -6,22 +6,7 @@
|
|
|
6
6
|
* (kebab-case and PascalCase).
|
|
7
7
|
*/
|
|
8
8
|
import type { StxOptions } from './types';
|
|
9
|
-
|
|
10
|
-
* Convert PascalCase to kebab-case with proper handling of consecutive uppercase letters.
|
|
11
|
-
*
|
|
12
|
-
* Examples:
|
|
13
|
-
* - `UserCard` → `user-card`
|
|
14
|
-
* - `XMLParser` → `xml-parser` (not `x-m-l-parser`)
|
|
15
|
-
* - `HTMLElement` → `html-element`
|
|
16
|
-
* - `MyURLParser` → `my-url-parser`
|
|
17
|
-
* - `IOStream` → `io-stream`
|
|
18
|
-
*
|
|
19
|
-
* The algorithm:
|
|
20
|
-
* 1. Insert hyphen before uppercase letters that follow lowercase letters
|
|
21
|
-
* 2. Insert hyphen before the last uppercase in a sequence of uppercase letters (before lowercase)
|
|
22
|
-
* 3. Convert to lowercase
|
|
23
|
-
*/
|
|
24
|
-
export declare function pascalToKebab(str: string): string;
|
|
9
|
+
export { pascalToKebab } from './component-resolution';
|
|
25
10
|
import { restoreStashedScripts, stashScriptElements } from './html-masking';
|
|
26
11
|
export { restoreStashedScripts, stashScriptElements };
|
|
27
12
|
/**
|
|
@@ -1,9 +1,8 @@
|
|
|
1
1
|
import path from "node:path";
|
|
2
2
|
import { createSafeFunction, isExpressionSafe, safeEvaluateObject } from "./safe-evaluator.js";
|
|
3
3
|
import { renderComponentWithSlot, userComponentFileExists } from "./utils.js";
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
}
|
|
4
|
+
import { pascalToKebab } from "./component-resolution.js";
|
|
5
|
+
export { pascalToKebab } from "./component-resolution.js";
|
|
7
6
|
import { restoreStashedScripts, stashScriptElements } from "./html-masking.js";
|
|
8
7
|
|
|
9
8
|
export { restoreStashedScripts, stashScriptElements };
|
|
@@ -689,7 +688,7 @@ export async function processCustomElements(template, context, filePath, compone
|
|
|
689
688
|
} else
|
|
690
689
|
props[attrName] = decodeAttributeEntities(attrValue);
|
|
691
690
|
}
|
|
692
|
-
const processedContent = await renderComponentWithSlot(componentPath, props, tag.content, componentsDir, context, filePath, options, processedComponents, dependencies);
|
|
691
|
+
const processedContent = await renderComponentWithSlot(componentPath, props, tag.content, componentsDir, context, filePath, options, processedComponents, dependencies, void 0, void 0, tag.tagName);
|
|
693
692
|
result = result.substring(0, tag.startIndex) + processedContent + result.substring(tag.endIndex);
|
|
694
693
|
}
|
|
695
694
|
return result;
|
|
@@ -78,12 +78,7 @@ export interface BuiltinComponentDef {
|
|
|
78
78
|
* @example kebabToPascal("stx-link") // "StxLink"
|
|
79
79
|
*/
|
|
80
80
|
export declare function kebabToPascal(str: string): string;
|
|
81
|
-
|
|
82
|
-
* Convert a PascalCase string to kebab-case.
|
|
83
|
-
*
|
|
84
|
-
* @example pascalToKebab("StxLink") // "stx-link"
|
|
85
|
-
*/
|
|
86
|
-
export declare function pascalToKebab(str: string): string;
|
|
81
|
+
export { pascalToKebab } from './component-resolution';
|
|
87
82
|
/**
|
|
88
83
|
* Central registry for STX components.
|
|
89
84
|
*
|
|
@@ -3,9 +3,7 @@ import { fileExists } from "./utils.js";
|
|
|
3
3
|
export function kebabToPascal(str) {
|
|
4
4
|
return str.split("-").map((part) => part.charAt(0).toUpperCase() + part.slice(1)).join("");
|
|
5
5
|
}
|
|
6
|
-
export
|
|
7
|
-
return str.replace(/([a-z0-9])([A-Z])/g, "$1-$2").toLowerCase();
|
|
8
|
-
}
|
|
6
|
+
export { pascalToKebab } from "./component-resolution.js";
|
|
9
7
|
|
|
10
8
|
export class ComponentRegistry {
|
|
11
9
|
builtins = new Map;
|