@stacksjs/stx 0.2.788 → 0.2.790
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-h88p9w9x.js → chunk-0dwh4g5q.js} +1 -1
- package/dist/{chunk-ebxmj4q2.js → chunk-0r5xawp8.js} +2 -2
- package/dist/{chunk-khndcwxy.js → chunk-0v03s1ec.js} +1 -1
- package/dist/{chunk-kbaay11r.js → chunk-18e7g53p.js} +1 -1
- package/dist/{chunk-nb8czvz1.js → chunk-24pwa3gm.js} +5 -5
- package/dist/{chunk-67ezpess.js → chunk-282sw7wt.js} +1 -1
- package/dist/{chunk-05taafth.js → chunk-2ghbfpve.js} +1 -1
- package/dist/{chunk-4vxz57e1.js → chunk-2w00dt3d.js} +1 -1
- package/dist/{chunk-y38rxnrr.js → chunk-3wm4t5tp.js} +1 -1
- package/dist/{chunk-2yexd919.js → chunk-44etj70r.js} +4 -4
- package/dist/{chunk-w1xzkkk3.js → chunk-5gk5nnqb.js} +1 -1
- package/dist/{chunk-ee2jz9xp.js → chunk-5xwdftne.js} +1 -1
- package/dist/chunk-65bnepha.js +3 -0
- package/dist/{chunk-ns1hpm7x.js → chunk-7ga3hwvw.js} +2 -2
- package/dist/{chunk-p2r6rbs4.js → chunk-7hex58nx.js} +1 -1
- package/dist/{chunk-yrqy4vka.js → chunk-7y1tzrb5.js} +1 -1
- package/dist/{chunk-9h532cqf.js → chunk-81fvwcv4.js} +3 -3
- package/dist/{chunk-epg3gkc6.js → chunk-82n173j5.js} +1 -1
- package/dist/{chunk-c7e78z00.js → chunk-84krcm57.js} +1 -1
- package/dist/{chunk-gp5japjb.js → chunk-8cc831sc.js} +2 -2
- package/dist/{chunk-dwrjs05v.js → chunk-9aasebkz.js} +1 -1
- package/dist/{chunk-y8wer7e1.js → chunk-9k50gdfa.js} +57 -57
- package/dist/{chunk-jf4kesf8.js → chunk-9vgt456p.js} +1 -1
- package/dist/{chunk-9pkazxn1.js → chunk-aevsybw1.js} +1 -1
- package/dist/{chunk-wjcph0yf.js → chunk-bvynz9z8.js} +1 -1
- package/dist/{chunk-qadv0nrt.js → chunk-g4qhpdra.js} +18 -18
- package/dist/{chunk-9pkx13hy.js → chunk-hn0tqgfw.js} +1 -1
- package/dist/{chunk-7w3p07yp.js → chunk-hrjhrwt5.js} +1 -1
- package/dist/{chunk-3772atqp.js → chunk-j20xtgnj.js} +2 -2
- package/dist/chunk-kksgn66f.js +2 -0
- package/dist/chunk-m0ppxx35.js +2 -0
- package/dist/{chunk-2hm4nmt9.js → chunk-m6gs86mk.js} +2 -2
- package/dist/{chunk-6sgqa52q.js → chunk-mjw1d14e.js} +1 -1
- package/dist/chunk-n2nfcq8a.js +2 -0
- package/dist/{chunk-s14v17b5.js → chunk-n6vp1m14.js} +4 -4
- package/dist/chunk-nhh55xc4.js +2 -0
- package/dist/chunk-nv3aze4j.js +2 -0
- package/dist/chunk-p40v345t.js +2 -0
- package/dist/{chunk-bwvnstrd.js → chunk-pp0fy0yr.js} +1 -1
- package/dist/{chunk-8p65gzw0.js → chunk-precehta.js} +1 -1
- package/dist/chunk-pvs12vay.js +2 -0
- package/dist/{chunk-9dzgkt5x.js → chunk-q5vqabha.js} +1 -1
- package/dist/{chunk-gwzp463h.js → chunk-qf5a8mmw.js} +1 -1
- package/dist/{chunk-shmm7135.js → chunk-qpfpjbtk.js} +1 -1
- package/dist/{chunk-8qex68bk.js → chunk-rn2kpdcj.js} +1 -1
- package/dist/{chunk-zd6cygn3.js → chunk-s48fv41x.js} +1 -1
- package/dist/{chunk-hexa0j1j.js → chunk-scjvs0y5.js} +1 -1
- package/dist/{chunk-yehq3z73.js → chunk-shvk57ba.js} +1 -1
- package/dist/{chunk-j10mdh4g.js → chunk-sqmqz4jb.js} +2 -2
- package/dist/{chunk-kb2xxmxp.js → chunk-t5fgdj4e.js} +1 -1
- package/dist/{chunk-4yhsmwcc.js → chunk-t817zpwe.js} +1 -1
- package/dist/{chunk-6vqz4qqy.js → chunk-tw5x7rv9.js} +1 -1
- package/dist/{chunk-se44k8bp.js → chunk-v2zscenh.js} +1 -1
- package/dist/{chunk-vrw1qs1j.js → chunk-v33r2veh.js} +1 -1
- package/dist/chunk-v3jgbsgd.js +2 -0
- package/dist/{chunk-z9h2s292.js → chunk-vgqhmjac.js} +1 -1
- package/dist/{chunk-mymnmr1m.js → chunk-vhwyymxh.js} +1 -1
- package/dist/chunk-vwvfedp7.js +2 -0
- package/dist/{chunk-4dd0yecs.js → chunk-wgnwempr.js} +4 -4
- package/dist/{chunk-fgz2kbwb.js → chunk-wnhcnm74.js} +1 -1
- package/dist/{chunk-a1kvc52k.js → chunk-x2ksr6hc.js} +1 -1
- package/dist/{chunk-t271s8p9.js → chunk-y40tgphb.js} +1 -1
- package/dist/chunk-yg78zaj8.js +2 -0
- package/dist/{chunk-9ppsnerc.js → chunk-zts834eb.js} +1 -1
- package/dist/cli.js +7 -7
- package/dist/craft-entry.js +1 -1
- package/dist/craft.js +1 -1
- package/dist/native/compiler/style-variables.js +7 -0
- package/dist/native/runtime/binding-tree.js +14 -9
- package/dist/native/runtime/native-host.js +5 -2
- package/dist/native/testing.js +7 -0
- package/dist/pwa.js +1 -1
- package/dist/ssg.js +2 -2
- package/dist/utils.js +13 -1
- package/package.json +5 -5
- package/dist/chunk-5d2dnhsf.js +0 -2
- package/dist/chunk-5jqcs1fz.js +0 -2
- package/dist/chunk-9cyfq8mn.js +0 -2
- package/dist/chunk-dk53ytvr.js +0 -3
- package/dist/chunk-fd572s2h.js +0 -2
- package/dist/chunk-fpvhmwqj.js +0 -2
- package/dist/chunk-gkqx3p8n.js +0 -2
- package/dist/chunk-hb7phtn2.js +0 -2
- package/dist/chunk-npm22znd.js +0 -2
- package/dist/chunk-p45s8mwh.js +0 -2
- package/dist/chunk-qbmy60z0.js +0 -2
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ve,Hs,pg,Kh,fg,Xh,Dt,p,V,Z,wn,Se,gg,bi,mg,Gh,_,hg,Jh,T,Yh}from"./chunk-
|
|
2
|
+
import{ve,Hs,pg,Kh,fg,Xh,Dt,p,V,Z,wn,Se,gg,bi,mg,Gh,_,hg,Jh,T,Yh}from"./chunk-9k50gdfa.js";import"./chunk-t5fgdj4e.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{hg as applyFilters,Xh as clearCustomFilters,gg as clientLoopScopes,Hs as defaultFilters,wn as escapeAttributeValue,p as escapeHtml,V as escapeHtmlValue,Z as escapeInterpolatedHtmlValue,T as evaluateExpression,ve as findMustacheEnd,fg as getAllFilters,mg as interpolateScriptAttributes,bi as interpolateScriptExpressions,Gh as interpolateScriptsInTemplate,_ as processExpressions,pg as registerFilter,Kh as registerFilters,Dt as replaceInterpolations,Jh as resetRejectedExpressionWarnings,Yh as unescapeHtml,Se as usesSignalsInScript};
|
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{b,x,ui,fn}from"./chunk-
|
|
2
|
+
import{b,x,ui,fn}from"./chunk-9k50gdfa.js";import{qo}from"./chunk-82n173j5.js";import{l}from"./chunk-jdj1358b.js";import M from"fs";import d from"path";import{hasLocalConfig as le}from"bunfig";var bt={fg:{light:"neutral-900",dark:"neutral-100",description:"Primary text"},"fg-strong":{light:"neutral-700",dark:"neutral-300",description:"Labels, secondary headings"},"fg-muted":{light:"neutral-600",dark:"neutral-400",description:"Supporting text"},"fg-soft":{light:"neutral-500",dark:"neutral-400",description:"De-emphasised text"},"fg-subtle":{light:"neutral-400",dark:"neutral-500",description:"Recessive, non-essential text"},surface:{light:"neutral-50",dark:"neutral-800",description:"Page and panel background"},"surface-raised":{light:"neutral-100",dark:"neutral-700",description:"Cards, popovers"},"surface-sunken":{light:"neutral-200",dark:"neutral-700",description:"Wells, track backgrounds"},panel:{light:"white",dark:"neutral-800",description:"Card, menu, dialog surface"},field:{light:"white",dark:"neutral-700",description:"Form control surface"},page:{light:"neutral-50",dark:"neutral-900",description:"Page background, behind panels"},content:{light:"white",dark:"neutral-900",description:"Content area under a chrome header - a table or list body"},"surface-hover":{light:"neutral-100",dark:"neutral-700",description:"Row or item highlight on a page or panel"},"surface-raised-hover":{light:"neutral-200",dark:"neutral-600",description:"Raised surface, hovered"},"surface-sunken-hover":{light:"neutral-300",dark:"neutral-600",description:"Sunken surface, hovered"},"field-hover":{light:"neutral-50",dark:"neutral-600",description:"Form control surface, hovered"},link:{light:"blue-500",dark:"blue-400",description:"Hyperlink"},"link-hover":{light:"blue-600",dark:"blue-300",description:"Hyperlink, hovered"},inverse:{light:"neutral-900",dark:"neutral-700",description:"Tooltip bubble, inverted surface"},"inverse-ink":{light:"white",dark:"white",description:"Text on an inverted surface"},line:{light:"neutral-200",dark:"neutral-700",description:"Default border, divider"},"line-strong":{light:"neutral-300",dark:"neutral-600",description:"Input border, focus ring track"},"line-hover":{light:"neutral-400",dark:"neutral-500",description:"Border of a hovered control"},accent:{light:"blue-600",dark:"blue-400",description:"Primary action, selected state"},info:{light:"cyan-600",dark:"cyan-400",description:"Informational emphasis"},danger:{light:"red-600",dark:"red-400",description:"Errors, destructive actions"},success:{light:"green-600",dark:"green-400",description:"Confirmation"},warning:{light:"yellow-600",dark:"yellow-400",description:"Caution"},"accent-solid":{light:"blue-500",dark:"blue-600",description:"Primary button fill"},"info-solid":{light:"cyan-500",dark:"cyan-600",description:"Informational fill"},"danger-solid":{light:"red-500",dark:"red-600",description:"Destructive button fill"},"success-solid":{light:"green-500",dark:"green-600",description:"Confirmation fill"},"warning-solid":{light:"yellow-500",dark:"yellow-600",description:"Caution fill"},"accent-solid-hover":{light:"blue-600",dark:"blue-700",description:"Primary button fill, hovered"},"info-solid-hover":{light:"cyan-600",dark:"cyan-700",description:"Informational fill, hovered"},"danger-solid-hover":{light:"red-600",dark:"red-700",description:"Destructive fill, hovered"},"success-solid-hover":{light:"green-600",dark:"green-700",description:"Confirmation fill, hovered"},"warning-solid-hover":{light:"yellow-600",dark:"yellow-700",description:"Caution fill, hovered"},"accent-ink":{light:"white",dark:"white",description:"Text on a primary fill"},"info-ink":{light:"neutral-900",dark:"neutral-900",description:"Text on an informational fill"},"danger-ink":{light:"white",dark:"white",description:"Text on a destructive fill"},"success-ink":{light:"neutral-900",dark:"neutral-900",description:"Text on a confirmation fill"},"warning-ink":{light:"neutral-900",dark:"neutral-900",description:"Text on a caution fill"},"accent-soft":{light:"blue-100",dark:"blue-900",description:"Tinted primary fill"},"accent-soft-ink":{light:"blue-800",dark:"blue-200",description:"Text on a tinted primary fill"},"info-soft":{light:"cyan-100",dark:"cyan-900",description:"Tinted informational fill"},"info-soft-ink":{light:"cyan-800",dark:"cyan-200",description:"Text on a tinted informational fill"},"danger-soft":{light:"red-100",dark:"red-900",description:"Tinted destructive fill"},"danger-soft-ink":{light:"red-800",dark:"red-200",description:"Text on a tinted destructive fill"},"success-soft":{light:"green-100",dark:"green-900",description:"Tinted confirmation fill"},"success-soft-ink":{light:"green-800",dark:"green-200",description:"Text on a tinted confirmation fill"},"warning-soft":{light:"yellow-100",dark:"yellow-900",description:"Tinted caution fill"},"warning-soft-ink":{light:"yellow-800",dark:"yellow-200",description:"Text on a tinted caution fill"},secondary:{light:"purple-600",dark:"purple-400",description:"Secondary emphasis"},"secondary-solid":{light:"purple-500",dark:"purple-600",description:"Secondary fill"},"secondary-solid-hover":{light:"purple-600",dark:"purple-700",description:"Secondary fill, hovered"},"secondary-ink":{light:"white",dark:"white",description:"Text on a secondary fill"},"secondary-soft":{light:"purple-100",dark:"purple-900",description:"Tinted secondary fill"},"secondary-soft-ink":{light:"purple-800",dark:"purple-200",description:"Text on a tinted secondary fill"},"danger-fg":{light:"red-900",dark:"red-300",description:"Text in a field with an error"},"danger-fg-subtle":{light:"red-300",dark:"red-500",description:"Recessive text in a field with an error"},"danger-line":{light:"red-300",dark:"red-600",description:"Border of a field with an error"},"danger-focus":{light:"red-500",dark:"red-400",description:"Focus ring of a field with an error"}};function Xe(n){return`--stx-${n}`}function F(n,t){let s=t.lastIndexOf("-");if(s===-1)return typeof n[t]==="string"?n[t]:void 0;let r=n[t.slice(0,s)];if(!r||typeof r!=="object")return;let i=r[t.slice(s+1)];return typeof i==="string"?i:void 0}var xe=/^(?:#[\da-f]{3,8}|(?:rgb|rgba|hsl|hsla|hwb|lab|lch|oklab|oklch|color|color-mix|var)\(.*\)|white|black|transparent|currentcolor)$/i;function X(n,t){let s=t.trim();return F(n,s)??(xe.test(s)?s:void 0)}function Z(n={}){return[...Object.keys(n.roles??{}).filter((t)=>!bt[t]).map((t)=>`roles.${t}`),...Object.keys(n.shapes??{}).filter((t)=>!ye[t]).map((t)=>`shapes.${t}`),...Object.keys(n.density??{}).filter((t)=>!Ae[t]).map((t)=>`density.${t}`)]}function q(n){let t={};for(let[s,r]of Object.entries(bt)){let i=F(n,r.light);if(i===void 0)continue;t[s]=`var(${Xe(s)}, ${i})`}return t}function ee(n,t={}){let s=[],r=[];for(let[i,o]of Object.entries(bt)){let a=t[i],g=typeof a==="string"?a:a?.light,c=typeof a==="string"?a:a?.dark,u=g&&X(n,g)||F(n,o.light),m=c&&X(n,c)||F(n,o.dark);if(u===void 0)continue;if(s.push(` ${Xe(i)}: ${u};`),m!==void 0)r.push(` ${Xe(i)}: ${m};`)}if(s.length===0)return"";return["/* stx role tokens \u2014 override any of these to re-theme by meaning. */",":root {",...s,"}",".dark {",...r,"}",""].join(`
|
|
3
3
|
`)}var ye={control:{value:"0.375rem",description:"Buttons, inputs, selects \u2014 rounded-md"},panel:{value:"0.5rem",description:"Cards, dialogs, menus \u2014 rounded-lg"},pill:{value:"9999px",description:"Chips and badges, which are pill-shaped by intent"}};function an(n){return`--stx-radius-${n}`}function te(){let n={};for(let[t,s]of Object.entries(ye))n[t]=`var(${an(t)}, ${s.value})`;return n}function ne(n={}){return["/* stx shape tokens \u2014 a radius by what the thing is. */",":root {",...Object.entries(ye).map(([t,s])=>` ${an(t)}: ${n[t]??s.value};`),"}",""].join(`
|
|
4
4
|
`)}var Ae={"control-px":{value:"1rem",description:"Inline padding of a md text control \u2014 px-4"},"control-py":{value:"0.5rem",description:"Block padding of a md text control \u2014 py-2"},"control-text":{value:"1rem",description:"Font size of a md text control \u2014 text-base"},"control-leading":{value:"1.5rem",description:"Line height of a md text control \u2014 text-base"},"cell-px":{value:"1.5rem",description:"Inline padding of every table cell, header or body \u2014 px-6"},"cell-py":{value:"1rem",description:"Block padding of a body cell \u2014 py-4"},"cell-text":{value:"0.875rem",description:"Font size of a body cell \u2014 text-sm"},"cell-leading":{value:"1.25rem",description:"Line height of a body cell \u2014 text-sm"},"cell-head-py":{value:"0.75rem",description:"Block padding of a header cell \u2014 py-3"},"cell-head-text":{value:"0.75rem",description:"Font size of a header cell \u2014 text-xs"},"cell-head-leading":{value:"1rem",description:"Line height of a header cell \u2014 text-xs"}},nr={"control-x":"control-px","control-y":"control-py","cell-x":"cell-px","cell-y":"cell-py","cell-head-y":"cell-head-py"},rr={control:{size:"control-text",leading:"control-leading"},cell:{size:"cell-text",leading:"cell-leading"},"cell-head":{size:"cell-head-text",leading:"cell-head-leading"}};function Ge(n){return`--stx-${n}`}function V(n){let t=Ae[n];if(!t)throw Error(`[stx] unknown density token "${n}"`);return`var(${Ge(n)}, ${t.value})`}function se(){let n={};for(let[t,s]of Object.entries(nr))n[t]=V(s);return n}function re(){let n={};for(let[t,{size:s,leading:r}]of Object.entries(rr))n[t]=[V(s),{lineHeight:V(r)}];return n}function ie(n={}){return["/* stx density tokens \u2014 how much room a control or a table cell takes. */",":root {",...Object.entries(Ae).map(([t,s])=>` ${Ge(t)}: ${n[t]??s.value};`),"}",""].join(`
|
|
5
5
|
`)}function oe(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function U(n,t){let s={...n};for(let[r,i]of Object.entries(t))s[r]=oe(i)&&oe(s[r])?U(s[r],i):i;return s}function ce(n,t){if(!t.fonts)return"";let s=new n({...t.config,fonts:t.fonts,cssVariables:!1}).toCSS(!1,t.minify);return s&&!t.minify?`${s}
|
|
6
|
-
`:s}function ae(n={},t={}){let s=n.theme||{},r=t.theme||{},{extend:i,...o}=r,{extend:a,...g}=s,c=g.colors||{};g.colors={...c,...q(c)};let u=g.borderRadius||{};g.borderRadius={...u,...te()};let m=g.spacing||{};g.spacing={...m,...se()};let H=g.fontSize||{};g.fontSize={...H,...re()};let R=U(g,o),k=U(a||{},i||{});if(Object.keys(k).length>0)R.extend=k;let E=[...n.safelist||[],...t.safelist||[]],_={...n.shortcuts||{},...t.shortcuts||{}},P=[...n.preflights||[],...t.preflights||[]],{fonts:K,...D}=n,{fonts:O,roles:T,shapes:N,density:C,...w}=t,f={roles:T,shapes:N,density:C},j=O??K;return{config:{...D,...w,theme:R,safelist:E,shortcuts:_,...P.length>0?{preflights:P}:{},content:[],output:""},safelist:E,shortcuts:_,includePreflight:t.preflight!==!1,minify:t.minify===!0,tokenCSS:ee({...c,...R.colors},T)+ne(N)+ie(C),unknownRoles:Z(f),...j?{fonts:j}:{}}}var e={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgGray:"\x1B[100m"};var p=null,A="";function de(n){try{let t=n.startsWith("file:")?new URL(n).pathname:n;A=`${t}@${Math.trunc(M.statSync(t).mtimeMs)}`}catch{A=n}}var Q=!1,v=null,I="",B=!1,pe=256,S=new Map,h=new Map,z=null,he=null,G=new Map,ge=new Set;function L(n){return Bun.hash(n).toString(16).padStart(16,"0").slice(0,16)}function W(n,t){if(S.has(n))S.delete(n);else if(S.size>=pe)S.delete(S.keys().next().value);S.set(n,t)}function ke(n){let t=L(n);if(h.has(t))h.delete(t);else if(h.size>=pe)h.delete(h.keys().next().value);return h.set(t,n),t}function Sh(n){let t=h.get(n);if(t===void 0)return;return h.delete(n),h.set(n,t),t}async function Ce(n,t=z){if(!t)return null;try{let s=Bun.file(d.join(t,`cw-${L(n)}.css`));if(!await s.exists())return null;return await s.text()}catch{return null}}async function Se(n,t,s=z){if(!s)return;try{if(!M.existsSync(s))M.mkdirSync(s,{recursive:!0});await Bun.write(d.join(s,`cw-${L(n)}.css`),t)}catch{}}async function ue(n){try{let t=await import(n);if(t&&t.CSSGenerator)return{CSSGenerator:t.CSSGenerator,config:t.config,build:t.build,defaultConfig:t.defaultConfig,extractClasses:t.extractClasses}}catch{}return null}var we=[["@stacksjs","ts-css","dist","engine","index.js"],["@stacksjs","ts-css","src","engine","index.ts"]],be=["@stacksjs/ts-css/engine","@stacksjs/ts-css/dist/engine/index.js"];function ve(){let n=[],t=process.cwd();while(t!==d.dirname(t)){for(let s of["node_modules","pantry"])for(let r of we)n.push(d.join(t,s,...r));t=d.dirname(t)}return n}function Re(){let n=[],t=process.env.HOME||process.env.USERPROFILE||"",s=[t&&d.join(t,"Code","Tools","ts-css"),t&&d.join(t,"Code","Tools","crosswind"),t&&d.join(t,"repos","stacks-org","ts-css"),t&&d.join(t,"repos","stacks-org","crosswind"),d.join(process.cwd(),"..","ts-css"),d.join(process.cwd(),"..","crosswind")].filter(Boolean);for(let r of s)n.push(d.join(r,"packages","toolkit","dist","engine","index.js")),n.push(d.join(r,"packages","toolkit","src","engine","index.ts"));if(t)n.push(d.join(t,"Code","Tools","stx","node_modules","@stacksjs","ts-css","dist","engine","index.js"));return n}async function nc(){if(Q)return p;Q=!0;try{let n=async(i)=>{for(let o of i){if(!await Bun.file(o).exists())continue;let a=await ue(o);if(a){if(de(o),!process.env.STACKS_DEV_QUIET)console.log(`${e.green}[ts-css]${e.reset} CSS engine loaded from ${d.dirname(d.dirname(o))}`);return a}}return null};if(process.env.CROSSWIND_SRC){let i=d.resolve(process.env.CROSSWIND_SRC),o=await n([i]);if(!o)throw Error(`CROSSWIND_SRC did not resolve to a Css module: ${i}`);return p=o,p}let t=await n(ve());if(t)return p=t,p;let s=be;for(let i of s){let o=await ue(i);if(o){p=o;try{de(import.meta.resolve(i))}catch{A=i}if(!process.env.STACKS_DEV_QUIET)console.log(`${e.green}[ts-css]${e.reset} CSS engine loaded`);return p}}let r=await n(Re());if(r)return p=r,p;throw Error("Css CSSGenerator not found in any location")}catch{return console.warn(`${e.yellow}[ts-css] CSS engine not available, Tailwind styles will not be generated${e.reset}`),console.warn(`${e.yellow}Run 'bun add @stacksjs/ts-css' to enable CSS generation${e.reset}`),null}}function kh(){Y.clear(),p=null,Q=!1,v=null,I="",S.clear(),h.clear(),he=null,G.clear()}var fe=!1;async function rc(n){try{let t=le({name:"css",cwd:n})?"css":le({name:"crosswind",cwd:n})?"crosswind":null;if(!t)return null;if(t==="crosswind"&&!process.env.STACKS_DEV_QUIET&&!fe)fe=!0,console.warn(`${e.yellow}[ts-css]${e.reset} Reading the CSS config from a \`crosswind\` file. Rename it to \`css\` (e.g. config/css.ts) \u2014 the old name is deprecated.`);let{loadConfigWithResult:s}=await import("bunfig"),r=await s({name:t,cwd:n,defaultConfig:{},checkEnv:!1,verbose:!1});if(!r?.path||!r.config||Object.keys(r.config).length===0)return null;let i=d.relative(n,r.path);if(!process.env.STACKS_DEV_QUIET)console.log(`${e.green}[ts-css]${e.reset} Loaded config from ${i||r.path}`);return r.config}catch(t){if(t instanceof Error&&t.name==="ConfigNotFoundError")return null;return console.warn(`${e.yellow}[ts-css]${e.reset} Failed to load css config:`,t instanceof Error?t.message:t),null}}async function Ef(n){let t=null;try{let{loadStxConfig:s}=await import("./chunk-
|
|
6
|
+
`:s}function ae(n={},t={}){let s=n.theme||{},r=t.theme||{},{extend:i,...o}=r,{extend:a,...g}=s,c=g.colors||{};g.colors={...c,...q(c)};let u=g.borderRadius||{};g.borderRadius={...u,...te()};let m=g.spacing||{};g.spacing={...m,...se()};let H=g.fontSize||{};g.fontSize={...H,...re()};let R=U(g,o),k=U(a||{},i||{});if(Object.keys(k).length>0)R.extend=k;let E=[...n.safelist||[],...t.safelist||[]],_={...n.shortcuts||{},...t.shortcuts||{}},P=[...n.preflights||[],...t.preflights||[]],{fonts:K,...D}=n,{fonts:O,roles:T,shapes:N,density:C,...w}=t,f={roles:T,shapes:N,density:C},j=O??K;return{config:{...D,...w,theme:R,safelist:E,shortcuts:_,...P.length>0?{preflights:P}:{},content:[],output:""},safelist:E,shortcuts:_,includePreflight:t.preflight!==!1,minify:t.minify===!0,tokenCSS:ee({...c,...R.colors},T)+ne(N)+ie(C),unknownRoles:Z(f),...j?{fonts:j}:{}}}var e={reset:"\x1B[0m",bright:"\x1B[1m",dim:"\x1B[2m",underscore:"\x1B[4m",blink:"\x1B[5m",reverse:"\x1B[7m",hidden:"\x1B[8m",black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",gray:"\x1B[90m",bgBlack:"\x1B[40m",bgRed:"\x1B[41m",bgGreen:"\x1B[42m",bgYellow:"\x1B[43m",bgBlue:"\x1B[44m",bgMagenta:"\x1B[45m",bgCyan:"\x1B[46m",bgWhite:"\x1B[47m",bgGray:"\x1B[100m"};var p=null,A="";function de(n){try{let t=n.startsWith("file:")?new URL(n).pathname:n;A=`${t}@${Math.trunc(M.statSync(t).mtimeMs)}`}catch{A=n}}var Q=!1,v=null,I="",B=!1,pe=256,S=new Map,h=new Map,z=null,he=null,G=new Map,ge=new Set;function L(n){return Bun.hash(n).toString(16).padStart(16,"0").slice(0,16)}function W(n,t){if(S.has(n))S.delete(n);else if(S.size>=pe)S.delete(S.keys().next().value);S.set(n,t)}function ke(n){let t=L(n);if(h.has(t))h.delete(t);else if(h.size>=pe)h.delete(h.keys().next().value);return h.set(t,n),t}function Sh(n){let t=h.get(n);if(t===void 0)return;return h.delete(n),h.set(n,t),t}async function Ce(n,t=z){if(!t)return null;try{let s=Bun.file(d.join(t,`cw-${L(n)}.css`));if(!await s.exists())return null;return await s.text()}catch{return null}}async function Se(n,t,s=z){if(!s)return;try{if(!M.existsSync(s))M.mkdirSync(s,{recursive:!0});await Bun.write(d.join(s,`cw-${L(n)}.css`),t)}catch{}}async function ue(n){try{let t=await import(n);if(t&&t.CSSGenerator)return{CSSGenerator:t.CSSGenerator,config:t.config,build:t.build,defaultConfig:t.defaultConfig,extractClasses:t.extractClasses}}catch{}return null}var we=[["@stacksjs","ts-css","dist","engine","index.js"],["@stacksjs","ts-css","src","engine","index.ts"]],be=["@stacksjs/ts-css/engine","@stacksjs/ts-css/dist/engine/index.js"];function ve(){let n=[],t=process.cwd();while(t!==d.dirname(t)){for(let s of["node_modules","pantry"])for(let r of we)n.push(d.join(t,s,...r));t=d.dirname(t)}return n}function Re(){let n=[],t=process.env.HOME||process.env.USERPROFILE||"",s=[t&&d.join(t,"Code","Tools","ts-css"),t&&d.join(t,"Code","Tools","crosswind"),t&&d.join(t,"repos","stacks-org","ts-css"),t&&d.join(t,"repos","stacks-org","crosswind"),d.join(process.cwd(),"..","ts-css"),d.join(process.cwd(),"..","crosswind")].filter(Boolean);for(let r of s)n.push(d.join(r,"packages","toolkit","dist","engine","index.js")),n.push(d.join(r,"packages","toolkit","src","engine","index.ts"));if(t)n.push(d.join(t,"Code","Tools","stx","node_modules","@stacksjs","ts-css","dist","engine","index.js"));return n}async function nc(){if(Q)return p;Q=!0;try{let n=async(i)=>{for(let o of i){if(!await Bun.file(o).exists())continue;let a=await ue(o);if(a){if(de(o),!process.env.STACKS_DEV_QUIET)console.log(`${e.green}[ts-css]${e.reset} CSS engine loaded from ${d.dirname(d.dirname(o))}`);return a}}return null};if(process.env.CROSSWIND_SRC){let i=d.resolve(process.env.CROSSWIND_SRC),o=await n([i]);if(!o)throw Error(`CROSSWIND_SRC did not resolve to a Css module: ${i}`);return p=o,p}let t=await n(ve());if(t)return p=t,p;let s=be;for(let i of s){let o=await ue(i);if(o){p=o;try{de(import.meta.resolve(i))}catch{A=i}if(!process.env.STACKS_DEV_QUIET)console.log(`${e.green}[ts-css]${e.reset} CSS engine loaded`);return p}}let r=await n(Re());if(r)return p=r,p;throw Error("Css CSSGenerator not found in any location")}catch{return console.warn(`${e.yellow}[ts-css] CSS engine not available, Tailwind styles will not be generated${e.reset}`),console.warn(`${e.yellow}Run 'bun add @stacksjs/ts-css' to enable CSS generation${e.reset}`),null}}function kh(){Y.clear(),p=null,Q=!1,v=null,I="",S.clear(),h.clear(),he=null,G.clear()}var fe=!1;async function rc(n){try{let t=le({name:"css",cwd:n})?"css":le({name:"crosswind",cwd:n})?"crosswind":null;if(!t)return null;if(t==="crosswind"&&!process.env.STACKS_DEV_QUIET&&!fe)fe=!0,console.warn(`${e.yellow}[ts-css]${e.reset} Reading the CSS config from a \`crosswind\` file. Rename it to \`css\` (e.g. config/css.ts) \u2014 the old name is deprecated.`);let{loadConfigWithResult:s}=await import("bunfig"),r=await s({name:t,cwd:n,defaultConfig:{},checkEnv:!1,verbose:!1});if(!r?.path||!r.config||Object.keys(r.config).length===0)return null;let i=d.relative(n,r.path);if(!process.env.STACKS_DEV_QUIET)console.log(`${e.green}[ts-css]${e.reset} Loaded config from ${i||r.path}`);return r.config}catch(t){if(t instanceof Error&&t.name==="ConfigNotFoundError")return null;return console.warn(`${e.yellow}[ts-css]${e.reset} Failed to load css config:`,t instanceof Error?t.message:t),null}}async function Ef(n){let t=null;try{let{loadStxConfig:s}=await import("./chunk-bvynz9z8.js"),r=await s(n);if(r.css)if(typeof r.css==="string"){let i=d.isAbsolute(r.css)?r.css:d.resolve(n,r.css);if(await Bun.file(i).exists()){let o=await import(i);t=o.default||o,console.log(`${e.green}[ts-css]${e.reset} Loaded config from stx.config.ts \u2192 ${r.css}`)}}else{if(t={...r.css,content:r.css.content||[],preflight:r.css.preflight??!0,minify:r.css.minify??!1},r.css.config){let i=d.isAbsolute(r.css.config)?r.css.config:d.resolve(n,r.css.config);if(await Bun.file(i).exists()){let o=await import(i);t={...o.default||o,...t}}}console.log(`${e.green}[ts-css]${e.reset} Using inline CSS config from stx.config.ts`)}}catch{}return t||await rc(n)}function Tf(n){try{let t=new WeakSet;return L(JSON.stringify(n??{},(s,r)=>{if(typeof r==="function")return`[fn]${String(r)}`;if(typeof r==="object"&&r!==null){if(t.has(r))return"[circular]";t.add(r)}return r})??"")}catch{return"unhashable"}}async function cn(n){if(B)return I;B=!0;try{let t=await nc();if(!t||!t.build)return B=!1,"";if(!v)v=await rc(n);if(!v)return B=!1,"";let s=t.defaultConfig?.theme||{},r=v.theme||{},i={...t.defaultConfig,...v,theme:{...s,...r,extend:{...s.extend||{},...r.extend||{}}}},o=performance.now(),a=await t.build(i),g=performance.now()-o;if(I=a.css,console.log(`${e.cyan}[ts-css]${e.reset} Built ${a.classes.size} classes in ${g.toFixed(1)}ms`),i.output){let c=d.isAbsolute(i.output)?i.output:d.join(n,i.output),u=d.dirname(c);if(!M.existsSync(u))M.mkdirSync(u,{recursive:!0});await Bun.write(c,a.css)}return B=!1,a.css}catch(t){return console.error(`${e.red}[ts-css]${e.reset} Build error:`,t),B=!1,I}}async function sr(n){v=null,await cn(n)}function _h(){return I}function $f(n){let t=new Set,s=/class\s*=\s*["']([^"']+)["']/gi,r=s.exec(n);while(r!==null){for(let a of r[1].split(/\s+/))if(a.trim())t.add(a.trim());r=s.exec(n)}let i=/(?:x-class|:class)\s*=\s*"([^"]+)"/gi,o=i.exec(n);while(o!==null){let a=o[1].match(/'([^']+)'/g);if(a){for(let g of a)for(let c of g.slice(1,-1).split(/\s+/))if(c.trim())t.add(c.trim())}o=i.exec(n)}return t}var Y=b(64);async function Rf(n,t){let s=()=>G.get(t?d.resolve(t):process.cwd())?.fingerprint??null,r=Y.get(x(n,t,s()));if(r!==void 0)return r;let i=await $e(n,t);if(i)Y.set(x(n,t,s()),i);return i}function*me(n){yield n;let t=new Set;for(let s of n.matchAll(/\/_stx\/modules\.([0-9a-f]{16})\.js/g)){let r=s[1];if(t.has(r))continue;t.add(r);let i=qo(r);if(i)yield i}}function Ch(n){return[...me(n)].join(`
|
|
7
7
|
`)}async function $e(n,t){try{let s=await nc();if(!s)return"";let r=new Set;for(let f of me(n)){let j=typeof s.extractClasses==="function"?s.extractClasses(f):$f(f);for(let J of j)r.add(J)}if(r.size===0)return"";let i=t?d.resolve(t):process.cwd(),o=l(i,"cache");if(!z)z=o;let a=G.get(i);if(!a){let f=await Ef(i);a={config:f,fingerprint:Tf(f)},G.set(i,a),he=a.fingerprint}let g=[...r].sort().join(" "),c=`${A}::${a.fingerprint||"default"}::${g}`,u=S.get(c);if(u!==void 0)return W(c,u),u;let m=await Ce(c,o);if(m!==null)return W(c,m),m;let H=s.defaultConfig||s.config,R=a.config||{},k=ae(H,R),{safelist:E,includePreflight:_,minify:P,tokenCSS:K}=k;if(k.unknownRoles.length>0&&!ge.has(i))ge.add(i),console.warn(`${e.yellow}[ts-css]${e.reset} No stx role for ${k.unknownRoles.join(", ")} - these keep the stock value. Role names: semanticTokenNames() in @stacksjs/stx/theme-tokens.`);let D=k.config,O=new s.CSSGenerator(D),T=D.shortcuts||R.shortcuts||{},N=Object.keys(T).filter((f)=>r.has(f)||E.includes(f));for(let f of E)if(!T[f])O.generate(f);for(let f of r)if(!T[f])O.generate(f);let C="";if(N.length>0){let f=new s.CSSGenerator(D);for(let j of N)f.generate(j);if(C=f.toCSS(!1,P),C&&!C.endsWith(`
|
|
8
8
|
`))C+=`
|
|
9
9
|
`}let w=C+O.toCSS(_,P);return w=ce(s.CSSGenerator,k)+K+w,W(c,w),Se(c,w,o),w}catch(s){return console.warn("Failed to generate Css CSS:",s),""}}async function y(n,t,s=!1,r=!1){let i=await Rf(n,t);if(!i)return r?fn(n):n;let o=s?`<link data-css="generated" rel="stylesheet" href="/_stx/css.${ke(i)}.css">`:`<style data-css="generated">
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import{b,x,C,Y}from"./chunk-
|
|
2
|
+
import"./chunk-gb65t4n1.js";import"./chunk-2yxva96k.js";import{b,x,C,Y}from"./chunk-9k50gdfa.js";import"./chunk-94gyfwpz.js";import"./chunk-27rzdq3n.js";import"./chunk-t5fgdj4e.js";import f from"path";var h=["applyOfflineUpdate","broadcast","cacheMedia","calculateDistance","canNotify","clearCookies","clearFetchCache","clearOfflineData","clearStorage","copyToClipboard","createShareableFile","defineForm","getBatteryLevel","getCookie","getCurrentPosition","getStorageKeys","getStorageSize","getVoices","hasBattery","hasCameraPermission","hasGeolocationPermission","hasMicrophonePermission","hasNotificationPermission","hasResizeObserver","hexToHsl","hexToRgb","isBroadcastChannelSupported","isCharging","isDeviceMotionSupported","isDeviceOrientationSupported","isEventSourceSupported","isEyeDropperSupported","isInFullscreen","isMutationObserverSupported","isPermissionGranted","isSpeechRecognitionSupported","isSpeechSynthesisSupported","isWakeLockSupported","isWebSocketSupported","notify","onOfflineUpdateReady","parseCookies","pickColor","prefetch","removeCookie","requestMediaPermissions","requestMotionPermission","requestNotificationPermission","requestOrientationPermission","setCookie","share","shareCurrentPage","shareFiles","shareText","shareURL","shareWithFallback","speak","stopSpeaking","toggleFullscreen","useAmbientSound","useAnimationFrame","useAsyncData","useAttributeObserver","useAutoLogout","useAutoWakeLock","useBattery","useBreakpoint","useBreathPacer","useBroadcastChannel","useChannel","useChildListObserver","useClipboard","useColorHistory","useCompletion","useConditionalWakeLock","useCookies","useCopySelection","useDeviceMotion","useDeviceOrientation","useElementSize","useElementTextSelection","useElementVisibility","useEventSource","useEyeDropper","useFavicon","useForm","useFullscreen","useGeolocation","useGeolocationWatch","useHotkey","useIdle","useIdleState","useInfiniteScroll","useIntersectionObserver","useIntersectionObserverMultiple","useIsDesktop","useIsMobile","useIsTablet","useKeyPressed","useKeySequence","useKeyboard","useLastActive","useLazyLoad","useMeta","useMouse","useMouseInElement","useMutationObserver","useNetwork","useNotification","useOnline","useOutbox","useParallax","usePermission","usePermissions","usePointer","usePost","useResizeObserver","useResizeObserverMultiple","useSSE","useScroll","useSelectionPopup","useShare","useSpeechRecognition","useSpeechSynthesis","useStorage","useTextObserver","useTextSelection","useTitle","useVirtualList","useVisibility","useWakeLock","useWindowSize"],L=new Set(h);var l=new Map,S=b(64),w=new Set,k=0,R=new Set(h);function T(){l.clear(),S.clear()}function P(n){let o=new Map;for(let r of n){let a=f.basename(r);if(a.endsWith(".d.ts"))continue;let t=a.replace(/\.[jt]s$/,"");if(t==="index")continue;if(t===a)continue;let i=o.get(t);if(i&&!i.endsWith(".js"))continue;o.set(t,r)}return[...o.values()].sort()}function I(n,o){let r=o.replace(/[$()*+.?[\\\]^{|}-]/g,"\\$&");return new RegExp(`(?:^|[^\\w$.])(?:const|let|var|function|class)\\s+${r}\\b`).test(n)}function M(n){if(!n)return[];let o=x(n,k),r=S.get(o);if(r)return r.slice();let a=n.replace(/<script\b[^>]*\bdata-stx-runtime\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<script\b[^>]*\bdata-stx-framework-composables\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<script\b[^>]*\bdata-stx-stores\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<script\b[^>]*\bdata-stx-composables\b[^>]*>[\s\S]*?<\/script>/gi,""),t=[];for(let i of R){if(w.has(i))continue;let u=i.replace(/[$()*+.?[\\\]^{|}-]/g,"\\$&");if(new RegExp(`(^|[^\\w$.])${u}\\s*\\(`).test(a))t.push(i)}return t.sort(),S.set(o,t),t.slice()}async function A(n,o){let r=M(n);if(r.length===0)return null;let a=o??f.join(import.meta.dir,"composables"),t=`${a}\x00${r.join(",")}`,i=l.get(t);if(i!==void 0)return i||null;let u=Y({loader:"ts",target:"browser",define:C()}),O=new Set(r),m=[],d=new Set,p=[];try{let s=new Bun.Glob("*.{ts,js}");for await(let e of s.scan({cwd:a,absolute:!0}))p.push(e)}catch{return l.set(t,""),null}p=P(p);for(let s of p){let e;try{e=await Bun.file(s).text()}catch{continue}let g=[];try{g=u.scan(e).exports.filter((c)=>c!=="default")}catch{continue}if(!g.some((c)=>O.has(c)))continue;try{e=e.replace(/^import\s+.*from\s+['"][^'"]+['"]\s*;?\s*$/gm,""),e=e.replace(/^import\s+type\s+.*$/gm,""),e=e.replace(/^export\s+\*\s+(?:as\s+\w+\s+)?from\s*['"][^'"]+['"]\s*;?\s*$/gm,""),e=e.replace(/^export\s+(?:type\s+)?\{[\s\S]*?\}\s*(?:from\s*['"][^'"]+['"]\s*)?;?\s*$/gm,""),e=e.replace(/^export\s+default\s+/gm,""),e=e.replace(/^export\s+(?=(?:declare\s+)?(?:abstract\s+)?(?:async\s+)?(?:function|class|const|let|var|type|interface|enum)\b)/gm,""),m.push(`// ${f.basename(s).replace(/\.[jt]s$/,"")}
|
|
3
3
|
${u.transformSync(e).trim()}`);for(let c of g)d.add(c)}catch(c){console.warn(`[stx] framework composable ${f.basename(s)} could not be bundled:`,c)}}let y=r.filter((s)=>!d.has(s)&&!I(n,s));if(y.length>0)console.warn(`[stx] could not bundle ${y.join(", ")} from @stacksjs/stx/composables \u2014 `+"calls to them will throw ReferenceError in the browser. Import them explicitly so the bundler inlines them, or use a runtime equivalent from window.stx.");if(m.length===0)return l.set(t,""),null;let E=[...d].map((s)=>` try { if (!(${JSON.stringify(s)} in __s)) { __s[${JSON.stringify(s)}] = ${s}; if (!(${JSON.stringify(s)} in window)) window[${JSON.stringify(s)}] = ${s}; } } catch (e) {}`).join(`
|
|
4
4
|
`),v=`<script data-stx-scoped data-stx-run="always" data-stx-framework-composables>
|
|
5
5
|
;(function(){
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{m,pi,Vc,Uc,sg,og,ig,ag,cg,zs,lg,je,Y,Be,ug,Cr,dg,Kc,Xc,hi,Fe,r,bn,Gc,h,fe,qh}from"./chunk-
|
|
2
|
+
import{m,pi,Vc,Uc,sg,og,ig,ag,cg,zs,lg,je,Y,Be,ug,Cr,dg,Kc,Xc,hi,Fe,r,bn,Gc,h,fe,qh}from"./chunk-9k50gdfa.js";import"./chunk-t5fgdj4e.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{Xc as SIGNAL_COMPOSABLE_CALL,fe as clearComponentCache,hi as componentClientSignalNames,pi as convertToCommonJS,h as createDetailedErrorMessage,cg as extractDirectiveNames,Vc as extractScriptFromTemplate,m as extractVariables,r as fileExists,qh as getComponentCacheStats,og as getPositionInfo,Y as getSharedTranspiler,Gc as getSourceLineInfo,ag as hasDirectives,Uc as hasVariables,dg as isHydrateTrigger,lg as isJavaScriptScript,Fe as renderComponentWithSlot,bn as resolveTemplatePath,ug as scopeOnRootElement,zs as scopeSequenceKey,je as shouldTranspileTypeScript,Kc as slotContentHasExpressions,Be as transpileTypeScript,Cr as userComponentFileExists,ig as validateDirective,sg as validateTemplate};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{oe,de,gn,Ot,Nt,m,r,fe,p}from"./chunk-
|
|
2
|
+
import{oe,de,gn,Ot,Nt,m,r,fe,p}from"./chunk-9k50gdfa.js";import{yt,Re,tc,ss,Io,Oo,i}from"./chunk-n6vp1m14.js";import{ae,Er,ke,B,Sn}from"./chunk-94gyfwpz.js";import{St,pr,Es,Ts,$s,kt,_t,Ct,Et,Tt,$t,et}from"./chunk-q14d714d.js";import{vs,a,P}from"./chunk-m6gs86mk.js";import{ft,An,Ce,D,oa,fo,qr,We,ia,qe,Ee}from"./chunk-81fvwcv4.js";import{lr,ur}from"./chunk-82n173j5.js";import{$n}from"./chunk-zts834eb.js";import{e,cn,sr,y}from"./chunk-0r5xawp8.js";import{Je}from"./chunk-44etj70r.js";import{$e}from"./chunk-7sh9fa3q.js";import{X,be,we}from"./chunk-wgnwempr.js";import{l}from"./chunk-jdj1358b.js";import{K}from"./chunk-bmfk3b29.js";async function Nn(t){try{let n=await Bun.file(t).text(),o=Un(n),d=Wn(n,t),s=Vn(n,o),c=qn(n,o);return{file:t,metrics:o,issues:d,suggestions:s,performance:c}}catch(n){throw Error(`Failed to analyze template ${t}: ${n instanceof Error?n.message:String(n)}`)}}function Un(t){let n=t.split(`
|
|
3
3
|
`),o=t.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),s=(o?o[1]:"").split(`
|
|
4
4
|
`).length,c={conditionals:(t.match(/@(if|unless|elseif|else|endif|endunless)\b/g)||[]).length,loops:(t.match(/@(foreach|for|endforeach|endfor|while|endwhile)\b/g)||[]).length,includes:(t.match(/@(include|component|extends|section|yield)\b/g)||[]).length,custom:0,total:0};c.total=c.conditionals+c.loops+c.includes+c.custom;let u=(t.match(/\{\{[\s\S]*?\}\}/g)||[]).length,f=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length,g=(t.match(/@(?:if|unless|elseif|foreach|for|while)\s*\([^)]+\)/g)||[]).length,h=u+f+g,x=(t.match(/<[A-Z][^>]*>/g)||[]).length,v=(t.match(/@(?:layout|extends)\(/g)||[]).length,S=0,T=0;for(let k of n)if(/@(?:if|unless|foreach|for|while|section)\b/.test(k)&&!/@end/.test(k)&&!/@else/.test(k))T++,S=Math.max(S,T);else if(/@end(?:if|unless|foreach|for|while|section)\b/.test(k))T--;let w=S>=4?3:0,b=Math.min(10,Math.ceil(c.total*0.5+h*0.1+x*0.3+(s>10?s*0.05:0)+w));return{lines:n.length,characters:t.length,directives:c,expressions:h,components:x,layouts:v,scriptLines:s,complexity:b}}function Wn(t,n){let o=[],d=Xt(t,"if","endif");if(d>0)o.push({type:"error",category:"syntax",message:`Found ${d} unmatched @if directive(s)`,suggestion:"Ensure every @if has a corresponding @endif"});let s=Xt(t,"foreach","endforeach");if(s>0)o.push({type:"error",category:"syntax",message:`Found ${s} unmatched @foreach directive(s)`,suggestion:"Ensure every @foreach has a corresponding @endforeach"});let c=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(c&&c.length>0)o.push({type:"warning",category:"performance",message:"Nested loops detected which may impact performance",suggestion:"Consider preprocessing data or using more efficient data structures"});let u=(t.match(/\{!![\s\S]*?!!\}/g)||[]).length;if(u>0)o.push({type:"warning",category:"security",message:`Found ${u} raw output expression(s) {!! !!}`,suggestion:"Ensure raw outputs are properly sanitized to prevent XSS"});let f=t.match(/<img[^>]*>/g);if(f){let x=f.filter((v)=>!v.includes("alt="));if(x.length>0)o.push({type:"warning",category:"accessibility",message:`Found ${x.length} image(s) without alt attributes`,suggestion:"Add alt attributes to all images for screen reader accessibility"})}let g=t.split(`
|
|
5
5
|
`).filter((x)=>x.length>120);if(g.length>0)o.push({type:"info",category:"maintainability",message:`Found ${g.length} line(s) longer than 120 characters`,suggestion:"Consider breaking long lines for better readability"});let h=(t.match(/style\s*=\s*["'][^"']*["']/g)||[]).length;if(h>3)o.push({type:"info",category:"maintainability",message:`Found ${h} inline style attributes`,suggestion:"Consider moving styles to CSS classes for better maintainability"});return o}function Vn(t,n){let o=[];if(n.complexity>7)o.push({type:"refactor",message:"Template complexity is high. Consider breaking into smaller components.",impact:"high",effort:"medium"});else if(n.complexity>5&&n.directives.total>8)o.push({type:"optimization",message:"Template has moderate complexity. Consider component extraction for reusability.",impact:"medium",effort:"low"});if(n.lines>100&&n.components===0)o.push({type:"refactor",message:"Large template with no components. Consider extracting reusable parts into components.",impact:"medium",effort:"medium"});if(n.expressions>20)o.push({type:"optimization",message:"Many template expressions detected. Consider preprocessing some data in the script section.",impact:"medium",effort:"low"});let d=t.match(/@foreach[\s\S]*?@foreach[\s\S]*?@endforeach[\s\S]*?@endforeach/g);if(d&&d.length>0)o.push({type:"optimization",message:"Nested loops detected. Consider preprocessing data or optimizing data structures.",impact:"high",effort:"medium"});if(n.directives.total===0&&n.expressions<5)o.push({type:"optimization",message:"Template appears static. Consider enabling aggressive caching.",impact:"high",effort:"low"});if(n.scriptLines>50)o.push({type:"refactor",message:"Large script section. Consider moving complex logic to external modules.",impact:"medium",effort:"medium"});return o}function qn(t,n){let o=1;if(o+=n.directives.conditionals*0.1,o+=n.directives.loops*0.5,o+=n.directives.includes*2,o+=n.expressions*0.05,o+=n.components*1,n.scriptLines>10)o+=n.scriptLines*0.1;let d;if(n.expressions===0&&n.directives.total===0)d="high";else if(n.expressions<5&&n.directives.total<3)d="medium";else d="low";let s=[];if(o>10)s.push("Consider optimizing template complexity");if(d==="low"&&n.directives.total>5)s.push("Reduce dynamic content for better caching");if(n.components===0&&n.lines>40)s.push("Extract components to improve reusability and performance");return{estimatedRenderTime:Math.round(o*100)/100,complexityScore:n.complexity,cacheability:d,recommendations:s}}function Xt(t,n,o){let d=t.replace(/<!--[\s\S]*?-->/g,""),s=(d.match(new RegExp(`@${n}\\b`,"g"))||[]).length,c=(d.match(new RegExp(`@${o}\\b`,"g"))||[]).length;return Math.abs(s-c)}async function Ki(t=["**/*.stx"],n){let o=[],d=[];for(let c of t){let u=await Array.fromAsync(new Bun.Glob(c).scan({cwd:n||process.cwd(),onlyFiles:!0,absolute:!0}));d.push(...u.filter((f)=>f.endsWith(".stx")))}for(let c of d)try{let u=await Nn(c);o.push(u)}catch(u){console.warn(`Failed to analyze ${c}:`,u)}let s=Kn(o);return{results:o,summary:s}}function Kn(t){let n=t.length,o=t.reduce((h,x)=>h+x.metrics.lines,0),d=n>0?t.reduce((h,x)=>h+x.metrics.complexity,0)/n:0,s=t.reduce((h,x)=>h+x.issues.length,0),c={};t.forEach((h)=>{h.issues.forEach((x)=>{c[x.category]=(c[x.category]||0)+1})});let u=n>0?t.reduce((h,x)=>h+x.performance.estimatedRenderTime,0)/n:0,f=Math.max(1,Math.min(10,Math.round(10-u/2-d/2))),g=[];if(d>6)g.push("Project has high average complexity. Consider refactoring complex templates.");if(s>n*2)g.push("High number of issues detected. Run detailed analysis on individual files.");if(c.security>0)g.push("Security issues found. Review raw output usage and input sanitization.");return{totalFiles:n,totalLines:o,avgComplexity:Math.round(d*100)/100,totalIssues:s,issuesByCategory:c,performanceScore:f,recommendations:g}}import{mkdir as Xn,readFile as Gn,readdir as Jn,stat as Gt,writeFile as Yn}from"fs/promises";import Te from"path";function tn(t){if(t==="connectedCallback")return`method "${t}" is reserved; define "onConnect" instead, which the element calls once it is connected, rendered and bound`;if(t==="disconnectedCallback")return`method "${t}" is reserved; define "onDisconnect" instead, which the element calls as it leaves the DOM, before it releases its own listeners`;return`method "${t}" is reserved`}var nn=new Set(["constructor","connectedCallback","disconnectedCallback","attributeChangedCallback","adoptedCallback"]);function Qn(t){return t.replace(/\.stx$/i,"").split(/[^a-z0-9]+/i).filter(Boolean).map((n)=>n.charAt(0).toUpperCase()+n.slice(1)).join("")}function It(t){return t.replace(/([a-z0-9])([A-Z])/g,"$1-$2").replace(/[^a-z0-9]+/gi,"-").replace(/^-+|-+$/g,"").toLowerCase()}function Zn(t){return/^[a-z][.0-9_a-z-]*-[.0-9_a-z-]*$/.test(t)&&!t.startsWith("xml")&&!/[A-Z]/.test(t)}function er(t){if(t===!0)return"open";if(t==="open"||t==="closed")return t;return!1}async function tr(t){let n=[];async function o(d){let s=await Jn(d,{withFileTypes:!0});s.sort((c,u)=>c.name.localeCompare(u.name));for(let c of s){let u=Te.join(d,c.name);if(c.isDirectory()){if(!c.name.startsWith(".")&&c.name!=="node_modules")await o(u)}else if(c.isFile()&&c.name.endsWith(".stx")&&!/\.(?:test|spec)\.stx$/i.test(c.name))n.push(u)}}return await o(t),n}function nr(t,n){let o=t.match(/<script\b(?=[^>]*(?:\bcomponent\b|\bstx:component\b))[^>]*>([\s\S]*?)<\/script>/i);if(!o)return{};let d=o[1].trim();if(!d)return{};try{return JSON.parse(d)}catch(s){throw Error(`${n}: <script component> must contain JSON metadata (${s.message})`)}}function rr(t,n){let o={},d=[...t.matchAll(/<script\b([^>]*)>([\s\S]*?)<\/script>/gi)];for(let s of d){if(!/\bclient\b/i.test(s[1])||/\bcomponent\b|\bstx:component\b/i.test(s[1]))continue;let c;try{c=new Bun.Transpiler({loader:"ts"}).transformSync(s[2])}catch(g){throw Error(`${n}: failed to transpile <script client> (${g.message})`)}let u=/(?:export\s+)?(?:async\s+)?function\s+([A-Za-z_$][\w$]*)\s*\(([^)]*)\)\s*\{/g,f;while(f=u.exec(c)){let g=f[1];if(nn.has(g))throw Error(`${n}: client ${tn(g)}`);let h=u.lastIndex,x=1,v="",S=!1,T=h;for(;T<c.length&&x>0;T++){let b=c[T];if(S){S=!1;continue}if(v){if(b==="\\")S=!0;else if(b===v)v="";continue}if(b==='"'||b==="'"||b==="`")v=b;else if(b==="{")x++;else if(b==="}")x--}if(x!==0)throw Error(`${n}: unterminated client function "${g}"`);let w=f[0].includes("async")?"async ":"";o[g]=`${w}${g}(${f[2]}) {${c.slice(h,T-1)}}`,u.lastIndex=T}}return o}function or(t){let n=t.match(/<template\b(?![^>]*\bshadowrootmode\b)[^>]*>([\s\S]*?)<\/template>/i);return(n?n[1]:t).replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"").replace(/<style\b[^>]*>[\s\S]*?<\/style>/gi,"").trim()}function Jt(t){return[...t.matchAll(/<style\b[^>]*>([\s\S]*?)<\/style>/gi)].map((n)=>n[1].trim()).filter(Boolean).join(`
|
|
@@ -887,7 +887,7 @@ else {
|
|
|
887
887
|
};
|
|
888
888
|
})();
|
|
889
889
|
</script>
|
|
890
|
-
`}function Ne(t,n,o={}){let d=Br(n,o),s=t.lastIndexOf("</body>");if(s!==-1)return t.slice(0,s)+d+t.slice(s);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let o={...await a(),...t.config?.stx},d=new Set,s=o.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",c=[];if(o.webComponents?.enabled)try{let u=await vs(o,d);if(c.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(o.cache&&o.cachePath){let b=await lr(u,o);if(b){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=oe.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let _=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of _){let M=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",I=C.match(/<script\b([^>]*)>/i),V=I?I[1]:"";if(/\bserver\b/i.test(V))E=M;else R.push(C)}let A=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:s,builtComponents:c}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(B.log(k,{filePath:u,scriptContent:h}),o.debug)throw k});let w=await oe.timeAsync("directive-processing",async()=>await i(x,S,u,o,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-
|
|
890
|
+
`}function Ne(t,n,o={}){let d=Br(n,o),s=t.lastIndexOf("</body>");if(s!==-1)return t.slice(0,s)+d+t.slice(s);if(t.includes("</html>"))return t.replace("</html>",`${d}</html>`);return t+d}function ht(t){let n=t.toLowerCase();return n.endsWith(".css")||n.endsWith(".scss")||n.endsWith(".sass")||n.endsWith(".less")}function bt(t){let n=t.toLowerCase();return[".stx",".html",".htm",".md",".js",".ts",".jsx",".tsx",".json"].some((d)=>n.endsWith(d))}function xt(t){return[/^\./,/node_modules/,/\.stx\/output/,/\.stx\/cache/,/~$/,/\.swp$/,/\.swo$/].some((o)=>o.test(t))}var nt=null;function vt(t){if(!nt)nt=new on(t);return nt}function it(){if(nt)nt.stop(),nt=null}import wt from"path";var rt={name:"bun-plugin-stx",async setup(t){let o={...await a(),...t.config?.stx},d=new Set,s=o.webComponents?.enabled?`./${wt.relative(wt.dirname(t.config?.outdir||"dist"),o.webComponents.outputDir||"dist/web-components")}`:"/web-components",c=[];if(o.webComponents?.enabled)try{let u=await vs(o,d);if(c.push(...u),o.debug&&u.length>0)console.log(`Successfully built ${u.length} web components`)}catch(u){console.error("Failed to build web components:",u)}t.onLoad({filter:/\.stx$/},async({path:u})=>{try{let f=new Set;if(o.cache&&o.cachePath){let b=await lr(u,o);if(b){if(o.debug)console.log(`Using cached version of ${u}`);return{contents:b,loader:"html"}}}let g=await ke(()=>Bun.file(u).text(),"",(b)=>{throw new Er(`Failed to read stx file: ${u}`,u,void 0,void 0,`File read error: ${b.message}`)});if(!g)throw new Er(`stx file is empty: ${u}`,u);let{scriptContent:h,templateContent:x,allScripts:v}=oe.time("script-extraction",()=>{let b=g,k=de(g);if(k)b=k.content.trim();let _=g.match(/<script\b[^>]*>[\s\S]*?<\/script>/gi)||[],E="",R=[];for(let C of _){let M=C.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i)?.[1]||"",I=C.match(/<script\b([^>]*)>/i),V=I?I[1]:"";if(/\bserver\b/i.test(V))E=M;else R.push(C)}let A=b.replace(/<script\b[^>]*>[\s\S]*?<\/script>/gi,"");return{scriptContent:E,templateContent:A,allScripts:R}}),S={__filename:u,__dirname:wt.dirname(u),__stx:{webComponentsPath:s,builtComponents:c}};await ke(()=>m(h,S,u),void 0,(b)=>{let k=new ae(`Script execution failed in ${u}: ${b.message}`,u,void 0,void 0,h.substring(0,100));if(B.log(k,{filePath:u,scriptContent:h}),o.debug)throw k});let w=await oe.timeAsync("directive-processing",async()=>await i(x,S,u,o,f));if(v.length>0){let{interpolateScriptsInTemplate:b}=await import("./chunk-0dwh4g5q.js"),k=b(v.join(`
|
|
891
891
|
`),S),_=w.search(/<\/body>/i);if(_!==-1)w=w.slice(0,_)+k+`
|
|
892
892
|
`+w.slice(_);else w+=`
|
|
893
893
|
${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),o.cache&&o.cachePath){if(await ur(u,w,f,o),o.debug)console.log(`Cached template ${u} with ${f.size} dependencies`)}return{contents:w,loader:"html"}}catch(f){let g=f instanceof Error?f:new ae(`Plugin processing failed: ${String(f)}`,u);if(B.log(g,{filePath:u,buildConfig:t.config}),Sn.logDetailedError(g,{filePath:u,plugin:"bun-plugin-stx"}),o.debug)console.error("stx Plugin Error:",g);let h=g,x=h.line||null,v=h.context||null;return{contents:o.debug||K()?`<!DOCTYPE html>
|
|
@@ -950,7 +950,7 @@ ${k}`}if(w=await we(w),f.forEach((b)=>d.add(b)),o.cache&&o.cachePath){if(await u
|
|
|
950
950
|
<h1>Something went wrong</h1>
|
|
951
951
|
<p>An internal error occurred. Please try again later.</p>
|
|
952
952
|
</body>
|
|
953
|
-
</html>`,loader:"html"}}})}};async function Fr(t,n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=l(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let M={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},I=await Bun.build({entrypoints:[f],outdir:g,plugins:[M,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!I.success)return console.error(`${e.red}Build failed:${e.reset}`,I.logs),!1;let V=I.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(M){return console.error(`${e.red}Error building stx file:${e.reset}`,M),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=o;try{if(T=await Ve(o),T!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let M=n.hmrPort||T+1;c=vt({wsPort:M,verbose:!1}),u=c.start(M)}let w={},b=null,k;try{let{loadStxConfig:M}=await import("./chunk-
|
|
953
|
+
</html>`,loader:"html"}}})}};async function Fr(t,n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=ge.resolve(t);if(!Be.existsSync(f))return console.error(`${e.red}Error: File not found: ${e.bright}${f}${e.reset}`),!1;if(f.endsWith(".md"))return Ft(f,n);else if(!f.endsWith(".stx"))return console.error(`${e.red}Error: Unsupported file type: ${e.bright}${f}${e.reset}. Only .stx and .md files are supported.`),!1;let g=l(process.cwd(),"output");Be.mkdirSync(g,{recursive:!0}),console.log(`${e.blue}Building ${e.bright}${t}${e.reset}...`);let h=null,x=async()=>{try{let M={name:"public-assets",setup(xe){xe.onResolve({filter:/^\/(images|fonts|assets|public)\//},(le)=>({path:le.path,external:!0}))}},I=await Bun.build({entrypoints:[f],outdir:g,plugins:[M,rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!I.success)return console.error(`${e.red}Build failed:${e.reset}`,I.logs),!1;let V=I.outputs.find((xe)=>xe.path.endsWith(".html"));if(!V)return console.error(`${e.red}No HTML output found${e.reset}`),!1;return h=await Bun.file(V.path).text(),!0}catch(M){return console.error(`${e.red}Error building stx file:${e.reset}`,M),!1}};if(!await x())return!1;let S=ge.dirname(f);await cn(S);let T=o;try{if(T=await Ve(o),T!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${T} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let M=n.hmrPort||T+1;c=vt({wsPort:M,verbose:!1}),u=c.start(M)}let w={},b=null,k;try{let{loadStxConfig:M}=await import("./chunk-vwvfedp7.js"),I=await M();if(k=n.stxOptions?.serverApi??I.serverApi,I?.apiRouter)b=I?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(I?.apiRoutes){w=I.apiRoutes;let V=Object.keys(w).length;if(V>0)console.log(`${e.blue}Loaded ${e.bright}${V} API route${V>1?"s":""}${e.reset}`)}if(I?.broadcasting?.enabled)try{let{startBroadcasting:V,loadChannels:Y}=await import("./chunk-d9p7xaj7.js"),xe=I.broadcasting;await V(xe);let le=xe.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${le}/ws${e.reset}`);let Oe=ge.join(process.cwd(),"channels.ts");if(Be.existsSync(Oe))try{let ne=await Y(Oe);console.log(`${e.blue}Loaded ${e.bright}${ne} broadcast channel${ne!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(ne){console.warn(`${e.yellow}Failed to load channels.ts: ${ne.message}${e.reset}`)}}catch(V){console.warn(`${e.yellow}Broadcasting failed to start: ${V.message}${e.reset}`)}}catch{}let{createServerApi:_,isServerApiSource:E}=await import("./chunk-7hex58nx.js"),R=await _(process.cwd(),k);if(console.log(`${e.blue}Starting server on ${e.cyan}http://localhost:${T}/${e.reset}...`),s)console.log(`${e.magenta}Hot reload enabled on ws://localhost:${u}${e.reset}`);let A=Nr({port:T,async fetch(M){return $n(M,await(async()=>{let I=new URL(M.url);if([g,ge.dirname(f),ge.join(process.cwd(),"public")].some((ne)=>E(ge.join(ne,I.pathname),process.cwd(),k)))return new Response("Not Found",{status:404});if(b)try{let ne=await b.handleRequest(M);if(ne.status!==404)return ne}catch{}if(w[I.pathname])try{return await w[I.pathname](M)}catch(ne){return new Response(JSON.stringify({error:ne.message}),{status:500,headers:{"Content-Type":"application/json"}})}let V=await R(M);if(V)return V;if(I.pathname==="/")return(async()=>{let z=await y(h||"");if(s)z=Ne(z,u);if(n.native)if(z.includes("<head>"))z=z.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>");else z="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+z;if(n.titlebarHidden)if(z.includes("<head>"))z=z.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else if(z.includes("<html"))z=z.replace(/(<html[^>]*>)/,"$1<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>");else z=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${z}`;return z})().then((z)=>new Response(z,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}}));let Y=ge.join(g,I.pathname);if(Be.existsSync(Y)&&Be.statSync(Y).isFile()){let ne=Bun.file(Y),z=ge.extname(Y).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let xe=ge.dirname(f),le=ge.join(xe,I.pathname);if(Be.existsSync(le)&&Be.statSync(le).isFile()){let ne=Bun.file(le),z=ge.extname(le).toLowerCase(),L="text/plain";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}let Oe=ge.join(process.cwd(),"public",I.pathname);if(Be.existsSync(Oe)&&Be.statSync(Oe).isFile()){let ne=Bun.file(Oe),z=ge.extname(Oe).toLowerCase(),L="application/octet-stream";if(z===".ts"||z===".tsx"){let Fe=new Bun.Transpiler({loader:z===".tsx"?"tsx":"ts"}),ze=await ne.text(),Ye=Fe.transformSync(ze);return new Response(Ye,{headers:{"Content-Type":"application/javascript","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}switch(z){case".html":L="text/html";break;case".css":L="text/css";break;case".js":L="text/javascript";break;case".json":L="application/json";break;case".png":L="image/png";break;case".jpg":case".jpeg":L="image/jpeg";break;case".gif":L="image/gif";break;case".svg":L="image/svg+xml";break;case".ico":L="image/x-icon";break;case".woff":L="font/woff";break;case".woff2":L="font/woff2";break;case".ttf":L="font/ttf";break;case".otf":L="font/otf";break;case".eot":L="application/vnd.ms-fontobject";break}return new Response(ne,{headers:{"Content-Type":L}})}return new Response("Not Found",{status:404})})())},error(M){return new Response(`<pre>${M}
|
|
954
954
|
${M.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),console.log(`
|
|
955
955
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
956
956
|
${e.bright}\u2192 ${e.cyan}http://localhost:${T}/${e.reset}`),console.log(`
|
|
@@ -1437,12 +1437,12 @@ ${w.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});console.clear(),con
|
|
|
1437
1437
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1438
1438
|
${e.bright}\u2192 ${e.cyan}http://localhost:${x}/${e.reset}`),console.log(`
|
|
1439
1439
|
${e.yellow}Routes:${e.reset}`);let S=new Set(f.map((w)=>w.routeTemplate)),T=Object.entries(u).filter(([w])=>!S.has(w)).sort(([w],[b])=>w.localeCompare(b)).map(([w,b])=>({route:w==="/"?"/":w,filePath:Pe.relative(process.cwd(),b.filePath),fileType:b.fileType}));for(let w of f){let b=w.routeTemplate.replace(/\[([^\]]+)\]/g,":$1");T.push({route:b,filePath:Pe.relative(process.cwd(),w.filePath),fileType:"stx"})}if(T.sort((w,b)=>w.route.localeCompare(b.route)),T.forEach((w,b)=>{let _=b===T.length-1?"\u2514\u2500 ":"\u251C\u2500 ",E=w.fileType==="md"?`${e.magenta}(markdown)${e.reset}`:"";console.log(` ${e.green}${_}${w.route}${e.reset} \u2192 ${e.bright}${w.filePath}${e.reset} ${E}`)}),console.log(`
|
|
1440
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(c,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(c,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),o=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},c=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[o]||"application/octet-stream",...c}})}async function Hr(t=".",n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-fd572s2h.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-p2r6rbs4.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((O)=>me.existsSync(O)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${b}/index.stx for the homepage.${e.reset}`),!1;let _=X(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(_.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${_.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:O,prefix:j}of E)if(me.existsSync(O)){let N=X(te.dirname(O),{pagesDir:te.basename(O)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let A=new Map,C=null,M=null;if(n.stxOptions?.shell!==!1){if(M=await oa(f,n.stxOptions?.shell),M){if(C=await fo(M,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,M)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let I=_t();if(I.length>0)console.log(`${e.blue}Loaded ${e.bright}${I.length}${e.blue} middleware: ${e.dim}${I.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:O}=await import("./chunk-fd572s2h.js"),j=await O(f);if(j?.apiRouter)Y=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){V=j.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-d9p7xaj7.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=l(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(O)=>{let j=Ts(k,O);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,L=async(O,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-fd572s2h.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-w1xzkkk3.js"),G=await Ae(f),Ue=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(f,ie)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??l(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let ie=pe.get(O.filePath);if(ie)try{if((await me.promises.stat(O.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(O.filePath);return{route:O,content:Se,status:st?.status??await dn(O.filePath),headers:st?.headers}}}}catch{}let Ie=await U(O.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(O.filePath);return{route:O,content:je,status:He?.status??await dn(O.filePath),headers:He?.headers}}}let Z=re?await W(O.filePath):await Bun.file(O.filePath).text(),se=gn(Z),{classifyAllScripts:ue}=await import("./chunk-fd572s2h.js"),F=ue(Z),Le=F.server.map((ie)=>ie.content),Me=Z;for(let ie of F.server)Me=Me.replace(ie.fullTag,"");let ee={__filename:O.filePath,__dirname:te.dirname(O.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,ee,O.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,ee,O.filePath,ce,De);let Ie=performance.now()-ie,je=te.relative(f,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,O.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-h88p9w9x.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(O.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-9dzgkt5x.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},O.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(O.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)z.set(O.filePath,{status:Vt,headers:qt});return{route:O,content:he,status:Vt??se,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let O=new Set(le.keys()),j=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?_.filter((q)=>O.has(q.pattern)):_,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>L(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>L(U)));for(let U of ve)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?_.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=o;try{if(Ge=await Ve(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let O=n.hmrPort||Ge+1;c=vt({wsPort:O,verbose:!1}),u=c.start(O)}let Pt=(O,j)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(j).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(O.includes("</head>"))return O.replace("</head>",`${Q}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+O};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(O){let j=new URL(O.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===Io&&N?.enabled){if(!["GET","HEAD"].includes(O.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(O.method==="HEAD"?null:Oo(N,ss()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Ae,f,S))return zt(Ae);if(W?.isFile()&&!v(ve,f,S))return zt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-43ynckvh.js"),re=await H(O,{publicDir:te.join(f,Q),cacheDir:l(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(O);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](O)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(O);if(pe)return pe;let G=pr(j.pathname,_);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),s)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,O,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let F=H.content;if(C&&ia(O)&&qe(F,h?.router?.container||"main")){let Le=et(F),Me=be(F),ee=F.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)F=Pt(F,G.params);F=await y(F,f);let he=h?.router?.container||"main";return F=Ee(F,he,!0),new Response(F,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[tc]:ss(),...D(),"Cache-Control":ft}})}if(C)F=qr(C,F);if(Object.keys(G.params).length>0)F=Pt(F,G.params);if(F=await y(F,f),s)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-9dzgkt5x.js");return Me(Le(F,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(F,{status:Z,headers:{"Content-Type":"text/html",...D(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let se=await L(re.route,re.params);if(se){if(Z=se,!re.route.isDynamic)A.set(re.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=qr(C,se);if(Object.keys(re.params).length>0)se=Pt(se,re.params);if(se=await y(se,f),s)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let ue=R.find(({route:F})=>F.pattern===Z||F.pattern===`${Z}/`);if(ue){let F=await L(ue.route);if(F)se=F,A.set(ue.route.pattern,F)}}if(se){let ue=se.content;if(C)ue=qr(C,ue);if(ue=await y(ue,f),s)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),s)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let H=ce;if(H=await y(H,f),s)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
|
|
1440
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(v.url.toString(),()=>{if(d)Xe.watch(c,{recursive:!0}).close();v.stop()}),d){console.log(`${e.blue}Watching for changes...${e.reset}`);let w=Xe.watch(c,{recursive:!0},async(b,k)=>{if(!k)return;if(k.endsWith(".stx")||k.endsWith(".js")||k.endsWith(".ts")||k.endsWith(".md"))console.log(`${e.yellow}File ${e.bright}${k}${e.yellow} changed, rebuilding...${e.reset}`),Je.clear(),fe(),await g()});process.on("SIGINT",()=>{w.close(),v.stop(),process.exit(0)})}return!0}function an(t){return String(t??"").replace(/&/g,"&").replace(/</g,"<").replace(/>/g,">")}var{serve:Wr}=globalThis.Bun;import me from"fs";import te from"path";async function dn(t){try{return gn(await Bun.file(t).text())}catch{return}}function zt(t){let n=Bun.file(t),o=te.extname(t).toLowerCase(),d={".html":"text/html",".css":"text/css",".js":"text/javascript",".json":"application/json",".png":"image/png",".jpg":"image/jpeg",".jpeg":"image/jpeg",".gif":"image/gif",".svg":"image/svg+xml",".ico":"image/x-icon",".woff":"font/woff",".woff2":"font/woff2",".ttf":"font/ttf",".otf":"font/otf",".eot":"application/vnd.ms-fontobject"},c=[".js",".css",".json"].includes(o)?{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}:{};return new Response(n,{headers:{"Content-Type":d[o]||"application/octet-stream",...c}})}async function Hr(t=".",n={}){let o=n.port||3000,d=n.watch!==!1,s=n.hotReload!==!1&&d,c=null,u=n.hmrPort||o+1,f=te.resolve(t),{loadStxConfig:g}=await import("./chunk-vwvfedp7.js"),h=await g(f),{createServerApi:x,isServerApiSource:v}=await import("./chunk-7hex58nx.js"),S=n.stxOptions?.serverApi??h.serverApi,T=await x(f,S),w=h.root&&h.root!=="."?te.join(f,h.root):f,b=n.pagesDir||h.pagesDir||"pages",k=te.join(w,b);if(!me.existsSync(k)&&!h._layerPageDirs?.some((O)=>me.existsSync(O)))return console.error(`${e.red}Error: No '${b}' directory found${e.reset}`),console.log(`${e.dim}Looked in: ${e.bright}${k}${e.reset}`),console.log(`${e.dim}Run stx dev from the app directory, pass it as an argument (stx dev <dir>),${e.reset}`),console.log(`${e.dim}point at another directory with --pages <dir>, or set pagesDir in stx.config.ts.${e.reset}`),console.log(`${e.dim}Starting fresh? Create ${b}/index.stx for the homepage.${e.reset}`),!1;let _=X(w,{pagesDir:b,pagesDirs:h._layerPageDirs?[k,...h._layerPageDirs.slice(1)]:void 0});if(_.length===0)return console.error(`${e.red}Error: No page files found in ${e.bright}${k}${e.reset}`),!1;console.log(`${e.blue}Found ${e.bright}${_.length}${e.blue} routes${e.reset}`);let E=h?._pluginPageDirs||[],R=[];for(let{dir:O,prefix:j}of E)if(me.existsSync(O)){let N=X(te.dirname(O),{pagesDir:te.basename(O)});for(let Q of N){let q=j==="/"?Q.pattern:`${j}${Q.pattern==="/"?"":Q.pattern}`;R.push({route:{...Q,pattern:q},prefix:j})}if(N.length>0)console.log(`${e.blue}Plugin pages: ${e.bright}${N.length}${e.blue} routes at ${e.cyan}${j}${e.reset}`)}let A=new Map,C=null,M=null;if(n.stxOptions?.shell!==!1){if(M=await oa(f,n.stxOptions?.shell),M){if(C=await fo(M,n.stxOptions||{}),C)console.log(`${e.blue}Using app shell: ${e.bright}${te.relative(f,M)}${e.reset} ${e.dim}(deprecated: use layouts/default.stx instead)${e.reset}`)}}kt(),await Ct(f);let I=_t();if(I.length>0)console.log(`${e.blue}Loaded ${e.bright}${I.length}${e.blue} middleware: ${e.dim}${I.join(", ")}${e.reset}`);let V={},Y=null;try{let{loadStxConfig:O}=await import("./chunk-vwvfedp7.js"),j=await O(f);if(j?.apiRouter)Y=j?.apiRouter,console.log(`${e.blue}Using custom router for API handling${e.reset}`);if(j?.apiRoutes){V=j.apiRoutes;let N=Object.keys(V).length;if(N>0)console.log(`${e.blue}Loaded ${e.bright}${N} API route${N>1?"s":""}${e.reset}`)}if(j?.broadcasting?.enabled)try{let{startBroadcasting:N,loadChannels:Q}=await import("./chunk-d9p7xaj7.js"),q=j.broadcasting;await N(q);let Ae=q.port??6001;console.log(`${e.magenta}Broadcasting on ${e.cyan}ws://localhost:${Ae}/ws${e.reset}`);let ve=te.join(process.cwd(),"channels.ts");if(me.existsSync(ve))try{let U=await Q(ve);console.log(`${e.blue}Loaded ${e.bright}${U} broadcast channel${U!==1?"s":""}${e.blue} from channels.ts${e.reset}`)}catch(U){console.warn(`${e.yellow}Failed to load channels.ts: ${U.message}${e.reset}`)}}catch(N){console.warn(`${e.yellow}Broadcasting failed to start: ${N.message}${e.reset}`)}}catch{}let xe=l(f,"output");me.mkdirSync(xe,{recursive:!0});let le=new Map,Oe=new Set,ne=async(O)=>{let j=Ts(k,O);if(!j)return null;try{let N=await Bun.build({entrypoints:[j],outdir:xe,plugins:[rt],publicPath:"/",define:{"process.env.NODE_ENV":'"development"'},...n.stxOptions});if(!N.success)return null;let Q=N.outputs.find((q)=>q.path.endsWith(".html"));if(!Q)return null;return await Bun.file(Q.path).text()}catch{return null}},z=new Map,L=async(O,j)=>{try{let{processDirectives:N,extractVariables:Q,defaultConfig:q,loadStxConfig:Ae,injectRouterScript:ve}=await import("./chunk-vwvfedp7.js"),{checkCache:U,cacheTemplate:J,readFileCached:W,templateCache:pe}=await import("./chunk-5gk5nnqb.js"),G=await Ae(f),Ue=(ie)=>{if(!ie)return ie;if(te.isAbsolute(ie))return ie;return te.resolve(f,ie)},ce={...q,...G,...n.stxOptions,autoShell:!0};if(n.debugDirectives)ce.debug=!0;ce.partialsDir=Ue(ce.partialsDir),ce.componentsDir=Ue(ce.componentsDir),ce.layoutsDir=Ue(ce.layoutsDir),ce.storesDir=Ue(ce.storesDir||"stores"),ce.cachePath=Ue(ce.cachePath)??l(f,"cache");let H=!j&&!n.profile,re=ce.cache!==!1;if(re&&H){let ie=pe.get(O.filePath);if(ie)try{if((await me.promises.stat(O.filePath)).mtime.getTime()<=ie.mtime){let He=!0;for(let Se of ie.dependencies){if(!me.existsSync(Se)){He=!1;break}if((await me.promises.stat(Se)).mtime.getTime()>ie.mtime){He=!1;break}}if(He){let Se=ie.output;if(C)Se=We(Se,{preserveHead:!0});let st=z.get(O.filePath);return{route:O,content:Se,status:st?.status??await dn(O.filePath),headers:st?.headers}}}}catch{}let Ie=await U(O.filePath,ce);if(Ie){let je=Ie;if(C)je=We(je,{preserveHead:!0});let He=z.get(O.filePath);return{route:O,content:je,status:He?.status??await dn(O.filePath),headers:He?.headers}}}let Z=re?await W(O.filePath):await Bun.file(O.filePath).text(),se=gn(Z),{classifyAllScripts:ue}=await import("./chunk-vwvfedp7.js"),F=ue(Z),Le=F.server.map((ie)=>ie.content),Me=Z;for(let ie of F.server)Me=Me.replace(ie.fullTag,"");let ee={__filename:O.filePath,__dirname:te.dirname(O.filePath),__stx_options:ce,params:j??{},__stx_runtime_head:{}};for(let ie of Le)try{await Q(ie,ee,O.filePath)}catch(Ie){if(n.stxOptions?.debug)console.error("[stx] variable extraction error",O.filePath,Ie?.message||Ie)}let De=new Set,he;if(n.profile){let ie=performance.now();he=await N(Me,ee,O.filePath,ce,De);let Ie=performance.now()-ie,je=te.relative(f,O.filePath)||O.filePath;console.log(`[stx:profile] ${je} \u2192 ${Ie.toFixed(2)}ms`)}else he=await N(Me,ee,O.filePath,ce,De);if(!C)he=await ve(he,{router:ce.router});{let{interpolateScriptExpressions:ie}=await import("./chunk-0dwh4g5q.js");he=he.replace(/<script\b([^>]*)>([\s\S]*?)<\/script>/g,(Ie,je,He)=>{if(!/function\s+__stx_setup_/.test(He))return Ie;return`<script${je}>${ie(He,ee)}</script>`})}if(C)he=We(he,{preserveHead:!0});if(re&&H)await J(O.filePath,he,De,ce);let{extractStreamBoundaries:ct}=await import("./chunk-q5vqabha.js"),Qe=ct(ee),ot=ee.__streamTemplates;if(ot&&typeof ot==="object"&&Object.keys(ot).length>0){let ie=ee.streamBoundaries||{},Ie={...ce,autoShell:!1},je=Object.keys(ot).map((Se)=>({id:Se,render:async()=>{let st=typeof ie[Se]==="function"?await ie[Se]():void 0;return N(ot[Se],{...ee,$boundary:st},O.filePath,Ie,new Set)}})),He=new Set(je.map((Se)=>Se.id));Qe=[...(Qe||[]).filter((Se)=>!He.has(Se.id)),...je]}if(Qe&&Qe.length>0)Oe.add(O.pattern);else Qe=void 0;let Vt=Ot(ee),qt=Nt(ee);if(H)z.set(O.filePath,{status:Vt,headers:qt});return{route:O,content:he,status:Vt??se,headers:qt,boundaries:Qe}}catch(N){return console.error(`${e.red}Error building ${e.bright}${O.pattern}${e.reset}:`,N),null}},Fe=8,ze=async()=>{let O=new Set(le.keys()),j=new Set(A.keys());le.clear(),A.clear();let N=n.prebuild===!1?_.filter((q)=>O.has(q.pattern)):_,Q=n.prebuild===!1?R.filter(({route:q})=>j.has(q.pattern)):R;for(let q=0;q<N.length;q+=Fe){let Ae=N.slice(q,q+Fe),ve=await Promise.all(Ae.map((U)=>L(U)));for(let U of ve)if(U)le.set(U.route.pattern,U)}for(let q=0;q<Q.length;q+=Fe){let Ae=Q.slice(q,q+Fe),ve=await Promise.all(Ae.map(({route:U})=>L(U)));for(let U of ve)if(U)A.set(U.route.pattern,U)}return le.size>0};if(console.log(`${e.blue}${n.prebuild===!1?"Rendering pages on request...":"Building pages..."}${e.reset}`),!(n.prebuild===!1?_.length+R.length>0:await ze()))return console.error(`${e.red}No pages were successfully built${e.reset}`),!1;await cn(f);let Ge=o;try{if(Ge=await Ve(o),Ge!==o)console.log(`${e.yellow}Port ${o} is busy, using port ${Ge} instead${e.reset}`)}catch{return console.error(`${e.red}Could not find an available port${e.reset}`),!1}if(s){let O=n.hmrPort||Ge+1;c=vt({wsPort:O,verbose:!1}),u=c.start(O)}let Pt=(O,j)=>{let Q=`<script data-stx-route-params>(function(){var p=${JSON.stringify(j).replace(/</g,"\\u003C").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")};window.__stx_rp=p;if(window.stx){window.stx._rp=p;if(window.stx.setRouteParams)window.stx.setRouteParams(p)}})()</script>`;if(O.includes("</head>"))return O.replace("</head>",`${Q}</head>`);if(O.includes("<body"))return O.replace(/<body([^>]*)>/,`<body$1>${Q}`);return Q+O};console.log(`${e.blue}Starting server...${e.reset}`);let At=Wr({port:Ge,hostname:n.hostname,async fetch(O){let j=new URL(O.url),N=n.stxOptions?.offline??h.offline;if(j.pathname===Io&&N?.enabled){if(!["GET","HEAD"].includes(O.method))return new Response("Method Not Allowed",{status:405,headers:{Allow:"GET, HEAD"}});return new Response(O.method==="HEAD"?null:Oo(N,ss()),{headers:{"Content-Type":"application/javascript; charset=utf-8","Cache-Control":"no-store","Service-Worker-Allowed":"/"}})}let Q=h?.publicDir||"public",q=te.join(f,Q,j.pathname),Ae=te.join(f,j.pathname),ve=te.join(xe,j.pathname);if([q,Ae,ve].some((H)=>v(H,f,S)))return new Response("Not Found",{status:404});let[U,J,W]=await Promise.all([me.promises.stat(q).catch(()=>null),me.promises.stat(Ae).catch(()=>null),me.promises.stat(ve).catch(()=>null)]);if(U?.isFile()&&!v(q,f,S))return zt(q);if(J?.isFile()&&!v(Ae,f,S))return zt(Ae);if(W?.isFile()&&!v(ve,f,S))return zt(ve);if(j.pathname.startsWith("/_stx/component/")){let H=decodeURIComponent(j.pathname.slice(16));if(H)try{let re=`<${H} />`,Z={...buildConfig,autoShell:!1},se=await processDirectives(re,{},te.join(f,"components",`${H}.stx`),Z,new Set);return new Response(se,{headers:{"Content-Type":"text/html"}})}catch(re){return new Response(`<div class="stx-async-error">${re.message}</div>`,{status:500,headers:{"Content-Type":"text/html"}})}}if(j.pathname==="/_stx/img"){let{handleImageRequest:H}=await import("./chunk-43ynckvh.js"),re=await H(O,{publicDir:te.join(f,Q),cacheDir:l(f,"cache","img")});if(re)return re}if(Y)try{let H=await Y.handleRequest(O);if(H.status!==404)return H}catch{}if(V[j.pathname])try{return await V[j.pathname](O)}catch(H){return new Response(JSON.stringify({error:H.message}),{status:500,headers:{"Content-Type":"application/json"}})}let pe=await T(O);if(pe)return pe;let G=pr(j.pathname,_);if(G){let H=le.get(G.route.pattern),re=Oe.has(G.route.pattern);if(!H||G.route.isDynamic&&Object.keys(G.params).length>0||re){let Z=await L(G.route,G.params);if(Z){if(H=Z,!G.route.isDynamic&&!re)le.set(G.route.pattern,Z)}}if(H){let Z=H.status??200,se=H.headers??{},ue=(G.route.filePath?yt(await Bun.file(G.route.filePath).text().catch(()=>"")):null)??{};if(ue.validate){if(!await ue.validate({params:G.params})){let Me=await ne(404);if(Me){let ee=Me;if(ee=await y(ee,f),s)ee=Ne(ee,u);return new Response(ee,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})}}if(ue.middleware){let Le=Et(j.pathname,G.params,ue,j.search),Me=Tt(Le,null,O,{isServer:!0}),ee=await $t(ue.middleware,Me);if(ee.redirect){let De=ee.redirect.path,he=ee.redirect.options.redirectCode||302,ct=new Headers(ee.responseHeaders);return ct.set("Location",De),new Response(null,{status:he,headers:ct})}if(ee.abort){let{statusCode:De,message:he}=ee.abort.error;return new Response(`<!DOCTYPE html><html><head><title>Error ${De}</title></head><body><h1>Error ${De}</h1><p>${he}</p></body></html>`,{status:De,headers:{"Content-Type":"text/html"}})}if(Object.keys(ee.state).length>0){let De=`<script>(function(){var s=typeof stx!=='undefined'?stx:{};s._ms=${JSON.stringify(ee.state)};if(s.setMiddlewareState)s.setMiddlewareState(s._ms);})()</script>`;H.content=H.content.replace("</head>",`${De}</head>`)}}let F=H.content;if(C&&ia(O)&&qe(F,h?.router?.container||"main")){let Le=et(F),Me=be(F),ee=F.match(/<title[^>]*>([\s\S]*?)<\/title>/i),De=ee?An(ee[1].trim()):"";if(Object.keys(G.params).length>0)F=Pt(F,G.params);F=await y(F,f);let he=h?.router?.container||"main";return F=Ee(F,he,!0),new Response(F,{status:Z,headers:{"Content-Type":"text/html","X-STX-Fragment":"true","X-STX-Layout":Le.layout,"X-STX-Layout-Group":Le.group,"X-STX-Runtime":Me?"true":"false",...De&&{"X-STX-Title":encodeURIComponent(De)},[tc]:ss(),...D(),"Cache-Control":ft}})}if(C)F=qr(C,F);if(Object.keys(G.params).length>0)F=Pt(F,G.params);if(F=await y(F,f),s)F=Ne(F,u);if(n.native)if(F.includes("<head>"))F=F.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else F="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+F;if(n.titlebarHidden)if(F.includes("<head>"))F=F.replace("<head>","<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script>");else F=`<head><style>html.stx-titlebar-hidden .stx-traffic-lights-dot{visibility:hidden}</style><script>document.documentElement.classList.add('stx-titlebar-hidden')</script></head>${F}`;if(H.boundaries&&H.boundaries.length>0){let{renderStreamingPage:Le,streamToResponse:Me}=await import("./chunk-q5vqabha.js");return Me(Le(F,H.boundaries,{timeoutMs:30000}),{status:Z,headers:{"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}return new Response(F,{status:Z,headers:{"Content-Type":"text/html",...D(),"Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0",...se}})}}if(R.length>0){let H=R.map((Z)=>Z.route),re=pr(j.pathname,H);if(re){let Z=A.get(re.route.pattern);if(!Z||re.route.isDynamic){let se=await L(re.route,re.params);if(se){if(Z=se,!re.route.isDynamic)A.set(re.route.pattern,se)}}if(Z){let se=Z.content;if(C)se=qr(C,se);if(Object.keys(re.params).length>0)se=Pt(se,re.params);if(se=await y(se,f),s)se=Ne(se,u);return new Response(se,{status:Z.status??200,headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}for(let{prefix:Z}of E)if(Z!=="/"&&j.pathname.startsWith(Z)){let se=A.get(Z)||A.get(Z+"/");if(!se){let ue=R.find(({route:F})=>F.pattern===Z||F.pattern===`${Z}/`);if(ue){let F=await L(ue.route);if(F)se=F,A.set(ue.route.pattern,F)}}if(se){let ue=se.content;if(C)ue=qr(C,ue);if(ue=await y(ue,f),s)ue=Ne(ue,u);return new Response(ue,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}}}if(St(j.pathname))return new Response("Not Found",{status:404,headers:{"Content-Type":"text/plain; charset=utf-8"}});let Ue=le.get("/");if(Ue){let H=Ue.content;if(H=await y(H,f),s)H=Ne(H,u);if(n.native)if(H.includes("<head>"))H=H.replace("<head>","<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script>");else H="<head><style>[data-stx-sidebar],.stx-sidebar{display:none!important}</style><script>window.__craftNativeSidebar=true;document.documentElement.classList.add('has-native-sidebar')</script></head>"+H;return new Response(H,{headers:{"Content-Type":"text/html","Cache-Control":"no-store, no-cache, must-revalidate",Pragma:"no-cache",Expires:"0"}})}let ce=await ne(404);if(ce){let H=ce;if(H=await y(H,f),s)H=Ne(H,u);return new Response(H,{status:404,headers:{"Content-Type":"text/html"}})}return new Response("Not Found",{status:404})},async error(O){let j=await ne(500);if(j)return new Response(j,{status:500,headers:{"Content-Type":"text/html"}});return new Response(`<pre>${O}
|
|
1441
1441
|
${O.stack}</pre>`,{headers:{"Content-Type":"text/html"}})}});if(console.clear(),console.log(`
|
|
1442
1442
|
${e.blue}stx${e.reset} ${e.green}${process.env.stx_VERSION||"v0.0.10"}${e.reset} ${e.dim}ready in ${Math.random()*10+5|0}.${Math.random()*90+10|0} ms${e.reset}`),console.log(`
|
|
1443
1443
|
${e.bright}\u2192 ${e.cyan}http://localhost:${Ge}/${e.reset}`),s)console.log(`${e.dim} HMR: ws://localhost:${u}${e.reset}`);console.log(`
|
|
1444
1444
|
${e.yellow}Routes:${e.reset}`);let Dt=[...$s(_,f)];for(let{route:O}of R)Dt.push(`${O.pattern}`);if(Dt.forEach((O,j)=>{let Q=j===Dt.length-1?"\u2514\u2500 ":"\u251C\u2500 ";console.log(` ${e.green}${Q}${e.reset}${O}`)}),console.log(`
|
|
1445
|
-
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(c)it();At.stop()}),n.native){let O,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();O=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),_.splice(0,_.length,...X(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(O(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),s&&c)c.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-
|
|
1445
|
+
Press ${e.cyan}h${e.reset} + ${e.cyan}Enter${e.reset} to show shortcuts`),Ke(At.url.toString(),()=>{if(c)it();At.stop()}),n.native){let O,j=te.join(k,"index.stx");if(me.existsSync(j)){let Q=await Bun.file(j).text();O=gt(Q)}let N=h?.app?.window??{};await Ze(Ge,{title:h?.app?.head?.title||te.basename(f)||"stx App",width:N.width,height:N.height,darkMode:N.darkMode,hotReload:N.hotReload,titlebarHidden:N.titlebarHidden??n.titlebarHidden===!0,nativeSidebar:!!O,sidebarConfig:O})}if(d){console.log(`${e.blue}Watching for changes...${e.reset}`);let O=(U)=>U.startsWith("public/")||U.startsWith("public\\"),j=(U)=>{let J=U.toLowerCase();return J.endsWith(".stx")||J.endsWith(".html")||J.endsWith(".md")},N=new Map,Q=()=>{let U=new Set([f,...h._layerGraph?.layers.map((J)=>J.root)??[],...h._layerGraph?.configDependencies.map((J)=>te.dirname(J))??[]].filter((J)=>me.existsSync(J)).map((J)=>me.realpathSync(J)));for(let J of h._layerGraph?.layers??[])for(let W of Object.values(J.resources)){if(!me.existsSync(W))continue;let pe=me.realpathSync(W);if(![...U].some((G)=>pe===G||pe.startsWith(`${G}${te.sep}`)))U.add(pe)}for(let[J,W]of N)if(!U.has(J))W.close(),N.delete(J);for(let J of U)if(!N.has(J)&&me.existsSync(J))N.set(J,me.watch(J,{recursive:!0},(W,pe)=>{Ae(J,W,pe).catch((G)=>console.error("[stx] Layer rebuild failed:",G))}))},q=Promise.resolve(),Ae=(U,J,W)=>(q=q.catch(()=>{}).then(()=>ve(U,J,W)),q),ve=async(U,J,W)=>{if(!W||xt(W))return;if(bt(W)){if(h._layerGraph){let pe=await g(f);Object.assign(h,pe),_.splice(0,_.length,...X(w,{pagesDir:b,pagesDirs:pe._layerPageDirs?[k,...pe._layerPageDirs.slice(1)]:void 0})),Q()}if(O(W)){if(console.log(`${e.cyan}${W} changed${e.reset}`),s&&c)c.reload(W)}else if(j(W)){console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-5gk5nnqb.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(M&&W){if(te.resolve(U,W)===M||te.basename(M)===W){let G=await fo(M,n.stxOptions||{});if(G)C=G}}if(await ze(),await sr(f),s&&c)c.reload(W)}else{console.log(`${e.yellow}${W} changed, rebuilding...${e.reset}`),Je.clear(),fe();try{let{invalidateFileCache:pe,templateCache:G}=await import("./chunk-5gk5nnqb.js");pe(te.resolve(U,W)),G.delete(te.resolve(U,W))}catch{}if(await ze(),s&&c)c.reload(W)}}else if(ht(W)){if(console.log(`${e.cyan}CSS ${W} changed${e.reset}`),s&&c)c.updateCss(W)}};Q(),process.on("SIGINT",()=>{for(let U of N.values())U.close();if(c)it();At.stop(),process.exit(0)})}return!0}import Ut from"fs";import at from"path";async function Vr(t){try{let o=(await Bun.file(t).text()).match(/<script\b[^>]*>([\s\S]*?)<\/script>/i);if(!o)return[];let d=o[1],s=[],c=/\/\*\*\s*([\s\S]*?)\s*\*\/\s*(?:(?:const|let|var)\s*)?(?:([\w$]+)\s*=|module\.exports\.([\w$]+)\s*=|\s*([\w$]+)\s*:)/g,u;while((u=c.exec(d))!==null){let f=u[1],g=u[2]||u[3]||u[4];if(!g)continue;let h={name:g},x=f.match(/@type\s+\{([^}]+)\}/i);if(x)h.type=x[1].trim();if(f.match(/@required/i))h.required=!0;let S=f.match(/@default\s+(.+?)(?:\s+|$)/i);if(S)h.default=S[1].trim();let T=f.split(`
|
|
1446
1446
|
`).map((w)=>w.trim().replace(/^\*\s*/,"")).filter((w)=>!w.startsWith("@")&&w.length>0);h.description=T.join(" ").trim(),s.push(h)}if(s.length===0){let f=d.match(/module\.exports\s*=\s*\{([^}]+)\}/i);if(f){let h=f[1].split(",").map((x)=>x.trim()).filter(Boolean);for(let x of h){let[v]=x.split(":").map((S)=>S.trim());if(v)s.push({name:v})}}}return s}catch(n){return console.error(`Error extracting props from ${t}:`,n),[]}}async function Kr(t){try{let n=await Bun.file(t).text(),o=n.match(/^\s*<!--\s*([\s\S]*?)\s*-->/)||n.match(/^\s*\/\*\*\s*([\s\S]*?)\s*\*\//);if(o)return o[1].split(`
|
|
1447
1447
|
`).map((d)=>d.trim().replace(/^\*\s*/,"")).join(" ").trim();return""}catch{return""}}async function Xr(t,n=!1,o){let d=at.basename(t,".stx"),s=await Vr(t),c=await Kr(t),u="";if(n&&o)u=`<${o}></${o}>`;else{let f=s.map((g)=>{if(g.type==="boolean")return`:${g.name}="true"`;return`${g.name}="value"`}).join(`
|
|
1448
1448
|
`);u=`<${d}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{vn,wi}from"./chunk-
|
|
2
|
+
import{vn,wi}from"./chunk-t5fgdj4e.js";import"./chunk-27rzdq3n.js";export{wi as generateRuntimeConfigTypes,vn as prepareRuntimeConfig};
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{dl,pl}from"./chunk-gb65t4n1.js";import{H,yr,Is,Os,ri,si,Ns,wr,Ne,pe,G,xr,ie,J,I,rt,Sr,ci,Cr,Fe,r,p,V,wn}from"./chunk-y8wer7e1.js";import{f,R,st,d}from"./chunk-94gyfwpz.js";import{n}from"./chunk-dk53ytvr.js";import{se}from"./chunk-qv85c3qy.js";import{s}from"./chunk-14ft0zc7.js";import{g}from"./chunk-0dve54ne.js";import{createHash as Rt}from"crypto";import Q from"fs";import K from"path";import{decode as on,generateThumbHash as an}from"ts-images";import{createImageDeliveryCatalog as bt}from"ts-images/delivery";import De from"fs";function Ce(e,t,i){let o=Buffer.alloc(i),a=De.readSync(e,o,0,i,t);return o.subarray(0,a)}function je(e){if(e.length<25)return!1;let t=(o,a)=>String.fromCharCode(...e.subarray(o,a));if(t(0,4)!=="RIFF"||t(8,12)!=="WEBP")return!1;let i=t(12,16);if(i==="VP8X")return(e[20]&16)!==0;if(i==="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=De.openSync(e,"r");let i=Ce(t,0,33);if(i.length>=3&&i[0]===255&&i[1]===216&&i[2]===255)return"none";if(i.length>=26&&i[0]===137&&i.toString("latin1",1,4)==="PNG"){let o=i[25];if(o===4||o===6)return"possible";let a=8;for(let c=0;c<64;c++){let l=Ce(t,a,8);if(l.length<8)return"unknown";let m=l.toString("latin1",4,8);if(m==="tRNS")return"possible";if(m==="IDAT"||m==="IEND")return"none";a+=12+l.readUInt32BE(0)}return"unknown"}if(i.length>=25&&i.toString("latin1",0,4)==="RIFF"&&i.toString("latin1",8,12)==="WEBP"){if(je(i))return"possible";let o=i.toString("latin1",12,16);return o==="VP8 "||o==="VP8X"?"none":"unknown"}return"unknown"}catch{return"unknown"}finally{if(t!==void 0)De.closeSync(t)}}import Yt from"fs";import Re from"os";import{join as gt}from"path";import{fileURLToPath as mt}from"url";import{Worker as pt}from"worker_threads";var ke=Symbol("stx.image-worker.unavailable");function Qt(e=typeof Re.availableParallelism==="function"?Re.availableParallelism():Re.cpus().length){return Math.max(1,Math.min(2,e-1))}var Ae=0,yt=[];async function en(){if(Ae<Qt()){Ae++;return}await new Promise((e)=>yt.push(e)),Ae++}function tn(){Ae--,yt.shift()?.()}var nn="@stacksjs/stx/builtins/image-warmup-worker";function rn(e=process.cwd()){let t=import.meta.url.endsWith(".ts")?"ts":"js";try{let i=new URL(`./image-warmup-worker.${t}`,import.meta.url);if(i.protocol==="file:"&&Yt.existsSync(mt(i)))return mt(i)}catch{}try{let i=typeof Bun<"u"?Bun.resolveSync(nn,e):void 0;return i&&sn(i)?i:void 0}catch{return}}function sn(e,t=process.env){let i=e.replace(/\\/g,"/");if(i.split("/").some((a)=>/@\d[^/]*@@@\d+$/.test(a)))return!1;return![t.BUN_INSTALL_CACHE_DIR,gt(t.BUN_INSTALL||gt(Re.homedir(),".bun"),"install","cache")].filter((a)=>!!a).map((a)=>`${a.replace(/\\/g,"/").replace(/\/$/,"")}/`).some((a)=>i.startsWith(a))}var ht=!1;function he(e){if(!ht)ht=!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 pt!=="function")return he("node:worker_threads has no Worker in this runtime");let i=rn();if(!i)return he("no image-warmup-worker entry beside this module or in the installed @stacksjs/stx");await en();try{return await new Promise((o,a)=>{let c;try{c=new pt(i)}catch(y){o(he(`could not start ${i}: ${Le(y)}`));return}let l=!1,m=!1,u=(y)=>{if(m)return;m=!0,y(),c.terminate()};c.on("message",(y)=>{if(y.type==="ready"){l=!0,c.postMessage({task:e,args:t});return}if(y.type==="result"){u(()=>o(y.value));return}let v=Error(y.error?.message??"image worker failed");if(y.error?.name)v.name=y.error.name;if(y.error?.stack)v.stack=y.error.stack;u(()=>a(v))}),c.on("error",(y)=>{u(()=>l?a(y instanceof Error?y:Error(Le(y)||"image worker crashed")):o(he(`the worker failed before it was ready: ${Le(y)}`)))}),c.on("exit",(y)=>{u(()=>l?a(Error("image worker exited before it finished")):o(he(`the worker exited with code ${y} before it was ready`)))})})}finally{tn()}}var cn=new Set([".avif",".jpeg",".jpg",".png",".webp"]),ln=[320,640,960,1280,1920],ye="/_stx/images",un=`stx:${ye}:alpha-1`,fn=`stx:${ye}:opaque-1`,dn=["@stacksjs/ts-webp","@stacksjs/ts-avif","ts-images"],Pe;function gn(e,t){let i=K.dirname(Bun.resolveSync(e,t));while(i!==K.dirname(i)){let o=K.join(i,"package.json");if(Q.existsSync(o)){let a=JSON.parse(Q.readFileSync(o,"utf8"));if(a.name===e)return a.version}i=K.dirname(i)}return}function xt(){if(Pe!==void 0)return Pe;let e;try{e=K.dirname(Bun.resolveSync("ts-images",import.meta.dir))}catch{}return Pe=dn.map((t)=>{let i;try{i=e?gn(t,e):void 0}catch{}return`${t.replace("@stacksjs/","")}@${i??"unknown"}`}).join("+"),Pe}var vt=Symbol.for("stx.image-delivery");function be(){let e=globalThis;return e[vt]??={catalog:new Map,transparent:new Set},e[vt]}var wt=new Set;function mn(e){return`/${e.split(K.sep).map(encodeURIComponent).join("/")}`}function pn(e){let t=K.extname(e),i=e.slice(0,-t.length).replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,""),o=Rt("sha256").update(e).digest("hex").slice(0,8);return`${i||"image"}-${o}`}function $t(e,t=`stx:${ye}`){let i=(o)=>`${ye}/${o.split("/").map(encodeURIComponent).join("/")}`;return{cacheNamespace:t,async stat(o){let a=K.join(e,o);try{let c=await Q.promises.stat(a);return c.size>0?{bytes:c.size,path:a,url:i(o)}:null}catch{return null}},async write(o,a){let c=K.join(e,o);await Q.promises.mkdir(K.dirname(c),{recursive:!0});let l=`${c}.${process.pid}.tmp`;return await Q.promises.writeFile(l,a),await Q.promises.rename(l,c),{bytes:a.byteLength,path:c,url:i(o)}},url:i}}async function At(e,t=e){let i=await Q.promises.readdir(t,{withFileTypes:!0});i.sort((a,c)=>a.name.localeCompare(c.name));let o=[];for(let a of i){let c=K.join(t,a.name);if(a.isDirectory()){o.push(...await At(e,c));continue}if(!a.isFile()||!cn.has(K.extname(a.name).toLowerCase()))continue;o.push({absolutePath:c,relativePath:K.relative(e,c)})}return o}function St(e,t){return e.map((i)=>({key:mn(i.relativePath),input:i.absolutePath,name:pn(i.relativePath),...hn(i.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 bn(e){let t=Object.entries(e).filter(([,a])=>a.fallback.format==="png"),i=new Set,o=8;for(let a=0;a<t.length;a+=8)await Promise.all(t.slice(a,a+8).map(async([c,l])=>{let m=l.variants.filter((u)=>u.format==="png").sort((u,y)=>u.width-y.width)[0];try{let u=await on(new Uint8Array(await Q.promises.readFile(m?.path??l.fallback.path)));if(yn(u.data))i.add(c)}catch{i.add(c)}}));return i}function xn(e,t){let i=[];for(let o of t){let a=e[o],c=a?.variants.filter((m)=>m.format==="webp")??[];if(!a||c.length===0)continue;if(!c.some((m)=>{let u;try{return u=Q.openSync(m.path,"r"),!je(Ce(u,0,32))}catch{return!0}finally{if(u!==void 0)Q.closeSync(u)}}))continue;if(a.variants=a.variants.filter((m)=>m.format!=="webp"),delete a.sources.webp,i.push(o),!wt.has(o))wt.add(o),console.warn(`[stx-images] ${o} is transparent but its WebP variants have no alpha channel; serving PNG instead. Upgrade @stacksjs/ts-webp to 0.1.6 or later.`)}return i}async function vn(e){let t=[],i=8;for(let o=0;o<e.length;o+=8){let a=e.slice(o,o+8),c=await Promise.all(a.map(async(l)=>{try{return await an(l.absolutePath),l}catch{return console.warn(`[stx-images] Skipping unreadable raster: ${l.relativePath}`),null}}));t.push(...c.filter((l)=>l!==null))}return t}function Ue(e){return K.join(e,"undecodable.json")}function $n(e){try{let t=Q.readFileSync(Ue(e),"utf-8"),i=JSON.parse(t);return i&&typeof i==="object"?i:{}}catch{return{}}}function Sn(e,t){try{Q.mkdirSync(K.dirname(Ue(e)),{recursive:!0}),Q.writeFileSync(Ue(e),JSON.stringify(t))}catch{}}function Ct(e){try{let t=Q.statSync(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return}}function kt(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 Mo(e){let t=kt(e);return t?be().catalog.get(t):void 0}function Do(e){let t=kt(e);return t?be().transparent.has(t):!1}function Lo(e){let t=(o)=>e.variants.filter((a)=>a.format===o).reduce((a,c)=>a+c.bytes,0),i=t(e.fallback.format);return["avif","webp"].map((o)=>({format:o,srcset:e.sources[o]||"",bytes:t(o)})).filter((o)=>o.srcset&&o.bytes>0&&o.bytes<i).sort((o,a)=>o.bytes-a.bytes).map(({format:o,srcset:a})=>({format:o,srcset:a}))}function $h(e){let t=Mo(e);if(!t)return;return{src:t.fallback.url,srcset:t.sources[t.fallback.format]||"",sources:Lo(t).map(({format:i,srcset:o})=>({type:`image/${i}`,srcset:o})),width:t.source.width,height:t.source.height,placeholder:Do(e)?void 0:t.placeholder?.dataUrl}}function cs(){let e=be();e.catalog=new Map,e.transparent=new Set}function Cn(e){let t=be();t.catalog=new Map(e.entries),t.transparent=new Set(e.transparent)}async function Rh(e,t,i={}){if(!e||!Q.existsSync(e))return cs(),{count:0,fingerprint:""};if(i.offThread){let h=await ze("delivery",{publicDir:e,outputDir:t});if(h!==ke)return Cn(h.state),h.result}let o=await At(e);if(o.length===0)return cs(),{count:0,fingerprint:""};let a=$n(t),c=o.filter((h)=>{let w=a[h.relativePath];if(!w)return!0;let S=Ct(h.absolutePath);return!S||S.mtimeMs!==w.mtimeMs||S.size!==w.size});if(c.length===0)return cs(),{count:0,fingerprint:""};let l=$t(K.join(t,"_stx","images"),`${un}:${xt()}`),m={outDir:K.join(t,"_stx","images"),storage:$t(K.join(t,"_stx","images"),`${fn}:${xt()}`),baseUrl:ye,widths:ln,formats:["avif","webp"],quality:{avif:70,webp:78,jpeg:82,png:100},includeOriginal:!1,placeholder:!0,batchConcurrency:4,concurrency:4},u=c,y;try{y=await bt({...m,entries:St(c,l)})}catch(h){if(u=await vn(c),u.length===c.length)throw h;let w=new Set(u.map((A)=>A.relativePath)),S=!1;for(let A of c){if(w.has(A.relativePath))continue;let P=Ct(A.absolutePath);if(!P)continue;a[A.relativePath]=P,S=!0}if(S)Sn(t,a);if(u.length===0)return cs(),{count:0,fingerprint:""};y=await bt({...m,entries:St(u,l)})}let v=await bn(y.entries),b=xn(y.entries,v),C=be();C.catalog=new Map(Object.entries(y.entries)),C.transparent=v;let x=v.size===0&&b.length===0?y.fingerprint:Rt("sha256").update(y.fingerprint).update(JSON.stringify({transparent:[...v].sort(),droppedWebp:b.sort()})).digest("hex");return{count:u.length,fingerprint:x}}class Pt{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,i,o){let a=ri(e,o);if(a!==void 0)return a;for(let c of si(e,t,i,o))if(await r(c))return c;return null}}var ue=new Pt;var re="\x00stx-boolean-attribute";function We(e){return e.indexOf("\x00")===-1?e:e.replace(/\0/g,"")}var Rn=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 He(e){let t=e.toLowerCase();return t.startsWith("aria-")||t.startsWith("data-")||Rn.has(t)}function oe(e,t){let i=[];for(let[o,a]of Object.entries(e.static)){if(t.has(o))continue;let c=e.staticNames?.[o]??o;if(typeof a==="boolean"){if(a)i.push(p(c));continue}if(a===re){i.push(p(c));continue}i.push(`${p(c)}="${wn(c,We(String(a)))}"`)}return i}function ae(e,t){let i=[];for(let[o,a]of Object.entries(e.serverDynamic??{})){if(t.has(o))continue;if(a===null||a===void 0||a===!1)continue;let c=e.serverDynamicNames?.[o]??o;if(a===!0){i.push(p(c));continue}if(typeof a==="object")continue;i.push(`${p(c)}="${wn(c,We(String(a)))}"`)}return i}function An(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 qe={name:"StxLink",aliases:["stx-link"],render(e,t,i){let o=An(e),a=(typeof e.static.class==="string"?e.static.class:"")||(typeof e.static.className==="string"?e.static.className:""),c=typeof e.static.activeClass==="string"?e.static.activeClass:"active",l=typeof e.static.exactActiveClass==="string"?e.static.exactActiveClass:"exact-active",m=e.static.prefetch===!0||e.static.prefetch==="true"||e.serverDynamic.prefetch===!0,u=[];if(o.reactive)u.push(`:href="${n(o.value)}"`);else u.push(`href="${n(wr(o.value,"navigable"))}"`);if(a)u.push(`class="${n(a)}"`);if(u.push("data-stx-link"),u.push(`data-stx-active-class="${n(c)}"`),u.push(`data-stx-exact-active-class="${n(l)}"`),m)u.push("data-stx-prefetch");let y=typeof e.static.activeMatch==="string"?e.static.activeMatch.trim():"";if(y)u.push(`data-stx-active-match="${n(y)}"`);let v=new Set(["to","class","className","activeClass","exactActiveClass","activeMatch","prefetch"]);return u.push(...oe(e,v)),u.push(...ae(e,v)),`<a ${u.join(" ")}>${t}</a>`}};var kn=new Map;function Xe(e){if(!e)return;let t=e.split("?")[0].split("#")[0];return kn.get(t)}var Pn={sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Ze=[320,640,768,1024,1280,1536,1920];function Z(e,t){if(e.serverDynamic[t]!==void 0)return String(e.serverDynamic[t]);let i=e.static[t];if(typeof i==="string")return i;return}function Ie(e,t,i=!1){let o=e.serverDynamic[t];if(o!==void 0)return o!==!1&&o!=="false";let a=e.static[t];if(a!==void 0)return a!=="false"&&a!==!1;return i}function Ve(e){if(e.includes("(")||e.includes(","))return e;let t=e.trim().split(/\s+/),i=[];for(let o of t)if(o.includes(":")){let[a,c]=o.split(":"),l=Pn[a];if(l)i.push(`(max-width: ${l}px) ${c}`);else{let m=Number.parseInt(a);if(!Number.isNaN(m))i.push(`(max-width: ${m}px) ${c}`)}}else i.push(o);return i.join(", ")}function Ge(e,t,i,o){return t.map((a)=>`${xe(e,a,void 0,i,o)} ${a}w`).join(", ")}function In(e,t,i,o,a){return t.map((c)=>{let l=i?i*c:void 0;return`${xe(e,l,void 0,o,a)} ${c}x`}).join(", ")}function xe(e,t,i,o,a){if(!o||o==="local"||o==="static")return e;if(o==="cloudinary"){let c=[];if(t)c.push(`w_${t}`);if(i)c.push(`h_${i}`);if(a)c.push(`f_${a}`);c.push("q_auto");let l=c.join(",");return e.replace("/upload/",`/upload/${l}/`)}if(o==="imgix"){let c=new URLSearchParams;if(t)c.set("w",String(t));if(i)c.set("h",String(i));if(a)c.set("fm",a);c.set("auto","format");let l=e.includes("?")?"&":"?";return`${e}${l}${c.toString()}`}if(o==="bunny"){let c=new URLSearchParams;if(t)c.set("width",String(t));if(i)c.set("height",String(i));if(a)c.set("format",a);let l=e.includes("?")?"&":"?";return`${e}${l}${c.toString()}`}return e}function _n(e){return`var s=this.style;${e.map((t)=>`s.${t}=''`).join(";")}`}function En(e,t,i="#e5e7eb"){let o=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}"><rect width="100%" height="100%" fill="${i}"/></svg>`;return`data:image/svg+xml;base64,${btoa(o)}`}var Ke={name:"StxImage",aliases:["Image","stx-image","stx-img"],render(e,t,i){let o=Z(e,"src")||"",a=Mo(o),c=Z(e,"alt")||"",l=Z(e,"width")||(a?String(a.source.width):void 0),m=Z(e,"height")||(a?String(a.source.height):void 0),u=Z(e,"sizes"),y=Z(e,"srcset"),v=Z(e,"densities"),b=Z(e,"format"),C=Do(o)||Xe(o)?.transparent===!0,x=Z(e,"placeholder")||(a&&!C?"thumbhash":void 0),h=Z(e,"placeholderColor")||"#e5e7eb",w=Z(e,"provider"),S=Z(e,"class")||Z(e,"className")||"",A=Z(e,"style")||"",P=Z(e,"objectFit")||Z(e,"fit"),k=Z(e,"objectPosition")||Z(e,"position"),O=Z(e,"quality"),W=Ie(e,"lazy",!0),z=Ie(e,"preload",!1),U=Ie(e,"priority",!1),q=Z(e,"loading"),B=Z(e,"decoding")||"async",N=!!a||Ie(e,"picture",!1)||!!b,T=l?Number.parseInt(l):void 0,j=m?Number.parseInt(m):void 0,F=y||"",X="";if(a)F=a.sources[a.fallback.format]||"",X=u?Ve(u):"100vw";else if(!F&&u&&w&&w!=="local"&&w!=="static")F=Ge(o,Ze,w,b),X=Ve(u);else if(!F&&v){let _=v.split(/\s+/).map((E)=>Number.parseFloat(E.replace("x","")));F=In(o,_,T,w,b)}else if(u)X=Ve(u);let L=[];if(A)L.push(A);if(P)L.push(`object-fit:${P}`);if(k)L.push(`object-position:${k}`);if(T&&j)L.push(`aspect-ratio:${T}/${j}`);let D=[],ce=x==="blur"||x==="color"||x==="thumbhash";if(ce&&!C){let _=a?.placeholder?{dataUrl:a.placeholder.dataUrl,color:h}:Xe(o);if(_&&x==="color")L.push(`background-color:${_.color}`),D.push("backgroundColor");else if(_)L.push(`background-color:${_.color}`),L.push(`background-image:url(${_.dataUrl})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),D.push("backgroundColor","backgroundImage");else{let E=En(T||16,j||9,h);L.push(`background-image:url(${E})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),D.push("backgroundImage")}}else if(!ce&&x&&x!=="empty"&&x!=="none")L.push(`background-image:url(${n(x)})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),D.push("backgroundImage");let $e=a?.fallback.url||xe(o,T,j,w,b),Y=[];if(Y.push(`src="${n(wr($e,"fetched"))}"`),Y.push(`alt="${n(c)}"`),l)Y.push(`width="${n(l)}"`);if(m)Y.push(`height="${n(m)}"`);let le=q||(U||z?"eager":W?"lazy":"");if(le)Y.push(`loading="${n(le)}"`);if(U)Y.push('fetchpriority="high"');if(Y.push(`decoding="${n(B)}"`),S)Y.push(`class="${n(S)}"`);if(L.length>0)Y.push(`style="${n(L.join(";"))}"`);if(F)Y.push(`srcset="${n(wr(F,"fetched"))}"`);if(X)Y.push(`sizes="${n(X)}"`);let te=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(D.length>0){let _=typeof e.static.onload==="string"?e.static.onload:"",E=_n(D)+(_?`;${_}`:"");Y.push(`onload="${n(E)}"`),te.add("onload")}Y.push(...oe(e,te)),Y.push(...ae(e,te));let Te=`<img ${Y.join(" ")} />`,M="";if(z){let E=b==="webp"?"image/webp":b==="avif"?"image/avif":"";M=`<link rel="preload" as="image" href="${n($e)}"${E?` type="${E}"`:""}${F?` imagesrcset="${n(F)}"`:""}${X?` imagesizes="${n(X)}"`:""} />
|
|
2
|
+
import{dl,pl}from"./chunk-gb65t4n1.js";import{H,yr,Is,Os,ri,si,Ns,wr,Ne,pe,G,xr,ie,J,I,rt,Sr,ci,Cr,Fe,r,p,V,wn}from"./chunk-9k50gdfa.js";import{f,R,st,d}from"./chunk-94gyfwpz.js";import{n}from"./chunk-65bnepha.js";import{se}from"./chunk-qv85c3qy.js";import{s}from"./chunk-14ft0zc7.js";import{g}from"./chunk-0dve54ne.js";import{createHash as Rt}from"crypto";import Q from"fs";import K from"path";import{decode as on,generateThumbHash as an}from"ts-images";import{createImageDeliveryCatalog as bt}from"ts-images/delivery";import De from"fs";function Ce(e,t,i){let o=Buffer.alloc(i),a=De.readSync(e,o,0,i,t);return o.subarray(0,a)}function je(e){if(e.length<25)return!1;let t=(o,a)=>String.fromCharCode(...e.subarray(o,a));if(t(0,4)!=="RIFF"||t(8,12)!=="WEBP")return!1;let i=t(12,16);if(i==="VP8X")return(e[20]&16)!==0;if(i==="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=De.openSync(e,"r");let i=Ce(t,0,33);if(i.length>=3&&i[0]===255&&i[1]===216&&i[2]===255)return"none";if(i.length>=26&&i[0]===137&&i.toString("latin1",1,4)==="PNG"){let o=i[25];if(o===4||o===6)return"possible";let a=8;for(let c=0;c<64;c++){let l=Ce(t,a,8);if(l.length<8)return"unknown";let m=l.toString("latin1",4,8);if(m==="tRNS")return"possible";if(m==="IDAT"||m==="IEND")return"none";a+=12+l.readUInt32BE(0)}return"unknown"}if(i.length>=25&&i.toString("latin1",0,4)==="RIFF"&&i.toString("latin1",8,12)==="WEBP"){if(je(i))return"possible";let o=i.toString("latin1",12,16);return o==="VP8 "||o==="VP8X"?"none":"unknown"}return"unknown"}catch{return"unknown"}finally{if(t!==void 0)De.closeSync(t)}}import Yt from"fs";import Re from"os";import{join as gt}from"path";import{fileURLToPath as mt}from"url";import{Worker as pt}from"worker_threads";var ke=Symbol("stx.image-worker.unavailable");function Qt(e=typeof Re.availableParallelism==="function"?Re.availableParallelism():Re.cpus().length){return Math.max(1,Math.min(2,e-1))}var Ae=0,yt=[];async function en(){if(Ae<Qt()){Ae++;return}await new Promise((e)=>yt.push(e)),Ae++}function tn(){Ae--,yt.shift()?.()}var nn="@stacksjs/stx/builtins/image-warmup-worker";function rn(e=process.cwd()){let t=import.meta.url.endsWith(".ts")?"ts":"js";try{let i=new URL(`./image-warmup-worker.${t}`,import.meta.url);if(i.protocol==="file:"&&Yt.existsSync(mt(i)))return mt(i)}catch{}try{let i=typeof Bun<"u"?Bun.resolveSync(nn,e):void 0;return i&&sn(i)?i:void 0}catch{return}}function sn(e,t=process.env){let i=e.replace(/\\/g,"/");if(i.split("/").some((a)=>/@\d[^/]*@@@\d+$/.test(a)))return!1;return![t.BUN_INSTALL_CACHE_DIR,gt(t.BUN_INSTALL||gt(Re.homedir(),".bun"),"install","cache")].filter((a)=>!!a).map((a)=>`${a.replace(/\\/g,"/").replace(/\/$/,"")}/`).some((a)=>i.startsWith(a))}var ht=!1;function he(e){if(!ht)ht=!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 pt!=="function")return he("node:worker_threads has no Worker in this runtime");let i=rn();if(!i)return he("no image-warmup-worker entry beside this module or in the installed @stacksjs/stx");await en();try{return await new Promise((o,a)=>{let c;try{c=new pt(i)}catch(y){o(he(`could not start ${i}: ${Le(y)}`));return}let l=!1,m=!1,u=(y)=>{if(m)return;m=!0,y(),c.terminate()};c.on("message",(y)=>{if(y.type==="ready"){l=!0,c.postMessage({task:e,args:t});return}if(y.type==="result"){u(()=>o(y.value));return}let v=Error(y.error?.message??"image worker failed");if(y.error?.name)v.name=y.error.name;if(y.error?.stack)v.stack=y.error.stack;u(()=>a(v))}),c.on("error",(y)=>{u(()=>l?a(y instanceof Error?y:Error(Le(y)||"image worker crashed")):o(he(`the worker failed before it was ready: ${Le(y)}`)))}),c.on("exit",(y)=>{u(()=>l?a(Error("image worker exited before it finished")):o(he(`the worker exited with code ${y} before it was ready`)))})})}finally{tn()}}var cn=new Set([".avif",".jpeg",".jpg",".png",".webp"]),ln=[320,640,960,1280,1920],ye="/_stx/images",un=`stx:${ye}:alpha-1`,fn=`stx:${ye}:opaque-1`,dn=["@stacksjs/ts-webp","@stacksjs/ts-avif","ts-images"],Pe;function gn(e,t){let i=K.dirname(Bun.resolveSync(e,t));while(i!==K.dirname(i)){let o=K.join(i,"package.json");if(Q.existsSync(o)){let a=JSON.parse(Q.readFileSync(o,"utf8"));if(a.name===e)return a.version}i=K.dirname(i)}return}function xt(){if(Pe!==void 0)return Pe;let e;try{e=K.dirname(Bun.resolveSync("ts-images",import.meta.dir))}catch{}return Pe=dn.map((t)=>{let i;try{i=e?gn(t,e):void 0}catch{}return`${t.replace("@stacksjs/","")}@${i??"unknown"}`}).join("+"),Pe}var vt=Symbol.for("stx.image-delivery");function be(){let e=globalThis;return e[vt]??={catalog:new Map,transparent:new Set},e[vt]}var wt=new Set;function mn(e){return`/${e.split(K.sep).map(encodeURIComponent).join("/")}`}function pn(e){let t=K.extname(e),i=e.slice(0,-t.length).replace(/[^a-zA-Z0-9_-]+/g,"-").replace(/^-+|-+$/g,""),o=Rt("sha256").update(e).digest("hex").slice(0,8);return`${i||"image"}-${o}`}function $t(e,t=`stx:${ye}`){let i=(o)=>`${ye}/${o.split("/").map(encodeURIComponent).join("/")}`;return{cacheNamespace:t,async stat(o){let a=K.join(e,o);try{let c=await Q.promises.stat(a);return c.size>0?{bytes:c.size,path:a,url:i(o)}:null}catch{return null}},async write(o,a){let c=K.join(e,o);await Q.promises.mkdir(K.dirname(c),{recursive:!0});let l=`${c}.${process.pid}.tmp`;return await Q.promises.writeFile(l,a),await Q.promises.rename(l,c),{bytes:a.byteLength,path:c,url:i(o)}},url:i}}async function At(e,t=e){let i=await Q.promises.readdir(t,{withFileTypes:!0});i.sort((a,c)=>a.name.localeCompare(c.name));let o=[];for(let a of i){let c=K.join(t,a.name);if(a.isDirectory()){o.push(...await At(e,c));continue}if(!a.isFile()||!cn.has(K.extname(a.name).toLowerCase()))continue;o.push({absolutePath:c,relativePath:K.relative(e,c)})}return o}function St(e,t){return e.map((i)=>({key:mn(i.relativePath),input:i.absolutePath,name:pn(i.relativePath),...hn(i.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 bn(e){let t=Object.entries(e).filter(([,a])=>a.fallback.format==="png"),i=new Set,o=8;for(let a=0;a<t.length;a+=8)await Promise.all(t.slice(a,a+8).map(async([c,l])=>{let m=l.variants.filter((u)=>u.format==="png").sort((u,y)=>u.width-y.width)[0];try{let u=await on(new Uint8Array(await Q.promises.readFile(m?.path??l.fallback.path)));if(yn(u.data))i.add(c)}catch{i.add(c)}}));return i}function xn(e,t){let i=[];for(let o of t){let a=e[o],c=a?.variants.filter((m)=>m.format==="webp")??[];if(!a||c.length===0)continue;if(!c.some((m)=>{let u;try{return u=Q.openSync(m.path,"r"),!je(Ce(u,0,32))}catch{return!0}finally{if(u!==void 0)Q.closeSync(u)}}))continue;if(a.variants=a.variants.filter((m)=>m.format!=="webp"),delete a.sources.webp,i.push(o),!wt.has(o))wt.add(o),console.warn(`[stx-images] ${o} is transparent but its WebP variants have no alpha channel; serving PNG instead. Upgrade @stacksjs/ts-webp to 0.1.6 or later.`)}return i}async function vn(e){let t=[],i=8;for(let o=0;o<e.length;o+=8){let a=e.slice(o,o+8),c=await Promise.all(a.map(async(l)=>{try{return await an(l.absolutePath),l}catch{return console.warn(`[stx-images] Skipping unreadable raster: ${l.relativePath}`),null}}));t.push(...c.filter((l)=>l!==null))}return t}function Ue(e){return K.join(e,"undecodable.json")}function $n(e){try{let t=Q.readFileSync(Ue(e),"utf-8"),i=JSON.parse(t);return i&&typeof i==="object"?i:{}}catch{return{}}}function Sn(e,t){try{Q.mkdirSync(K.dirname(Ue(e)),{recursive:!0}),Q.writeFileSync(Ue(e),JSON.stringify(t))}catch{}}function Ct(e){try{let t=Q.statSync(e);return{mtimeMs:t.mtimeMs,size:t.size}}catch{return}}function kt(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 Mo(e){let t=kt(e);return t?be().catalog.get(t):void 0}function Do(e){let t=kt(e);return t?be().transparent.has(t):!1}function Lo(e){let t=(o)=>e.variants.filter((a)=>a.format===o).reduce((a,c)=>a+c.bytes,0),i=t(e.fallback.format);return["avif","webp"].map((o)=>({format:o,srcset:e.sources[o]||"",bytes:t(o)})).filter((o)=>o.srcset&&o.bytes>0&&o.bytes<i).sort((o,a)=>o.bytes-a.bytes).map(({format:o,srcset:a})=>({format:o,srcset:a}))}function $h(e){let t=Mo(e);if(!t)return;return{src:t.fallback.url,srcset:t.sources[t.fallback.format]||"",sources:Lo(t).map(({format:i,srcset:o})=>({type:`image/${i}`,srcset:o})),width:t.source.width,height:t.source.height,placeholder:Do(e)?void 0:t.placeholder?.dataUrl}}function cs(){let e=be();e.catalog=new Map,e.transparent=new Set}function Cn(e){let t=be();t.catalog=new Map(e.entries),t.transparent=new Set(e.transparent)}async function Rh(e,t,i={}){if(!e||!Q.existsSync(e))return cs(),{count:0,fingerprint:""};if(i.offThread){let h=await ze("delivery",{publicDir:e,outputDir:t});if(h!==ke)return Cn(h.state),h.result}let o=await At(e);if(o.length===0)return cs(),{count:0,fingerprint:""};let a=$n(t),c=o.filter((h)=>{let w=a[h.relativePath];if(!w)return!0;let S=Ct(h.absolutePath);return!S||S.mtimeMs!==w.mtimeMs||S.size!==w.size});if(c.length===0)return cs(),{count:0,fingerprint:""};let l=$t(K.join(t,"_stx","images"),`${un}:${xt()}`),m={outDir:K.join(t,"_stx","images"),storage:$t(K.join(t,"_stx","images"),`${fn}:${xt()}`),baseUrl:ye,widths:ln,formats:["avif","webp"],quality:{avif:70,webp:78,jpeg:82,png:100},includeOriginal:!1,placeholder:!0,batchConcurrency:4,concurrency:4},u=c,y;try{y=await bt({...m,entries:St(c,l)})}catch(h){if(u=await vn(c),u.length===c.length)throw h;let w=new Set(u.map((A)=>A.relativePath)),S=!1;for(let A of c){if(w.has(A.relativePath))continue;let P=Ct(A.absolutePath);if(!P)continue;a[A.relativePath]=P,S=!0}if(S)Sn(t,a);if(u.length===0)return cs(),{count:0,fingerprint:""};y=await bt({...m,entries:St(u,l)})}let v=await bn(y.entries),b=xn(y.entries,v),C=be();C.catalog=new Map(Object.entries(y.entries)),C.transparent=v;let x=v.size===0&&b.length===0?y.fingerprint:Rt("sha256").update(y.fingerprint).update(JSON.stringify({transparent:[...v].sort(),droppedWebp:b.sort()})).digest("hex");return{count:u.length,fingerprint:x}}class Pt{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,i,o){let a=ri(e,o);if(a!==void 0)return a;for(let c of si(e,t,i,o))if(await r(c))return c;return null}}var ue=new Pt;var re="\x00stx-boolean-attribute";function We(e){return e.indexOf("\x00")===-1?e:e.replace(/\0/g,"")}var Rn=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 He(e){let t=e.toLowerCase();return t.startsWith("aria-")||t.startsWith("data-")||Rn.has(t)}function oe(e,t){let i=[];for(let[o,a]of Object.entries(e.static)){if(t.has(o))continue;let c=e.staticNames?.[o]??o;if(typeof a==="boolean"){if(a)i.push(p(c));continue}if(a===re){i.push(p(c));continue}i.push(`${p(c)}="${wn(c,We(String(a)))}"`)}return i}function ae(e,t){let i=[];for(let[o,a]of Object.entries(e.serverDynamic??{})){if(t.has(o))continue;if(a===null||a===void 0||a===!1)continue;let c=e.serverDynamicNames?.[o]??o;if(a===!0){i.push(p(c));continue}if(typeof a==="object")continue;i.push(`${p(c)}="${wn(c,We(String(a)))}"`)}return i}function An(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 qe={name:"StxLink",aliases:["stx-link"],render(e,t,i){let o=An(e),a=(typeof e.static.class==="string"?e.static.class:"")||(typeof e.static.className==="string"?e.static.className:""),c=typeof e.static.activeClass==="string"?e.static.activeClass:"active",l=typeof e.static.exactActiveClass==="string"?e.static.exactActiveClass:"exact-active",m=e.static.prefetch===!0||e.static.prefetch==="true"||e.serverDynamic.prefetch===!0,u=[];if(o.reactive)u.push(`:href="${n(o.value)}"`);else u.push(`href="${n(wr(o.value,"navigable"))}"`);if(a)u.push(`class="${n(a)}"`);if(u.push("data-stx-link"),u.push(`data-stx-active-class="${n(c)}"`),u.push(`data-stx-exact-active-class="${n(l)}"`),m)u.push("data-stx-prefetch");let y=typeof e.static.activeMatch==="string"?e.static.activeMatch.trim():"";if(y)u.push(`data-stx-active-match="${n(y)}"`);let v=new Set(["to","class","className","activeClass","exactActiveClass","activeMatch","prefetch"]);return u.push(...oe(e,v)),u.push(...ae(e,v)),`<a ${u.join(" ")}>${t}</a>`}};var kn=new Map;function Xe(e){if(!e)return;let t=e.split("?")[0].split("#")[0];return kn.get(t)}var Pn={sm:640,md:768,lg:1024,xl:1280,"2xl":1536},Ze=[320,640,768,1024,1280,1536,1920];function Z(e,t){if(e.serverDynamic[t]!==void 0)return String(e.serverDynamic[t]);let i=e.static[t];if(typeof i==="string")return i;return}function Ie(e,t,i=!1){let o=e.serverDynamic[t];if(o!==void 0)return o!==!1&&o!=="false";let a=e.static[t];if(a!==void 0)return a!=="false"&&a!==!1;return i}function Ve(e){if(e.includes("(")||e.includes(","))return e;let t=e.trim().split(/\s+/),i=[];for(let o of t)if(o.includes(":")){let[a,c]=o.split(":"),l=Pn[a];if(l)i.push(`(max-width: ${l}px) ${c}`);else{let m=Number.parseInt(a);if(!Number.isNaN(m))i.push(`(max-width: ${m}px) ${c}`)}}else i.push(o);return i.join(", ")}function Ge(e,t,i,o){return t.map((a)=>`${xe(e,a,void 0,i,o)} ${a}w`).join(", ")}function In(e,t,i,o,a){return t.map((c)=>{let l=i?i*c:void 0;return`${xe(e,l,void 0,o,a)} ${c}x`}).join(", ")}function xe(e,t,i,o,a){if(!o||o==="local"||o==="static")return e;if(o==="cloudinary"){let c=[];if(t)c.push(`w_${t}`);if(i)c.push(`h_${i}`);if(a)c.push(`f_${a}`);c.push("q_auto");let l=c.join(",");return e.replace("/upload/",`/upload/${l}/`)}if(o==="imgix"){let c=new URLSearchParams;if(t)c.set("w",String(t));if(i)c.set("h",String(i));if(a)c.set("fm",a);c.set("auto","format");let l=e.includes("?")?"&":"?";return`${e}${l}${c.toString()}`}if(o==="bunny"){let c=new URLSearchParams;if(t)c.set("width",String(t));if(i)c.set("height",String(i));if(a)c.set("format",a);let l=e.includes("?")?"&":"?";return`${e}${l}${c.toString()}`}return e}function _n(e){return`var s=this.style;${e.map((t)=>`s.${t}=''`).join(";")}`}function En(e,t,i="#e5e7eb"){let o=`<svg xmlns="http://www.w3.org/2000/svg" width="${e}" height="${t}"><rect width="100%" height="100%" fill="${i}"/></svg>`;return`data:image/svg+xml;base64,${btoa(o)}`}var Ke={name:"StxImage",aliases:["Image","stx-image","stx-img"],render(e,t,i){let o=Z(e,"src")||"",a=Mo(o),c=Z(e,"alt")||"",l=Z(e,"width")||(a?String(a.source.width):void 0),m=Z(e,"height")||(a?String(a.source.height):void 0),u=Z(e,"sizes"),y=Z(e,"srcset"),v=Z(e,"densities"),b=Z(e,"format"),C=Do(o)||Xe(o)?.transparent===!0,x=Z(e,"placeholder")||(a&&!C?"thumbhash":void 0),h=Z(e,"placeholderColor")||"#e5e7eb",w=Z(e,"provider"),S=Z(e,"class")||Z(e,"className")||"",A=Z(e,"style")||"",P=Z(e,"objectFit")||Z(e,"fit"),k=Z(e,"objectPosition")||Z(e,"position"),O=Z(e,"quality"),W=Ie(e,"lazy",!0),z=Ie(e,"preload",!1),U=Ie(e,"priority",!1),q=Z(e,"loading"),B=Z(e,"decoding")||"async",N=!!a||Ie(e,"picture",!1)||!!b,T=l?Number.parseInt(l):void 0,j=m?Number.parseInt(m):void 0,F=y||"",X="";if(a)F=a.sources[a.fallback.format]||"",X=u?Ve(u):"100vw";else if(!F&&u&&w&&w!=="local"&&w!=="static")F=Ge(o,Ze,w,b),X=Ve(u);else if(!F&&v){let _=v.split(/\s+/).map((E)=>Number.parseFloat(E.replace("x","")));F=In(o,_,T,w,b)}else if(u)X=Ve(u);let L=[];if(A)L.push(A);if(P)L.push(`object-fit:${P}`);if(k)L.push(`object-position:${k}`);if(T&&j)L.push(`aspect-ratio:${T}/${j}`);let D=[],ce=x==="blur"||x==="color"||x==="thumbhash";if(ce&&!C){let _=a?.placeholder?{dataUrl:a.placeholder.dataUrl,color:h}:Xe(o);if(_&&x==="color")L.push(`background-color:${_.color}`),D.push("backgroundColor");else if(_)L.push(`background-color:${_.color}`),L.push(`background-image:url(${_.dataUrl})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),D.push("backgroundColor","backgroundImage");else{let E=En(T||16,j||9,h);L.push(`background-image:url(${E})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),D.push("backgroundImage")}}else if(!ce&&x&&x!=="empty"&&x!=="none")L.push(`background-image:url(${n(x)})`),L.push("background-size:cover"),L.push("background-repeat:no-repeat"),D.push("backgroundImage");let $e=a?.fallback.url||xe(o,T,j,w,b),Y=[];if(Y.push(`src="${n(wr($e,"fetched"))}"`),Y.push(`alt="${n(c)}"`),l)Y.push(`width="${n(l)}"`);if(m)Y.push(`height="${n(m)}"`);let le=q||(U||z?"eager":W?"lazy":"");if(le)Y.push(`loading="${n(le)}"`);if(U)Y.push('fetchpriority="high"');if(Y.push(`decoding="${n(B)}"`),S)Y.push(`class="${n(S)}"`);if(L.length>0)Y.push(`style="${n(L.join(";"))}"`);if(F)Y.push(`srcset="${n(wr(F,"fetched"))}"`);if(X)Y.push(`sizes="${n(X)}"`);let te=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(D.length>0){let _=typeof e.static.onload==="string"?e.static.onload:"",E=_n(D)+(_?`;${_}`:"");Y.push(`onload="${n(E)}"`),te.add("onload")}Y.push(...oe(e,te)),Y.push(...ae(e,te));let Te=`<img ${Y.join(" ")} />`,M="";if(z){let E=b==="webp"?"image/webp":b==="avif"?"image/avif":"";M=`<link rel="preload" as="image" href="${n($e)}"${E?` type="${E}"`:""}${F?` imagesrcset="${n(F)}"`:""}${X?` imagesizes="${n(X)}"`:""} />
|
|
3
3
|
`}if(N){let _=[];if(a)for(let E of Lo(a))_.push(`<source type="image/${E.format}" srcset="${n(E.srcset)}"${X?` sizes="${n(X)}"`:""} />`);if(!a&&(b==="avif"||b==="auto")){let E=xe(o,T,j,w,"avif"),ee=F?Ge(o,Ze,w,"avif"):`${E}`;_.push(`<source type="image/avif" srcset="${n(ee)}"${X?` sizes="${n(X)}"`:""} />`)}if(!a&&(b==="webp"||b==="auto")){let E=xe(o,T,j,w,"webp"),ee=F?Ge(o,Ze,w,"webp"):`${E}`;_.push(`<source type="image/webp" srcset="${n(ee)}"${X?` sizes="${n(X)}"`:""} />`)}return`${M}<picture>
|
|
4
4
|
${_.join(`
|
|
5
5
|
`)}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{hn,Jf,Yf,Zf,Qf,eg,m,tg,pi,ng,Vc,Uc}from"./chunk-
|
|
2
|
+
import{hn,Jf,Yf,Zf,Qf,eg,m,tg,pi,ng,Vc,Uc}from"./chunk-9k50gdfa.js";import"./chunk-t5fgdj4e.js";import"./chunk-27rzdq3n.js";import"./chunk-94gyfwpz.js";import"./chunk-2yxva96k.js";import"./chunk-gb65t4n1.js";export{hn as STX_ENGINE_BINDING_NAMES,pi as convertToCommonJS,Vc as extractScriptFromTemplate,m as extractVariables,Uc as hasVariables,tg as isCompleteImport,eg as isMissingBindingFailure,Zf as isModuleResolutionFailure,Qf as isSyntaxFailure,ng as splitDeclaration,Jf as stripTypeScript,Yf as withoutStxReferrer};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
// @bun
|
|
2
2
|
import{ue}from"./chunk-q14d714d.js";import{ze,O}from"./chunk-27rzdq3n.js";import{bc}from"./chunk-605b93pe.js";import{l}from"./chunk-jdj1358b.js";import v from"fs";import m from"path";import{pathToFileURL as I}from"url";var P=["GET","POST","PUT","PATCH","DELETE","HEAD","OPTIONS"],R=new Set;function on(s,c={}){let o=m.resolve(s,c.dir??"server/api"),i=[],f=new Map;if(!v.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(!P.includes(g)||d!==d.toLowerCase())throw Error(`Unsupported API method suffix in ${e}; use ${P.map((A)=>A.toLowerCase()).join(", ")}`);if(u>=0)n=n.slice(0,u);if(n!=="index")p.push(n);let r=new Set,h=p.map((A,j)=>{let y=/^\[(\.\.\.)?([A-Za-z_]\w*)\]$/.exec(A);if(y){if(r.has(y[2])||y[1]&&j!==p.length-1)throw Error(`Invalid API parameter in ${e}`);return r.add(y[2]),`:${y[2]}${y[1]?"*":""}`}if(!/^[\w-]+$/.test(A))throw Error(`Unsupported API path segment ${A} in ${e}`);return A}),w=`/api${h.length?`/${h.join("/")}`:""}`,S=`${g} ${w.replace(/:\w+/g,":param")}`;if(f.has(S))throw Error(`Ambiguous API route ${g} ${w}: ${f.get(S)} and ${e}`);f.set(S,e);let x=m.join(o,e);R.add(m.resolve(x)),R.add(v.realpathSync(x)),i.push({pattern:w,method:g,filePath:x})}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 $o(s,c){let o=l(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 c){let e=`./${m.relative(m.dirname(o),t.filePath).replace(/\\/g,"/")}`,{params:a}=ue(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 Ro(s,c,o={}){let i=on(s,o);await $o(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(c,n),a),f.push({...t,filePath:n})}return f}function E(s,c){let o=s.map((i)=>({route:i,...ue(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 c(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 Ao(s,c){return E(c,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function xh(s,c){if(!c)return async()=>null;let o=c===!0?{}:c,i=on(s,o);return await $o(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=on(s,o);await $o(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(c,n),a),f.push({...t,filePath:n})}return f}function E(s,c){let o=s.map((i)=>({route:i,...ue(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 c(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 Ao(s,c){return E(c,async(o)=>(await import(I(m.resolve(s,o.filePath)).href)).default)}async function xh(s,c){if(!c)return async()=>null;let o=c===!0?{}:c,i=on(s,o);return await $o(s,i),async(f)=>{if(!new URL(f.url).pathname.match(/^\/api(?:\/|$)/))return null;try{let t=on(s,o);await $o(s,t);let{loadStxConfig:e}=await import("./chunk-bvynz9z8.js"),a=O((await e(s)).runtimeConfig);return await ze(a,()=>E(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 Po(s,c,o){if(bc(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(v.realpathSync(s))))return!0}catch{}if(R.has(m.resolve(s)))return!0;if(!o)return!1;let f=m.resolve(c,typeof o==="object"?o.dir??"server/api":"server/api"),t=(a)=>{try{return v.realpathSync(a)}catch{return m.resolve(a)}},e=t(s);return[f,m.resolve(c,"server"),m.resolve(c,".output/server")].some((a)=>{let p=t(a);return e===p||e.startsWith(`${p}${m.sep}`)})}
|
|
6
6
|
export{on,$o,Ro,Ao,xh,Po};
|