@stacksjs/stx 0.2.528 → 0.2.529
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-t3mg529n.js → chunk-16k8mkwm.js} +1 -1
- package/dist/{chunk-44e5tk5g.js → chunk-1c7v7pqv.js} +1 -1
- package/dist/chunk-1n8d0htz.js +2 -0
- package/dist/{chunk-gkzvxt62.js → chunk-1q4yn31s.js} +1 -1
- package/dist/{chunk-vfc4fg8v.js → chunk-1wp8qb5f.js} +1 -1
- package/dist/{chunk-e0p7p7p2.js → chunk-2p0dbz34.js} +1 -1
- package/dist/chunk-4dm3fj16.js +2 -0
- package/dist/{chunk-mh7k2ps4.js → chunk-4mmz9xxh.js} +18 -18
- package/dist/{chunk-dx23ntmm.js → chunk-5ew3rq40.js} +1 -1
- package/dist/{chunk-cen7wkv8.js → chunk-5zk6kyjt.js} +1 -1
- package/dist/{chunk-he404gbh.js → chunk-6rdnzn77.js} +1 -1
- package/dist/{chunk-zw2xxaza.js → chunk-7c1ntx2e.js} +1 -1
- package/dist/{chunk-j19b6d9m.js → chunk-7mg0cybn.js} +1 -1
- package/dist/{chunk-xg08g7xd.js → chunk-7rz4fy4y.js} +2 -2
- package/dist/{chunk-gmx73f50.js → chunk-84p3bcpx.js} +1 -1
- package/dist/{chunk-fdbtr4my.js → chunk-8a4mndgc.js} +1 -1
- package/dist/chunk-8dbnvypv.js +2 -0
- package/dist/{chunk-syde729h.js → chunk-9x9bp5w8.js} +1 -1
- package/dist/{chunk-n48v0cma.js → chunk-baxwjmj3.js} +1 -1
- package/dist/{chunk-8rxammgf.js → chunk-bs2e3g25.js} +2 -2
- package/dist/{chunk-r0n937ex.js → chunk-dzt3bvvn.js} +1 -1
- package/dist/{chunk-bqah6yhk.js → chunk-e9f55nee.js} +1 -1
- package/dist/{chunk-wg7jz0ta.js → chunk-eadr1eph.js} +1 -1
- package/dist/{chunk-jya4r00e.js → chunk-f3y397xy.js} +1 -1
- package/dist/{chunk-6ywr110f.js → chunk-fdcrrpgn.js} +1 -1
- package/dist/{chunk-nc1wcdfs.js → chunk-hnn0pdz1.js} +1 -1
- package/dist/{chunk-0gzm7em2.js → chunk-j00h4d3w.js} +1 -1
- package/dist/{chunk-4bfdyf1s.js → chunk-jagpqt9y.js} +1 -1
- package/dist/{chunk-byr1derh.js → chunk-jh6nh2m0.js} +1 -1
- package/dist/{chunk-wv9es0ra.js → chunk-jwgzj5at.js} +1 -1
- package/dist/{chunk-1r5zd4a9.js → chunk-k3tq1k4m.js} +1 -1
- package/dist/{chunk-2kjxd3v1.js → chunk-m2wzrk3d.js} +1 -1
- package/dist/{chunk-jnpyzq5m.js → chunk-n26xx6x5.js} +1 -1
- package/dist/{chunk-kg4navnh.js → chunk-n6rzr34r.js} +1 -1
- package/dist/{chunk-h80p2gkn.js → chunk-pqwx5hw8.js} +1 -1
- package/dist/{chunk-fhsy7dc5.js → chunk-qap3fwv8.js} +1 -1
- package/dist/{chunk-etdx3fye.js → chunk-raqbqt1r.js} +41 -9
- package/dist/{chunk-mftzhj7x.js → chunk-s1evrkrv.js} +1 -1
- package/dist/{chunk-52mjjszq.js → chunk-smn7sssc.js} +1 -1
- package/dist/{chunk-93cf01s9.js → chunk-tn7nvmah.js} +1 -1
- package/dist/{chunk-7e7mcrf9.js → chunk-vbv5jqkz.js} +1 -1
- package/dist/{chunk-kpbpmmdk.js → chunk-wpm4emgb.js} +1 -1
- package/dist/{chunk-j7615qvy.js → chunk-wsjrvxs9.js} +1 -1
- package/dist/{chunk-xw45r9b5.js → chunk-ww68p1kb.js} +1 -1
- package/dist/{chunk-rypj5y6d.js → chunk-xgmqes1s.js} +1 -1
- package/dist/{chunk-4625sykb.js → chunk-ycxz2exz.js} +1 -1
- package/dist/{chunk-w9srfsfk.js → chunk-yy19rrw6.js} +1 -1
- package/dist/{chunk-qtvth7eg.js → chunk-yyb5se8j.js} +2 -2
- package/dist/{chunk-zfct5zbe.js → chunk-zc8cz12e.js} +1 -1
- package/dist/{chunk-my4s7k0x.js → chunk-ze832cpr.js} +5 -5
- package/dist/cli.js +8 -8
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/pwa.js +1 -1
- package/dist/signals.js +39 -7
- package/dist/ssg.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-0d9rx3n4.js +0 -2
- package/dist/chunk-70cr8xzz.js +0 -2
- package/dist/chunk-gbb8dze1.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{en,ae}from"./chunk-2hc5mbw8.js";import{m,tn,w,Ne,o,A}from"./chunk-
|
|
2
|
+
import{en,ae}from"./chunk-2hc5mbw8.js";import{m,tn,w,Ne,o,A}from"./chunk-4mmz9xxh.js";import{Xr}from"./chunk-6rdnzn77.js";import{s,we}from"./chunk-zw029e7n.js";import{a}from"./chunk-2y82wf9d.js";import h from"path";import v from"fs";var pe=10;function V(e,n,i){return/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/.test(h.basename(e))||Xr(e,n,i)}var ne=1,re=new Map,W=600,fe=100,P=new Map;async function me(e){let n=P.get(e)??0;if(n>0&&n<fe){P.set(e,n+1);return}P.set(e,1);try{let i=(await v.promises.readdir(e)).filter((u)=>u.endsWith(".js"));if(i.length<=W)return;let g=(await Promise.all(i.map(async(u)=>{try{return{name:u,at:(await v.promises.stat(h.join(e,u))).mtimeMs}}catch{return null}}))).filter((u)=>u!==null);g.sort((u,l)=>l.at-u.at);for(let u of g.slice(W)){let l=u.name.slice(0,-3);await v.promises.rm(h.join(e,`${l}.js`),{force:!0}),await v.promises.rm(h.join(e,`${l}.deps.json`),{force:!0})}I("pruned bundle cache to",W,"entries")}catch{}}function ie(e){return re.get(e)??[]}function X(e,n){if(e)re.set(e,n)}function Ka(e=process.env){return e.STX_DEBUG==="true"||e.STX_DEBUG==="1"}function I(...e){if(Ka())console.log("[stx:bundler]",...e)}var Z=[];function Fo(e,n,i){Z.push({filePath:e||"<inline>",message:n,details:i})}function mt(){return Z.slice()}function ht(){Z.length=0}var q;function Td(e){q=e}function zo(){if(q)return q;try{let e=A.strict;return typeof e==="object"&&e!==null?e.bundlerFallback??"warn":"warn"}catch{return"warn"}}var H=[/^stx$/,/^@stacksjs\/stx$/,/^@stores$/,/^stx\/stores$/,/^@composables$/];function yt(e){let n=/^[ \t]*import[ \t]+(?!type(?:[ \t]|{))[\s\S]*?\s+from\s+['"]([^'"]+)['"][ \t]*;?/gm,i;while((i=n.exec(e))!==null){let g=i[1];if(!H.some((l)=>l.test(g)))return I("detected user import:",g),!0}let c=/^[ \t]*import[ \t]*['"]([^'"]+)['"]/gm;while((i=c.exec(e))!==null){let g=i[1];if(/\.css(?:\?.*)?$/.test(g))continue;if(!H.some((l)=>l.test(g)))return I("detected side-effect import:",g),!0}return!1}var Qt="stx-module:",ge=/\.(?:[cm]?[jt]sx?|json)$/i;function Xa(e,n){return h.relative(e,n).split(h.sep).join("/")}function Ga(e,n){if(n.size===0)return e;return e.replace(/^([ \t]*import(?:(?:\s+|(?=[{*]))[^;"']*?\s*from\s*|\s*))(["'])([^"']+)\2/gm,(i,c,g,u)=>{let l=n.get(u);return l&&!u.startsWith(Qt)?`${c}${g}${l}${g}`:i})}function Ja(e,n){let i=0,c=(u)=>{let l=`__stxMod${i++}`,S=JSON.stringify(u);return n.push(`var ${l} = globalThis.__stxModules && globalThis.__stxModules[${S}];`,`if (${l} === undefined) throw new Error("[stx] module " + ${JSON.stringify(S)} + " is not registered on this page (#1957)");`),l},g=(u,l)=>{for(let S of u.split(",")){let M=S.trim();if(!M)continue;let f=M.match(/^("(?:[^"\\]|\\.)*"|[\w$]+)(?:\s+as\s+([\w$]+))?$/);if(!f)continue;let t=f[1].startsWith('"')?JSON.parse(f[1]):f[1],r=f[2]??t;n.push(`var ${r} = ${l}[${JSON.stringify(t)}];`)}};return e=e.replace(/^[ \t]*import(?:\s+|(?=[{*]))([^;"']+?)\s*from\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(u,l,S)=>{let M=S.slice(Qt.length),f=c(M),t=l.trim(),r=t.match(/^([\w$]+)\s*(?:,\s*|$)/);if(r&&!t.startsWith("{")&&!t.startsWith("*"))n.push(`var ${r[1]} = ${f}.default;`),t=t.slice(r[0].length).trim();let d=t.match(/^\*\s*as\s+([\w$]+)$/);if(d)n.push(`var ${d[1]} = ${f};`);else if(t.startsWith("{"))g(t.replace(/^\{|\}$/g,""),f);return""}),e=e.replace(/^[ \t]*import\s*["'](stx-module:[^"']+)["'];?[ \t]*$/gm,(u,l)=>(c(l.slice(Qt.length)),"")),e}function ee(e){let n=[e,`${e}.ts`,`${e}.tsx`,`${e}.js`,`${e}.mjs`,`${e}.jsx`,h.join(e,"index.ts"),h.join(e,"index.tsx"),h.join(e,"index.js"),h.join(e,"index.mjs")];for(let i of n)try{if(v.existsSync(i)&&v.statSync(i,{throwIfNoEntry:!1})?.isFile())return i}catch{}return}function he(e,n,i,c,g,u=new Map,l){let S=(f,t,r)=>{if(V(t,e,l))return null;if(!g||f!==i||!ge.test(t))return null;try{if(!v.statSync(t,{throwIfNoEntry:!1})?.isFile())return null}catch{return null}c.add(t);let d=`${Qt}${Xa(process.cwd(),t)}`;return u.set(r,d),{path:d,external:!0}},M=(f,t)=>{let r=f===i?n:h.dirname(f),d=h.resolve(r,t);return ee(d)??d};return{name:"stx-client-bundle",setup(f){if(f.onResolve({filter:/^(stx|@stacksjs\/stx)$/},(t)=>({path:t.path,external:!0})),f.onResolve({filter:/^(@stores|@composables|stx\/stores)$/},(t)=>({path:t.path,external:!0})),f.onResolve({filter:/^\//},(t)=>{let r=ee(t.path);if(r){let d=S(t.importer,r,t.path);if(d)return d;if(r!==i)c.add(r);return{path:r}}return{path:t.path,external:!0}}),f.onResolve({filter:/^\.\.?\//},(t)=>{let r=M(t.importer,t.path),d=S(t.importer,r,t.path);if(d)return d;return c.add(r),{path:r}}),f.onResolve({filter:/^[@~]\//},(t)=>{let r=h.resolve(e,t.path.slice(2)),d=[r,`${r}.ts`,`${r}.tsx`,`${r}.js`,`${r}.mjs`,`${r}.jsx`,h.join(r,"index.ts"),h.join(r,"index.tsx"),h.join(r,"index.js"),h.join(r,"index.mjs")];for(let E of d)if(v.existsSync(E)&&v.statSync(E,{throwIfNoEntry:!1})?.isFile()){let C=S(t.importer,E,t.path);if(C)return C;return I(`resolved ${t.path[0]}/ import:`,t.path,"\u2192",E),c.add(E),{path:E}}return console.warn(`[stx:bundler] could not resolve ${t.path[0]}/ import:`,t.path),{path:r}}),g)f.onResolve({filter:/^(?!node:|bun:)(?:@[\w.-]+\/)?[\w.-]/},(t)=>{if(t.importer!==i)return;let r=`${Qt}npm:${t.path}`;return u.set(t.path,r),{path:r,external:!0}});f.onLoad({filter:/\.(?:[cm]?[jt]sx?|json)$/},(t)=>{if(V(t.path,e,l))throw Error(`Server-only API source cannot be imported by a client script: ${t.path}`);let r=h.extname(t.path).toLowerCase(),d=r===".json"?"json":r===".tsx"?"tsx":r===".jsx"?"jsx":r===".ts"||r===".mts"||r===".cts"?"ts":"js";if(t.path!==i)c.add(t.path);return{contents:v.readFileSync(t.path,"utf8"),loader:d}})}}}var G=new Map,L=m(64),te=Symbol.for("stx.client-bundle-build-queue");function Ya(e){let n=globalThis,c=(n[te]??Promise.resolve()).then(e,e);return n[te]=c.then(()=>{return},()=>{return}),c}async function bt(e,n,i={}){let c=i.projectRoot||process.cwd(),g=(await o(c)).serverApi,u=i.minify??!1,l=i.externalizeUserModules??!0,S=i.expose?.length?[...new Set(i.expose)].sort():void 0,M=i.cacheDir||a(c,"bundle-cache"),f=new Bun.CryptoHasher("md5");f.update(`${pe}\x00${Ne()}\x00${JSON.stringify(g??!1)}\x00${l?"registry":"inline"}\x00${S?S.join(","):"*"}\x00${e}\x00${n}`);let t=f.digest("hex").slice(0,12),r=h.join(M,`${t}.js`),d=L.get(r);if(d){if(tn(d.files)&&d.files.every((N)=>!V(N.path,c,g))){I("memo hit:",t);let N=d.files.map((B)=>B.path);return X(n,N),i.collectInputs?.push(...N),d.code}L.delete(r),I("memo invalidated by dep change:",t)}let E=h.join(M,`${t}.deps.json`),C=Bun.file(r);if(await C.exists()){let N=Bun.file(E),B=!1,R=null;if(await N.exists())try{let O=JSON.parse(await N.text());if(O.metadataVersion!==ne||!Array.isArray(O.files))B=!1;else R=O.files,B=!0;if(R&&(!tn(R)||R.some((D)=>V(D.path,c,g))))B=!1}catch{B=!1}if(B){if(I("cache hit:",t),R)X(n,R.map((D)=>D.path)),i.collectInputs?.push(...R.map((D)=>D.path));let O=await C.text();if(R)L.set(r,{code:O,files:R});return O}I("cache invalidated by dep change:",t)}let _=G.get(t);if(_){let N=await _;if(i.collectInputs)i.collectInputs.push(...(L.get(r)?.files??[]).map((B)=>B.path));return N}let z=Ya(()=>$e(e,n,{projectRoot:c,minify:u,cacheDir:M,hash:t,cachePath:r,depsPath:E,collectInputs:i.collectInputs,externalizeUserModules:l,serverApi:g,expose:S,throwOnFailure:i.throwOnFailure}));G.set(t,z);try{return await z}finally{G.delete(t)}}var xe=0;function Za(e){return`${e}-${process.pid}-${++xe}`}async function $e(e,n,i){let{projectRoot:c,minify:g,cacheDir:u,hash:l,cachePath:S,depsPath:M,externalizeUserModules:f}=i,t=a(c,"bundle-tmp"),r=Za(l),d=h.join(t,`${r}.ts`),E=h.join(t,"out",r);v.mkdirSync(t,{recursive:!0}),v.mkdirSync(E,{recursive:!0});let C=h.dirname(n),_=new Set,z=/^[ \t]*(export\s+)?(?:const|let|var)\s+(?:\{([^}]+)\}|(\w+))/gm,N=/^[ \t]*(export\s+)?(?:async\s+)?function\s+(\w+)/gm,B=s(e),{depths:R,balanced:O}=we(B),D=(j)=>!O||R[j]===0,y;while((y=z.exec(B))!==null){if(y[1])continue;if(!D(y.index))continue;if(y[2])y[2].split(",").forEach((j)=>{let p=ye(j);if(p)_.add(p)});else if(y[3])_.add(y[3])}while((y=N.exec(B))!==null){if(y[1])continue;if(!D(y.index))continue;_.add(y[2])}let se=/^[ \t]*import[ \t]+(?!type\b)(?:(\w+)\s*(?:,\s*)?)?(?:\*\s+as\s+(\w+)|\{([^}]+)\})?\s+from\b/gm;while((y=se.exec(B))!==null){if(!D(y.index))continue;let j=/^\s*['"]([^'"]+)['"]/.exec(e.slice(y.index+y[0].length))?.[1];if(j&&H.some((p)=>p.test(j)))continue;if(y[1])_.add(y[1]);if(y[2])_.add(y[2]);for(let p of(y[3]??"").split(",")){let b=p.trim();if(!b||/^type\s/.test(b))continue;let U=/\bas\s+(\w+)\s*$/.exec(b)?.[1]??/^\w+$/.exec(b)?.[0];if(U)_.add(U)}}for(let j of B.matchAll(/\bexport\s*\{([^}]+)\}/g))for(let p of j[1].split(",")){let b=/\bas\s+(\w+)\s*$/.exec(p)?.[1]??/^\s*(\w+)\s*$/.exec(p)?.[1];if(b)_.delete(b)}let oe=_.size>0?`
|
|
3
3
|
export { ${[..._].join(", ")} }`:"";await Bun.write(d,e+oe),I("bundling:",l,"from:",h.basename(n));let Y=new Set,Q=new Map;try{let j=await Bun.build({entrypoints:[d],outdir:E,target:"browser",format:"esm",minify:g?{whitespace:!1,identifiers:!0,syntax:!0}:!1,plugins:[he(c,C,d,Y,f,Q,i.serverApi)],define:{"process.env.NODE_ENV":g?'"production"':'"development"',...w()},root:c});if(!j.success){let F=j.logs.filter((T)=>T.level==="error").map((T)=>T.message).join(", ")||`Unable to bundle ${h.basename(n)}`,k=en(j.logs,n||void 0);if(console.warn("[stx:bundler] build failed:",F),Fo(n||"",F,k),i.throwOnFailure||zo()==="error")throw Error(F);return e}let p="";for(let x of j.outputs){p=await x.text();break}let b=[];for(let x of p.matchAll(/^\s*export\s*\{([^}]*)\}\s*;?\s*$/gm))for(let F of x[1].split(",")){let k=F.trim().match(/^([A-Za-z_$][\w$]*)\s+as\s+([A-Za-z_$][\w$]*)$/);if(k){b.push([k[2],k[1]]);continue}let T=F.trim();if(/^[A-Za-z_$][\w$]*$/.test(T))b.push([T,T])}if(i.expose){let x=new Set(i.expose);for(let F=b.length-1;F>=0;F--)if(!x.has(b[F][0]))b.splice(F,1)}let U=[];p=Ja(Ga(p,Q),U);let le=p.match(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm)||[];if(p=p.replace(/^\s*import(?:\s+|(?=["'{*]))[^;]+;?\s*$/gm,"").replace(/^\s*export\s*\{[^}]*\}\s*;?\s*$/gm,"").replace(/^\s*export\s+default\s+.*$/gm,"").trim(),g&&p)try{p=new Bun.Transpiler({loader:"js",minifyWhitespace:!0}).transformSync(p)}catch{}let K=`__stxBundle_${l}`,ce=b.map(([x,F])=>`${JSON.stringify(x)}: ${F}`).join(", "),ue=b.map(([x])=>`var ${x} = undefined;`).join(`
|
|
4
4
|
`),de=b.map(([x])=>`${x} = ${K}[${JSON.stringify(x)}];`).join(`
|
|
5
5
|
`);if(p=`${le.join(`
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{_t,C}from"./chunk-6k4f583z.js";import m from"fs";import e from"path";async function dn(r,o,i){if(r.__stx_runtime_config)return;let n=_t();if(n||i){r.__stx_runtime_config=n??C(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-
|
|
2
|
+
import{_t,C}from"./chunk-6k4f583z.js";import m from"fs";import e from"path";async function dn(r,o,i){if(r.__stx_runtime_config)return;let n=_t();if(n||i){r.__stx_runtime_config=n??C(i);return}let t=e.dirname(e.resolve(o));while(!0){if(["stx.config.ts","stx.config.js",".config/stx.config.ts",".config/stx.config.js"].some((f)=>m.existsSync(e.join(t,f)))){let{loadStxConfig:f}=await import("./chunk-1wp8qb5f.js"),c=await f(t);if(c.runtimeConfig)r.__stx_runtime_config=C(c.runtimeConfig);return}let s=e.dirname(t);if(s===t)return;t=s}}async function Cs(r,o){function i(n){if(n===null)return"null";if(Array.isArray(n))return`Array<${n.length?[...new Set(n.map(i))].join(" | "):"unknown"}>`;if(typeof n==="object")return`{ ${Object.entries(n).map(([t,s])=>`readonly ${JSON.stringify(t)}: ${i(s)}`).join("; ")} }`;return typeof n}await Bun.write(e.join(r,".stx/runtime-config.d.ts"),`import '@stacksjs/stx/runtime-config'
|
|
3
3
|
declare module '@stacksjs/stx/runtime-config' { interface PublicRuntimeConfig ${i(o.public??{})} }
|
|
4
4
|
`),await Bun.write(e.join(r,".stx/runtime-config-server.d.ts"),`import '@stacksjs/stx/runtime-config-server'
|
|
5
5
|
declare module '@stacksjs/stx/runtime-config-server' { interface PrivateRuntimeConfig ${i(o.private??{})} }
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{jn,Me,Le,he,Yo,Vn,Z,K,an,u,n,R}from"./chunk-
|
|
2
|
+
import{jn,Me,Le,he,Yo,Vn,Z,K,an,u,n,R}from"./chunk-4mmz9xxh.js";import{dirname as k,resolve as _}from"path";function h(o){return o.endsWith(".md")||o.endsWith(".markdown")}function C(o){let e=[];g(/<pre\b[^>]*>[\s\S]*?<\/pre>/gi);let r=[...e];g(/<code\b[^>]*>[\s\S]*?<\/code>/gi,r);function g(s,p){let m;while((m=s.exec(o))!==null){let t=m.index,i=t+m[0].length;if(p?.some((l)=>t>=l.start&&i<=l.end))continue;e.push({start:t,end:i})}}if(e.length===0)return o;e.sort((s,p)=>s.start-p.start);let a="",c=0;for(let s of e){if(s.start<c)continue;a+=o.slice(c,s.start),a+=`@raw${o.slice(s.start,s.end)}@endraw`,c=s.end}return a+=o.slice(c),a}async function b(o,e={}){let{data:r,content:g}=jn(o),c=await(e.renderer??((s)=>Me(s)))(g);return{html:C(c),frontmatter:r??{}}}function v(o){let e=o,r=Z(o);if(r)e=r.content.trim();let g=/<script\b([^>]*)>([\s\S]*?)<\/script>/gi,a=[],c=[],s=[],p=(i)=>/\b(?:state|derived|effect|batch)\s*(?:<[^<>()]*>)?\s*\(/.test(i),m;while((m=g.exec(o))!==null){let i=m[1],l=m[2],f=m[0],d=i.includes("server");if(p(l))s.push(f);else if(d)c.push(l);else a.push(f)}let t=e;{let i=/<script\b(?![^>]*\b(?:client|type\s*=\s*["']module["']|src\s*=))[^>]*>/gi,l,f=[];while((l=i.exec(t))!==null){let d=l.index+l[0].length,x=t.indexOf("</script>",d);if(x===-1)continue;f.push({start:l.index,end:x+9}),i.lastIndex=x+9}for(let d=f.length-1;d>=0;d--)t=t.substring(0,f[d].start)+t.substring(f[d].end)}for(let i of a)t=t.replace(i,"");return{templateContent:t,serverScripts:c,clientScripts:a,signalsScripts:s}}function M(o,e){return`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="UTF-8">
|
|
@@ -14,5 +14,5 @@ ${c.join(`
|
|
|
14
14
|
`)}`}else{if(r.processClientScripts!==!1&&c.length>0){let i=p.__stx_event_bindings||[],l=Le(p),d=(await Promise.all(c.map(async(w)=>{let y=w.match(/<script\b[^>]*>([\s\S]*?)<\/script>/);if(!y)return w;return await he(y[1],{eventBindings:i,templateContent:t,serverData:l,filePath:e})}))).join(`
|
|
15
15
|
`);if(t.match(/(<\/body>)/i))t=t.replace(/(<\/body>)/i,`${d}
|
|
16
16
|
$1`);else t+=`
|
|
17
|
-
${d}`}t=await K(t)}if(r.wrapInDocument){if(!t.trim().toLowerCase().startsWith("<!doctype")&&!t.trim().toLowerCase().startsWith("<html"))t=M(t,r.title)}if(r.injectCSS)try{let{injectCss:i}=await import("./chunk-
|
|
17
|
+
${d}`}t=await K(t)}if(r.wrapInDocument){if(!t.trim().toLowerCase().startsWith("<!doctype")&&!t.trim().toLowerCase().startsWith("<html"))t=M(t,r.title)}if(r.injectCSS)try{let{injectCss:i}=await import("./chunk-pqwx5hw8.js");t=await i(t)}catch{}return t}
|
|
18
18
|
export{Io};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ne,ic,Nd,Ld,jd,Bd,ac,cc,Fd,zd,Xo,Hd,nn,rn,zn}from"./chunk-
|
|
2
|
+
import{Ne,ic,Nd,Ld,jd,Bd,ac,cc,Fd,zd,Xo,Hd,nn,rn,zn}from"./chunk-4mmz9xxh.js";import"./chunk-58jyc7kp.js";import"./chunk-9mjy16pw.js";import"./chunk-299xbyhn.js";import"./chunk-yy19rrw6.js";import"./chunk-6k4f583z.js";import"./chunk-8m3k43d3.js";import"./chunk-7p0zerfj.js";import"./chunk-0ytm2ecf.js";import"./chunk-ba88n1j7.js";import"./chunk-5tyes97j.js";import"./chunk-kpns3659.js";import"./chunk-e6y6s7q8.js";export{Bd as __setSignalsGeneratorsForTest,Ne as cacheEngineFingerprint,rn as cacheTemplate,nn as checkCache,Hd as clearDevCaches,cc as getCachedRouterScript,ac as getCachedSignalsRuntime,Fd as getServeClientAsset,Xo as getServeModuleBundle,zn as hashFilePath,Ld as invalidateFileCache,jd as invalidateFileCacheByDir,Nd as readFileCached,zd as registerServeModuleBundle,ic as templateCache};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{X,yn,te,P,Rt}from"./chunk-0ytm2ecf.js";import{Qe,xn,lr,dr,ur,et,tt,nt,rt,st,ot,ke}from"./chunk-kpns3659.js";import{U,b,nn,rn,e,kt,sn,f,Be,Ct,Fe,ze,Z,N,ce,K,u,be,fi,bs,n,r,ee,Jn,o,A,le}from"./chunk-
|
|
2
|
+
import{X,yn,te,P,Rt}from"./chunk-0ytm2ecf.js";import{Qe,xn,lr,dr,ur,et,tt,nt,rt,st,ot,ke}from"./chunk-kpns3659.js";import{U,b,nn,rn,e,kt,sn,f,Be,Ct,Fe,ze,Z,N,ce,K,u,be,fi,bs,n,r,ee,Jn,o,A,le}from"./chunk-4mmz9xxh.js";import{Ae,ao,ne,_,co,Cr,An,me,lo,re}from"./chunk-7rz4fy4y.js";import{It}from"./chunk-1c7v7pqv.js";import{ae}from"./chunk-2hc5mbw8.js";import{a}from"./chunk-2y82wf9d.js";import{D}from"./chunk-ggb57j6c.js";function Ks(t,s){let i=[],d=`${s}=`;for(let c=0;c<t.length;c++){let l=t[c];if(l.startsWith(d)){let m=l.slice(d.length);if(m)i.push(m);continue}if(l===s){let m=t[c+1];if(m!==void 0&&!m.startsWith("-"))i.push(m),c++}}return i}var{serve:rr}=globalThis.Bun;import Bt from"fs";import pt from"path";function bt(){return`
|
|
3
3
|
/* Theme selector for code blocks */
|
|
4
4
|
.theme-selector {
|
|
5
5
|
margin: 1rem 0;
|
|
@@ -1786,7 +1786,7 @@ else {
|
|
|
1786
1786
|
})()
|
|
1787
1787
|
</script>
|
|
1788
1788
|
`;import _e from"fs";import $e from"path";function On(t){try{return _e.statSync(t).mtimeMs}catch{return null}}function Dt(t,s){let i=Math.max(0,Math.round((s-t)/1000));if(i<60)return`${i}s ago`;if(i<3600)return`${Math.round(i/60)}m ago`;return`${Math.round(i/3600)}h ago`}function Ei(t,s){try{return globalThis.Bun?.resolveSync(t,s)??null}catch{return null}}function Dn(t,s="stx"){let i=$e.resolve(t);for(let d=0;d<10;d++){let c=$e.join(i,"pantry","@stacksjs",s);if(_e.existsSync(c))return c;let l=$e.dirname(i);if(l===i)break;i=l}return null}var Mn=["@stacksjs/stx","bun-plugin-stx"];function Pi(t){try{let s=_e.readFileSync($e.join(t,"package.json"),"utf8"),i=JSON.parse(s)?.version;return typeof i==="string"?i:null}catch{return null}}function Oi(t,s=6){let i=$e.resolve(t),d=[],c=new Set;function l(p,h){if(h>s)return;let g;try{g=_e.realpathSync(p)}catch{return}if(c.has(g))return;c.add(g);for(let w of Mn){let S=$e.join(p,w),C=Pi(S);if(C!==null)d.push({name:w,version:C,dir:$e.relative(i,S)||S,nested:h>0})}let y;try{y=_e.readdirSync(p,{withFileTypes:!0})}catch{return}for(let w of y){if(!w.isDirectory()&&!w.isSymbolicLink())continue;if(w.name===".bin"||w.name===".cache")continue;let S=$e.join(p,w.name);if(w.name.startsWith("@")){let v;try{v=_e.readdirSync(S,{withFileTypes:!0})}catch{continue}for(let x of v){let T=$e.join(S,x.name,"node_modules");if(_e.existsSync(T))l(T,h+1)}continue}let C=$e.join(S,"node_modules");if(_e.existsSync(C))l(C,h+1)}}let m=$e.join(i,"node_modules");if(_e.existsSync(m))l(m,0);return d}function Ai(t){let s=[];for(let i of Mn){let d=t.filter((m)=>m.name===i);if(d.length<=1)continue;let c=[...new Set(d.map((m)=>m.version))],l=d.map((m)=>`${m.version} at ${m.dir}`).join("; ");if(c.length===1){s.push({name:`${i} copies`,status:"info",detail:`${d.length} copies, all ${c[0]} \u2014 duplicated but in agreement`});continue}s.push({name:`${i} copies disagree`,status:"error",detail:`${c.length} versions installed, so which one runs depends on who imports it: ${l}`,fix:`remove the nested copies, or add an overrides entry pinning ${i}, then reinstall \u2014 and verify with: find -L node_modules -path '*/${i}/package.json' -exec grep -H '"version"' {} +`})}return s}async function yr(t={}){let s=t.cwd?$e.resolve(t.cwd):process.cwd(),i=t.resolve??Ei,d=Date.now(),c=[],l=i("@stacksjs/stx",s);c.push(l?{name:"@stacksjs/stx resolves to",status:"ok",detail:l}:{name:"@stacksjs/stx resolves to",status:"info",detail:"not resolvable from here (running inside the stx repo, or not installed)"});let m=i("bun-plugin-stx",s);if(m)c.push({name:"bun-plugin-stx resolves to",status:"ok",detail:m});for(let h of Ai(Oi(s)))c.push(h);let p=Dn(s,"stx");if(!p)c.push({name:"pantry",status:"info",detail:"no pantry/@stacksjs/stx found \u2014 standard install (nothing to rebuild)"});else{let h=$e.join(p,"src/signals.ts"),g=[$e.join(p,"dist/index.js"),$e.join(p,"dist/signals.js")].find((v)=>_e.existsSync(v))||null,y=On(h),w=g?On(g):null;if(y==null)c.push({name:"pantry dist freshness",status:"info",detail:`found pantry at ${p} but no src/signals.ts to compare`});else if(w==null)c.push({name:"pantry dist freshness",status:"error",detail:"pantry has src but no built dist \u2014 the dev server will resolve nothing (or a stale copy elsewhere)",fix:`cd ${p} && bun build.ts`});else if(w<y){let v=Math.round((y-w)/1000);c.push({name:"pantry dist freshness",status:"error",detail:`dist (${Dt(w,d)}) is OLDER than src/signals.ts (${Dt(y,d)}) by ${v}s \u2014 your edit isn't built`,fix:`cd ${p} && bun build.ts`})}else c.push({name:"pantry dist freshness",status:"ok",detail:`dist rebuilt after src (src ${Dt(y,d)}, dist ${Dt(w,d)})`});let S=$e.join(s,"node_modules/@stacksjs/stx"),C=null;try{C=_e.lstatSync(S)}catch{C=null}if(!C)c.push({name:"node_modules \u2192 pantry",status:"info",detail:"node_modules/@stacksjs/stx not present (not installed here)"});else if(C.isSymbolicLink()){let v=null;try{v=_e.realpathSync(S)}catch{}let x=(()=>{try{return _e.realpathSync(p)}catch{return p}})();c.push(v===x?{name:"node_modules \u2192 pantry",status:"ok",detail:"symlinked to pantry"}:{name:"node_modules \u2192 pantry",status:"warn",detail:`symlinked to ${v||"(dangling)"}, not pantry`})}else c.push({name:"node_modules \u2192 pantry",status:"warn",detail:"is a real directory, NOT symlinked to pantry \u2014 edits to pantry src/dist won't be resolved",fix:"rm -rf node_modules/@stacksjs/stx && ln -s ../../pantry/@stacksjs/stx node_modules/@stacksjs/stx"})}if(c.push({name:"dev runtime cache",status:"info",detail:"cleared automatically on source edits by the dev watcher (clearDevCaches, #1745 item C)"}),t.generateRuntime)try{let g=t.generateRuntime().length;c.push(g>1000?{name:"signals runtime",status:"ok",detail:`generated ${g.toLocaleString()} chars`}:{name:"signals runtime",status:"warn",detail:`generated only ${g} chars \u2014 suspiciously short`})}catch(h){c.push({name:"signals runtime",status:"error",detail:`failed to generate: ${h.message}`})}return{checks:c,ok:!c.some((h)=>h.status==="error")}}function br(t){let s={ok:"\u2713",warn:"\u26A0",error:"\u2717",info:"\xB7"},i=["stx runtime resolution:"];for(let d of t.checks)if(i.push(` ${s[d.status]} ${d.name}: ${d.detail}`),d.fix)i.push(` \u2192 ${d.fix}`);return i.push(""),i.push(t.ok?"\u2713 All framework-runtime layers are aligned.":"\u2717 A runtime layer is stale \u2014 see the fixes above."),i.join(`
|
|
1789
|
-
`)}var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Mt.relative(Mt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Jn(i,d);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let p=new Set;if(i.cache&&i.cachePath){let x=await nn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await te(()=>Bun.file(m).text(),"",(x)=>{throw new yn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new yn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=U.time("script-extraction",()=>{let x=h,T=Z(h);if(T)x=T.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",M=[];for(let R of k){let L=R.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=R.match(/<script\b([^>]*)>/i),G=B?B[1]:"";if(/\bserver\b/i.test(G))H=L;else M.push(R)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:M}}),S={__filename:m,__dirname:Mt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>u(g,S,m),void 0,(x)=>{let T=new X(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(P.log(T,{filePath:m,scriptContent:g}),i.debug)throw T});let v=await U.timeAsync("directive-processing",async()=>await n(y,S,m,i,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-
|
|
1789
|
+
`)}var ft={name:"bun-plugin-stx",async setup(t){let i={...await o(),...t.config?.stx},d=new Set,c=i.webComponents?.enabled?`./${Mt.relative(Mt.dirname(t.config?.outdir||"dist"),i.webComponents.outputDir||"dist/web-components")}`:"/web-components",l=[];if(i.webComponents?.enabled)try{let m=await Jn(i,d);if(l.push(...m),i.debug&&m.length>0)console.log(`Successfully built ${m.length} web components`)}catch(m){console.error("Failed to build web components:",m)}t.onLoad({filter:/\.stx$/},async({path:m})=>{try{let p=new Set;if(i.cache&&i.cachePath){let x=await nn(m,i);if(x){if(i.debug)console.log(`Using cached version of ${m}`);return{contents:x,loader:"html"}}}let h=await te(()=>Bun.file(m).text(),"",(x)=>{throw new yn(`Failed to read stx file: ${m}`,m,void 0,void 0,`File read error: ${x.message}`)});if(!h)throw new yn(`stx file is empty: ${m}`,m);let{scriptContent:g,templateContent:y,allScripts:w}=U.time("script-extraction",()=>{let x=h,T=Z(h);if(T)x=T.content.trim();let k=h.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],H="",M=[];for(let R of k){let L=R.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",B=R.match(/<script\b([^>]*)>/i),G=B?B[1]:"";if(/\bserver\b/i.test(G))H=L;else M.push(R)}let I=x.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:H,templateContent:I,allScripts:M}}),S={__filename:m,__dirname:Mt.dirname(m),__stx:{webComponentsPath:c,builtComponents:l}};await te(()=>u(g,S,m),void 0,(x)=>{let T=new X(`Script execution failed in ${m}: ${x.message}`,m,void 0,void 0,g.substring(0,100));if(P.log(T,{filePath:m,scriptContent:g}),i.debug)throw T});let v=await U.timeAsync("directive-processing",async()=>await n(y,S,m,i,p));if(w.length>0){let{interpolateScriptsInTemplate:x}=await import("./chunk-fdcrrpgn.js"),T=x(w.join(`
|
|
1790
1790
|
`),S),k=v.search(/<\/body>/i);if(k!==-1)v=v.slice(0,k)+T+`
|
|
1791
1791
|
`+v.slice(k);else v+=`
|
|
1792
1792
|
${T}`}if(v=await K(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await rn(m,v,p,i),i.debug)console.log(`Cached template ${m} with ${p.size} dependencies`)}return{contents:v,loader:"html"}}catch(p){let h=p instanceof Error?p:new X(`Plugin processing failed: ${String(p)}`,m);if(P.log(h,{filePath:m,buildConfig:t.config}),Rt.logDetailedError(h,{filePath:m,plugin:"bun-plugin-stx"}),i.debug)console.error("stx Plugin Error:",h);let g=h,y=g.line||null,w=g.context||null;return{contents:i.debug||D()?`<!DOCTYPE html>
|
|
@@ -1849,7 +1849,7 @@ ${T}`}if(v=await K(v),p.forEach((x)=>d.add(x)),i.cache&&i.cachePath){if(await rn
|
|
|
1849
1849
|
<h1>Something went wrong</h1>
|
|
1850
1850
|
<p>An internal error occurred. Please try again later.</p>
|
|
1851
1851
|
</body>
|
|
1852
|
-
</html>`,loader:"html"}}})}};async function Cn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=Se.resolve(t);if(!Ne.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return Ft(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Ne.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let L={name:"public-assets",setup(Ce){Ce.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ye)=>({path:ye.path,external:!0}))}},B=await Bun.build({entrypoints:[p],outdir:h,plugins:[L,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let G=B.outputs.find((Ce)=>Ce.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(L){return console.error(`${e.red}Error building stx file:${e.reset}`,L),!1}};if(!await y())return!1;let S=Se.dirname(p);await kt(S);let C=i;try{if(C=await Ye(i),C!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||C+1;l=Pt({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,T;try{let{loadStxConfig:L}=await import("./chunk-
|
|
1852
|
+
</html>`,loader:"html"}}})}};async function Cn(t,s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=Se.resolve(t);if(!Ne.existsSync(p))return console.error(`${e.red}Error: File not found: ${e.bright}${p}${e.reset}`),!1;if(p.endsWith(".md"))return Ft(p,s);else if(!p.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${p}${e.reset}. Only .stx and .md files are supported.`),!1;let h=a(process.cwd(),"output");Ne.mkdirSync(h,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let g=null,y=async()=>{try{let L={name:"public-assets",setup(Ce){Ce.onResolve({filter:/^\/(images|fonts|assets|public)\//},(ye)=>({path:ye.path,external:!0}))}},B=await Bun.build({entrypoints:[p],outdir:h,plugins:[L,ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!B.success)return console.error(`${e.red}Build failed:${e.reset}`,B.logs),!1;let G=B.outputs.find((Ce)=>Ce.path.endsWith(".html"));if(!G)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return g=await Bun.file(G.path).text(),!0}catch(L){return console.error(`${e.red}Error building stx file:${e.reset}`,L),!1}};if(!await y())return!1;let S=Se.dirname(p);await kt(S);let C=i;try{if(C=await Ye(i),C!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${C} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let L=s.hmrPort||C+1;l=Pt({wsPort:L,verbose:!1}),m=l.start(L)}let v={},x=null,T;try{let{loadStxConfig:L}=await import("./chunk-8dbnvypv.js"),B=await L();if(T=s.stxOptions?.serverApi??B.serverApi,B?.apiRouter)x=B?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(B?.apiRoutes){v=B.apiRoutes;let G=Object.keys(v).length;if(G>0)console.log(`${e.blue}Loaded ${e.bright}${G} API route${G>1?"s":""}${e.reset}`)}if(B?.broadcasting?.enabled)try{let{startBroadcasting:G,loadChannels:oe}=await import("./chunk-k4p80n25.js"),Ce=B.broadcasting;await G(Ce);let ye=Ce.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${ye}/ws${e.reset}`);let De=Se.join(process.cwd(),"channels.ts");if(Ne.existsSync(De))try{let de=await oe(De);console.log(`${e.blue}Loaded ${e.bright}${de} broadcast channel${de!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(de){console.warn(`${e.yellow}Failed to load channels.ts: ${de.message}${e.reset}`)}}catch(G){console.warn(`${e.yellow}Broadcasting failed to start: ${G.message}${e.reset}`)}}catch{}let{createServerApi:k,isServerApiSource:H}=await import("./chunk-7c1ntx2e.js"),M=await k(process.cwd(),T);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${C}/${e.reset}...`),c)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${m}${e.reset}`);let I=Fi({port:C,async fetch(L){return It(L,await(async()=>{let B=new URL(L.url);if([h,Se.dirname(p),Se.join(process.cwd(),"public")].some((de)=>H(Se.join(de,B.pathname),process.cwd(),T)))return new Response("Not Found",{status:404});if(x)try{let de=await x.handleRequest(L);if(de.status!==404)return de}catch{}if(v[B.pathname])try{return await v[B.pathname](L)}catch(de){return new Response(JSON.stringify({error:de.message}),{status:500,headers:{"Content-Type":"application/json"}})}let G=await M(L);if(G)return G;if(B.pathname==="/")return(async()=>{let W=await f(g||"");if(c)W=Xe(W,m);if(s.native)if(W.includes("<head>"))W=W.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else W="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+W;if(s.titlebarHidden)if(W.includes("<head>"))W=W.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(W.includes("<html"))W=W.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else W=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${W}`;return W})().then((W)=>new Response(W,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let oe=Se.join(h,B.pathname);if(Ne.existsSync(oe)&&Ne.statSync(oe).isFile()){let de=Bun.file(oe),W=Se.extname(oe).toLowerCase(),j="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await de.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(de,{headers:{"Content-Type":j}})}let Ce=Se.dirname(p),ye=Se.join(Ce,B.pathname);if(Ne.existsSync(ye)&&Ne.statSync(ye).isFile()){let de=Bun.file(ye),W=Se.extname(ye).toLowerCase(),j="text/plain";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await de.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(de,{headers:{"Content-Type":j}})}let De=Se.join(process.cwd(),"public",B.pathname);if(Ne.existsSync(De)&&Ne.statSync(De).isFile()){let de=Bun.file(De),W=Se.extname(De).toLowerCase(),j="application/octet-stream";if(W===".ts"||W===".tsx"){let Ue=new Bun.Transpiler({loader:W===".tsx"?"tsx":"ts"}),qe=await de.text(),ct=Ue.transformSync(qe);return new Response(ct,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(W){case".html":j="text/html";break;case".css":j="text/css";break;case".js":j="text/javascript";break;case".json":j="application/json";break;case".png":j="image/png";break;case".jpg":case".jpeg":j="image/jpeg";break;case".gif":j="image/gif";break;case".svg":j="image/svg+xml";break;case".ico":j="image/x-icon";break;case".woff":j="font/woff";break;case".woff2":j="font/woff2";break;case".ttf":j="font/ttf";break;case".otf":j="font/otf";break;case".eot":j="application/vnd.ms-fontobject";break}return new Response(de,{headers:{"Content-Type":j}})}return new Response("Not Found",{status:404})})())},error(L){return new Response(`<pre>${L}
|
|
1853
1853
|
${L.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
1854
1854
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1855
1855
|
${e.bright}\u2192 ${e.cyan}http://localhost:${C}/${e.reset}`),console.log(`
|
|
@@ -2025,9 +2025,9 @@ ${v.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
2025
2025
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
2026
2026
|
${e.bright}\u2192 ${e.cyan}http://localhost:${y}/${e.reset}`),console.log(`
|
|
2027
2027
|
${e.yellow}Routes:${e.reset}`);let S=new Set(p.map((v)=>v.routeTemplate)),C=Object.entries(m).filter(([v])=>!S.has(v)).sort(([v],[x])=>v.localeCompare(x)).map(([v,x])=>({route:v==="/"?"/":v,filePath:Oe.relative(process.cwd(),x.filePath),fileType:x.fileType}));for(let v of p){let x=v.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");C.push({route:x,filePath:Oe.relative(process.cwd(),v.filePath),fileType:"stx"})}if(C.sort((v,x)=>v.route.localeCompare(x.route)),C.forEach((v,x)=>{let k=x===C.length-1?"\u2514\u2500 ":"\u251C\u2500 ",H=v.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${k}${v.route}${e.reset} \u2192 ${e.bright}${v.filePath}${e.reset} ${H}`)}),console.log(`
|
|
2028
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(w.url.toString(),()=>{if(d)it.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=it.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),be.clear(),ee(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Wn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Ni}=globalThis.Bun;import ve from"fs";import ie from"path";async function qn(t){try{return Ct(await Bun.file(t).text())}catch{return}}function qt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":d[i]||"application/octet-stream",...l}})}async function $n(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-0d9rx3n4.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-zw2xxaza.js"),S=s.stxOptions?.serverApi??g.serverApi,C=await y(p,S),v=g.root&&g.root!=="."?ie.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",T=ie.join(v,x);if(!ve.existsSync(T)&&!g._layerPageDirs?.some((E)=>ve.existsSync(E)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],M=[];for(let{dir:E,prefix:F}of H)if(ve.existsSync(E)){let z=N(ie.dirname(E),{pagesDir:ie.basename(E)});for(let V of z){let we=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;M.push({route:{...V,pattern:we},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let I=new Map,R=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await co(p,s.stxOptions?.shell),L){if(R=await Cr(L,s.stxOptions||{}),R)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(p,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}et(),await nt(p);let B=tt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let G={},oe=null;try{let{loadStxConfig:E}=await import("./chunk-0d9rx3n4.js"),F=await E(p);if(F?.apiRouter)oe=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){G=F.apiRoutes;let z=Object.keys(G).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:V}=await import("./chunk-k4p80n25.js"),we=F.broadcasting;await z(we);let We=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let se=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${se} broadcast channel${se!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(se){console.warn(`${e.yellow}Failed to load channels.ts: ${se.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let Ce=a(p,"output");ve.mkdirSync(Ce,{recursive:!0});let ye=new Map,De=new Set,de=async(E)=>{let F=dr(T,E);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:Ce,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let V=z.outputs.find((we)=>we.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,j=async(E,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-0d9rx3n4.js"),{checkCache:se,cacheTemplate:Q,readFileCached:q,templateCache:J}=await import("./chunk-zfct5zbe.js"),Te=await We(p),Je=(pe)=>{if(!pe)return pe;if(ie.isAbsolute(pe))return pe;return ie.resolve(p,pe)},O={...we,...Te,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=Je(O.partialsDir),O.componentsDir=Je(O.componentsDir),O.layoutsDir=Je(O.layoutsDir),O.storesDir=Je(O.storesDir||"stores"),O.cachePath=Je(O.cachePath)??a(p,"cache");let xe=!F&&!s.profile,ue=O.cache!==!1;if(ue&&xe){let pe=J.get(E.filePath);if(pe)try{if((await ve.promises.stat(E.filePath)).mtime.getTime()<=pe.mtime){let He=!0;for(let Ee of pe.dependencies){if(!ve.existsSync(Ee)){He=!1;break}if((await ve.promises.stat(Ee)).mtime.getTime()>pe.mtime){He=!1;break}}if(He){let Ee=pe.output;if(R)Ee=me(Ee,{preserveHead:!0});let gt=W.get(E.filePath);return{route:E,content:Ee,status:gt?.status??await qn(E.filePath),headers:gt?.headers}}}}catch{}let Ie=await se(E.filePath,O);if(Ie){let je=Ie;if(R)je=me(je,{preserveHead:!0});let He=W.get(E.filePath);return{route:E,content:je,status:He?.status??await qn(E.filePath),headers:He?.headers}}}let he=ue?await q(E.filePath):await Bun.file(E.filePath).text(),Re=Ct(he),{classifyAllScripts:Y}=await import("./chunk-0d9rx3n4.js"),Le=Y(he),Ve=Le.server.map((pe)=>pe.content),fe=he;for(let pe of Le.server)fe=fe.replace(pe.fullTag,"");let ge={__filename:E.filePath,__dirname:ie.dirname(E.filePath),__stx_options:O,params:F??{},__stx_runtime_head:{}};for(let pe of Ve)try{await V(pe,ge,E.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",E.filePath,Ie?.message||Ie)}let Ke=new Set,Me;if(s.profile){let pe=performance.now();Me=await z(fe,ge,E.filePath,O,Ke);let Ie=performance.now()-pe,je=ie.relative(p,E.filePath)||E.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Me=await z(fe,ge,E.filePath,O,Ke);if(!R)Me=await Ge(Me,{router:O.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-6ywr110f.js");Me=Me.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${pe(He,ge)}</script>`})}if(R)Me=me(Me,{preserveHead:!0});if(ue&&xe)await Q(E.filePath,Me,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-0gzm7em2.js"),lt=Kn(ge),mt=ge.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let pe=ge.streamBoundaries||{},Ie={...O,autoShell:!1},je=Object.keys(mt).map((Ee)=>({id:Ee,render:async()=>{let gt=typeof pe[Ee]==="function"?await pe[Ee]():void 0;return z(mt[Ee],{...ge,$boundary:gt},E.filePath,Ie,new Set)}})),He=new Set(je.map((Ee)=>Ee.id));lt=[...(lt||[]).filter((Ee)=>!He.has(Ee.id)),...je]}if(lt&<.length>0)De.add(E.pattern);else lt=void 0;let Kt=Fe(ge),Xt=ze(ge);if(xe)W.set(E.filePath,{status:Kt,headers:Xt});return{route:E,content:Me,status:Kt??Re,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${E.pattern}${e.reset}:`,z),null}},Ue=8,qe=async()=>{ye.clear(),I.clear();for(let E=0;E<k.length;E+=Ue){let F=k.slice(E,E+Ue),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)ye.set(V.route.pattern,V)}for(let E=0;E<M.length;E+=Ue){let F=M.slice(E,E+Ue),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return ye.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await kt(p);let at=i;try{if(at=await Ye(i),at!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${at} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let E=s.hmrPort||at+1;l=Pt({wsPort:E,verbose:!1}),m=l.start(E)}let _t=(E,F)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(E.includes("</head>"))return E.replace("</head>",`${V}</head>`);if(E.includes("<body"))return E.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+E};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Ni({port:at,async fetch(E){let F=new URL(E.url),z=g?.publicDir||"public",V=ie.join(p,z,F.pathname),we=ie.join(p,F.pathname),We=ie.join(Ce,F.pathname);if([V,we,We].some((O)=>w(O,p,S)))return new Response("Not Found",{status:404});let[Ge,se,Q]=await Promise.all([ve.promises.stat(V).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,p,S))return qt(V);if(se?.isFile()&&!w(we,p,S))return qt(we);if(Q?.isFile()&&!w(We,p,S))return qt(We);if(F.pathname.startsWith("/_stx/component/")){let O=decodeURIComponent(F.pathname.slice(16));if(O)try{let xe=`<${O} />`,ue={...buildConfig,autoShell:!1},he=await processDirectives(xe,{},ie.join(p,"components",`${O}.stx`),ue,new Set);return new Response(he,{headers:{"Content-Type":"text/html"}})}catch(xe){return new Response(`<div class="stx-async-error">${xe.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:O}=await import("./chunk-v70hfs6d.js"),xe=await O(E,{publicDir:ie.join(p,z),cacheDir:a(p,"cache","img")});if(xe)return xe}if(oe)try{let O=await oe.handleRequest(E);if(O.status!==404)return O}catch{}if(G[F.pathname])try{return await G[F.pathname](E)}catch(O){return new Response(JSON.stringify({error:O.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await C(E);if(q)return q;let J=xn(F.pathname,k);if(J){let O=ye.get(J.route.pattern),xe=De.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||xe){let ue=await j(J.route,J.params);if(ue)O=ue}if(O){let ue=O.status??200,he=O.headers??{},Re=(J.route.filePath?Be(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Re.validate){if(!await Re.validate({params:J.params})){let Ve=await de(404);if(Ve){let fe=Ve;if(fe=await f(fe,p),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Re.middleware){let Le=rt(F.pathname,J.params,Re,F.search),Ve=st(Le,null,E,{isServer:!0}),fe=await ot(Re.middleware,Ve);if(fe.redirect){let ge=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Me=new Headers(fe.responseHeaders);return Me.set("Location",ge),new Response(null,{status:Ke,headers:Me})}if(fe.abort){let{statusCode:ge,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${ge}</title></head><body><h1>Error ${ge}</h1><p>${Ke}</p></body></html>`,{status:ge,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let ge=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;O.content=O.content.replace("</head>",`${ge}</head>`)}}let Y=O.content;if(R&&lo(E)){let Le=ke(Y),Ve=ce(Y),fe=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),ge=fe?ao(fe[1].trim()):"";if(Object.keys(J.params).length>0)Y=_t(Y,J.params);Y=await f(Y,p);let Ke=g?.router?.container||"main";return Y=re(Y,Ke),new Response(Y,{status:ue,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...ge&&{"X-STX-Title":encodeURIComponent(ge)},[fi]:bs(),..._(),"Cache-Control":Ae}})}if(R)Y=An(R,Y);if(Object.keys(J.params).length>0)Y=_t(Y,J.params);if(Y=await f(Y,p),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(O.boundaries&&O.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-0gzm7em2.js");return Ve(Le(Y,O.boundaries,{timeoutMs:30000}),{status:ue,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:ue,headers:{"Content-Type":"text/html",..._(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...he}})}}if(M.length>0){let O=M.map((ue)=>ue.route),xe=xn(F.pathname,O);if(xe){let ue=I.get(xe.route.pattern);if(ue){let he=ue.content;if(R)he=An(R,he);if(Object.keys(xe.params).length>0)he=_t(he,xe.params);if(he=await f(he,p),c)he=Xe(he,m);return new Response(he,{status:ue.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ue}of H)if(ue!=="/"&&F.pathname.startsWith(ue)){let he=I.get(ue)||I.get(ue+"/");if(he){let Re=he.content;if(R)Re=An(R,Re);if(Re=await f(Re,p),c)Re=Xe(Re,m);return new Response(Re,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Qe(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Te=ye.get("/");if(Te){let O=Te.content;if(O=await f(O,p),c)O=Xe(O,m);if(s.native)if(O.includes("<head>"))O=O.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else O="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+O;return new Response(O,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await de(404);if(Je){let O=Je;if(O=await f(O,p),c)O=Xe(O,m);return new Response(O,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(E){let F=await de(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${E}
|
|
2028
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(w.url.toString(),()=>{if(d)it.watch(l,{recursive:!0}).close();w.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let v=it.watch(l,{recursive:!0},async(x,T)=>{if(!T)return;if(T.endsWith(".stx")||T.endsWith(".js")||T.endsWith(".ts")||T.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${T}${e.yellow} changed, rebuilding...${e.reset}`),be.clear(),ee(),await h()});process.on("SIGINT",()=>{v.close(),w.stop(),process.exit(0)})}return!0}function Wn(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Ni}=globalThis.Bun;import ve from"fs";import ie from"path";async function qn(t){try{return Ct(await Bun.file(t).text())}catch{return}}function qt(t){let s=Bun.file(t),i=ie.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},l=[".js",".css",".json"].includes(i)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(s,{headers:{"Content-Type":d[i]||"application/octet-stream",...l}})}async function $n(t=".",s={}){let i=s.port||3000,d=s.watch!==!1,c=s.hotReload!==!1&&d,l=null,m=s.hmrPort||i+1,p=ie.resolve(t),{loadStxConfig:h}=await import("./chunk-8dbnvypv.js"),g=await h(p),{createServerApi:y,isServerApiSource:w}=await import("./chunk-7c1ntx2e.js"),S=s.stxOptions?.serverApi??g.serverApi,C=await y(p,S),v=g.root&&g.root!=="."?ie.join(p,g.root):p,x=s.pagesDir||g.pagesDir||"pages",T=ie.join(v,x);if(!ve.existsSync(T)&&!g._layerPageDirs?.some((E)=>ve.existsSync(E)))return console.error(`${e.red}Error: No '${x}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${T}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${x}/index.stx for the homepage.${e.reset}`),!1;let k=N(v,{pagesDir:x,pagesDirs:g._layerPageDirs?[T,...g._layerPageDirs.slice(1)]:void 0});if(k.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${T}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${k.length}${e.blue} routes${e.reset}`);let H=g?._pluginPageDirs||[],M=[];for(let{dir:E,prefix:F}of H)if(ve.existsSync(E)){let z=N(ie.dirname(E),{pagesDir:ie.basename(E)});for(let V of z){let we=F==="/"?V.pattern:`${F}${V.pattern==="/"?"":V.pattern}`;M.push({route:{...V,pattern:we},prefix:F})}if(z.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${z.length}${e.blue} routes at ${e.cyan}${F}${e.reset}`)}let I=new Map,R=null,L=null;if(s.stxOptions?.shell!==!1){if(L=await co(p,s.stxOptions?.shell),L){if(R=await Cr(L,s.stxOptions||{}),R)console.log(`${e.blue}Using app shell: ${e.bright}${ie.relative(p,L)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}et(),await nt(p);let B=tt();if(B.length>0)console.log(`${e.blue}Loaded ${e.bright}${B.length}${e.blue} middleware: ${e.dim}${B.join(", ")}${e.reset}`);let G={},oe=null;try{let{loadStxConfig:E}=await import("./chunk-8dbnvypv.js"),F=await E(p);if(F?.apiRouter)oe=F?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(F?.apiRoutes){G=F.apiRoutes;let z=Object.keys(G).length;if(z>0)console.log(`${e.blue}Loaded ${e.bright}${z} API route${z>1?"s":""}${e.reset}`)}if(F?.broadcasting?.enabled)try{let{startBroadcasting:z,loadChannels:V}=await import("./chunk-k4p80n25.js"),we=F.broadcasting;await z(we);let We=we.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${We}/ws${e.reset}`);let Ge=ie.join(process.cwd(),"channels.ts");if(ve.existsSync(Ge))try{let se=await V(Ge);console.log(`${e.blue}Loaded ${e.bright}${se} broadcast channel${se!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(se){console.warn(`${e.yellow}Failed to load channels.ts: ${se.message}${e.reset}`)}}catch(z){console.warn(`${e.yellow}Broadcasting failed to start: ${z.message}${e.reset}`)}}catch{}let Ce=a(p,"output");ve.mkdirSync(Ce,{recursive:!0});let ye=new Map,De=new Set,de=async(E)=>{let F=dr(T,E);if(!F)return null;try{let z=await Bun.build({entrypoints:[F],outdir:Ce,plugins:[ft],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...s.stxOptions});if(!z.success)return null;let V=z.outputs.find((we)=>we.path.endsWith(".html"));if(!V)return null;return await Bun.file(V.path).text()}catch{return null}},W=new Map,j=async(E,F)=>{try{let{processDirectives:z,extractVariables:V,defaultConfig:we,loadStxConfig:We,injectRouterScript:Ge}=await import("./chunk-8dbnvypv.js"),{checkCache:se,cacheTemplate:Q,readFileCached:q,templateCache:J}=await import("./chunk-zc8cz12e.js"),Te=await We(p),Je=(pe)=>{if(!pe)return pe;if(ie.isAbsolute(pe))return pe;return ie.resolve(p,pe)},O={...we,...Te,...s.stxOptions,autoShell:!0};if(s.debugDirectives)O.debug=!0;O.partialsDir=Je(O.partialsDir),O.componentsDir=Je(O.componentsDir),O.layoutsDir=Je(O.layoutsDir),O.storesDir=Je(O.storesDir||"stores"),O.cachePath=Je(O.cachePath)??a(p,"cache");let xe=!F&&!s.profile,ue=O.cache!==!1;if(ue&&xe){let pe=J.get(E.filePath);if(pe)try{if((await ve.promises.stat(E.filePath)).mtime.getTime()<=pe.mtime){let He=!0;for(let Ee of pe.dependencies){if(!ve.existsSync(Ee)){He=!1;break}if((await ve.promises.stat(Ee)).mtime.getTime()>pe.mtime){He=!1;break}}if(He){let Ee=pe.output;if(R)Ee=me(Ee,{preserveHead:!0});let gt=W.get(E.filePath);return{route:E,content:Ee,status:gt?.status??await qn(E.filePath),headers:gt?.headers}}}}catch{}let Ie=await se(E.filePath,O);if(Ie){let je=Ie;if(R)je=me(je,{preserveHead:!0});let He=W.get(E.filePath);return{route:E,content:je,status:He?.status??await qn(E.filePath),headers:He?.headers}}}let he=ue?await q(E.filePath):await Bun.file(E.filePath).text(),Re=Ct(he),{classifyAllScripts:Y}=await import("./chunk-8dbnvypv.js"),Le=Y(he),Ve=Le.server.map((pe)=>pe.content),fe=he;for(let pe of Le.server)fe=fe.replace(pe.fullTag,"");let ge={__filename:E.filePath,__dirname:ie.dirname(E.filePath),__stx_options:O,params:F??{},__stx_runtime_head:{}};for(let pe of Ve)try{await V(pe,ge,E.filePath)}catch(Ie){if(s.stxOptions?.debug)console.error("[stx] variable extraction error",E.filePath,Ie?.message||Ie)}let Ke=new Set,Me;if(s.profile){let pe=performance.now();Me=await z(fe,ge,E.filePath,O,Ke);let Ie=performance.now()-pe,je=ie.relative(p,E.filePath)||E.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else Me=await z(fe,ge,E.filePath,O,Ke);if(!R)Me=await Ge(Me,{router:O.router});{let{interpolateScriptExpressions:pe}=await import("./chunk-fdcrrpgn.js");Me=Me.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${pe(He,ge)}</script>`})}if(R)Me=me(Me,{preserveHead:!0});if(ue&&xe)await Q(E.filePath,Me,Ke,O);let{extractStreamBoundaries:Kn}=await import("./chunk-j00h4d3w.js"),lt=Kn(ge),mt=ge.__streamTemplates;if(mt&&typeof mt==="object"&&Object.keys(mt).length>0){let pe=ge.streamBoundaries||{},Ie={...O,autoShell:!1},je=Object.keys(mt).map((Ee)=>({id:Ee,render:async()=>{let gt=typeof pe[Ee]==="function"?await pe[Ee]():void 0;return z(mt[Ee],{...ge,$boundary:gt},E.filePath,Ie,new Set)}})),He=new Set(je.map((Ee)=>Ee.id));lt=[...(lt||[]).filter((Ee)=>!He.has(Ee.id)),...je]}if(lt&<.length>0)De.add(E.pattern);else lt=void 0;let Kt=Fe(ge),Xt=ze(ge);if(xe)W.set(E.filePath,{status:Kt,headers:Xt});return{route:E,content:Me,status:Kt??Re,headers:Xt,boundaries:lt}}catch(z){return console.error(`${e.red}Error building ${e.bright}${E.pattern}${e.reset}:`,z),null}},Ue=8,qe=async()=>{ye.clear(),I.clear();for(let E=0;E<k.length;E+=Ue){let F=k.slice(E,E+Ue),z=await Promise.all(F.map((V)=>j(V)));for(let V of z)if(V)ye.set(V.route.pattern,V)}for(let E=0;E<M.length;E+=Ue){let F=M.slice(E,E+Ue),z=await Promise.all(F.map(({route:V})=>j(V)));for(let V of z)if(V)I.set(V.route.pattern,V)}return ye.size>0};if(console.log(`${e.blue}Building pages...${e.reset}`),!await qe())return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await kt(p);let at=i;try{if(at=await Ye(i),at!==i)console.log(`${e.yellow}Port ${i} is busy, using port ${at} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(c){let E=s.hmrPort||at+1;l=Pt({wsPort:E,verbose:!1}),m=l.start(E)}let _t=(E,F)=>{let V=`<script data-stx-route-params>(function(){var p=${JSON.stringify(F).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(E.includes("</head>"))return E.replace("</head>",`${V}</head>`);if(E.includes("<body"))return E.replace(/<body([^>]*)>/,`<body$1>${V}`);return V+E};console.log(`${e.blue}Starting server...${e.reset}`);let Lt=Ni({port:at,async fetch(E){let F=new URL(E.url),z=g?.publicDir||"public",V=ie.join(p,z,F.pathname),we=ie.join(p,F.pathname),We=ie.join(Ce,F.pathname);if([V,we,We].some((O)=>w(O,p,S)))return new Response("Not Found",{status:404});let[Ge,se,Q]=await Promise.all([ve.promises.stat(V).catch(()=>null),ve.promises.stat(we).catch(()=>null),ve.promises.stat(We).catch(()=>null)]);if(Ge?.isFile()&&!w(V,p,S))return qt(V);if(se?.isFile()&&!w(we,p,S))return qt(we);if(Q?.isFile()&&!w(We,p,S))return qt(We);if(F.pathname.startsWith("/_stx/component/")){let O=decodeURIComponent(F.pathname.slice(16));if(O)try{let xe=`<${O} />`,ue={...buildConfig,autoShell:!1},he=await processDirectives(xe,{},ie.join(p,"components",`${O}.stx`),ue,new Set);return new Response(he,{headers:{"Content-Type":"text/html"}})}catch(xe){return new Response(`<div class="stx-async-error">${xe.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(F.pathname==="/_stx/img"){let{handleImageRequest:O}=await import("./chunk-v70hfs6d.js"),xe=await O(E,{publicDir:ie.join(p,z),cacheDir:a(p,"cache","img")});if(xe)return xe}if(oe)try{let O=await oe.handleRequest(E);if(O.status!==404)return O}catch{}if(G[F.pathname])try{return await G[F.pathname](E)}catch(O){return new Response(JSON.stringify({error:O.message}),{status:500,headers:{"Content-Type":"application/json"}})}let q=await C(E);if(q)return q;let J=xn(F.pathname,k);if(J){let O=ye.get(J.route.pattern),xe=De.has(J.route.pattern);if(J.route.isDynamic&&Object.keys(J.params).length>0||xe){let ue=await j(J.route,J.params);if(ue)O=ue}if(O){let ue=O.status??200,he=O.headers??{},Re=(J.route.filePath?Be(await Bun.file(J.route.filePath).text().catch(()=>"")):null)??{};if(Re.validate){if(!await Re.validate({params:J.params})){let Ve=await de(404);if(Ve){let fe=Ve;if(fe=await f(fe,p),c)fe=Xe(fe,m);return new Response(fe,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(Re.middleware){let Le=rt(F.pathname,J.params,Re,F.search),Ve=st(Le,null,E,{isServer:!0}),fe=await ot(Re.middleware,Ve);if(fe.redirect){let ge=fe.redirect.path,Ke=fe.redirect.options.redirectCode||302,Me=new Headers(fe.responseHeaders);return Me.set("Location",ge),new Response(null,{status:Ke,headers:Me})}if(fe.abort){let{statusCode:ge,message:Ke}=fe.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${ge}</title></head><body><h1>Error ${ge}</h1><p>${Ke}</p></body></html>`,{status:ge,headers:{"Content-Type":"text/html"}})}if(Object.keys(fe.state).length>0){let ge=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(fe.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;O.content=O.content.replace("</head>",`${ge}</head>`)}}let Y=O.content;if(R&&lo(E)){let Le=ke(Y),Ve=ce(Y),fe=Y.match(/<title[^>]*>([\s\S]*?)<\/title>/i),ge=fe?ao(fe[1].trim()):"";if(Object.keys(J.params).length>0)Y=_t(Y,J.params);Y=await f(Y,p);let Ke=g?.router?.container||"main";return Y=re(Y,Ke),new Response(Y,{status:ue,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Ve?"true":"false",...ge&&{"X-STX-Title":encodeURIComponent(ge)},[fi]:bs(),..._(),"Cache-Control":Ae}})}if(R)Y=An(R,Y);if(Object.keys(J.params).length>0)Y=_t(Y,J.params);if(Y=await f(Y,p),c)Y=Xe(Y,m);if(s.native)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else Y="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+Y;if(s.titlebarHidden)if(Y.includes("<head>"))Y=Y.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else Y=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${Y}`;if(O.boundaries&&O.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Ve}=await import("./chunk-j00h4d3w.js");return Ve(Le(Y,O.boundaries,{timeoutMs:30000}),{status:ue,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(Y,{status:ue,headers:{"Content-Type":"text/html",..._(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...he}})}}if(M.length>0){let O=M.map((ue)=>ue.route),xe=xn(F.pathname,O);if(xe){let ue=I.get(xe.route.pattern);if(ue){let he=ue.content;if(R)he=An(R,he);if(Object.keys(xe.params).length>0)he=_t(he,xe.params);if(he=await f(he,p),c)he=Xe(he,m);return new Response(he,{status:ue.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:ue}of H)if(ue!=="/"&&F.pathname.startsWith(ue)){let he=I.get(ue)||I.get(ue+"/");if(he){let Re=he.content;if(R)Re=An(R,Re);if(Re=await f(Re,p),c)Re=Xe(Re,m);return new Response(Re,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(Qe(F.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Te=ye.get("/");if(Te){let O=Te.content;if(O=await f(O,p),c)O=Xe(O,m);if(s.native)if(O.includes("<head>"))O=O.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else O="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+O;return new Response(O,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let Je=await de(404);if(Je){let O=Je;if(O=await f(O,p),c)O=Xe(O,m);return new Response(O,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(E){let F=await de(500);if(F)return new Response(F,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${E}
|
|
2029
2029
|
${E.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
2030
2030
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
2031
2031
|
${e.bright}\u2192 ${e.cyan}http://localhost:${at}/${e.reset}`),c)console.log(`${e.dim} HMR: ws://localhost:${m}${e.reset}`);console.log(`
|
|
2032
2032
|
${e.yellow}Routes:${e.reset}`);let jt=[...ur(k,p)];for(let{route:E}of M)jt.push(`${E.pattern}`);if(jt.forEach((E,F)=>{let V=F===jt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${V}${e.reset}${E}`)}),console.log(`
|
|
2033
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.url.toString(),()=>{if(l)ht();Lt.stop()}),s.native){let E,F=ie.join(T,"index.stx");if(ve.existsSync(F)){let V=await Bun.file(F).text();E=St(V)}let z=g?.app?.window??{};await dt(at,{title:g?.app?.head?.title||ie.basename(p)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!E,sidebarConfig:E})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let E=(se)=>se.startsWith("public/")||se.startsWith("public\\"),F=(se)=>{let Q=se.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},z=new Map,V=()=>{let se=new Set([p,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let q of Object.values(Q.resources)){if(!ve.existsSync(q))continue;let J=ve.realpathSync(q);if(![...se].some((Te)=>J===Te||J.startsWith(`${Te}${ie.sep}`)))se.add(J)}for(let[Q,q]of z)if(!se.has(Q))q.close(),z.delete(Q);for(let Q of se)if(!z.has(Q)&&ve.existsSync(Q))z.set(Q,ve.watch(Q,{recursive:!0},(q,J)=>{We(Q,q,J).catch((Te)=>console.error("[stx] Layer rebuild failed:",Te))}))},we=Promise.resolve(),We=(se,Q,q)=>(we=we.catch(()=>{}).then(()=>Ge(se,Q,q)),we),Ge=async(se,Q,q)=>{if(!q||Et(q))return;if($t(q)){if(g._layerGraph){let J=await h(p);Object.assign(g,J),k.splice(0,k.length,...N(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[T,...J._layerPageDirs.slice(1)]:void 0})),V()}if(E(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(F(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),be.clear(),ee();try{let{invalidateFileCache:J,templateCache:Te}=await import("./chunk-
|
|
2033
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ze(Lt.url.toString(),()=>{if(l)ht();Lt.stop()}),s.native){let E,F=ie.join(T,"index.stx");if(ve.existsSync(F)){let V=await Bun.file(F).text();E=St(V)}let z=g?.app?.window??{};await dt(at,{title:g?.app?.head?.title||ie.basename(p)||"stx App",width:z.width,height:z.height,darkMode:z.darkMode,hotReload:z.hotReload,titlebarHidden:z.titlebarHidden??s.titlebarHidden===!0,nativeSidebar:!!E,sidebarConfig:E})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let E=(se)=>se.startsWith("public/")||se.startsWith("public\\"),F=(se)=>{let Q=se.toLowerCase();return Q.endsWith(".stx")||Q.endsWith(".html")||Q.endsWith(".md")},z=new Map,V=()=>{let se=new Set([p,...g._layerGraph?.layers.map((Q)=>Q.root)??[],...g._layerGraph?.configDependencies.map((Q)=>ie.dirname(Q))??[]].filter((Q)=>ve.existsSync(Q)).map((Q)=>ve.realpathSync(Q)));for(let Q of g._layerGraph?.layers??[])for(let q of Object.values(Q.resources)){if(!ve.existsSync(q))continue;let J=ve.realpathSync(q);if(![...se].some((Te)=>J===Te||J.startsWith(`${Te}${ie.sep}`)))se.add(J)}for(let[Q,q]of z)if(!se.has(Q))q.close(),z.delete(Q);for(let Q of se)if(!z.has(Q)&&ve.existsSync(Q))z.set(Q,ve.watch(Q,{recursive:!0},(q,J)=>{We(Q,q,J).catch((Te)=>console.error("[stx] Layer rebuild failed:",Te))}))},we=Promise.resolve(),We=(se,Q,q)=>(we=we.catch(()=>{}).then(()=>Ge(se,Q,q)),we),Ge=async(se,Q,q)=>{if(!q||Et(q))return;if($t(q)){if(g._layerGraph){let J=await h(p);Object.assign(g,J),k.splice(0,k.length,...N(v,{pagesDir:x,pagesDirs:J._layerPageDirs?[T,...J._layerPageDirs.slice(1)]:void 0})),V()}if(E(q)){if(console.log(`${e.cyan}${q} changed${e.reset}`),c&&l)l.reload(q)}else if(F(q)){console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),be.clear(),ee();try{let{invalidateFileCache:J,templateCache:Te}=await import("./chunk-zc8cz12e.js");J(ie.resolve(se,q)),Te.delete(ie.resolve(se,q))}catch{}if(L&&q){if(ie.resolve(se,q)===L||ie.basename(L)===q){let Te=await Cr(L,s.stxOptions||{});if(Te)R=Te}}if(await qe(),await sn(p),c&&l)l.reload(q)}else{console.log(`${e.yellow}${q} changed, rebuilding...${e.reset}`),be.clear(),ee();try{let{invalidateFileCache:J,templateCache:Te}=await import("./chunk-zc8cz12e.js");J(ie.resolve(se,q)),Te.delete(ie.resolve(se,q))}catch{}if(await qe(),c&&l)l.reload(q)}}else if(Tt(q)){if(console.log(`${e.cyan}CSS ${q} changed${e.reset}`),c&&l)l.updateCss(q)}};V(),process.on("SIGINT",()=>{for(let se of z.values())se.close();if(l)ht();Lt.stop(),process.exit(0)})}return!0}export{Ks,Xs,Gs,Js,hr,Ys,Zs,Qs,Wi,qi,yr,br,Cn,En,$n};
|
package/dist/cli.js
CHANGED
|
@@ -1,13 +1,13 @@
|
|
|
1
1
|
#!/usr/bin/env bun
|
|
2
2
|
// @bun
|
|
3
|
-
import"./chunk-0ytm2ecf.js";import"./chunk-9mjy16pw.js";import"./chunk-kpns3659.js";import"./chunk-5tyes97j.js";import"./chunk-ba88n1j7.js";import{U}from"./chunk-
|
|
3
|
+
import"./chunk-0ytm2ecf.js";import"./chunk-9mjy16pw.js";import"./chunk-kpns3659.js";import"./chunk-5tyes97j.js";import"./chunk-ba88n1j7.js";import{U}from"./chunk-4mmz9xxh.js";import"./chunk-7p0zerfj.js";import"./chunk-8m3k43d3.js";import"./chunk-6k4f583z.js";import"./chunk-yy19rrw6.js";import"./chunk-e6y6s7q8.js";import"./chunk-299xbyhn.js";import"./chunk-1s7qdv2h.js";import"./chunk-xpvvne6r.js";import"./chunk-jj8ssn0d.js";import"./chunk-d8ramz4s.js";import"./chunk-21rm5kv6.js";import"./chunk-fk45zc1b.js";import"./chunk-7rz4fy4y.js";import"./chunk-x1tzt7yc.js";import"./chunk-baxwjmj3.js";import"./chunk-raqbqt1r.js";import"./chunk-yh3p86qa.js";import"./chunk-hbwmmt91.js";import"./chunk-1c7v7pqv.js";import"./chunk-2twfqcxm.js";import"./chunk-k3tq1k4m.js";import"./chunk-y0c1srgj.js";import"./chunk-6rdnzn77.js";import"./chunk-5zk6kyjt.js";import"./chunk-vbv5jqkz.js";import"./chunk-p8c5g5n2.js";import"./chunk-35j1evvy.js";import"./chunk-f5pmyxtn.js";import"./chunk-2hc5mbw8.js";import{mt,ht}from"./chunk-ycxz2exz.js";import"./chunk-wsjrvxs9.js";import"./chunk-7mg0cybn.js";import"./chunk-v2zxxjqn.js";import"./chunk-869wyw0j.js";import"./chunk-2m5mx0x8.js";import"./chunk-wn5zjs5m.js";import"./chunk-346zc43s.js";import"./chunk-jwgzj5at.js";import"./chunk-s1evrkrv.js";import{Ks,Xs,Gs,Js,hr,Ys,Zs,Qs,yr,br,Cn,En,$n}from"./chunk-ze832cpr.js";import"./chunk-yyb5se8j.js";import"./chunk-1v6yyvxf.js";import{bi}from"./chunk-58jyc7kp.js";import{d}from"./chunk-yn2d8x8m.js";import{spawn as R}from"child_process";import S from"fs";import M from"os";import f from"path";import n from"process";import{CLI as V}from"@stacksjs/clapp";var j="0.2.529";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("["),H=(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 L(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 G(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.join(M.tmpdir(),`stx-test-report-${Date.now()}.xml`);x.push("--reporter",p.reporter),x.push("--reporter-outfile",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 u=((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&&(H(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 En(t,p))n.exit(1)}catch(x){console.error("Failed to process files:",x),n.exit(1)}else Cn(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 Js(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-ktvr45qg.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 u=l;console.log(` ${r.padEnd(30)} ${u.name} (${u.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-fanmabb0.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-fanmabb0.js"),{loadConfig:s}=await import("./chunk-1wp8qb5f.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 U.timeAsync("glob-expansion",async()=>Array.fromAsync(new Bun.Glob(t).scan({onlyFiles:!0,absolute:!0}))),s=t.endsWith(".stx")?i.filter((u)=>u.endsWith(".stx")):t.endsWith(".md")?i.filter((u)=>u.endsWith(".md")):i.filter((u)=>u.endsWith(".stx")||u.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 u=new Bun.Glob("**/*.stx"),m=(await Array.fromAsync(u.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 En(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 Cn(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 bi(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-jagpqt9y.js");ht();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:(u)=>console.log(` Generating: ${u}`),onPageEnd:(u,a)=>console.log(` Generated: ${u} (${a.length} bytes)`),onError:(u,a)=>console.error(` Error in ${a}: ${u.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-9x9bp5w8.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-2bwhc8ea.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),u++}if(e.check&&u>0)console.log(`
|
|
125
125
|
${u} 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){U.clear(),console.log("\u2705 Performance statistics cleared");return}let o=U.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-2p0dbz34.js"),{resolveStxTargets:s}=await import("./chunk-yqh6dny3.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 u=Ks(n.argv,"--lib"),a=u.length>0?u: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 @@ ${u} 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-1e7g79x4.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 u=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/")||u.has(w)||g.has(w))continue;u.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-eadr1eph.js");e=i.generateSignalsRuntime}catch{e=void 0}let o=await yr({generateRuntime:e});if(t.json)console.log(JSON.stringify(o,null,2));else console.log(br(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:`),u.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:u,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-3v2bf157.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-hnn0pdz1.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-jh6nh2m0.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],u=s(l);if(e.format&&!u.includes(e.format))console.error(`\u274C Invalid format for ${l}: ${e.format}`),console.error(`\uD83D\uDCA1 Available formats: ${u.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:L(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-bs2e3g25.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-p4gbvge6.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-wy36z6qp.js"),{runVisualTests:o,updateSnapshots:i,formatTestResults:s}=await import("./chunk-3cn7973z.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-smn7sssc.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-jkd0c82m.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}),u=f.resolve(e.output);if(!S.existsSync(u))S.mkdirSync(u,{recursive:!0});let a=f.basename(t,f.extname(t)),m=e.format==="typescript"?"ts":e.format==="json"?"json":"zig",g=f.join(u,`${a}.${m}`);S.writeFileSync(g,l.code);let b=f.join(u,`${a}.manifest.json`);if(S.writeFileSync(b,JSON.stringify(l.manifest,null,2)),e.sourcemaps&&l.sourceMaps){let w=f.join(u,`${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(u,`${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(`
|
package/dist/craft-entry.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Hr,Ao,Po}from"./chunk-csbft3wz.js";import"./chunk-0ytm2ecf.js";import"./chunk-9mjy16pw.js";import"./chunk-kpns3659.js";import"./chunk-5tyes97j.js";import"./chunk-ba88n1j7.js";import"./chunk-
|
|
2
|
+
import{Hr,Ao,Po}from"./chunk-csbft3wz.js";import"./chunk-0ytm2ecf.js";import"./chunk-9mjy16pw.js";import"./chunk-kpns3659.js";import"./chunk-5tyes97j.js";import"./chunk-ba88n1j7.js";import"./chunk-4mmz9xxh.js";import"./chunk-7p0zerfj.js";import"./chunk-8m3k43d3.js";import"./chunk-6k4f583z.js";import"./chunk-yy19rrw6.js";import"./chunk-e6y6s7q8.js";import"./chunk-299xbyhn.js";import{vd,ko,xd,Sd,Co,zr,Eo,kd,$o,Cd,Ed,_o,To,Ro}from"./chunk-f3y397xy.js";import"./chunk-yyb5se8j.js";import"./chunk-58jyc7kp.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
|
|
3
3
|
`),scripts:t.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
|
|
5
5
|
`),scripts:t.scripts.join(`
|
package/dist/craft.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Hr,Ao,Po}from"./chunk-csbft3wz.js";import"./chunk-0ytm2ecf.js";import"./chunk-9mjy16pw.js";import"./chunk-kpns3659.js";import"./chunk-5tyes97j.js";import"./chunk-ba88n1j7.js";import"./chunk-
|
|
2
|
+
import{Hr,Ao,Po}from"./chunk-csbft3wz.js";import"./chunk-0ytm2ecf.js";import"./chunk-9mjy16pw.js";import"./chunk-kpns3659.js";import"./chunk-5tyes97j.js";import"./chunk-ba88n1j7.js";import"./chunk-4mmz9xxh.js";import"./chunk-7p0zerfj.js";import"./chunk-8m3k43d3.js";import"./chunk-6k4f583z.js";import"./chunk-yy19rrw6.js";import"./chunk-e6y6s7q8.js";import"./chunk-299xbyhn.js";import{vd,ko,xd,Sd,Co,zr,Eo,kd,$o,Cd,Ed,_o,To,Ro}from"./chunk-f3y397xy.js";import"./chunk-yyb5se8j.js";import"./chunk-58jyc7kp.js";var m=new Map,d=new Map;function R(t,e){let n=e?.id||E(t),r=I(t),a=m.get(n);if(a&&a.hash===r)return a;let i=M(t),s=L(t),o=W(t),c=O(i),{staticParts:p,dynamicParts:l}=A(i),f=_(t),g={id:n,hash:r,tree:i,scripts:s,styles:o,staticParts:p,dynamicParts:l,dependencies:f,metadata:c};return m.set(n,g),g}async function Q(t,e={},n={}){let r=performance.now();if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`,c=d.get(o);if(c&&Date.now()-c.timestamp<(n.cacheTTL||60000))return{html:c.html,styles:t.styles.join(`
|
|
3
3
|
`),scripts:t.scripts.join(`
|
|
4
4
|
`),metadata:{renderTime:0,cacheHit:!0,totalSize:c.html.length,componentCount:t.metadata.componentCount}}}let a;if(n.streaming)a=await H(t.tree,e);else a=h(t.tree,e);let i;if(n.hydrate){let o=j(a,t,e);a=o.html,i=o.data}if(n.minify)a=D(a);if(n.cache){let o=`${t.id}:${JSON.stringify(e)}`;d.set(o,{html:a,timestamp:Date.now()})}let s=performance.now()-r;return{html:a,styles:t.styles.join(`
|
|
5
5
|
`),scripts:t.scripts.join(`
|