@stacksjs/stx 0.2.686 → 0.2.689
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-7gprzmd9.js → chunk-0s6kqr1h.js} +1 -1
- package/dist/chunk-1w15scke.js +2 -0
- package/dist/{chunk-vewm4kr8.js → chunk-280pa4mp.js} +1 -1
- package/dist/{chunk-dnbdxbkb.js → chunk-2h39d4wz.js} +5 -5
- package/dist/chunk-2khba4de.js +2 -0
- package/dist/{chunk-ywpyxqn5.js → chunk-3t8aag0q.js} +1 -1
- package/dist/{chunk-exbs8qm6.js → chunk-3tv5h9xn.js} +1 -1
- package/dist/{chunk-1rgjy80j.js → chunk-4cnphtcz.js} +2 -2
- package/dist/{chunk-yf42bhjw.js → chunk-4mnynzf6.js} +2 -2
- package/dist/{chunk-dbxq6fd7.js → chunk-5grcasys.js} +1 -1
- package/dist/{chunk-x828kq22.js → chunk-5k013c4h.js} +1 -1
- package/dist/{chunk-7w7e24e9.js → chunk-5tkby4j6.js} +1 -1
- package/dist/{chunk-j7phk6kh.js → chunk-60aezg8h.js} +1 -1
- package/dist/{chunk-67v3rh14.js → chunk-623w7x5z.js} +2 -2
- package/dist/{chunk-xw0cqb5m.js → chunk-6eazxhpe.js} +61 -61
- package/dist/{chunk-6te346zf.js → chunk-736bs5xa.js} +1 -1
- package/dist/{chunk-pf25jb54.js → chunk-81meeqhp.js} +4 -4
- package/dist/{chunk-s84zv8ky.js → chunk-84fn7myr.js} +1 -1
- package/dist/{chunk-kqzrm2ym.js → chunk-89m0kxj9.js} +5 -5
- package/dist/{chunk-dv8a3gp8.js → chunk-9629wqte.js} +1 -1
- package/dist/chunk-98sa3jgn.js +2 -0
- package/dist/{chunk-0y2hkbc6.js → chunk-9ed0hr7y.js} +1 -1
- package/dist/chunk-9jwxj1yr.js +2 -0
- package/dist/chunk-a3s7tqsp.js +2 -0
- package/dist/{chunk-51fqvchq.js → chunk-a81452y9.js} +2 -2
- package/dist/{chunk-hxnvcvkz.js → chunk-b13rac0d.js} +1 -1
- package/dist/{chunk-cge9pgyb.js → chunk-bsnactb2.js} +1 -1
- package/dist/{chunk-bg6t69qq.js → chunk-bwcejt6t.js} +1 -1
- package/dist/{chunk-90ggz2m1.js → chunk-cbbheh2r.js} +1 -1
- package/dist/chunk-dr7j2a0t.js +2 -0
- package/dist/{chunk-fw12pvmr.js → chunk-eq9s8dcp.js} +4 -4
- package/dist/chunk-ezj2c0gk.js +2 -0
- package/dist/chunk-gjj8krdx.js +2 -0
- package/dist/{chunk-0nt17nas.js → chunk-hyk31r03.js} +1 -1
- package/dist/{chunk-a7hcwkjz.js → chunk-j7ktb5se.js} +2 -2
- package/dist/{chunk-4dzh6g52.js → chunk-jdb6qhat.js} +1 -1
- package/dist/{chunk-n4qp4q2x.js → chunk-kkxwgx4n.js} +1 -1
- package/dist/{chunk-9c3x72qy.js → chunk-km9qyqqm.js} +1 -1
- package/dist/{chunk-w0zrp51m.js → chunk-m2vm06rh.js} +1 -1
- package/dist/{chunk-f4fxj7xg.js → chunk-m7ce359r.js} +1 -1
- package/dist/chunk-mj3y2dhh.js +2 -0
- package/dist/{chunk-d9esaahz.js → chunk-mm6xx4pm.js} +2 -2
- package/dist/{chunk-ffwvbqkp.js → chunk-mxpmt6wm.js} +1 -1
- package/dist/{chunk-z10ffhzy.js → chunk-ne7rbqw4.js} +1 -1
- package/dist/{chunk-ymjpqt50.js → chunk-p7j8y51n.js} +1 -1
- package/dist/{chunk-840waqpm.js → chunk-q3kg8dde.js} +1 -1
- package/dist/{chunk-yqgrjf9q.js → chunk-qa2mkh94.js} +1 -1
- package/dist/{chunk-jq4h969v.js → chunk-qm61depd.js} +1 -1
- package/dist/{chunk-fndg9ar3.js → chunk-qw2skxm6.js} +1 -1
- package/dist/{chunk-em77nd40.js → chunk-rcr7tncg.js} +1 -1
- package/dist/{chunk-58m0kfb3.js → chunk-rvebwzdj.js} +1 -1
- package/dist/{chunk-dxcn65hq.js → chunk-ryg1ww7v.js} +1 -1
- package/dist/{chunk-xp2cn23j.js → chunk-s6vn2w80.js} +1 -1
- package/dist/{chunk-5ahrdnm0.js → chunk-sbad32da.js} +1 -1
- package/dist/{chunk-av02901t.js → chunk-tbrznnt4.js} +1 -1
- package/dist/{chunk-jdhdae0h.js → chunk-v1qkdg8f.js} +1 -1
- package/dist/chunk-xzpwfs7n.js +2 -0
- package/dist/chunk-y4kzqam8.js +2 -0
- package/dist/{chunk-1x0pf3sw.js → chunk-yn9dwq2b.js} +1 -1
- package/dist/{chunk-4j9p27kn.js → chunk-ys6a6azq.js} +1 -1
- package/dist/{chunk-v6wa51js.js → chunk-ys6zjdfc.js} +3 -3
- package/dist/{chunk-4cksc4n3.js → chunk-zgwp7pdp.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/menubar.d.ts +1 -0
- package/dist/menubar.js +27 -5
- package/dist/native/runtime/native-host.js +4 -0
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/dist/utils.js +2 -2
- package/package.json +5 -5
- package/dist/chunk-31jvtxpx.js +0 -2
- package/dist/chunk-4ntt6d6q.js +0 -2
- package/dist/chunk-71d927c6.js +0 -2
- package/dist/chunk-ebmcecyh.js +0 -2
- package/dist/chunk-ejphs9fs.js +0 -2
- package/dist/chunk-gyye3mcb.js +0 -2
- package/dist/chunk-k8b4fme9.js +0 -2
- package/dist/chunk-q4jpjjdc.js +0 -2
- package/dist/chunk-rz0kkfd3.js +0 -2
- package/dist/chunk-t2eadw9a.js +0 -2
- package/dist/chunk-z0r4vm2m.js +0 -2
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{x}from"./chunk-
|
|
2
|
+
import{x}from"./chunk-6eazxhpe.js";import{o}from"./chunk-2h39d4wz.js";import p from"fs";import g from"path";import*as y from"readline";var e={reset:"\x1B[0m",bold:"\x1B[1m",dim:"\x1B[2m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m"},u={help:{description:"Show available commands",usage:"help [command]",handler:async(t,n)=>{if(t[0]&&u[t[0]]){let r=u[t[0]];console.log(`
|
|
3
3
|
${e.bold}${t[0]}${e.reset} - ${r.description}`),console.log(` Usage: ${e.cyan}${r.usage}${e.reset}
|
|
4
4
|
`)}else{console.log(`
|
|
5
5
|
${e.bold}Available Commands:${e.reset}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{F,Ie}from"./chunk-
|
|
2
|
+
import{F,Ie}from"./chunk-6eazxhpe.js";var o=/\b(?:state|derived|effect|batch|ref|reactive|computed|watch|watchEffect)\s*(?:<[^>]*>)?\s*\(/;function u(t,e,r){let i={fullTag:r,content:e,attrs:t};if(/\bserver\b/.test(t))return{...i,type:"server"};if(/\bdata-stx-scoped\b/.test(t))return{...i,type:"client"};if(o.test(e))return{...i,type:"signals"};if(/\bclient\b/.test(t)||/\btype\s*=\s*["']module["']/.test(t)||/\bsrc\s*=/.test(t))return{...i,type:"client"};return{...i,type:"server"}}var S=/^<script\b([^>]*)>([\s\S]*)<\/script\s*>$/i;function Gt(t){let e=[],r=[],i=[],c=0;while(c<t.length){let s=t.indexOf("<",c);if(s===-1)break;let p=Ie(t,s);if(p>s){c=p;continue}let a=F(t,s);if(a>s){let f=t.slice(s,a),l=S.exec(f);if(l){let n=u(l[1],l[2],f);switch(n.type){case"signals":e.push(n);break;case"client":r.push(n);break;case"server":i.push(n);break}}c=a;continue}c=s+(t.startsWith("<!--",s)?4:1)}return{signals:e,client:r,server:i}}
|
|
3
3
|
export{Gt};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{yn,A}from"./chunk-t6m5d64b.js";import m from"fs";import e from"path";async function hn(r,o,i){if(r.__stx_runtime_config)return;let n=yn();if(n||i){r.__stx_runtime_config=n??A(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{yn,A}from"./chunk-t6m5d64b.js";import m from"fs";import e from"path";async function hn(r,o,i){if(r.__stx_runtime_config)return;let n=yn();if(n||i){r.__stx_runtime_config=n??A(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-5tkby4j6.js"),c=await f(t);if(c.runtimeConfig)r.__stx_runtime_config=A(c.runtimeConfig);return}let s=e.dirname(t);if(s===t)return;t=s}}async function Vo(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,4 +1,4 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{x}from"./chunk-
|
|
2
|
+
import{x}from"./chunk-6eazxhpe.js";import{ce}from"./chunk-bz3zn6f7.js";function g(e,t){let r={};for(let n of e)r[n]=ce(t(n));return new Proxy({},{get:(n,a)=>r[a]?.(),set:(n,a,o)=>{if(r[a])r[a].set(o);else r[a]=ce(o);return!0},has:(n,a)=>(a in r),deleteProperty:(n,a)=>(delete r[a],!0),ownKeys:()=>Reflect.ownKeys(r),getOwnPropertyDescriptor:(n,a)=>(a in r)?{enumerable:!0,configurable:!0,writable:!0,value:r[a]()}:void 0})}function v(e,t){let r={};for(let n of t)r[n]=e[n];return r}function Fi(e,t){let r=Object.keys(e),n=g(r,(i)=>t?.[i]??e[i].getDefaultValue()),a=g(r,()=>[]),o=g(r,()=>!1),c=g(r,()=>!1),f=g(r,()=>!1),s=ce(!1);async function u(i){f[i]=!0;let d=await e[i].validate(n[i],n);return a[i]=d,f[i]=!1,d.length===0}async function l(){s.set(!0);let i=await Promise.all(r.map(u));return s.set(!1),i.every(Boolean)}function m(){for(let i of r)n[i]=t?.[i]??e[i].getDefaultValue(),a[i]=[],o[i]=!1,c[i]=!1}function h(i){for(let d of r)if(d in i)n[d]=i[d],c[d]=!0}function b(i,d){n[i]=d,c[i]=!0}function y(i,d=!0){if(o[i]=d,d)u(i)}function p(i){return{value:n[i],errors:a[i],touched:o[i],dirty:c[i],valid:a[i].length===0,validating:f[i]}}function V(i){return async(d)=>{d?.preventDefault?.();for(let w of r)o[w]=!0;if(await l())await i(v(n,r))}}return{values:n,errors:a,touched:o,dirty:c,get isValid(){return r.every((i)=>a[i].length===0)},get isValidating(){return s()||r.some((i)=>f[i])},get isDirty(){return r.some((i)=>c[i])},validate:l,validateField:u,reset:m,setValues:h,setFieldValue:b,setFieldTouched:y,getFieldState:p,handleSubmit:V}}var il=Fi;class On{rules=[];defaultValue="";addRule(e){let t=new On;return t.rules=[...this.rules,e],t.defaultValue=this.defaultValue,t}required(e="This field is required"){return this.addRule({name:"required",message:e,validate:(t)=>{if(t===null||t===void 0)return e;if(typeof t==="string"&&t.trim()==="")return e;if(Array.isArray(t)&&t.length===0)return e;return!0}})}email(e="Please enter a valid email"){return this.addRule({name:"email",message:e,validate:(t)=>{if(!t)return!0;return/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(String(t))||e}})}url(e="Please enter a valid URL"){return this.addRule({name:"url",message:e,validate:(t)=>{if(!t)return!0;try{return new URL(String(t)),!0}catch{return e}}})}min(e,t){let r=t||`Must be at least ${e} characters`;return this.addRule({name:"min",message:r,validate:(n)=>{if(!n)return!0;return String(n).length>=e||r}})}max(e,t){let r=t||`Must be no more than ${e} characters`;return this.addRule({name:"max",message:r,validate:(n)=>{if(!n)return!0;return String(n).length<=e||r}})}length(e,t,r){let n=r||`Must be between ${e} and ${t} characters`;return this.addRule({name:"length",message:n,validate:(a)=>{if(!a)return!0;let o=String(a).length;return o>=e&&o<=t||n}})}pattern(e,t="Invalid format"){return this.addRule({name:"pattern",message:t,validate:(r)=>{if(!r)return!0;return e.test(String(r))||t}})}hasUppercase(e="Must contain an uppercase letter"){return this.pattern(/[A-Z]/,e)}hasLowercase(e="Must contain a lowercase letter"){return this.pattern(/[a-z]/,e)}hasNumber(e="Must contain a number"){return this.pattern(/\d/,e)}hasSpecial(e="Must contain a special character"){return this.pattern(/[!@#$%^&*(),.?":{}|<>]/,e)}alphanumeric(e="Only letters and numbers allowed"){return this.pattern(/^[a-zA-Z0-9]+$/,e)}startsWithLetter(e="Must start with a letter"){return this.pattern(/^[a-zA-Z]/,e)}noSpaces(e="Spaces are not allowed"){return this.addRule({name:"noSpaces",message:e,validate:(t)=>{if(!t)return!0;return!String(t).includes(" ")||e}})}number(e="Must be a number"){let t=this.addRule({name:"number",message:e,validate:(r)=>{if(!r&&r!==0)return!0;return!Number.isNaN(Number(r))||e}});return t.defaultValue=0,t}integer(e="Must be a whole number"){return this.addRule({name:"integer",message:e,validate:(t)=>{if(!t&&t!==0)return!0;return Number.isInteger(Number(t))||e}})}positive(e="Must be a positive number"){return this.addRule({name:"positive",message:e,validate:(t)=>{if(!t&&t!==0)return!0;return Number(t)>0||e}})}negative(e="Must be a negative number"){return this.addRule({name:"negative",message:e,validate:(t)=>{if(!t&&t!==0)return!0;return Number(t)<0||e}})}minValue(e,t){let r=t||`Must be at least ${e}`;return this.addRule({name:"minValue",message:r,validate:(n)=>{if(!n&&n!==0)return!0;return Number(n)>=e||r}})}maxValue(e,t){let r=t||`Must be no more than ${e}`;return this.addRule({name:"maxValue",message:r,validate:(n)=>{if(!n&&n!==0)return!0;return Number(n)<=e||r}})}between(e,t,r){let n=r||`Must be between ${e} and ${t}`;return this.addRule({name:"between",message:n,validate:(a)=>{if(!a&&a!==0)return!0;let o=Number(a);return o>=e&&o<=t||n}})}matches(e,t){let r=t||`Must match ${e}`;return this.addRule({name:"matches",message:r,validate:(n,a)=>{if(!a)return!0;return n===a[e]||r}})}oneOf(e,t){let r=t||`Must be one of: ${e.join(", ")}`;return this.addRule({name:"oneOf",message:r,validate:(n)=>{if(!n)return!0;return e.includes(n)||r}})}notOneOf(e,t){let r=t||`Cannot be one of: ${e.join(", ")}`;return this.addRule({name:"notOneOf",message:r,validate:(n)=>{if(!n)return!0;return!e.includes(n)||r}})}date(e="Must be a valid date"){return this.addRule({name:"date",message:e,validate:(t)=>{if(!t)return!0;let r=new Date(String(t));return!Number.isNaN(r.getTime())||e}})}before(e,t){let r=new Date(e),n=t||`Must be before ${r.toLocaleDateString()}`;return this.addRule({name:"before",message:n,validate:(a)=>{if(!a)return!0;return new Date(String(a))<r||n}})}after(e,t){let r=new Date(e),n=t||`Must be after ${r.toLocaleDateString()}`;return this.addRule({name:"after",message:n,validate:(a)=>{if(!a)return!0;return new Date(String(a))>r||n}})}custom(e,t="Invalid value"){return this.addRule({name:"custom",message:t,validate:e})}async(e,t="Invalid value"){return this.addRule({name:"async",message:t,async:!0,validate:e})}when(e,t){let r=new On;r.rules=[...this.rules],r.defaultValue=this.defaultValue;for(let n of t.getRules())r.rules.push({...n,validate:(a,o)=>{if(!e(a,o||{}))return!0;return n.validate(a,o)}});return r}getRules(){return this.rules}getDefaultValue(){return this.defaultValue}default(e){let t=new On;return t.rules=[...this.rules],t.defaultValue=e,t}async validate(e,t){let r=[];for(let n of this.rules){let a=await n.validate(e,t);if(a!==!0)r.push(a)}return r}validateSync(e,t){let r=[];for(let n of this.rules){if(n.async)continue;let a=n.validate(e,t);if(a!==!0)r.push(a)}return r}}var id=new On;function al(e,t,r){let n=/@error\s*\(\s*([^)]+)\s*\)([\s\S]*?)@enderror/g;return e.replace(n,(a,o,c)=>{try{let f=o.trim().split("."),s=t;for(let l of f)if(s&&typeof s==="object"&&l in s)s=s[l];else return"";let u=s;if(!u||!Array.isArray(u)||u.length===0)return"";return u.map((l)=>x(c,{...t,message:l},r)).join(`
|
|
3
3
|
`)}catch{return""}})}function cl(e,t,r){let n=/@errors\s*\(\s*([^)]+)\s*\)([\s\S]*?)@enderrors/g;return e.replace(n,(a,o,c)=>{try{let f=o.trim().split("."),s=t;for(let l of f)if(s&&typeof s==="object"&&l in s)s=s[l];else return"";let u=s;if(!u||!Array.isArray(u)||u.length===0)return"";return u.map((l)=>x(c,{...t,message:l},r)).join(`
|
|
4
4
|
`)}catch{return""}})}function ll(e,t,r){let n=/@hasErrors\s*\(\s*([^)]+)\s*\)([\s\S]*?)@endhasErrors/g;return e.replace(n,(a,o,c)=>{try{let f=o.trim().split("."),s=t;for(let l of f)if(s&&typeof s==="object"&&l in s)s=s[l];else return"";let u=s;if(!u||!Array.isArray(u)||u.length===0)return"";return c}catch{return""}})}function ad(e,t,r){let n=e;return n=al(n,t,r),n=cl(n,t,r),n=ll(n,t,r),n}export{Fi,il,On,id,al,cl,ll,ad};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Mc,$i,Lu,Lc,jc,ju,Bu}from"./chunk-qm61depd.js";import"./chunk-3t8aag0q.js";import"./chunk-mxpmt6wm.js";import"./chunk-hyk31r03.js";import"./chunk-374nhgyf.js";import"./chunk-a81452y9.js";import"./chunk-eq9s8dcp.js";import"./chunk-jgxzbthg.js";import"./chunk-4cnphtcz.js";import"./chunk-9ed0hr7y.js";import"./chunk-tenbwcts.js";import"./chunk-912r15hr.js";import"./chunk-ygb33q5w.js";import"./chunk-kypwg2ws.js";import{Rt,Wl}from"./chunk-6eazxhpe.js";import"./chunk-bwcejt6t.js";import"./chunk-t6m5d64b.js";import"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{Mc as buildVirtualSource,Rt as extractScriptBlocks,Wl as extractTemplateExpressions,Lc as findRuntimeTypeDeclarations,jc as findStxModuleDeclarations,Bu as formatTypecheckDiagnostics,Lu as sourcePathFor,ju as typecheckStxFiles,$i as virtualPathFor};
|
|
@@ -1,14 +1,14 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{nr}from"./chunk-kypwg2ws.js";import{gr}from"./chunk-r0ys9aqa.js";import{i}from"./chunk-
|
|
2
|
+
import{nr}from"./chunk-kypwg2ws.js";import{gr}from"./chunk-r0ys9aqa.js";import{i}from"./chunk-4cnphtcz.js";import{K,Ge}from"./chunk-yft8yn6y.js";import{fa}from"./chunk-k3e0hcv7.js";var p=/<style\b[^>]*>/iy,x=/<\/style>/gi,R=/<script\b[^>]*>/iy,b=/<template(?=[\s>/])[^>]*>/iy,S=/<\/template\s*>/iy;function Jn(e){let r=0,t=0,o=-1;while(r<e.length){let n=e.indexOf("<",r);if(n===-1)return-1;if(e.startsWith("<!--",n)){let d=e.indexOf("-->",n+4);r=d===-1?e.length:d+3;continue}p.lastIndex=n;let u=p.exec(e);if(u){x.lastIndex=n+u[0].length;let d=x.exec(e);r=d===null?e.length:d.index+8;continue}b.lastIndex=n;let c=b.exec(e);if(c){if(t===0)o=n;t++,r=n+c[0].length;continue}S.lastIndex=n;let a=S.exec(e);if(a){if(t>0)t--;r=n+a[0].length;continue}if(R.lastIndex=n,R.test(e))return t>0?o:n;r=n+1}return-1}function q(e,r={}){return new nr(e,r).routes}import w from"path";var T=new Map;async function y(e,r){let t=e,o=r;if(!t||!o)try{let a=await i();t||=a?.pagesDir||"pages",o||=a?.root||"."}catch{t||="pages",o||="."}let n=w.isAbsolute(t)?t:w.join(o,t),u=T.get(n);if(u)return u;let c=[];try{c=q(".",{pagesDir:n,emit:!1}).map((a)=>a.regex.source).filter(Boolean)}catch{c=[]}return T.set(n,c),c}function O(e){return e.replace(/</g,"\\u003c").replace(/>/g,"\\u003e").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function l(e){return O(JSON.stringify(e))}function he(e){return e.includes("data-stx-runtime")}function da(e){let r=/window\.stx\s*\.\s*[A-Za-z_$]|\}\s*=\s*window\.stx\s*;/g;for(let t=r.exec(e);t!==null;t=r.exec(e)){let o=e.slice(Math.max(0,t.index-80),t.index);if(/if\s*\(\s*window\.stx\s*\)|window\.stx\s*&&/.test(o))continue;return!0}return!1}function f(e,r){let t=Jn(e),o=e.search(/<!doctype\b/i);if(t!==-1&&(o===-1||t>o))return e.slice(0,t)+r+`
|
|
3
3
|
`+e.slice(t);let n=gr(e);if(n!==null)return`${e.slice(0,n)}
|
|
4
4
|
${r}${e.slice(n)}`;if(e.includes("</head>")){let c=e.indexOf("</head>");return e.slice(0,c)+r+`
|
|
5
5
|
`+e.slice(c)}if(K(e))return Ge(e,(c)=>`${c}
|
|
6
6
|
${r}`);return`${r}
|
|
7
|
-
${e}`}async function Yn(e,r){if(e.includes("data-stx-runtime")||e.includes("window.stx.state")||e.includes("STX Signals Runtime"))return e;if(r.buildMode==="serve"){let{getServeClientAsset:n}=await import("./chunk-
|
|
7
|
+
${e}`}async function Yn(e,r){if(e.includes("data-stx-runtime")||e.includes("window.stx.state")||e.includes("STX Signals Runtime"))return e;if(r.buildMode==="serve"){let{getServeClientAsset:n}=await import("./chunk-60aezg8h.js"),{url:u}=await n("runtime",r.debug===!0);return f(e,`<script data-stx-runtime src="${u}"></script>`)}if(r.buildMode==="compile")return f(e,'<script data-stx-runtime src="/__stx/runtime.__STX_HASH__.js"></script>');let{getCachedSignalsRuntime:t}=await import("./chunk-60aezg8h.js"),o=await t(r.debug);return f(e,`<script data-stx-scoped data-stx-runtime>${o}</script>`)}function m(e){return/<[a-z][^>]*?\sx-tooltip\s*=/i.test(e)}function pa(e){if(e.includes("data-stx-tooltip-runtime")||!m(e))return e;let r=`<script data-stx-scoped data-stx-tooltip-runtime>${fa()}</script>`,t=e.lastIndexOf("</body>");if(t===-1)return`${e}
|
|
8
8
|
${r}`;return`${e.slice(0,t)}${r}
|
|
9
|
-
${e.slice(t)}`}var E=/<script\b[^>]*\sdata-stx-router(?=[\s=>])/i;function C(e){return E.test(e)||e.includes("__stxRouter)return")||e.includes("__stxRouter=true")}async function ye(e,r){if(!e.includes("</body>"))return e;if(C(e))return e;let t=r?.router,o="",n="";{let s={};if(t){if(t.container)s.container=t.container;if(t.interceptAllLinks!==void 0)s.interceptAllLinks=t.interceptAllLinks;if(t.progress!==void 0)s.progress=t.progress;if(t.viewTransitions!==void 0)s.viewTransitions=t.viewTransitions;if(t.viewTransitionDuration!==void 0)s.viewTransitionDuration=t.viewTransitionDuration;if(t.viewTransitionEasing!==void 0)s.viewTransitionEasing=t.viewTransitionEasing;if(t.scrollToTop!==void 0)s.scrollToTop=t.scrollToTop;if(t.scrollRestoration!==void 0)s.scrollRestoration=t.scrollRestoration;if(t.prefetch!==void 0)s.prefetch=t.prefetch;if(t.cache!==void 0)s.cache=t.cache;if(t.progressColor!==void 0)s.progressColor=t.progressColor;if(t.progressHeight!==void 0)s.progressHeight=t.progressHeight;if(t.prefetchVisible!==void 0)s.prefetchVisible=t.prefetchVisible;if(t.prefetchVisibleMax!==void 0)s.prefetchVisibleMax=t.prefetchVisibleMax;if(t.keepOpening!==void 0)s.keepOpening=t.keepOpening}try{let g=await y(r?.pagesDir,r?.root);if(g.length>0)if(r?.buildMode==="serve"){let{registerServeModuleBundle:h}=await import("./chunk-
|
|
9
|
+
${e.slice(t)}`}var E=/<script\b[^>]*\sdata-stx-router(?=[\s=>])/i;function C(e){return E.test(e)||e.includes("__stxRouter)return")||e.includes("__stxRouter=true")}async function ye(e,r){if(!e.includes("</body>"))return e;if(C(e))return e;let t=r?.router,o="",n="";{let s={};if(t){if(t.container)s.container=t.container;if(t.interceptAllLinks!==void 0)s.interceptAllLinks=t.interceptAllLinks;if(t.progress!==void 0)s.progress=t.progress;if(t.viewTransitions!==void 0)s.viewTransitions=t.viewTransitions;if(t.viewTransitionDuration!==void 0)s.viewTransitionDuration=t.viewTransitionDuration;if(t.viewTransitionEasing!==void 0)s.viewTransitionEasing=t.viewTransitionEasing;if(t.scrollToTop!==void 0)s.scrollToTop=t.scrollToTop;if(t.scrollRestoration!==void 0)s.scrollRestoration=t.scrollRestoration;if(t.prefetch!==void 0)s.prefetch=t.prefetch;if(t.cache!==void 0)s.cache=t.cache;if(t.progressColor!==void 0)s.progressColor=t.progressColor;if(t.progressHeight!==void 0)s.progressHeight=t.progressHeight;if(t.prefetchVisible!==void 0)s.prefetchVisible=t.prefetchVisible;if(t.prefetchVisibleMax!==void 0)s.prefetchVisibleMax=t.prefetchVisibleMax;if(t.keepOpening!==void 0)s.keepOpening=t.keepOpening}try{let g=await y(r?.pagesDir,r?.root);if(g.length>0)if(r?.buildMode==="serve"){let{registerServeModuleBundle:h}=await import("./chunk-60aezg8h.js");n=`<script data-stx-owned-routes src="${h(`(window.__stxRouterConfig=window.__stxRouterConfig||{}).ownedRoutes=${l(g)};
|
|
10
10
|
`)}"></script>
|
|
11
11
|
`}else s.ownedRoutes=g}catch{}if(Object.keys(s).length>0)o=`<script>window.__stxRouterConfig=${l(s)};</script>
|
|
12
|
-
`}let{getCachedRouterScript:u,getServeClientAsset:c}=await import("./chunk-
|
|
12
|
+
`}let{getCachedRouterScript:u,getServeClientAsset:c}=await import("./chunk-60aezg8h.js"),a=r?.buildMode==="compile"?'<script data-stx-router src="/__stx/router.__STX_HASH__.js"></script>':r?.buildMode==="serve"?`<script data-stx-router src="${(await c("router")).url}"></script>`:`<script data-stx-router>${await u()}</script>`,d=e.lastIndexOf("</body>");return e.slice(0,d)+o+n+a+`
|
|
13
13
|
</body>`+e.slice(d+7)}
|
|
14
14
|
export{Jn,q,he,da,Yn,pa,ye};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ou}from"./chunk-km9qyqqm.js";import"./chunk-mm6xx4pm.js";import"./chunk-bsnactb2.js";import"./chunk-hyk31r03.js";import"./chunk-eq9s8dcp.js";import"./chunk-4cnphtcz.js";import"./chunk-9ed0hr7y.js";import"./chunk-tenbwcts.js";import"./chunk-912r15hr.js";import"./chunk-ygb33q5w.js";import"./chunk-kypwg2ws.js";import"./chunk-6eazxhpe.js";import"./chunk-bwcejt6t.js";import"./chunk-t6m5d64b.js";import"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{Ou as startProductionServer};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ec,Tc}from"./chunk-89m0kxj9.js";import"./chunk-b13rac0d.js";import"./chunk-km9qyqqm.js";import"./chunk-xr9a0hcr.js";import"./chunk-km37yrk4.js";import"./chunk-qm61depd.js";import"./chunk-58dv14c3.js";import"./chunk-9629wqte.js";import"./chunk-mm6xx4pm.js";import"./chunk-5tbey00z.js";import"./chunk-xvnrm5c3.js";import"./chunk-m7ce359r.js";import"./chunk-f4z9w4kc.js";import"./chunk-sbad32da.js";import"./chunk-brftzqzj.js";import"./chunk-cjf01cp4.js";import"./chunk-3zbege39.js";import"./chunk-cbbheh2r.js";import"./chunk-pzxy40a2.js";import"./chunk-280pa4mp.js";import"./chunk-qh7fvr2z.js";import"./chunk-ae12wgc5.js";import"./chunk-d7js6v1m.js";import"./chunk-ry501z40.js";import"./chunk-974prn41.js";import"./chunk-d1ssvg9k.js";import"./chunk-s6vn2w80.js";import"./chunk-3t8aag0q.js";import"./chunk-ct0ee0fr.js";import"./chunk-4mnynzf6.js";import"./chunk-03xn8244.js";import"./chunk-rspe6qa5.js";import{Gt}from"./chunk-bsnactb2.js";import"./chunk-mxpmt6wm.js";import"./chunk-hyk31r03.js";import"./chunk-374nhgyf.js";import{$e,o}from"./chunk-2h39d4wz.js";import"./chunk-623w7x5z.js";import"./chunk-9bgb9n12.js";import"./chunk-ryg1ww7v.js";import"./chunk-81meeqhp.js";import"./chunk-kkxwgx4n.js";import"./chunk-hx787tfa.js";import"./chunk-a81452y9.js";import{ye}from"./chunk-eq9s8dcp.js";import"./chunk-jgxzbthg.js";import{Zn,Qn}from"./chunk-rvebwzdj.js";import{Jr,N,i}from"./chunk-4cnphtcz.js";import"./chunk-9ed0hr7y.js";import"./chunk-tenbwcts.js";import"./chunk-912r15hr.js";import"./chunk-ygb33q5w.js";import"./chunk-kypwg2ws.js";import{g,De}from"./chunk-6eazxhpe.js";import"./chunk-bwcejt6t.js";import"./chunk-t6m5d64b.js";import"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";import"./chunk-b7z6rqfg.js";import"./chunk-drabexxq.js";export{Jr as buildWebComponents,Qn as cacheTemplate,Zn as checkCache,Gt as classifyAllScripts,Ec as createMiddleware,Tc as createRoute,N as defaultConfig,g as extractVariables,ye as injectRouterScript,i as loadStxConfig,De as processClientScript,o as processDirectives,$e as readMarkdownFile};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{le}from"./chunk-kypwg2ws.js";import{Be,A}from"./chunk-t6m5d64b.js";import{Sa}from"./chunk-912r15hr.js";import{c}from"./chunk-xvs84gas.js";import S from"fs";import m from"path";import{pathToFileURL as O}from"url";var E=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],P=new Set;function en(s,l={}){let o=m.resolve(s,l.dir??"server/api"),i=[],f=new Map;if(!S.existsSync(o))return i;let t=Array.from(new Bun.Glob("**/*.{ts,js,mts,mjs}").scanSync({cwd:o})).sort();for(let e of t){if(e.endsWith(".d.ts"))continue;let p=e.replace(/\.(?:ts|js|mts|mjs)$/,"").split("/"),n=p.pop(),u=n.lastIndexOf("."),d=u>=0?n.slice(u+1):"get",g=d.toUpperCase();if(!E.includes(g)||d!==d.toLowerCase())throw Error(`Unsupported API method suffix in ${e}; use ${E.map((y)=>y.toLowerCase()).join(", ")}`);if(u>=0)n=n.slice(0,u);if(n!=="index")p.push(n);let r=new Set,h=p.map((y,I)=>{let v=/^\[(\.\.\.)?([A-Za-z_]\w*)\]$/.exec(y);if(v){if(r.has(v[2])||v[1]&&I!==p.length-1)throw Error(`Invalid API parameter in ${e}`);return r.add(v[2]),`:${v[2]}${v[1]?"*":""}`}if(!/^[\w-]+$/.test(y))throw Error(`Unsupported API path segment ${y} in ${e}`);return y}),w=`/api${h.length?`/${h.join("/")}`:""}`,x=`${g} ${w.replace(/:\w+/g,":param")}`;if(f.has(x))throw Error(`Ambiguous API route ${g} ${w}: ${f.get(x)} and ${e}`);f.set(x,e);let R=m.join(o,e);P.add(m.resolve(R)),P.add(S.realpathSync(R)),i.push({pattern:w,method:g,filePath:R})}return i.sort((e,a)=>{let p=e.pattern.split("/"),n=a.pattern.split("/"),u=(d)=>d?.endsWith("*")?0:d?.startsWith(":")?1:2;for(let d=0;d<Math.max(p.length,n.length);d++){let g=u(n[d])-u(p[d]);if(g)return g}return e.pattern.localeCompare(a.pattern)||e.method.localeCompare(a.method)})}async function Ys(s,l){let o=c(s,"api-types.d.ts"),i=["// Generated by stx. Include this file in tsconfig.json.","declare module '@stacksjs/stx/api-client' {"," interface KnownApiRoutes {"];for(let t of l){let e=`./${m.relative(m.dirname(o),t.filePath).replace(/\\/g,"/")}`,{params:a}=le(t.pattern);i.push(` ${JSON.stringify(`${t.method} ${t.pattern}`)}: { params: { ${a.map((p)=>`${JSON.stringify(p)}: string`).join("; ")} }; response: Awaited<ReturnType<typeof import(${JSON.stringify(e)}).default>> }`)}i.push(" }","}","export {}","");let f=i.join(`
|
|
3
3
|
`);if(!await Bun.file(o).exists()||await Bun.file(o).text()!==f)await Bun.write(o,f);return o}async function Zs(s,l,o={}){let i=en(s,o);await Ys(s,i);let f=[];for(let t of i){let e=await Bun.build({entrypoints:[t.filePath],target:"bun",format:"esm",minify:!1,splitting:!1});if(!e.success)throw Error(`API build failed for ${t.filePath}: ${e.logs.join(`
|
|
4
|
-
`)}`);let a=e.outputs.find((u)=>u.kind==="entry-point");if(!a)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await a.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(l,n),a),f.push({...t,filePath:n})}return f}function j(s,l){let o=s.map((i)=>({route:i,...le(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,a=(r)=>r.replace(/:\w+/g,":param"),p=t.filter((r)=>a(r.route.pattern)===a(e)),n=i.method,u=p.find((r)=>r.route.method===n)??(n==="HEAD"?p.find((r)=>r.route.method==="GET"):void 0);if(!u){let r=new Set(p.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=u.regex.exec(f),g=Object.create(null);try{u.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await l(u.route);if(typeof r!=="function")throw Error(`API endpoint ${u.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function Qs(s,l){return j(l,async(o)=>(await import(O(m.resolve(s,o.filePath)).href)).default)}async function lp(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=en(s,o);return await Ys(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=en(s,o);await Ys(s,t);let{loadStxConfig:e}=await import("./chunk-
|
|
4
|
+
`)}`);let a=e.outputs.find((u)=>u.kind==="entry-point");if(!a)throw Error(`No API bundle for ${t.filePath}`);if(e.outputs.length!==1)throw Error(`API endpoint ${t.filePath} emits assets; package those explicitly instead`);let n=`server/api/endpoint-${new Bun.CryptoHasher("sha256").update(await a.arrayBuffer()).digest("hex").slice(0,20)}.mjs`;await Bun.write(m.join(l,n),a),f.push({...t,filePath:n})}return f}function j(s,l){let o=s.map((i)=>({route:i,...le(i.pattern)}));return async(i)=>{let f=new URL(i.url).pathname,t=o.filter((r)=>r.regex.test(f));if(!t.length)return null;let e=t[0].route.pattern,a=(r)=>r.replace(/:\w+/g,":param"),p=t.filter((r)=>a(r.route.pattern)===a(e)),n=i.method,u=p.find((r)=>r.route.method===n)??(n==="HEAD"?p.find((r)=>r.route.method==="GET"):void 0);if(!u){let r=new Set(p.map((h)=>h.route.method));if(r.has("GET"))r.add("HEAD");return r.add("OPTIONS"),new Response(null,{status:n==="OPTIONS"?204:405,headers:{Allow:Array.from(r).sort().join(", ")}})}let d=u.regex.exec(f),g=Object.create(null);try{u.params.forEach((r,h)=>{g[r]=decodeURIComponent(d[h+1])})}catch{return new Response("Invalid URL parameter encoding",{status:400})}try{let r=await l(u.route);if(typeof r!=="function")throw Error(`API endpoint ${u.route.filePath} must default-export a handler`);let h=await r(i,{params:g}),w=h instanceof Response?h:h===void 0?new Response(null,{status:204}):Response.json(h);if(n==="HEAD")return new Response(null,{status:w.status,headers:w.headers});return w}catch(r){return console.error(`[stx] API error for ${n} ${e}:`,r),Response.json({error:"Internal Server Error"},{status:500})}}}function Qs(s,l){return j(l,async(o)=>(await import(O(m.resolve(s,o.filePath)).href)).default)}async function lp(s,l){if(!l)return async()=>null;let o=l===!0?{}:l,i=en(s,o);return await Ys(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=en(s,o);await Ys(s,t);let{loadStxConfig:e}=await import("./chunk-5tkby4j6.js"),a=A((await e(s)).runtimeConfig);return await Be(a,()=>j(t,async(p)=>{let n=await Bun.build({entrypoints:[p.filePath],target:"bun",format:"esm",splitting:!1});if(!n.success)throw Error(n.logs.join(`
|
|
5
5
|
`));let u=n.outputs.find((d)=>d.kind==="entry-point");if(!u||n.outputs.length!==1)throw Error(`Unsupported API bundle output: ${p.filePath}`);return(await import(`data:text/javascript;base64,${Buffer.from(await u.text()).toString("base64")}`)).default})(f))}catch(t){return console.error("[stx] API discovery failed:",t),Response.json({error:"API discovery failed; check the server log"},{status:500})}}}function eo(s,l,o){if(Sa(s))return!0;let i=/^(?:(?:stx|ui)\.config\.[cm]?[jt]s|runtime-config-(?:server|loader)\.[cm]?[jt]s)$/;if(i.test(m.basename(s)))return!0;try{if(i.test(m.basename(S.realpathSync(s))))return!0}catch{}if(P.has(m.resolve(s)))return!0;if(!o)return!1;let f=m.resolve(l,typeof o==="object"?o.dir??"server/api":"server/api"),t=(a)=>{try{return S.realpathSync(a)}catch{return m.resolve(a)}},e=t(s);return[f,m.resolve(l,"server"),m.resolve(l,".output/server")].some((a)=>{let p=t(a);return e===p||e.startsWith(`${p}${m.sep}`)})}
|
|
6
6
|
export{en,Ys,Zs,Qs,lp,eo};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{it,at,ct}from"./chunk-tp4eqfxq.js";import"./chunk-gtktv6nn.js";import"./chunk-6beg47t4.js";import{g}from"./chunk-
|
|
2
|
+
import{it,at,ct}from"./chunk-tp4eqfxq.js";import"./chunk-gtktv6nn.js";import"./chunk-6beg47t4.js";import{g}from"./chunk-6eazxhpe.js";import"./chunk-r0ys9aqa.js";import"./chunk-t6m5d64b.js";import"./chunk-bwcejt6t.js";import{Ft,Is,zt,pi,ot,fi,Os,Ht,mi,Vt}from"./chunk-vxnf3xab.js";import M from"fs";import x from"path";function E(t,e){let r=[x.join(t.root,"stx.config.ts"),x.join(t.root,"stx.config.js"),x.join(t.root,"stx.config.mjs")],s=e.debounceMs??300,o=null,a=[];for(let c of r)try{if(!M.existsSync(c))continue;let n=M.watch(c,(d)=>{if(d==="change"){if(o)clearTimeout(o);o=setTimeout(async()=>{fi("Config file changed, restarting...");try{await e.onChange()}catch(p){ot(`Failed to restart: ${p}`)}},s)}});a.push(n)}catch{}return{stop(){if(o)clearTimeout(o);for(let c of a)c.close()}}}import w from"fs";import j from"path";var st=".stx/story/analytics.json",dt=1,A=1e4;class k{storage;storagePath;currentSession=null;dirty=!1;viewStartTimes=new Map;constructor(t){this.storagePath=j.join(t,st),this.storage=this.loadStorage(),this.startSession()}loadStorage(){try{let t=w.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:dt,events:[],sessions:[]}}}async save(){if(!this.dirty)return;let t=j.dirname(this.storagePath);if(await w.promises.mkdir(t,{recursive:!0}),this.storage.events.length>A)this.storage.events=this.storage.events.slice(-A);await w.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}startSession(){this.endSession(),this.currentSession={id:pt(),startTime:Date.now(),componentViews:[]},this.storage.sessions.push(this.currentSession),this.dirty=!0}endSession(){if(this.currentSession)this.currentSession.endTime=Date.now(),this.currentSession=null}track(t){this.storage.events.push({...t,timestamp:Date.now()}),this.dirty=!0}trackView(t,e){if(this.endViewTiming(t),this.viewStartTimes.set(t,Date.now()),this.track({type:"view",componentId:t,variantId:e}),this.currentSession&&!this.currentSession.componentViews.includes(t))this.currentSession.componentViews.push(t)}endViewTiming(t){let e=this.viewStartTimes.get(t);if(e){let r=Date.now()-e;this.track({type:"view",componentId:t,metadata:{duration:r,endView:!0}}),this.viewStartTimes.delete(t)}}trackPropChange(t,e,r){this.track({type:"prop_change",componentId:t,propName:e,metadata:{value:r}})}trackVariantSwitch(t,e){this.track({type:"variant_switch",componentId:t,variantId:e})}trackSearch(t,e){this.track({type:"search",query:t,metadata:{resultCount:e}})}getComponentAnalytics(t,e){let r=this.storage.events.filter((i)=>i.componentId===t),s=r.filter((i)=>i.type==="view"&&!i.metadata?.endView),o=r.filter((i)=>i.type==="prop_change"),a=r.filter((i)=>i.type==="variant_switch"),c={};for(let i of o)if(i.propName)c[i.propName]=(c[i.propName]||0)+1;let n={};for(let i of a)if(i.variantId)n[i.variantId]=(n[i.variantId]||0)+1;let d=new Set(this.storage.sessions.filter((i)=>i.componentViews.includes(t)).map((i)=>i.id)),p=r.filter((i)=>i.metadata?.duration).map((i)=>i.metadata.duration),u=p.length>0?p.reduce((i,l)=>i+l,0)/p.length:0,y=Object.entries(c).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i])=>i);return{componentId:t,componentName:e,viewCount:s.length,uniqueViews:d.size,lastViewed:s[s.length-1]?.timestamp,propChanges:c,topChangedProps:y,variantViews:n,avgTimeSpent:u}}getMostViewedComponents(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="view"&&r.componentId&&!r.metadata?.endView)e.set(r.componentId,(e.get(r.componentId)||0)+1);return Array.from(e.entries()).map(([r,s])=>({componentId:r,viewCount:s})).sort((r,s)=>s.viewCount-r.viewCount).slice(0,t)}getMostChangedProps(t=10){let e=new Map;for(let r of this.storage.events)if(r.type==="prop_change"&&r.propName)e.set(r.propName,(e.get(r.propName)||0)+1);return Array.from(e.entries()).map(([r,s])=>({propName:r,changeCount:s})).sort((r,s)=>s.changeCount-r.changeCount).slice(0,t)}getSearchAnalytics(){let t=this.storage.events.filter((o)=>o.type==="search"),e=new Map,r=0;for(let o of t){if(o.query)e.set(o.query,(e.get(o.query)||0)+1);if(o.metadata?.resultCount!==void 0)r+=o.metadata.resultCount}let s=Array.from(e.entries()).map(([o,a])=>({query:o,count:a})).sort((o,a)=>a.count-o.count).slice(0,10);return{totalSearches:t.length,topQueries:s,avgResultCount:t.length>0?r/t.length:0}}clear(){this.storage.events=[],this.storage.sessions=[],this.dirty=!0,this.startSession()}exportAnalytics(){return JSON.stringify({exportedAt:Date.now(),...this.storage},null,2)}}function pt(){return`session-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import S from"fs";import B from"path";var lt=".stx/story/bookmarks.json",mt=1;class P{storage;storagePath;dirty=!1;constructor(t){this.storagePath=B.join(t,lt),this.storage=this.loadStorage()}loadStorage(){try{let t=S.readFileSync(this.storagePath,"utf-8");return JSON.parse(t)}catch{return{version:mt,bookmarks:[]}}}async save(){if(!this.dirty)return;let t=B.dirname(this.storagePath);await S.promises.mkdir(t,{recursive:!0}),await S.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}addBookmark(t,e,r,s={}){let o={id:ut(),name:s.name||`${t}/${e}`,storyId:t,variantId:e,props:r,created:Date.now(),notes:s.notes,color:s.color};return this.storage.bookmarks.push(o),this.dirty=!0,o}getAllBookmarks(){return[...this.storage.bookmarks]}getBookmarksForStory(t){return this.storage.bookmarks.filter((e)=>e.storyId===t)}getBookmark(t){return this.storage.bookmarks.find((e)=>e.id===t)}isBookmarked(t,e){return this.storage.bookmarks.some((r)=>r.storyId===t&&r.variantId===e)}updateBookmark(t,e){let r=this.getBookmark(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deleteBookmark(t){let e=this.storage.bookmarks.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.bookmarks.splice(e,1),this.dirty=!0,!0}toggleBookmark(t,e,r){let s=this.storage.bookmarks.find((a)=>a.storyId===t&&a.variantId===e);if(s)return this.deleteBookmark(s.id),{added:!1};return{added:!0,bookmark:this.addBookmark(t,e,r)}}exportBookmarks(){return JSON.stringify(this.storage,null,2)}importBookmarks(t,e=!0){let r=JSON.parse(t),s=0;for(let o of r.bookmarks){if(e){let a=this.storage.bookmarks.find((c)=>c.id===o.id);if(a)Object.assign(a,o);else this.storage.bookmarks.push(o)}else this.storage.bookmarks.push(o);s++}if(s>0)this.dirty=!0;return s}}function ut(){return`bm-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}var v=new Set;function N(){return{open(t){v.add(t),t.send(JSON.stringify({type:"connected",timestamp:Date.now()}))},close(t){v.delete(t)},message(t,e){}}}function C(t){let e=JSON.stringify({...t,timestamp:t.timestamp||Date.now()});for(let r of v)try{r.send(e)}catch{v.delete(r)}}function V(t,e){C({type:"story-update",data:{storyId:t,...e}})}function H(t,e){C({type:"story-add",data:{storyId:t,...e}})}function O(t){C({type:"story-remove",data:{storyId:t}})}function F(t){return`
|
|
3
3
|
<script>
|
|
4
4
|
(function() {
|
|
5
5
|
const ws = new WebSocket('${t}');
|
|
@@ -556,7 +556,7 @@ window.__stxPerformance = {
|
|
|
556
556
|
|
|
557
557
|
window.clearPerformanceMetrics = () => window.__stxPerformance.clear();
|
|
558
558
|
</script>
|
|
559
|
-
`}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-
|
|
559
|
+
`}import T from"fs";import K from"path";var ft=".stx/story/presets.json",R=1,yt=10;class I{storage;storagePath;dirty=!1;constructor(t){this.storagePath=K.join(t,ft),this.storage=this.loadStorage()}loadStorage(){try{let t=T.readFileSync(this.storagePath,"utf-8"),e=JSON.parse(t);if(e.version!==R)return this.migrateStorage(e);return e}catch{return{version:R,presets:[],recentIds:[]}}}migrateStorage(t){return{version:R,presets:t.presets||[],recentIds:t.recentIds||[]}}async save(){if(!this.dirty)return;let t=K.dirname(this.storagePath);await T.promises.mkdir(t,{recursive:!0}),await T.promises.writeFile(this.storagePath,JSON.stringify(this.storage,null,2)),this.dirty=!1}createPreset(t,e,r={}){let s={id:ht(),name:t,description:r.description,props:e,componentId:r.componentId,created:Date.now(),usageCount:0,tags:r.tags};return this.storage.presets.push(s),this.dirty=!0,s}getPreset(t){return this.storage.presets.find((e)=>e.id===t)}getAllPresets(){return[...this.storage.presets]}getPresetsForComponent(t){return this.storage.presets.filter((e)=>!e.componentId||e.componentId===t)}getRecentPresets(){return this.storage.recentIds.map((t)=>this.getPreset(t)).filter((t)=>t!==void 0)}usePreset(t){let e=this.getPreset(t);if(!e)return;return e.lastUsed=Date.now(),e.usageCount++,this.storage.recentIds=[t,...this.storage.recentIds.filter((r)=>r!==t)].slice(0,yt),this.dirty=!0,e}updatePreset(t,e){let r=this.getPreset(t);if(!r)return;return Object.assign(r,e),this.dirty=!0,r}deletePreset(t){let e=this.storage.presets.findIndex((r)=>r.id===t);if(e===-1)return!1;return this.storage.presets.splice(e,1),this.storage.recentIds=this.storage.recentIds.filter((r)=>r!==t),this.dirty=!0,!0}searchPresets(t){let e=t.toLowerCase();return this.storage.presets.filter((r)=>{if(r.name.toLowerCase().includes(e))return!0;if(r.description?.toLowerCase().includes(e))return!0;if(r.tags?.some((s)=>s.toLowerCase().includes(e)))return!0;return!1})}getMostUsedPresets(t=5){return[...this.storage.presets].sort((e,r)=>r.usageCount-e.usageCount).slice(0,t)}exportPresets(t){let e=t?this.storage.presets.filter((r)=>t.includes(r.id)):this.storage.presets;return JSON.stringify({presets:e},null,2)}importPresets(t,e=!1){let r=JSON.parse(t),s=0;for(let o of r.presets){let a=this.storage.presets.find((c)=>c.id===o.id);if(a&&!e)continue;if(a)Object.assign(a,o);else this.storage.presets.push(o);s++}if(s>0)this.dirty=!0;return s}}function ht(){return`preset-${Date.now()}-${Math.random().toString(36).slice(2,8)}`}import _ from"fs";var q=new Map;async function b(t,e,r={}){let s=performance.now(),o=[];try{let a=await _.promises.stat(e),c=q.get(e),n;if(c&&c.mtime===a.mtimeMs)n=c.content;else n=await _.promises.readFile(e,"utf-8"),q.set(e,{content:n,mtime:a.mtimeMs,analyzed:null});let{processDirectives:d}=await import("./chunk-a3s7tqsp.js"),p={},u=h(n);if(u)try{await g(u,p,e)}catch(f){o.push(`Warning: Could not extract script variables: ${f instanceof Error?f.message:String(f)}`)}if(r.props)Object.assign(p,r.props);let i=await d(n,p,e,{},new Set),l=Z(n),m=h(n);return i=Q(i),i=tt(i,p),{html:i,css:l,js:m,errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}async function vt(t){try{let e=await _.promises.readFile(t,"utf-8"),r=h(e);if(!r)return null;let s={};if(await g(r,s,t),Array.isArray(s.variants))return s.variants;return null}catch{return null}}async function Y(t,e,r,s){let o=e.story?.variants;if(!o){let n=await vt(e.path);if(n)o=n}if(!o&&r==="default")return b(t,e.path,{props:s||{}});if(!o)return b(t,e.path,{props:s||{}});let a=o.find((n)=>n.id===r);if(!a&&r==="default")return b(t,e.path,{props:s||{}});if(!a)return{html:'<div class="stx-render-error">Variant not found</div>',css:"",js:"",errors:[`Variant '${r}' not found`],duration:0};let c={...a.state,...s};if(a.source)return bt(t,a.source,c);return b(t,e.path,{props:c})}async function bt(t,e,r={}){let s=performance.now(),o=[];try{let{processDirectives:a}=await import("./chunk-a3s7tqsp.js"),c={...r},n=h(e);if(n)try{await g(n,c,"inline-template.stx")}catch{}let p=await a(e,c,"inline-template.stx",{},new Set);return p=Q(p),p=tt(p,c),{html:p,css:Z(e),js:h(e),errors:o,duration:performance.now()-s}}catch(a){return o.push(a instanceof Error?a.message:String(a)),{html:`<div class="stx-render-error">${et(o[0])}</div>`,css:"",js:"",errors:o,duration:performance.now()-s}}}function Z(t){let e=[],r=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
560
560
|
`)}function Q(t){return t.replace(/<!--[\s\S]*?-->/g,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/^\s*\n/gm,"").trim()}function h(t){let e=[],r=/<script\b[^>]*>([\s\S]*?)<\/script>/gi,s=r.exec(t);while(s!==null)e.push(s[1].trim()),s=r.exec(t);return e.join(`
|
|
561
561
|
`)}function tt(t,e){let r=`<script>window.__stxProps = ${JSON.stringify(e)};</script>`;return t+r}function et(t){return t.replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">").replace(/"/g,""")}async function rt(t,e){let r=await Ht(t);at(t,r);let s=Vt(t.config,r);ct(t,s),console.log(` Found ${r.length} story files`);let o=typeof e.host==="string"?e.host:e.host===!0?"0.0.0.0":"localhost",a=new I(t.root),c=new P(t.root),n=new k(t.root),d=N(),p=Bun.serve({port:e.port,hostname:o,fetch:async(i,l)=>{let f=new URL(i.url).pathname;if(f==="/__hmr"){if(l.upgrade(i,{data:{isHmr:!0}}))return;return new Response("WebSocket upgrade failed",{status:400})}if(f.startsWith("/api/"))return xt(t,f,i,{presetsManager:a,bookmarksManager:c,analyticsTracker:n});return wt(t,f,e.port)},websocket:{open(i){d.open(i)},close(i){d.close(i)},message(i,l){d.message(i,l)}}}),u=`http://${o}:${e.port}`,y=mi(t,async(i,l)=>{console.log(` [${i}] ${l.relativePath}`);let m=await Ht(t);at(t,m);let f=Vt(t.config,m);if(ct(t,f),i==="add")H(l.id,{fileName:l.fileName});else if(i==="unlink")O(l.id);else V(l.id,{fileName:l.fileName})});if(e.open){let i=u;try{let{exec:l}=await import("child_process"),m=process.platform;l(`${m==="darwin"?"open":m==="win32"?"start":"xdg-open"} ${i}`)}catch{}}return{server:p,url:u,close:async()=>{y(),p.stop()}}}async function xt(t,e,r,s){let{presetsManager:o,bookmarksManager:a,analyticsTracker:c}=s;if(e==="/api/stories")return Response.json({files:t.storyFiles.map((n)=>({id:n.id,fileName:n.fileName,relativePath:n.relativePath,treePath:n.treePath})),tree:t.tree});if(e.startsWith("/api/story/")){let n=e.slice(11),d=t.storyFiles.find((p)=>p.id===n);if(!d)return new Response("Story not found",{status:404});try{let p=await Bun.file(d.path).text();return Response.json({id:d.id,fileName:d.fileName,relativePath:d.relativePath,content:p})}catch{return new Response("Error reading story",{status:500})}}if(e==="/api/config")return Response.json({theme:t.config.theme,responsivePresets:t.config.responsivePresets,backgroundPresets:t.config.backgroundPresets});if(e.startsWith("/api/render/")){let n=new URL(r.url),d=e.slice(12).split("/"),p=d[0],u=d[1]||"default",y,i=n.searchParams.get("props");if(i)try{y=JSON.parse(i)}catch{}let l=t.storyFiles.find((m)=>m.id===p);if(!l)return new Response("Story not found",{status:404});try{let m=await Y(t,l,u,y);return Response.json({html:m.html,css:m.css,js:m.js,errors:m.errors,duration:m.duration})}catch(m){return Response.json({html:"",css:"",js:"",errors:[m instanceof Error?m.message:String(m)],duration:0},{status:500})}}if(e==="/api/presets"&&r.method==="GET")return Response.json({presets:o.getAllPresets()});if(e==="/api/presets"&&r.method==="POST")try{let n=await r.json(),d=o.createPreset(n.name,n.props,{componentId:n.componentId,description:n.description});return await o.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/presets/")&&!e.includes("/use")&&r.method==="GET"){let n=e.slice(13),d=o.getPreset(n);if(!d)return new Response("Preset not found",{status:404});return Response.json(d)}if(e.endsWith("/use")&&r.method==="POST"){let n=e.slice(13,-4),d=o.usePreset(n);if(!d)return new Response("Preset not found",{status:404});return await o.save(),Response.json(d)}if(e.startsWith("/api/presets/")&&r.method==="DELETE"){let n=e.slice(13);if(!o.deletePreset(n))return new Response("Preset not found",{status:404});return await o.save(),Response.json({success:!0})}if(e==="/api/bookmarks"&&r.method==="GET")return Response.json({bookmarks:a.getAllBookmarks()});if(e==="/api/bookmarks"&&r.method==="POST")try{let n=await r.json(),d=a.addBookmark(n.storyId,n.variantId,n.props,{name:n.name,notes:n.notes,color:n.color});return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/bookmarks/toggle"&&r.method==="POST")try{let n=await r.json(),d=a.toggleBookmark(n.storyId,n.variantId,n.props);return await a.save(),Response.json(d)}catch(n){return Response.json({error:String(n)},{status:400})}if(e.startsWith("/api/bookmarks/")&&e!=="/api/bookmarks/toggle"&&r.method==="GET"){let n=e.slice(15),d=a.getBookmark(n);if(!d)return new Response("Bookmark not found",{status:404});return Response.json(d)}if(e.startsWith("/api/bookmarks/")&&r.method==="DELETE"){let n=e.slice(15);if(!a.deleteBookmark(n))return new Response("Bookmark not found",{status:404});return await a.save(),Response.json({success:!0})}if(e==="/api/analytics/track"&&r.method==="POST")try{let n=await r.json();if(n.type==="view"&&n.componentId)c.trackView(n.componentId,n.variantId);else if(n.type==="prop_change"&&n.componentId&&n.propName)c.trackPropChange(n.componentId,n.propName,null);else if(n.type==="variant_switch"&&n.componentId&&n.variantId)c.trackVariantSwitch(n.componentId,n.variantId);else if(n.type==="search"&&n.query)c.trackSearch(n.query,0);return await c.save(),Response.json({success:!0})}catch(n){return Response.json({error:String(n)},{status:400})}if(e==="/api/analytics/summary"&&r.method==="GET")return Response.json({mostViewed:c.getMostViewedComponents(10),mostChangedProps:c.getMostChangedProps(10),searchAnalytics:c.getSearchAnalytics()});if(e.startsWith("/api/analytics/component/")&&r.method==="GET"){let n=e.slice(25),d=t.storyFiles.find((u)=>u.id===n),p=c.getComponentAnalytics(n,d?.fileName||n);return Response.json(p)}return new Response("Not found",{status:404})}function wt(t,e,r){let s=kt(t,r);return new Response(s,{headers:{"Content-Type":"text/html; charset=utf-8"}})}function kt(t,e){let{theme:r}=t.config,s=r.title||"STX Story",o=`ws://localhost:${e}/__hmr`,a=F(o);return`<!DOCTYPE html>
|
|
562
562
|
<html lang="en" class="${r.darkClass||"dark"}">
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Fi,il,On,id,al,cl,ll,ad}from"./chunk-
|
|
2
|
+
import{Fi,il,On,id,al,cl,ll,ad}from"./chunk-cbbheh2r.js";import"./chunk-6eazxhpe.js";import"./chunk-bwcejt6t.js";import"./chunk-t6m5d64b.js";import"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{On as Validator,il as defineForm,al as processErrorDirective,cl as processErrorsDirective,ad as processFormValidationDirectives,ll as processHasErrorsDirective,Fi as useForm,id as v};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{gc,mc}from"./chunk-gtktv6nn.js";import{j,cs,ls,us,To,$o,ar,Ie,de,G,ps,oe,X,H,et,lr,Io,pr,je,n,d,V,mn}from"./chunk-xw0cqb5m.js";import{p,E,tt,u}from"./chunk-r0ys9aqa.js";import{re}from"./chunk-hx787tfa.js";import{r}from"./chunk-9tg4995v.js";import{f}from"./chunk-b7e07ybq.js";import{createHash as Ct}from"crypto";import ee from"fs";import Q from"path";import{decode as sn,generateThumbHash as on}from"ts-images";import{createImageDeliveryCatalog as yt}from"ts-images/delivery";import Te from"fs";function Ce(e,t,s){let i=Buffer.alloc(s),o=Te.readSync(e,i,0,s,t);return i.subarray(0,o)}function De(e){if(e.length<25)return!1;let t=(i,o)=>String.fromCharCode(...e.subarray(i,o));if(t(0,4)!=="RIFF"||t(8,12)!=="WEBP")return!1;let s=t(12,16);if(s==="VP8X")return(e[20]&16)!==0;if(s==="VP8L")return((e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>28&1)===1;return!1}function Me(e){let t;try{t=Te.openSync(e,"r");let s=Ce(t,0,33);if(s.length>=3&&s[0]===255&&s[1]===216&&s[2]===255)return"none";if(s.length>=26&&s[0]===137&&s.toString("latin1",1,4)==="PNG"){let i=s[25];if(i===4||i===6)return"possible";let o=8;for(let a=0;a<64;a++){let c=Ce(t,o,8);if(c.length<8)return"unknown";let g=c.toString("latin1",4,8);if(g==="tRNS")return"possible";if(g==="IDAT"||g==="IEND")return"none";o+=12+c.readUInt32BE(0)}return"unknown"}if(s.length>=25&&s.toString("latin1",0,4)==="RIFF"&&s.toString("latin1",8,12)==="WEBP"){if(De(s))return"possible";let i=s.toString("latin1",12,16);return i==="VP8 "||i==="VP8X"?"none":"unknown"}return"unknown"}catch{return"unknown"}finally{if(t!==void 0)Te.closeSync(t)}}import Jt from"fs";import Re from"os";import{join as dt}from"path";import{fileURLToPath as gt}from"url";import{Worker as mt}from"worker_threads";var ke=Symbol("stx.image-worker.unavailable");function Yt(e=typeof Re.availableParallelism==="function"?Re.availableParallelism():Re.cpus().length){return Math.max(1,Math.min(2,e-1))}var Ae=0,ht=[];async function Qt(){if(Ae<Yt()){Ae++;return}await new Promise((e)=>ht.push(e)),Ae++}function en(){Ae--,ht.shift()?.()}var tn="@stacksjs/stx/builtins/image-warmup-worker";function nn(e=process.cwd()){let t=import.meta.url.endsWith(".ts")?"ts":"js";try{let s=new URL(`./image-warmup-worker.${t}`,import.meta.url);if(s.protocol==="file:"&&Jt.existsSync(gt(s)))return gt(s)}catch{}try{let s=typeof Bun<"u"?Bun.resolveSync(tn,e):void 0;return s&&rn(s)?s:void 0}catch{return}}function rn(e,t=process.env){let s=e.replace(/\\/g,"/");if(s.split("/").some((o)=>/@\d[^/]*@@@\d+$/.test(o)))return!1;return![t.BUN_INSTALL_CACHE_DIR,dt(t.BUN_INSTALL||dt(Re.homedir(),".bun"),"install","cache")].filter((o)=>!!o).map((o)=>`${o.replace(/\\/g,"/").replace(/\/$/,"")}/`).some((o)=>s.startsWith(o))}var pt=!1;function pe(e){if(!pt)pt=!0,console.warn(`[stx] image worker unavailable (${e}); running the image pass on the serving thread instead. Results are the same, but requests may stall while it runs.`);return ke}function Le(e){return e instanceof Error?e.message:String(e)}async function ze(e,t){if(typeof mt!=="function")return pe("node:worker_threads has no Worker in this runtime");let s=nn();if(!s)return pe("no image-warmup-worker entry beside this module or in the installed @stacksjs/stx");await Qt();try{return await new Promise((i,o)=>{let a;try{a=new mt(s)}catch(h){i(pe(`could not start ${s}: ${Le(h)}`));return}let c=!1,g=!1,l=(h)=>{if(g)return;g=!0,h(),a.terminate()};a.on("message",(h)=>{if(h.type==="ready"){c=!0,a.postMessage({task:e,args:t});return}if(h.type==="result"){l(()=>i(h.value));return}let v=Error(h.error?.message??"image worker failed");if(h.error?.name)v.name=h.error.name;if(h.error?.stack)v.stack=h.error.stack;l(()=>o(v))}),a.on("error",(h)=>{l(()=>c?o(h instanceof Error?h:Error(Le(h)||"image worker crashed")):i(pe(`the worker failed before it was ready: ${Le(h)}`)))}),a.on("exit",(h)=>{l(()=>c?o(Error("image worker exited before it finished")):i(pe(`the worker exited with code ${h} before it was ready`)))})})}finally{en()}}var an=new Set([".avif",".jpeg",".jpg",".png",".webp"]),cn=[320,640,960,1280,1920],he="/_stx/images",ln=`stx:${he}:alpha-1`,un=`stx:${he}:opaque-1`,fn=["@stacksjs/ts-webp","@stacksjs/ts-avif","ts-images"],Pe;function dn(e,t){let s=Q.dirname(Bun.resolveSync(e,t));while(s!==Q.dirname(s)){let i=Q.join(s,"package.json");if(ee.existsSync(i)){let o=JSON.parse(ee.readFileSync(i,"utf8"));if(o.name===e)return o.version}s=Q.dirname(s)}return}function xt(){if(Pe!==void 0)return Pe;let e;try{e=Q.dirname(Bun.resolveSync("ts-images",import.meta.dir))}catch{}return Pe=fn.map((t)=>{let s;try{s=e?dn(t,e):void 0}catch{}return`${t.replace("@stacksjs/","")}@${s??"unknown"}`}).join("+"),Pe}var bt=Symbol.for("stx.image-delivery");function ye(){let e=globalThis;return e[bt]??={catalog:new Map,transparent:new Set},e[bt]}var vt=new Set;function gn(e){return`/${e.split(Q.sep).map(encodeURIComponent).join("/")}`}function pn(e){let t=Q.extname(e),s=e.slice(0,-t.length).replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,""),i=Ct("sha256").update(e).digest("hex").slice(0,8);return`${s||"image"}-${i}`}function wt(e,t=`stx:${he}`){let s=(i)=>`${he}/${i.split("/").map(encodeURIComponent).join("/")}`;return{cacheNamespace:t,async stat(i){let o=Q.join(e,i);try{let a=await ee.promises.stat(o);return a.size>0?{bytes:a.size,path:o,url:s(i)}:null}catch{return null}},async write(i,o){let a=Q.join(e,i);await ee.promises.mkdir(Q.dirname(a),{recursive:!0});let c=`${a}.${process.pid}.tmp`;return await ee.promises.writeFile(c,o),await ee.promises.rename(c,a),{bytes:o.byteLength,path:a,url:s(i)}},url:s}}async function Rt(e,t=e){let s=await ee.promises.readdir(t,{withFileTypes:!0});s.sort((o,a)=>o.name.localeCompare(a.name));let i=[];for(let o of s){let a=Q.join(t,o.name);if(o.isDirectory()){i.push(...await Rt(e,a));continue}if(!o.isFile()||!an.has(Q.extname(o.name).toLowerCase()))continue;i.push({absolutePath:a,relativePath:Q.relative(e,a)})}return i}function $t(e,t){return e.map((s)=>({key:gn(s.relativePath),input:s.absolutePath,name:pn(s.relativePath),...hn(s.absolutePath)?{options:{storage:t}}:{}}))}function hn(e){return Me(e)==="possible"}function yn(e){for(let t=3;t<e.length;t+=4)if(e[t]!==255)return!0;return!1}async function xn(e){let t=Object.entries(e).filter(([,o])=>o.fallback.format==="png"),s=new Set,i=8;for(let o=0;o<t.length;o+=8)await Promise.all(t.slice(o,o+8).map(async([a,c])=>{let g=c.variants.filter((l)=>l.format==="png").sort((l,h)=>l.width-h.width)[0];try{let l=await sn(new Uint8Array(await ee.promises.readFile(g?.path??c.fallback.path)));if(yn(l.data))s.add(a)}catch{s.add(a)}}));return s}function bn(e,t){let s=[];for(let i of t){let o=e[i],a=o?.variants.filter((g)=>g.format==="webp")??[];if(!o||a.length===0)continue;if(!a.some((g)=>{let l;try{return l=ee.openSync(g.path,"r"),!De(Ce(l,0,32))}catch{return!0}finally{if(l!==void 0)ee.closeSync(l)}}))continue;if(o.variants=o.variants.filter((g)=>g.format!=="webp"),delete o.sources.webp,s.push(i),!vt.has(i))vt.add(i),console.warn(`[stx-images] ${i} is transparent but its WebP variants have no alpha channel; serving PNG instead. Upgrade @stacksjs/ts-webp to 0.1.6 or later.`)}return s}async function vn(e){let t=[],s=8;for(let i=0;i<e.length;i+=8){let o=e.slice(i,i+8),a=await Promise.all(o.map(async(c)=>{try{return await on(c.absolutePath),c}catch{return console.warn(`[stx-images] Skipping unreadable raster: ${c.relativePath}`),null}}));t.push(...a.filter((c)=>c!==null))}return t}function Ue(e){return Q.join(e,"undecodable.json")}function wn(e){try{let t=ee.readFileSync(Ue(e),"utf-8"),s=JSON.parse(t);return s&&typeof s==="object"?s:{}}catch{return{}}}function $n(e,t){try{ee.mkdirSync(Q.dirname(Ue(e)),{recursive:!0}),ee.writeFileSync(Ue(e),JSON.stringify(t))}catch{}}function St(e){try{let t=ee.statSync(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return}}function At(e){if(!e||e.startsWith("data:")||e.startsWith("blob:")||/^https?:\/\//i.test(e)||e.startsWith("//"))return;let t=e.split(/[?#]/,1)[0];if(!t)return;try{return`/${t.replace(/^\/+/,"").split("/").map(decodeURIComponent).map(encodeURIComponent).join("/")}`}catch{return}}function so(e){let t=At(e);return t?ye().catalog.get(t):void 0}function oo(e){let t=At(e);return t?ye().transparent.has(t):!1}function io(e){let t=(i)=>e.variants.filter((o)=>o.format===i).reduce((o,a)=>o+a.bytes,0),s=t(e.fallback.format);return["avif","webp"].map((i)=>({format:i,srcset:e.sources[i]||"",bytes:t(i)})).filter((i)=>i.srcset&&i.bytes>0&&i.bytes<s).sort((i,o)=>i.bytes-o.bytes).map(({format:i,srcset:o})=>({format:i,srcset:o}))}function hp(e){let t=so(e);if(!t)return;return{src:t.fallback.url,srcset:t.sources[t.fallback.format]||"",sources:io(t).map(({format:s,srcset:i})=>({type:`image/${s}`,srcset:i})),width:t.source.width,height:t.source.height,placeholder:oo(e)?void 0:t.placeholder?.dataUrl}}function Hr(){let e=ye();e.catalog=new Map,e.transparent=new Set}function Sn(e){let t=ye();t.catalog=new Map(e.entries),t.transparent=new Set(e.transparent)}async function yp(e,t,s={}){if(!e||!ee.existsSync(e))return Hr(),{count:0,fingerprint:""};if(s.offThread){let m=await ze("delivery",{publicDir:e,outputDir:t});if(m!==ke)return Sn(m.state),m.result}let i=await Rt(e);if(i.length===0)return Hr(),{count:0,fingerprint:""};let o=wn(t),a=i.filter((m)=>{let b=o[m.relativePath];if(!b)return!0;let w=St(m.absolutePath);return!w||w.mtimeMs!==b.mtimeMs||w.size!==b.size});if(a.length===0)return Hr(),{count:0,fingerprint:""};let c=wt(Q.join(t,"_stx","images"),`${ln}:${xt()}`),g={outDir:Q.join(t,"_stx","images"),storage:wt(Q.join(t,"_stx","images"),`${un}:${xt()}`),baseUrl:he,widths:cn,formats:["avif","webp"],quality:{avif:70,webp:78,jpeg:82,png:100},includeOriginal:!1,placeholder:!0,batchConcurrency:4,concurrency:4},l=a,h;try{h=await yt({...g,entries:$t(a,c)})}catch(m){if(l=await vn(a),l.length===a.length)throw m;let b=new Set(l.map((C)=>C.relativePath)),w=!1;for(let C of a){if(b.has(C.relativePath))continue;let k=St(C.absolutePath);if(!k)continue;o[C.relativePath]=k,w=!0}if(w)$n(t,o);if(l.length===0)return Hr(),{count:0,fingerprint:""};h=await yt({...g,entries:$t(l,c)})}let v=await xn(h.entries),y=bn(h.entries,v),S=ye();S.catalog=new Map(Object.entries(h.entries)),S.transparent=v;let x=v.size===0&&y.length===0?h.fingerprint:Ct("sha256").update(h.fingerprint).update(JSON.stringify({transparent:[...v].sort(),droppedWebp:y.sort()})).digest("hex");return{count:l.length,fingerprint:x}}class kt{builtins=new Map;registerBuiltin(e){this.builtins.set(e.name.toLowerCase(),e);for(let t of e.aliases)this.builtins.set(t.toLowerCase(),e)}isBuiltin(e){return this.builtins.has(e.toLowerCase())}getBuiltin(e){return this.builtins.get(e.toLowerCase())??null}async resolveFile(e,t,s,i){let o=To(e,i);if(o!==void 0)return o;for(let a of $o(e,t,s,i))if(await n(a))return a;return null}}var le=new kt;function R(e){return V(e)}var se="\x00stx-boolean-attribute";function We(e){return e.indexOf("\x00")===-1?e:e.replace(/\0/g,"")}var Cn=new Set(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","is","itemid","itemprop","itemref","itemscope","itemtype","lang","nonce","part","role","slot","spellcheck","style","tabindex","title","translate","accept","action","alt","autocomplete","capture","cite","cols","colspan","content","controls","datetime","default","download","enctype","for","form","formaction","formenctype","formmethod","formnovalidate","formtarget","height","href","hreflang","kind","label","loading","loop","max","maxlength","media","method","min","minlength","multiple","muted","name","open","pattern","placeholder","playsinline","poster","preload","readonly","referrerpolicy","rel","required","reversed","rows","rowspan","scope","selected","shape","size","span","src","srcdoc","srclang","srcset","start","step","target","type","usemap","value","width","wrap"]);function Fe(e){let t=e.toLowerCase();return t.startsWith("aria-")||t.startsWith("data-")||Cn.has(t)}function ie(e,t){let s=[];for(let[i,o]of Object.entries(e.static)){if(t.has(i))continue;let a=e.staticNames?.[i]??i;if(typeof o==="boolean"){if(o)s.push(d(a));continue}if(o===se){s.push(d(a));continue}s.push(`${d(a)}="${mn(a,We(String(o)))}"`)}return s}function ae(e,t){let s=[];for(let[i,o]of Object.entries(e.serverDynamic??{})){if(t.has(i))continue;if(o===null||o===void 0||o===!1)continue;let a=e.serverDynamicNames?.[i]??i;if(o===!0){s.push(d(a));continue}if(typeof o==="object")continue;s.push(`${d(a)}="${mn(a,We(String(o)))}"`)}return s}function Rn(e){if(e.clientReactive.to)return{value:e.clientReactive.to,reactive:!0};if(e.serverDynamic.to!==void 0)return{value:String(e.serverDynamic.to),reactive:!1};if(typeof e.static.to==="string")return{value:e.static.to,reactive:!1};return{value:"#",reactive:!1}}var He={name:"StxLink",aliases:["stx-link"],render(e,t,s){let i=Rn(e),o=(typeof e.static.class==="string"?e.static.class:"")||(typeof e.static.className==="string"?e.static.className:""),a=typeof e.static.activeClass==="string"?e.static.activeClass:"active",c=typeof e.static.exactActiveClass==="string"?e.static.exactActiveClass:"exact-active",g=e.static.prefetch===!0||e.static.prefetch==="true"||e.serverDynamic.prefetch===!0,l=[];if(i.reactive)l.push(`:href="${R(i.value)}"`);else l.push(`href="${R(ar(i.value,"navigable"))}"`);if(o)l.push(`class="${R(o)}"`);if(l.push("data-stx-link"),l.push(`data-stx-active-class="${R(a)}"`),l.push(`data-stx-exact-active-class="${R(c)}"`),g)l.push("data-stx-prefetch");let h=typeof e.static.activeMatch==="string"?e.static.activeMatch.trim():"";if(h)l.push(`data-stx-active-match="${R(h)}"`);let v=new Set(["to","class","className","activeClass","exactActiveClass","activeMatch","prefetch"]);return l.push(...ie(e,v)),l.push(...ae(e,v)),`<a ${l.join(" ")}>${t}</a>`}};var An=new Map;function qe(e){if(!e)return;let t=e.split("?")[0].split("#")[0];return An.get(t)}var kn={sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Xe=[320,640,768,1024,1280,1536,1920];function J(e,t){if(e.serverDynamic[t]!==void 0)return String(e.serverDynamic[t]);let s=e.static[t];if(typeof s==="string")return s;return}function _e(e,t,s=!1){let i=e.serverDynamic[t];if(i!==void 0)return i!==!1&&i!=="false";let o=e.static[t];if(o!==void 0)return o!=="false"&&o!==!1;return s}function Ze(e){if(e.includes("(")||e.includes(","))return e;let t=e.trim().split(/\s+/),s=[];for(let i of t)if(i.includes(":")){let[o,a]=i.split(":"),c=kn[o];if(c)s.push(`(max-width: ${c}px) ${a}`);else{let g=Number.parseInt(o);if(!Number.isNaN(g))s.push(`(max-width: ${g}px) ${a}`)}}else s.push(i);return s.join(", ")}function Ve(e,t,s,i){return t.map((o)=>`${xe(e,o,void 0,s,i)} ${o}w`).join(", ")}function Pn(e,t,s,i,o){return t.map((a)=>{let c=s?s*a:void 0;return`${xe(e,c,void 0,i,o)} ${a}x`}).join(", ")}function xe(e,t,s,i,o){if(!i||i==="local"||i==="static")return e;if(i==="cloudinary"){let a=[];if(t)a.push(`w_${t}`);if(s)a.push(`h_${s}`);if(o)a.push(`f_${o}`);a.push("q_auto");let c=a.join(",");return e.replace("/upload/",`/upload/${c}/`)}if(i==="imgix"){let a=new URLSearchParams;if(t)a.set("w",String(t));if(s)a.set("h",String(s));if(o)a.set("fm",o);a.set("auto","format");let c=e.includes("?")?"&":"?";return`${e}${c}${a.toString()}`}if(i==="bunny"){let a=new URLSearchParams;if(t)a.set("width",String(t));if(s)a.set("height",String(s));if(o)a.set("format",o);let c=e.includes("?")?"&":"?";return`${e}${c}${a.toString()}`}return e}function _n(e){return`var s=this.style;${e.map((t)=>`s.${t}=''`).join(";")}`}function In(e,t,s="#e5e7eb"){let i=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}"><rect width="100%" height="100%" fill="${s}"/></svg>`;return`data:image/svg+xml;base64,${btoa(i)}`}var Ge={name:"StxImage",aliases:["Image","stx-image","stx-img"],render(e,t,s){let i=J(e,"src")||"",o=so(i),a=J(e,"alt")||"",c=J(e,"width")||(o?String(o.source.width):void 0),g=J(e,"height")||(o?String(o.source.height):void 0),l=J(e,"sizes"),h=J(e,"srcset"),v=J(e,"densities"),y=J(e,"format"),S=oo(i)||qe(i)?.transparent===!0,x=J(e,"placeholder")||(o&&!S?"thumbhash":void 0),m=J(e,"placeholderColor")||"#e5e7eb",b=J(e,"provider"),w=J(e,"class")||J(e,"className")||"",C=J(e,"style")||"",k=J(e,"objectFit")||J(e,"fit"),A=J(e,"objectPosition")||J(e,"position"),I=J(e,"quality"),U=_e(e,"lazy",!0),M=_e(e,"preload",!1),L=_e(e,"priority",!1),q=J(e,"loading"),N=J(e,"decoding")||"async",_=!!o||_e(e,"picture",!1)||!!y,O=c?Number.parseInt(c):void 0,B=g?Number.parseInt(g):void 0,z=h||"",K="";if(o)z=o.sources[o.fallback.format]||"",K=l?Ze(l):"100vw";else if(!z&&l&&b&&b!=="local"&&b!=="static")z=Ve(i,Xe,b,y),K=Ze(l);else if(!z&&v){let P=v.split(/\s+/).map((F)=>Number.parseFloat(F.replace("x","")));z=Pn(i,P,O,b,y)}else if(l)K=Ze(l);let D=[];if(C)D.push(C);if(k)D.push(`object-fit:${k}`);if(A)D.push(`object-position:${A}`);if(O&&B)D.push(`aspect-ratio:${O}/${B}`);let W=[],ce=x==="blur"||x==="color"||x==="thumbhash";if(ce&&!S){let P=o?.placeholder?{dataUrl:o.placeholder.dataUrl,color:m}:qe(i);if(P&&x==="color")D.push(`background-color:${P.color}`),W.push("backgroundColor");else if(P)D.push(`background-color:${P.color}`),D.push(`background-image:url(${P.dataUrl})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundColor","backgroundImage");else{let F=In(O||16,B||9,m);D.push(`background-image:url(${F})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundImage")}}else if(!ce&&x&&x!=="empty"&&x!=="none")D.push(`background-image:url(${R(x)})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundImage");let we=o?.fallback.url||xe(i,O,B,b,y),Y=[];if(Y.push(`src="${R(ar(we,"fetched"))}"`),Y.push(`alt="${R(a)}"`),c)Y.push(`width="${R(c)}"`);if(g)Y.push(`height="${R(g)}"`);let ne=q||(L||M?"eager":U?"lazy":"");if(ne)Y.push(`loading="${R(ne)}"`);if(L)Y.push('fetchpriority="high"');if(Y.push(`decoding="${R(N)}"`),w)Y.push(`class="${R(w)}"`);if(D.length>0)Y.push(`style="${R(D.join(";"))}"`);if(z)Y.push(`srcset="${R(ar(z,"fetched"))}"`);if(K)Y.push(`sizes="${R(K)}"`);let $e=new Set(["src","alt","width","height","lazy","sizes","srcset","placeholder","placeholderColor","class","className","style","objectFit","objectPosition","fit","position","format","provider","quality","densities","preload","priority","picture","loading","decoding"]);if(W.length>0){let P=typeof e.static.onload==="string"?e.static.onload:"",F=_n(W)+(P?`;${P}`:"");Y.push(`onload="${R(F)}"`),$e.add("onload")}Y.push(...ie(e,$e)),Y.push(...ae(e,$e));let T=`<img ${Y.join(" ")} />`,Z="";if(M){let F=y==="webp"?"image/webp":y==="avif"?"image/avif":"";Z=`<link rel="preload" as="image" href="${R(we)}"${F?` type="${F}"`:""}${z?` imagesrcset="${R(z)}"`:""}${K?` imagesizes="${R(K)}"`:""} />
|
|
2
|
+
import{gc,mc}from"./chunk-gtktv6nn.js";import{j,cs,ls,us,To,$o,ar,Ie,de,G,ps,oe,X,H,et,lr,Io,pr,je,n,d,V,mn}from"./chunk-6eazxhpe.js";import{p,E,tt,u}from"./chunk-r0ys9aqa.js";import{re}from"./chunk-hx787tfa.js";import{r}from"./chunk-9tg4995v.js";import{f}from"./chunk-b7e07ybq.js";import{createHash as Ct}from"crypto";import ee from"fs";import Q from"path";import{decode as sn,generateThumbHash as on}from"ts-images";import{createImageDeliveryCatalog as yt}from"ts-images/delivery";import Te from"fs";function Ce(e,t,s){let i=Buffer.alloc(s),o=Te.readSync(e,i,0,s,t);return i.subarray(0,o)}function De(e){if(e.length<25)return!1;let t=(i,o)=>String.fromCharCode(...e.subarray(i,o));if(t(0,4)!=="RIFF"||t(8,12)!=="WEBP")return!1;let s=t(12,16);if(s==="VP8X")return(e[20]&16)!==0;if(s==="VP8L")return((e[21]|e[22]<<8|e[23]<<16|e[24]<<24)>>>28&1)===1;return!1}function Me(e){let t;try{t=Te.openSync(e,"r");let s=Ce(t,0,33);if(s.length>=3&&s[0]===255&&s[1]===216&&s[2]===255)return"none";if(s.length>=26&&s[0]===137&&s.toString("latin1",1,4)==="PNG"){let i=s[25];if(i===4||i===6)return"possible";let o=8;for(let a=0;a<64;a++){let c=Ce(t,o,8);if(c.length<8)return"unknown";let g=c.toString("latin1",4,8);if(g==="tRNS")return"possible";if(g==="IDAT"||g==="IEND")return"none";o+=12+c.readUInt32BE(0)}return"unknown"}if(s.length>=25&&s.toString("latin1",0,4)==="RIFF"&&s.toString("latin1",8,12)==="WEBP"){if(De(s))return"possible";let i=s.toString("latin1",12,16);return i==="VP8 "||i==="VP8X"?"none":"unknown"}return"unknown"}catch{return"unknown"}finally{if(t!==void 0)Te.closeSync(t)}}import Jt from"fs";import Re from"os";import{join as dt}from"path";import{fileURLToPath as gt}from"url";import{Worker as mt}from"worker_threads";var ke=Symbol("stx.image-worker.unavailable");function Yt(e=typeof Re.availableParallelism==="function"?Re.availableParallelism():Re.cpus().length){return Math.max(1,Math.min(2,e-1))}var Ae=0,ht=[];async function Qt(){if(Ae<Yt()){Ae++;return}await new Promise((e)=>ht.push(e)),Ae++}function en(){Ae--,ht.shift()?.()}var tn="@stacksjs/stx/builtins/image-warmup-worker";function nn(e=process.cwd()){let t=import.meta.url.endsWith(".ts")?"ts":"js";try{let s=new URL(`./image-warmup-worker.${t}`,import.meta.url);if(s.protocol==="file:"&&Jt.existsSync(gt(s)))return gt(s)}catch{}try{let s=typeof Bun<"u"?Bun.resolveSync(tn,e):void 0;return s&&rn(s)?s:void 0}catch{return}}function rn(e,t=process.env){let s=e.replace(/\\/g,"/");if(s.split("/").some((o)=>/@\d[^/]*@@@\d+$/.test(o)))return!1;return![t.BUN_INSTALL_CACHE_DIR,dt(t.BUN_INSTALL||dt(Re.homedir(),".bun"),"install","cache")].filter((o)=>!!o).map((o)=>`${o.replace(/\\/g,"/").replace(/\/$/,"")}/`).some((o)=>s.startsWith(o))}var pt=!1;function pe(e){if(!pt)pt=!0,console.warn(`[stx] image worker unavailable (${e}); running the image pass on the serving thread instead. Results are the same, but requests may stall while it runs.`);return ke}function Le(e){return e instanceof Error?e.message:String(e)}async function ze(e,t){if(typeof mt!=="function")return pe("node:worker_threads has no Worker in this runtime");let s=nn();if(!s)return pe("no image-warmup-worker entry beside this module or in the installed @stacksjs/stx");await Qt();try{return await new Promise((i,o)=>{let a;try{a=new mt(s)}catch(h){i(pe(`could not start ${s}: ${Le(h)}`));return}let c=!1,g=!1,l=(h)=>{if(g)return;g=!0,h(),a.terminate()};a.on("message",(h)=>{if(h.type==="ready"){c=!0,a.postMessage({task:e,args:t});return}if(h.type==="result"){l(()=>i(h.value));return}let v=Error(h.error?.message??"image worker failed");if(h.error?.name)v.name=h.error.name;if(h.error?.stack)v.stack=h.error.stack;l(()=>o(v))}),a.on("error",(h)=>{l(()=>c?o(h instanceof Error?h:Error(Le(h)||"image worker crashed")):i(pe(`the worker failed before it was ready: ${Le(h)}`)))}),a.on("exit",(h)=>{l(()=>c?o(Error("image worker exited before it finished")):i(pe(`the worker exited with code ${h} before it was ready`)))})})}finally{en()}}var an=new Set([".avif",".jpeg",".jpg",".png",".webp"]),cn=[320,640,960,1280,1920],he="/_stx/images",ln=`stx:${he}:alpha-1`,un=`stx:${he}:opaque-1`,fn=["@stacksjs/ts-webp","@stacksjs/ts-avif","ts-images"],Pe;function dn(e,t){let s=Q.dirname(Bun.resolveSync(e,t));while(s!==Q.dirname(s)){let i=Q.join(s,"package.json");if(ee.existsSync(i)){let o=JSON.parse(ee.readFileSync(i,"utf8"));if(o.name===e)return o.version}s=Q.dirname(s)}return}function xt(){if(Pe!==void 0)return Pe;let e;try{e=Q.dirname(Bun.resolveSync("ts-images",import.meta.dir))}catch{}return Pe=fn.map((t)=>{let s;try{s=e?dn(t,e):void 0}catch{}return`${t.replace("@stacksjs/","")}@${s??"unknown"}`}).join("+"),Pe}var bt=Symbol.for("stx.image-delivery");function ye(){let e=globalThis;return e[bt]??={catalog:new Map,transparent:new Set},e[bt]}var vt=new Set;function gn(e){return`/${e.split(Q.sep).map(encodeURIComponent).join("/")}`}function pn(e){let t=Q.extname(e),s=e.slice(0,-t.length).replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,""),i=Ct("sha256").update(e).digest("hex").slice(0,8);return`${s||"image"}-${i}`}function wt(e,t=`stx:${he}`){let s=(i)=>`${he}/${i.split("/").map(encodeURIComponent).join("/")}`;return{cacheNamespace:t,async stat(i){let o=Q.join(e,i);try{let a=await ee.promises.stat(o);return a.size>0?{bytes:a.size,path:o,url:s(i)}:null}catch{return null}},async write(i,o){let a=Q.join(e,i);await ee.promises.mkdir(Q.dirname(a),{recursive:!0});let c=`${a}.${process.pid}.tmp`;return await ee.promises.writeFile(c,o),await ee.promises.rename(c,a),{bytes:o.byteLength,path:a,url:s(i)}},url:s}}async function Rt(e,t=e){let s=await ee.promises.readdir(t,{withFileTypes:!0});s.sort((o,a)=>o.name.localeCompare(a.name));let i=[];for(let o of s){let a=Q.join(t,o.name);if(o.isDirectory()){i.push(...await Rt(e,a));continue}if(!o.isFile()||!an.has(Q.extname(o.name).toLowerCase()))continue;i.push({absolutePath:a,relativePath:Q.relative(e,a)})}return i}function $t(e,t){return e.map((s)=>({key:gn(s.relativePath),input:s.absolutePath,name:pn(s.relativePath),...hn(s.absolutePath)?{options:{storage:t}}:{}}))}function hn(e){return Me(e)==="possible"}function yn(e){for(let t=3;t<e.length;t+=4)if(e[t]!==255)return!0;return!1}async function xn(e){let t=Object.entries(e).filter(([,o])=>o.fallback.format==="png"),s=new Set,i=8;for(let o=0;o<t.length;o+=8)await Promise.all(t.slice(o,o+8).map(async([a,c])=>{let g=c.variants.filter((l)=>l.format==="png").sort((l,h)=>l.width-h.width)[0];try{let l=await sn(new Uint8Array(await ee.promises.readFile(g?.path??c.fallback.path)));if(yn(l.data))s.add(a)}catch{s.add(a)}}));return s}function bn(e,t){let s=[];for(let i of t){let o=e[i],a=o?.variants.filter((g)=>g.format==="webp")??[];if(!o||a.length===0)continue;if(!a.some((g)=>{let l;try{return l=ee.openSync(g.path,"r"),!De(Ce(l,0,32))}catch{return!0}finally{if(l!==void 0)ee.closeSync(l)}}))continue;if(o.variants=o.variants.filter((g)=>g.format!=="webp"),delete o.sources.webp,s.push(i),!vt.has(i))vt.add(i),console.warn(`[stx-images] ${i} is transparent but its WebP variants have no alpha channel; serving PNG instead. Upgrade @stacksjs/ts-webp to 0.1.6 or later.`)}return s}async function vn(e){let t=[],s=8;for(let i=0;i<e.length;i+=8){let o=e.slice(i,i+8),a=await Promise.all(o.map(async(c)=>{try{return await on(c.absolutePath),c}catch{return console.warn(`[stx-images] Skipping unreadable raster: ${c.relativePath}`),null}}));t.push(...a.filter((c)=>c!==null))}return t}function Ue(e){return Q.join(e,"undecodable.json")}function wn(e){try{let t=ee.readFileSync(Ue(e),"utf-8"),s=JSON.parse(t);return s&&typeof s==="object"?s:{}}catch{return{}}}function $n(e,t){try{ee.mkdirSync(Q.dirname(Ue(e)),{recursive:!0}),ee.writeFileSync(Ue(e),JSON.stringify(t))}catch{}}function St(e){try{let t=ee.statSync(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return}}function At(e){if(!e||e.startsWith("data:")||e.startsWith("blob:")||/^https?:\/\//i.test(e)||e.startsWith("//"))return;let t=e.split(/[?#]/,1)[0];if(!t)return;try{return`/${t.replace(/^\/+/,"").split("/").map(decodeURIComponent).map(encodeURIComponent).join("/")}`}catch{return}}function so(e){let t=At(e);return t?ye().catalog.get(t):void 0}function oo(e){let t=At(e);return t?ye().transparent.has(t):!1}function io(e){let t=(i)=>e.variants.filter((o)=>o.format===i).reduce((o,a)=>o+a.bytes,0),s=t(e.fallback.format);return["avif","webp"].map((i)=>({format:i,srcset:e.sources[i]||"",bytes:t(i)})).filter((i)=>i.srcset&&i.bytes>0&&i.bytes<s).sort((i,o)=>i.bytes-o.bytes).map(({format:i,srcset:o})=>({format:i,srcset:o}))}function hp(e){let t=so(e);if(!t)return;return{src:t.fallback.url,srcset:t.sources[t.fallback.format]||"",sources:io(t).map(({format:s,srcset:i})=>({type:`image/${s}`,srcset:i})),width:t.source.width,height:t.source.height,placeholder:oo(e)?void 0:t.placeholder?.dataUrl}}function Hr(){let e=ye();e.catalog=new Map,e.transparent=new Set}function Sn(e){let t=ye();t.catalog=new Map(e.entries),t.transparent=new Set(e.transparent)}async function yp(e,t,s={}){if(!e||!ee.existsSync(e))return Hr(),{count:0,fingerprint:""};if(s.offThread){let m=await ze("delivery",{publicDir:e,outputDir:t});if(m!==ke)return Sn(m.state),m.result}let i=await Rt(e);if(i.length===0)return Hr(),{count:0,fingerprint:""};let o=wn(t),a=i.filter((m)=>{let b=o[m.relativePath];if(!b)return!0;let w=St(m.absolutePath);return!w||w.mtimeMs!==b.mtimeMs||w.size!==b.size});if(a.length===0)return Hr(),{count:0,fingerprint:""};let c=wt(Q.join(t,"_stx","images"),`${ln}:${xt()}`),g={outDir:Q.join(t,"_stx","images"),storage:wt(Q.join(t,"_stx","images"),`${un}:${xt()}`),baseUrl:he,widths:cn,formats:["avif","webp"],quality:{avif:70,webp:78,jpeg:82,png:100},includeOriginal:!1,placeholder:!0,batchConcurrency:4,concurrency:4},l=a,h;try{h=await yt({...g,entries:$t(a,c)})}catch(m){if(l=await vn(a),l.length===a.length)throw m;let b=new Set(l.map((C)=>C.relativePath)),w=!1;for(let C of a){if(b.has(C.relativePath))continue;let k=St(C.absolutePath);if(!k)continue;o[C.relativePath]=k,w=!0}if(w)$n(t,o);if(l.length===0)return Hr(),{count:0,fingerprint:""};h=await yt({...g,entries:$t(l,c)})}let v=await xn(h.entries),y=bn(h.entries,v),S=ye();S.catalog=new Map(Object.entries(h.entries)),S.transparent=v;let x=v.size===0&&y.length===0?h.fingerprint:Ct("sha256").update(h.fingerprint).update(JSON.stringify({transparent:[...v].sort(),droppedWebp:y.sort()})).digest("hex");return{count:l.length,fingerprint:x}}class kt{builtins=new Map;registerBuiltin(e){this.builtins.set(e.name.toLowerCase(),e);for(let t of e.aliases)this.builtins.set(t.toLowerCase(),e)}isBuiltin(e){return this.builtins.has(e.toLowerCase())}getBuiltin(e){return this.builtins.get(e.toLowerCase())??null}async resolveFile(e,t,s,i){let o=To(e,i);if(o!==void 0)return o;for(let a of $o(e,t,s,i))if(await n(a))return a;return null}}var le=new kt;function R(e){return V(e)}var se="\x00stx-boolean-attribute";function We(e){return e.indexOf("\x00")===-1?e:e.replace(/\0/g,"")}var Cn=new Set(["accesskey","autocapitalize","autofocus","class","contenteditable","dir","draggable","enterkeyhint","exportparts","hidden","id","inert","inputmode","is","itemid","itemprop","itemref","itemscope","itemtype","lang","nonce","part","role","slot","spellcheck","style","tabindex","title","translate","accept","action","alt","autocomplete","capture","cite","cols","colspan","content","controls","datetime","default","download","enctype","for","form","formaction","formenctype","formmethod","formnovalidate","formtarget","height","href","hreflang","kind","label","loading","loop","max","maxlength","media","method","min","minlength","multiple","muted","name","open","pattern","placeholder","playsinline","poster","preload","readonly","referrerpolicy","rel","required","reversed","rows","rowspan","scope","selected","shape","size","span","src","srcdoc","srclang","srcset","start","step","target","type","usemap","value","width","wrap"]);function Fe(e){let t=e.toLowerCase();return t.startsWith("aria-")||t.startsWith("data-")||Cn.has(t)}function ie(e,t){let s=[];for(let[i,o]of Object.entries(e.static)){if(t.has(i))continue;let a=e.staticNames?.[i]??i;if(typeof o==="boolean"){if(o)s.push(d(a));continue}if(o===se){s.push(d(a));continue}s.push(`${d(a)}="${mn(a,We(String(o)))}"`)}return s}function ae(e,t){let s=[];for(let[i,o]of Object.entries(e.serverDynamic??{})){if(t.has(i))continue;if(o===null||o===void 0||o===!1)continue;let a=e.serverDynamicNames?.[i]??i;if(o===!0){s.push(d(a));continue}if(typeof o==="object")continue;s.push(`${d(a)}="${mn(a,We(String(o)))}"`)}return s}function Rn(e){if(e.clientReactive.to)return{value:e.clientReactive.to,reactive:!0};if(e.serverDynamic.to!==void 0)return{value:String(e.serverDynamic.to),reactive:!1};if(typeof e.static.to==="string")return{value:e.static.to,reactive:!1};return{value:"#",reactive:!1}}var He={name:"StxLink",aliases:["stx-link"],render(e,t,s){let i=Rn(e),o=(typeof e.static.class==="string"?e.static.class:"")||(typeof e.static.className==="string"?e.static.className:""),a=typeof e.static.activeClass==="string"?e.static.activeClass:"active",c=typeof e.static.exactActiveClass==="string"?e.static.exactActiveClass:"exact-active",g=e.static.prefetch===!0||e.static.prefetch==="true"||e.serverDynamic.prefetch===!0,l=[];if(i.reactive)l.push(`:href="${R(i.value)}"`);else l.push(`href="${R(ar(i.value,"navigable"))}"`);if(o)l.push(`class="${R(o)}"`);if(l.push("data-stx-link"),l.push(`data-stx-active-class="${R(a)}"`),l.push(`data-stx-exact-active-class="${R(c)}"`),g)l.push("data-stx-prefetch");let h=typeof e.static.activeMatch==="string"?e.static.activeMatch.trim():"";if(h)l.push(`data-stx-active-match="${R(h)}"`);let v=new Set(["to","class","className","activeClass","exactActiveClass","activeMatch","prefetch"]);return l.push(...ie(e,v)),l.push(...ae(e,v)),`<a ${l.join(" ")}>${t}</a>`}};var An=new Map;function qe(e){if(!e)return;let t=e.split("?")[0].split("#")[0];return An.get(t)}var kn={sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Xe=[320,640,768,1024,1280,1536,1920];function J(e,t){if(e.serverDynamic[t]!==void 0)return String(e.serverDynamic[t]);let s=e.static[t];if(typeof s==="string")return s;return}function _e(e,t,s=!1){let i=e.serverDynamic[t];if(i!==void 0)return i!==!1&&i!=="false";let o=e.static[t];if(o!==void 0)return o!=="false"&&o!==!1;return s}function Ze(e){if(e.includes("(")||e.includes(","))return e;let t=e.trim().split(/\s+/),s=[];for(let i of t)if(i.includes(":")){let[o,a]=i.split(":"),c=kn[o];if(c)s.push(`(max-width: ${c}px) ${a}`);else{let g=Number.parseInt(o);if(!Number.isNaN(g))s.push(`(max-width: ${g}px) ${a}`)}}else s.push(i);return s.join(", ")}function Ve(e,t,s,i){return t.map((o)=>`${xe(e,o,void 0,s,i)} ${o}w`).join(", ")}function Pn(e,t,s,i,o){return t.map((a)=>{let c=s?s*a:void 0;return`${xe(e,c,void 0,i,o)} ${a}x`}).join(", ")}function xe(e,t,s,i,o){if(!i||i==="local"||i==="static")return e;if(i==="cloudinary"){let a=[];if(t)a.push(`w_${t}`);if(s)a.push(`h_${s}`);if(o)a.push(`f_${o}`);a.push("q_auto");let c=a.join(",");return e.replace("/upload/",`/upload/${c}/`)}if(i==="imgix"){let a=new URLSearchParams;if(t)a.set("w",String(t));if(s)a.set("h",String(s));if(o)a.set("fm",o);a.set("auto","format");let c=e.includes("?")?"&":"?";return`${e}${c}${a.toString()}`}if(i==="bunny"){let a=new URLSearchParams;if(t)a.set("width",String(t));if(s)a.set("height",String(s));if(o)a.set("format",o);let c=e.includes("?")?"&":"?";return`${e}${c}${a.toString()}`}return e}function _n(e){return`var s=this.style;${e.map((t)=>`s.${t}=''`).join(";")}`}function In(e,t,s="#e5e7eb"){let i=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}"><rect width="100%" height="100%" fill="${s}"/></svg>`;return`data:image/svg+xml;base64,${btoa(i)}`}var Ge={name:"StxImage",aliases:["Image","stx-image","stx-img"],render(e,t,s){let i=J(e,"src")||"",o=so(i),a=J(e,"alt")||"",c=J(e,"width")||(o?String(o.source.width):void 0),g=J(e,"height")||(o?String(o.source.height):void 0),l=J(e,"sizes"),h=J(e,"srcset"),v=J(e,"densities"),y=J(e,"format"),S=oo(i)||qe(i)?.transparent===!0,x=J(e,"placeholder")||(o&&!S?"thumbhash":void 0),m=J(e,"placeholderColor")||"#e5e7eb",b=J(e,"provider"),w=J(e,"class")||J(e,"className")||"",C=J(e,"style")||"",k=J(e,"objectFit")||J(e,"fit"),A=J(e,"objectPosition")||J(e,"position"),I=J(e,"quality"),U=_e(e,"lazy",!0),M=_e(e,"preload",!1),L=_e(e,"priority",!1),q=J(e,"loading"),N=J(e,"decoding")||"async",_=!!o||_e(e,"picture",!1)||!!y,O=c?Number.parseInt(c):void 0,B=g?Number.parseInt(g):void 0,z=h||"",K="";if(o)z=o.sources[o.fallback.format]||"",K=l?Ze(l):"100vw";else if(!z&&l&&b&&b!=="local"&&b!=="static")z=Ve(i,Xe,b,y),K=Ze(l);else if(!z&&v){let P=v.split(/\s+/).map((F)=>Number.parseFloat(F.replace("x","")));z=Pn(i,P,O,b,y)}else if(l)K=Ze(l);let D=[];if(C)D.push(C);if(k)D.push(`object-fit:${k}`);if(A)D.push(`object-position:${A}`);if(O&&B)D.push(`aspect-ratio:${O}/${B}`);let W=[],ce=x==="blur"||x==="color"||x==="thumbhash";if(ce&&!S){let P=o?.placeholder?{dataUrl:o.placeholder.dataUrl,color:m}:qe(i);if(P&&x==="color")D.push(`background-color:${P.color}`),W.push("backgroundColor");else if(P)D.push(`background-color:${P.color}`),D.push(`background-image:url(${P.dataUrl})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundColor","backgroundImage");else{let F=In(O||16,B||9,m);D.push(`background-image:url(${F})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundImage")}}else if(!ce&&x&&x!=="empty"&&x!=="none")D.push(`background-image:url(${R(x)})`),D.push("background-size:cover"),D.push("background-repeat:no-repeat"),W.push("backgroundImage");let we=o?.fallback.url||xe(i,O,B,b,y),Y=[];if(Y.push(`src="${R(ar(we,"fetched"))}"`),Y.push(`alt="${R(a)}"`),c)Y.push(`width="${R(c)}"`);if(g)Y.push(`height="${R(g)}"`);let ne=q||(L||M?"eager":U?"lazy":"");if(ne)Y.push(`loading="${R(ne)}"`);if(L)Y.push('fetchpriority="high"');if(Y.push(`decoding="${R(N)}"`),w)Y.push(`class="${R(w)}"`);if(D.length>0)Y.push(`style="${R(D.join(";"))}"`);if(z)Y.push(`srcset="${R(ar(z,"fetched"))}"`);if(K)Y.push(`sizes="${R(K)}"`);let $e=new Set(["src","alt","width","height","lazy","sizes","srcset","placeholder","placeholderColor","class","className","style","objectFit","objectPosition","fit","position","format","provider","quality","densities","preload","priority","picture","loading","decoding"]);if(W.length>0){let P=typeof e.static.onload==="string"?e.static.onload:"",F=_n(W)+(P?`;${P}`:"");Y.push(`onload="${R(F)}"`),$e.add("onload")}Y.push(...ie(e,$e)),Y.push(...ae(e,$e));let T=`<img ${Y.join(" ")} />`,Z="";if(M){let F=y==="webp"?"image/webp":y==="avif"?"image/avif":"";Z=`<link rel="preload" as="image" href="${R(we)}"${F?` type="${F}"`:""}${z?` imagesrcset="${R(z)}"`:""}${K?` imagesizes="${R(K)}"`:""} />
|
|
3
3
|
`}if(_){let P=[];if(o)for(let F of io(o))P.push(`<source type="image/${F.format}" srcset="${R(F.srcset)}"${K?` sizes="${R(K)}"`:""} />`);if(!o&&(y==="avif"||y==="auto")){let F=xe(i,O,B,b,"avif"),te=z?Ve(i,Xe,b,"avif"):`${F}`;P.push(`<source type="image/avif" srcset="${R(te)}"${K?` sizes="${R(K)}"`:""} />`)}if(!o&&(y==="webp"||y==="auto")){let F=xe(i,O,B,b,"webp"),te=z?Ve(i,Xe,b,"webp"):`${F}`;P.push(`<source type="image/webp" srcset="${R(te)}"${K?` sizes="${R(K)}"`:""} />`)}return`${Z}<picture>
|
|
4
4
|
${P.join(`
|
|
5
5
|
`)}
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{B}from"./chunk-
|
|
2
|
+
import{B}from"./chunk-6eazxhpe.js";import{Be,A,Nt}from"./chunk-t6m5d64b.js";import{ut,ke,O,_e,Ni,Vs,Di,Cn}from"./chunk-mm6xx4pm.js";import{vt,le,Ye}from"./chunk-kypwg2ws.js";import{Qs}from"./chunk-hyk31r03.js";import{En}from"./chunk-pfn70zdr.js";import{he}from"./chunk-eq9s8dcp.js";import Z from"fs";import T from"path";var{serve:ce}=globalThis.Bun;import F from"zlib";import{promisify as Q}from"util";var K=Q(F.brotliCompress),ee=Q(F.gzip),te=["text/","application/json","application/javascript","application/xml","application/xhtml+xml","application/rss+xml","application/atom+xml","application/manifest+json","image/svg+xml"],ne=["text/event-stream","multipart/x-mixed-replace"],re=1024;function se(t){if(!t)return!1;let e=t.toLowerCase();if(ne.some((o)=>e.startsWith(o)))return!1;return te.some((o)=>e.startsWith(o))}function oe(t){let e=new Map;for(let o of t.split(",")){let[r,...a]=o.trim().split(";"),f=r.trim().toLowerCase();if(!f)continue;let h=1;for(let g of a){let l=/^\s*q\s*=\s*([\d.]+)\s*$/i.exec(g);if(!l)continue;let m=Number.parseFloat(l[1]);if(Number.isFinite(m))h=m}e.set(f,h)}return e}function ae(t){if(!t)return null;let e=oe(t),o=e.get("*"),r=(a)=>e.get(a)??o??0;if(r("br")>0)return"br";if(r("gzip")>0)return"gzip";return null}var Y=33554432,H=new Map,U=0;function ie(t,e){if(e.length>Y/8)return;H.set(t,e),U+=e.length;for(let[o,r]of H){if(U<=Y)break;H.delete(o),U-=r.length}}async function kn(t,e,o={}){if(e.headers.get("content-encoding"))return e;if(e.status===204||e.status===304||!e.body)return e;if(!se(e.headers.get("content-type")))return e;let r=ae(t.headers.get("accept-encoding"));if(!r)return e;let a;try{a=new Uint8Array(await e.arrayBuffer())}catch{return e}let f=()=>new Response(a,{status:e.status,statusText:e.statusText,headers:J(e.headers)});if(a.length<(o.threshold??re))return f();try{let h=o.quality??5,g=`${r}:${h}:${a.length}:${Bun.hash(a)}`,l=H.get(g);if(!l)l=r==="br"?await K(a,{params:{[F.constants.BROTLI_PARAM_QUALITY]:h,[F.constants.BROTLI_PARAM_SIZE_HINT]:a.length}}):await ee(a),ie(g,l);if(l.length>=a.length)return f();let m=J(e.headers);return m.set("Content-Encoding",r),m.set("Content-Length",String(l.length)),new Response(l,{status:e.status,statusText:e.statusText,headers:m})}catch{return f()}}function J(t){let e=new Headers(t),o=e.get("Vary");if(!o)return e.set("Vary","Accept-Encoding"),e;if(!o.split(",").some((a)=>a.trim().toLowerCase()==="accept-encoding"))e.set("Vary",`${o}, Accept-Encoding`);return e}class G{now;entries=new B(1000,{maxBytes:33554432,sizeOf:(t)=>t.body.byteLength+JSON.stringify(t.headers).length*2});pending=new Map;generation=0;constructor(t=Date.now){this.now=t}invalidate(t){this.generation++,this.pending.clear();for(let e of Array.from(this.entries.keys()))if(t===void 0||this.entries.get(e)?.path===t)this.entries.delete(e)}async respond(t,e,o){let r,a=async()=>{let s=r??await o();return s.headers.set("Cache-Control","private, no-store"),s.headers.set("Vary",O(s.headers.get("Vary")).Vary),s};if(!e||t.method!=="GET"||t.headers.has("Cookie")||t.headers.has("Authorization")||t.headers.has("Range"))return a();let f=new URL(t.url),h=`${f.origin}${f.pathname}${f.search}|${ke(t)?"fragment":"document"}`,g=this.entries.get(h),l=(s)=>{let b=new Headers(s.headers);return b.set("Cache-Control","private, no-store"),b.set("Age",String(Math.max(0,Math.floor((this.now()-s.created)/1000)))),new Response(s.body.slice(0),{headers:b})},m=g?(this.now()-g.created)/1000:1/0;if(g&&m<e.maxAge)return l(g);let v=this.generation,N=async()=>{let s=await o();r=s;let b=(s.headers.get("Vary")??"").toLowerCase().split(",").map((y)=>y.trim()).filter(Boolean);if(s.status!==200||s.headers.has("Set-Cookie")||/(?:private|no-store|no-cache)/i.test(s.headers.get("Cache-Control")??"")||b.some((y)=>y!=="x-stx-router"&&y!=="accept-encoding"))return null;let E=await s.clone().arrayBuffer();if(E.byteLength>1048576)return null;s.headers.set("Vary",O(s.headers.get("Vary")).Vary);let n={body:E,headers:Array.from(s.headers.entries()),created:this.now(),path:f.pathname};if(this.generation===v)this.entries.set(h,n);return n},x=this.pending.get(h);if(!x){if(this.pending.size>=1000)return a();x=N().finally(()=>{if(this.pending.get(h)===x)this.pending.delete(h)}),this.pending.set(h,x)}if(g&&m<e.maxAge+(e.swr??0))return x.catch(()=>{}),l(g);let M=await x;return M?l(M):a()}}var pe={".js":"application/javascript",".mjs":"application/javascript",".css":"text/css",".json":"application/json",".html":"text/html",".txt":"text/plain",".xml":"application/xml",".pdf":"application/pdf",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".webp":"image/webp",".avif":"image/avif",".svg":"image/svg+xml",".ico":"image/x-icon",".bmp":"image/bmp",".mp4":"video/mp4",".webm":"video/webm",".ogg":"audio/ogg",".mp3":"audio/mpeg",".wav":"audio/wav",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"};async function Ou(t={}){let e=T.resolve(t.outputDir||".output"),o=t.port??3000,r=Ni(e);if(!r)console.error("[stx] No build manifest found. Run `stx build` first."),process.exit(1);console.log(`[stx] Production server loading ${r.routes.length} routes...`);let a=En(r.routeRules),f=new G,h=Qs(e,r.apiRoutes??[]),g=Bun.file(T.join(e,"server/runtime-config.json")),l=t.runtimeConfig??(await g.exists()?await g.json():void 0),m=l?A(l):void 0,v=new Map,N=new Map,x=new Map,M=new Map;for(let n of r.routes)try{let y=T.join(e,n.compiledPath),i=JSON.parse(await Bun.file(y).text());if(m)i.html=Nt(i.html,m);v.set(n.pattern,i),x.set(n.pattern,Ye(i.html)),M.set(n.pattern,he(i.html));let X=T.join(e,n.fragmentPath);if(await Bun.file(X).exists()){let P=await Bun.file(X).text();N.set(n.pattern,m?Nt(P,m):P)}}catch(y){console.warn(`[stx] Failed to load route ${n.pattern}:`,y)}let s=new Map,b=[];for(let n of r.routes)if(n.hasParams){let{regex:y,params:i}=le(n.pattern,{page:!0});b.push({regex:y,route:n,paramNames:i})}else s.set(n.pattern,n);let E=ce({port:o,async fetch(n){return kn(n,await Be(m??A(),async()=>{let i=new URL(n.url).pathname;if(t.onRequest){let p=await t.onRequest(n);if(p)return p}if(t.apiRouter){let p=await t.apiRouter.handleRequest(n);if(p.status!==404)return p}if(t.apiRoutes?.[i])return t.apiRoutes[i](n);let X=await h(n);if(X)return X;if((n.method==="GET"||n.method==="HEAD")&&i!=="/"){let p=T.resolve(e,"public"),d;try{d=decodeURIComponent(i)}catch{d=i}if(!d.includes("\x00")){let u=T.resolve(p,`.${d}`);if(u===p||u.startsWith(`${p}${T.sep}`))try{if(Z.existsSync(u)&&Z.statSync(u).isFile()){let R=T.extname(u).toLowerCase(),L=pe[R]||"application/octet-stream",_=i.startsWith("/__stx/")||/\.[0-9a-f]{8}\./.test(i);return new Response(Bun.file(u),{headers:{"Content-Type":L,"Cache-Control":_?"public, max-age=31536000, immutable":"public, max-age=3600"}})}}catch{}}}let P=ke(n),C=null,q={};if(C=s.get(i)||null,!C)for(let{regex:p,route:d,paramNames:u}of b){let c=i.match(p);if(c){C=d,u.forEach((R,L)=>{q[R]=c[L+1]});break}}if(!C){let p=vt(i)?null:s.get("/404")||null;if(p){let d=v.get(p.pattern);if(d)return new Response(d.html,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}})}let k=a(i),W=Object.keys(k).length>0;return f.respond(n,k.cache,async()=>{let p=v.get(C.pattern);if(P&&n.method==="GET"&&p&&!p.hasServerScripts&&Object.keys(p.placeholders).length===0){let c=N.get(C.pattern);if(c){let R=x.get(C.pattern);return new Response(c,{status:p.status??200,headers:{"Content-Type":"text/html","X-STX-Fragment":"true",...M.has(C.pattern)?{"X-STX-Runtime":M.get(C.pattern)?"true":"false"}:{},...R?{"X-STX-Layout":R.layout,"X-STX-Layout-Group":R.group}:{},...O(),...k.cache?{}:{"Cache-Control":ut}}})}}let d=Vs(n.method),u=v.get(C.pattern);if(!u){let c=s.get("/500")||null;if(c){let R=v.get(c.pattern);if(R)return new Response(R.html,{status:500,headers:{"Content-Type":"text/html"}})}return new Response("Internal Server Error",{status:500})}if(C.prerendered&&d)return new Response("Prerendered pages do not accept actions",{status:405,headers:{Allow:"GET, HEAD"}});if(!d&&!u.hasServerScripts&&Object.keys(u.placeholders).length===0)return new Response(u.html,{status:u.status??200,headers:{"Content-Type":"text/html",...O(),"Cache-Control":"public, max-age=60"}});try{let{html:c,boundaries:R,redirect:L,cookies:_,status:I,headers:D}=await Cn(u,{params:q,request:n,method:n.method,__stx_strict_hydration:W,__stx_runtime_config:m});if(L)return Di(L,_,D);if(R&&R.length>0){let{renderStreamingPage:S,streamToResponse:z}=await import("./chunk-2khba4de.js"),j=new Headers({...O(),...D,"Cache-Control":"private, no-store"});for(let V of _??[])j.append("Set-Cookie",V);if(P&&!d){let V=Ye(c);j.set("X-STX-Fragment","true"),j.set("X-STX-Runtime",he(c)?"true":"false"),j.set("X-STX-Layout",V.layout),j.set("X-STX-Layout-Group",V.group)}return z(S(P&&!d?_e(c,r.routerContainer||"main"):c,R,{timeoutMs:30000}),{status:I??u.status??200,headers:j})}let w=new Headers({"Content-Type":"text/html",...O(),...k.cache?{}:{"Cache-Control":"private, no-store"}});for(let S of _??[])w.append("Set-Cookie",S);for(let[S,z]of Object.entries(D??{}))w.set(S,z);if(w.set("Vary",O(w.get("Vary")).Vary),P&&!d){let S=Ye(c);return w.set("X-STX-Fragment","true"),w.set("X-STX-Runtime",he(c)?"true":"false"),w.set("X-STX-Layout",S.layout),w.set("X-STX-Layout-Group",S.group),new Response(_e(c,r.routerContainer||"main"),{status:I??u.status??200,headers:w})}return new Response(c,{status:I??u.status??200,headers:w})}catch(c){if(console.error(`[stx] Hydration error for ${i}:`,c),W)return new Response("Internal Server Error",{status:500});return new Response(u.html,{headers:{"Content-Type":"text/html"}})}})}))}});return console.log(`[stx] Production server running at http://localhost:${E.port}`),console.log(`[stx] Serving ${r.routes.length} routes (${v.size} pre-loaded)`),{port:E.port,stop:()=>{f.invalidate(),E.stop()},invalidate:(n)=>f.invalidate(n)}}
|
|
3
3
|
export{kn,Ou};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{en,Ys,Zs,Qs,lp,eo}from"./chunk-
|
|
2
|
+
import{en,Ys,Zs,Qs,lp,eo}from"./chunk-hyk31r03.js";import"./chunk-912r15hr.js";import"./chunk-kypwg2ws.js";import"./chunk-t6m5d64b.js";export{Zs as buildServerApi,lp as createServerApi,en as discoverServerApi,Ys as generateApiTypes,eo as isServerApiSource,Qs as productionApiDispatcher};
|
|
@@ -1,3 +1,3 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{i}from"./chunk-
|
|
2
|
+
import{i}from"./chunk-4cnphtcz.js";import{Us}from"./chunk-pfn70zdr.js";import p from"path";async function Qu(t={}){let d=performance.now(),o=t.root||process.cwd(),e=await i(o),u=t.ssr?.routeRules??e.routeRules??{};if(Us(u),!e.ssr&&Object.keys(u).length)throw Error("routeRules require ssr: true and the production server; flat SSG output cannot apply request/cache policies");if(!e.ssr&&(t.ssr?.serverApi??e.serverApi))throw Error("serverApi requires ssr: true; flat SSG output cannot execute API endpoints");let r=e.ssr?"ssr":"ssg";console.log(`[stx build] Mode: ${r.toUpperCase()}${e.ssr?" (ssr: true in stx.config.ts)":" (default \u2014 ssr is false)"}`);let n,l;if(r==="ssg"){let{generateStaticSite:s}=await import("./ssg.js");n=await s({pagesDir:p.join(e.root||".",e.pagesDir||e.build?.pagesDir||"pages"),publicDir:e.publicDir||e.build?.publicDir||"public",outputDir:e.build?.outputDir||"dist",generate404:e.build?.generate404??!0,minify:e.build?.minify??!0,cleanOutput:e.build?.cleanOutput??!0,router:e.router,...t.ssg})}else{let{buildForProduction:s}=await import("./chunk-y4kzqam8.js");l=await s({root:o,outputDir:".output",debug:t.debug,...t.ssr})}let a=Math.round(performance.now()-d);return{mode:r,ssg:n,ssr:l,duration:a}}
|
|
3
3
|
export{Qu};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Ws,qd,Kd}from"./chunk-3t8aag0q.js";import"./chunk-mxpmt6wm.js";import"./chunk-hyk31r03.js";import"./chunk-374nhgyf.js";import"./chunk-a81452y9.js";import"./chunk-eq9s8dcp.js";import"./chunk-jgxzbthg.js";import"./chunk-4cnphtcz.js";import"./chunk-9ed0hr7y.js";import"./chunk-tenbwcts.js";import"./chunk-912r15hr.js";import"./chunk-ygb33q5w.js";import"./chunk-kypwg2ws.js";import"./chunk-6eazxhpe.js";import"./chunk-bwcejt6t.js";import"./chunk-t6m5d64b.js";import"./chunk-r0ys9aqa.js";import"./chunk-6beg47t4.js";import"./chunk-gtktv6nn.js";export{Kd as clearComposableCache,qd as getComposableScript,Ws as listComposableModules};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{vn}from"./chunk-r0ys9aqa.js";import{F,z,At,Pt,dr,g,tc,zo,V,_}from"./chunk-
|
|
2
|
+
import{vn}from"./chunk-r0ys9aqa.js";import{F,z,At,Pt,dr,g,tc,zo,V,_}from"./chunk-6eazxhpe.js";import{Gt}from"./chunk-bsnactb2.js";import{W}from"./chunk-078as147.js";var H=new Set(["area","base","br","col","embed","hr","img","input","link","meta","param","source","track","wbr"]);function B(e){let n=[],t=/<!--[\s\S]*?(?:-->|$)|<(script|style|textarea|title|template)\b[^>]*>[\s\S]*?<\/\1\s*>/gi,r;while((r=t.exec(e))!==null)n.push({start:r.index,end:r.index+r[0].length});return n}function P(e,n){return n.some((t)=>e>=t.start&&e<t.end)}function q(e){let n=(e||"").trim();if(!n)return null;if(/[\s>+~,:]/.test(n))return null;let t={},r=n,s=r.match(/^[a-z][\w-]*/i);if(s)t.tag=s[0].toLowerCase(),r=r.slice(s[0].length);while(r.length>0){let o=r.match(/^\[([\w-]+)(?:=(["']?)([^\]"']*)\2)?\]/);if(o){if(t.attr=o[1],o[3]!==void 0&&o[3]!=="")t.attrValue=o[3];r=r.slice(o[0].length);continue}let a=r.match(/^#([\w-]+)/);if(a){t.id=a[1],r=r.slice(a[0].length);continue}let i=r.match(/^\.([\w-]+)/);if(i){t.className=i[1],r=r.slice(i[0].length);continue}return null}if(!t.tag&&!t.attr&&!t.id&&!t.className)return null;return t}function U(e,n){if(n.attr){if(!(n.attrValue===void 0?new RegExp(`\\b${n.attr}(?=[\\s=>/]|$)`,"i"):new RegExp(`\\b${n.attr}\\s*=\\s*(["'])\\s*${n.attrValue}\\s*\\1`,"i")).test(e))return!1}if(n.id){if(!new RegExp(`\\bid\\s*=\\s*(["'])\\s*${n.id}\\s*\\1`,"i").test(e))return!1}if(n.className){let t=e.match(/\bclass\s*=\s*(["'])([\s\S]*?)\1/i);if(!t)return!1;if(!t[2].split(/\s+/).includes(n.className))return!1}return!0}function T(e,n="main"){let t=q(n);if(!t)return null;let r=/<([a-z][\w-]*)\b([^>]*)>/gi,s=B(e),o;while((o=r.exec(e))!==null){if(P(o.index,s))continue;let a=o[1].toLowerCase(),i=o[2]||"";if(i.trimEnd().endsWith("/")||H.has(a))continue;if(t.tag&&t.tag!==a)continue;if(!U(i,t))continue;let c=o[0],u=o.index+c.length,l=new RegExp(`<(/?)${a}\\b([^>]*)>`,"gi");l.lastIndex=u;let f=1,m;while((m=l.exec(e))!==null){if(P(m.index,s))continue;let x=m[1]==="/";if(!x&&(m[2]||"").trimEnd().endsWith("/"))continue;if(f+=x?-1:1,f===0)return{openTag:c,openIndex:o.index,start:u,end:m.index,tagName:a}}return null}return null}var ut="private, no-store";function Ri(e){return e.replace(/&#(\d+);/g,(n,t)=>M(Number(t),n)).replace(/&#x([0-9a-f]+);/gi,(n,t)=>M(Number.parseInt(t,16),n)).replace(/</g,"<").replace(/>/g,">").replace(/"/g,'"').replace(/'/g,"'").replace(/&/g,"&")}function M(e,n){if(!Number.isInteger(e)||e<0||e>1114111)return n;try{return String.fromCodePoint(e)}catch{return n}}function ke(e){return e.headers.get("X-STX-Router")==="true"}function G(e,n){if(!e)return n;return e.split(",").some((r)=>r.trim().toLowerCase()===n.toLowerCase())?e:`${e}, ${n}`}function O(e){return{Vary:G(e,"X-STX-Router")}}import E from"path";var X="stx-page-head:",J=/<!--stx-page-head:([A-Za-z0-9+/=]+)-->\n?/,C={dev:null,prod:null};function K(){let e=W()?"dev":"prod",n=C[e];if(n!==null)return n;try{let t=import.meta.require("./chunk-mkaw0bn4.js"),r=e==="dev"&&typeof t.getRouterScriptDev==="function"?t.getRouterScriptDev:t.getRouterScript;C[e]=`<script>${r()}</script>`}catch{C[e]=""}return C[e]}async function Ai(e,n){if(n===!1)return null;if(n&&typeof n==="string"){let r=E.resolve(e,n);if(await Bun.file(r).exists())return r;return null}let t=E.join(e,"app.stx");if(await Bun.file(t).exists())return t;return null}async function Hs(e,n){try{let t=await Bun.file(e).text(),r=t,s=t.match(/<template\b[^>]*>([\s\S]*?)<\/template>/i);if(s)r=s[1].trim();let o=Gt(t),a=[...o.client.map((d)=>d.fullTag),...o.signals.map((d)=>d.fullTag)],i=[],c=/<style\b[^>]*>([\s\S]*?)<\/style>/gi,u;while((u=c.exec(t))!==null)i.push(u[0]);let l=r;for(let d of o.server)l=l.replace(d.fullTag,"");for(let d of o.client)l=l.replace(d.fullTag,"");l=l.replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"");let f="<!--__STX_PAGE_SLOT__-->";if(l=l.replace(/<slot\s*\/>/gi,f).replace(/<slot\s*>\s*<\/slot>/gi,f),!l.includes(f))return console.warn(`[stx] Shell ${e} has no <slot /> \u2014 pages won't be injected`),null;let{processDirectives:m,extractVariables:x,defaultConfig:y,loadStxConfig:R}=await import("./chunk-gjj8krdx.js"),S=await R(),p={__filename:e,__dirname:E.dirname(e)};for(let d of a){let w=d.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(w&&!d.includes("client")&&!d.includes('type="module"'))await x(w[1],p,e)}let b=await m(l,p,e,{...y,...S,...n},new Set),h=b.indexOf(f);if(h===-1)return console.warn("[stx] Shell slot placeholder lost during processing"),null;return{beforeSlot:b.substring(0,h),afterSlot:b.substring(h+f.length),filePath:e,shellScripts:a,shellStyles:i}}catch(t){return console.error(`[stx] Error processing shell ${e}:`,t),null}}function Pr(e,n,t){let r,s="",o=n.match(J);if(o){n=n.replace(o[0],"");try{let l=Buffer.from(o[1],"base64").toString("utf8"),f=l.match(/<title[^>]*>([\s\S]*?)<\/title>/i);if(f)r=f[1].trim();s=l.replace(/<title[^>]*>[\s\S]*?<\/title>/i,"").trim()}catch{}}let a=t||r||"stx App",i=K(),c="<script>window.__stxRouterConfig={container:'[data-stx-content]'};</script>";return`<!DOCTYPE html>
|
|
3
3
|
<html lang="en">
|
|
4
4
|
<head>
|
|
5
5
|
<meta charset="UTF-8">
|
|
@@ -27,5 +27,5 @@ ${i}
|
|
|
27
27
|
`));if(s.length>0)S.push(s.filter((p)=>!c.has(p)).join(`
|
|
28
28
|
`));if(x.length>0)S.push(x.filter((p)=>!c.has(p)).join(`
|
|
29
29
|
`));return S.push(m),S.join(`
|
|
30
|
-
`)}import v from"fs";import I from"path";function Ii(e,n,t){return{version:1,buildTime:new Date().toISOString(),routes:e,assets:n,outputDir:t}}function Oi(e,n){let t=I.join(n,"manifest.json");v.writeFileSync(t,JSON.stringify(e,null,2))}function Ni(e){let n=I.join(e,"manifest.json");if(!v.existsSync(n))return null;try{let t=v.readFileSync(n,"utf-8"),r=JSON.parse(t);if(r.version!==1)return console.warn(`[stx] Manifest version mismatch: expected 1, got ${r.version}`),null;return r}catch(t){return console.warn("[stx] Failed to load manifest:",t),null}}function k(e,n,t={}){let r=`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(t.maxAge!==void 0)r+=`; Max-Age=${t.maxAge}`;if(t.expires)r+=`; Expires=${t.expires.toUTCString()}`;if(t.path)r+=`; Path=${t.path}`;if(t.domain)r+=`; Domain=${t.domain}`;if(t.secure)r+="; Secure";if(t.httpOnly)r+="; HttpOnly";if(t.sameSite)r+=`; SameSite=${t.sameSite}`;return r}async function Z(e){let n=e.headers.get("content-type")||"",t={},r=(s,o)=>{let a=t[s];if(a===void 0)t[s]=o;else if(Array.isArray(a))a.push(o);else t[s]=[a,o]};if(n.includes("multipart/form-data")){let s=await e.formData();for(let[o,a]of s.entries())if(typeof a==="string")r(o,a);return t}if(n.includes("application/x-www-form-urlencoded")){for(let[s,o]of new URLSearchParams(await e.text()).entries())r(s,o);return t}return t}function Vs(e){if(!e)return!1;let n=e.toUpperCase();return n!=="GET"&&n!=="HEAD"}async function D(e,n={}){let t=n.request,r=n.method??t?.method;if(!t||!Vs(r))return{ran:!1};if(typeof e.action!=="function")return{ran:!1};let s={};try{s=await Z(t)}catch{}let o=await e.action({request:t,form:s,params:n.params??{},query:e.query??{},cookies:n.cookies??{}});if(o&&typeof o==="object"){let a=o,i=Q(a.cookies),c=a.redirect;if(typeof c==="string"&&c)return{redirect:c,ran:!0,...i.length>0?{cookies:i}:{}};let{cookies:u,redirect:l,...f}=a;if(Object.assign(e,f),i.length>0)return{ran:!0,cookies:i}}return{ran:!0}}function Q(e){if(!e||typeof e!=="object"||Array.isArray(e))return[];let n=[];for(let[t,r]of Object.entries(e)){if(!t)continue;if(typeof r==="string"){n.push(k(t,r));continue}if(r&&typeof r==="object"){let s=r;if(typeof s.value!=="string")continue;n.push(k(t,s.value,s))}}return n}function Di(e,n=[],t){let r=new Headers({Location:e,"Cache-Control":"no-store"});for(let s of n)r.append("Set-Cookie",s);for(let[s,o]of Object.entries(t??{}))if(s.toLowerCase()!=="location")r.set(s,o);return new Response(null,{status:303,headers:r})}async function Cn(e,n={}){let{html:t,context:r,redirect:s,cookies:o}=await tt(e,n),a=At(r),i=Pt(r);if(s)return{html:t,redirect:s,cookies:o,status:a,headers:i};let{extractStreamBoundaries:c}=await import("./chunk-
|
|
30
|
+
`)}import v from"fs";import I from"path";function Ii(e,n,t){return{version:1,buildTime:new Date().toISOString(),routes:e,assets:n,outputDir:t}}function Oi(e,n){let t=I.join(n,"manifest.json");v.writeFileSync(t,JSON.stringify(e,null,2))}function Ni(e){let n=I.join(e,"manifest.json");if(!v.existsSync(n))return null;try{let t=v.readFileSync(n,"utf-8"),r=JSON.parse(t);if(r.version!==1)return console.warn(`[stx] Manifest version mismatch: expected 1, got ${r.version}`),null;return r}catch(t){return console.warn("[stx] Failed to load manifest:",t),null}}function k(e,n,t={}){let r=`${encodeURIComponent(e)}=${encodeURIComponent(n)}`;if(t.maxAge!==void 0)r+=`; Max-Age=${t.maxAge}`;if(t.expires)r+=`; Expires=${t.expires.toUTCString()}`;if(t.path)r+=`; Path=${t.path}`;if(t.domain)r+=`; Domain=${t.domain}`;if(t.secure)r+="; Secure";if(t.httpOnly)r+="; HttpOnly";if(t.sameSite)r+=`; SameSite=${t.sameSite}`;return r}async function Z(e){let n=e.headers.get("content-type")||"",t={},r=(s,o)=>{let a=t[s];if(a===void 0)t[s]=o;else if(Array.isArray(a))a.push(o);else t[s]=[a,o]};if(n.includes("multipart/form-data")){let s=await e.formData();for(let[o,a]of s.entries())if(typeof a==="string")r(o,a);return t}if(n.includes("application/x-www-form-urlencoded")){for(let[s,o]of new URLSearchParams(await e.text()).entries())r(s,o);return t}return t}function Vs(e){if(!e)return!1;let n=e.toUpperCase();return n!=="GET"&&n!=="HEAD"}async function D(e,n={}){let t=n.request,r=n.method??t?.method;if(!t||!Vs(r))return{ran:!1};if(typeof e.action!=="function")return{ran:!1};let s={};try{s=await Z(t)}catch{}let o=await e.action({request:t,form:s,params:n.params??{},query:e.query??{},cookies:n.cookies??{}});if(o&&typeof o==="object"){let a=o,i=Q(a.cookies),c=a.redirect;if(typeof c==="string"&&c)return{redirect:c,ran:!0,...i.length>0?{cookies:i}:{}};let{cookies:u,redirect:l,...f}=a;if(Object.assign(e,f),i.length>0)return{ran:!0,cookies:i}}return{ran:!0}}function Q(e){if(!e||typeof e!=="object"||Array.isArray(e))return[];let n=[];for(let[t,r]of Object.entries(e)){if(!t)continue;if(typeof r==="string"){n.push(k(t,r));continue}if(r&&typeof r==="object"){let s=r;if(typeof s.value!=="string")continue;n.push(k(t,s.value,s))}}return n}function Di(e,n=[],t){let r=new Headers({Location:e,"Cache-Control":"no-store"});for(let s of n)r.append("Set-Cookie",s);for(let[s,o]of Object.entries(t??{}))if(s.toLowerCase()!=="location")r.set(s,o);return new Response(null,{status:303,headers:r})}async function Cn(e,n={}){let{html:t,context:r,redirect:s,cookies:o}=await tt(e,n),a=At(r),i=Pt(r);if(s)return{html:t,redirect:s,cookies:o,status:a,headers:i};let{extractStreamBoundaries:c}=await import("./chunk-2khba4de.js"),u=c(r),l=e.streamTemplates;if(l&&Object.keys(l).length>0){let{processDirectives:f}=await import("./chunk-a3s7tqsp.js"),{defaultConfig:m}=await import("./chunk-5tkby4j6.js"),x=r.streamBoundaries||{},y={...m,autoShell:!1},R=Object.keys(l).map((p)=>({id:p,render:async()=>{let b=typeof x[p]==="function"?await x[p]():void 0;return f(l[p],{...r,$boundary:b},e.sourceFile,y,new Set)}})),S=new Set(R.map((p)=>p.id));u=[...(u||[]).filter((p)=>!S.has(p.id)),...R]}return{html:t,boundaries:u&&u.length>0?u:void 0,cookies:o,status:a,headers:i}}async function tt(e,n){let t={__filename:e.sourceFile,__dirname:e.sourceFile.replace(/[/\\][^/\\]+$/,""),...n};if(!e.hasServerScripts&&!zo(e.html))return{html:e.html,context:t};for(let a of e.serverScriptContent)try{await g(a,t,e.sourceFile)}catch(i){if(n.__stx_strict_hydration)throw i;console.warn(`[stx] Server script error in ${e.sourceFile}:`,i)}let r=await D(t,{request:n.request,method:n.method,params:n.params??{},cookies:n.cookies??{}}),s=(a)=>{let i=a.replace(/<script\b[^>]*\bdata-stx-server-data\b[^>]*>[\s\S]*?<\/script>/gi,""),c=dr(t);if(!c)return i;let u=i.indexOf("</head>");return u<0?c+i:i.slice(0,u)+c+i.slice(u)};if(r.redirect)return{html:e.html,context:t,redirect:r.redirect,cookies:r.cookies};if(!zo(e.html))return{html:s(e.html),context:t,cookies:r.cookies};let o=new Map;for(let[a,i]of Object.entries(e.placeholders))if(i.expression)try{let c=_(i.expression,t);if(i.type==="raw")o.set(a,c!==void 0&&c!==null?String(c):"");else o.set(a,c!==void 0&&c!==null?V(String(c)):"")}catch(c){if(n.__stx_strict_hydration)throw c;o.set(a,"")}return{html:s(tc(e.html,o)),context:t,cookies:r.cookies}}
|
|
31
31
|
export{ut,Ri,ke,O,Ai,Hs,Pr,Ve,Pi,_e,Ii,Oi,Ni,Vs,Di,Cn};
|