// @bun
var{defineProperty:$,getOwnPropertyNames:P,getOwnPropertyDescriptor:M}=Object,N=Object.prototype.hasOwnProperty;function D(q){return this[q]}var d=(q)=>{var z=(j??=new WeakMap).get(q),A;if(z)return z;if(z=$({},"__esModule",{value:!0}),q&&typeof q==="object"||typeof q==="function"){for(var I of P(q))if(!N.call(z,I))$(z,I,{get:D.bind(q,I),enumerable:!(A=M(q,I))||A.enumerable})}return j.set(q,z),z},j;var H=(q)=>q;function V(q,z){this[q]=H.bind(null,z)}var l=(q,z)=>{for(var A in z)$(q,A,{get:z[A],enumerable:!0,configurable:!0,set:V.bind(z,A)})};var i=(q,z)=>()=>(q&&(z=q(q=0)),z);var c=import.meta.require;var W=new Map,X=new Map;function b(q){W.set(q.name,{component:q,type:"server"})}function T(q){W.set(q.name,{component:q,type:"client"})}function s(q){return W.get(q)}function p(q){return W.has(q)}function r(){return Array.from(W.keys())}function a(){W.clear(),X.clear()}function K(q,z){let A=JSON.stringify(z);return`${q}:${k(A)}`}function k(q){let z=0;for(let A=0;A<q.length;A++){let I=q.charCodeAt(A);z=(z<<5)-z+I,z=z|0}return Math.abs(z).toString(36)}function R(q,z,A){if(!A?.enabled)return null;let F=(A.keyGenerator||((Q)=>K(q,Q)))(z),J=X.get(F);if(!J)return null;let O=Date.now(),L=A.ttl||60000;if(O-J.timestamp>L){if(A.staleWhileRevalidate)return{html:J.html,data:J.data};return X.delete(F),null}return{html:J.html,data:J.data}}function f(q,z,A,I,F){if(!F?.enabled)return;let O=(F.keyGenerator||((L)=>K(q,L)))(z);X.set(O,{html:A,timestamp:Date.now(),data:I})}function o(q){if(q){for(let z of X.keys())if(z.startsWith(`${q}:`))X.delete(z)}else X.clear()}async function S(q,z={}){let A=performance.now(),{props:I={},signal:F}=z,J=W.get(q);if(!J)throw Error(`Server component "${q}" not found`);if(J.type!=="server")throw Error(`Component "${q}" is not a server component`);let O=J.component,L=R(q,I,O.cache);if(L)return{html:L.html,renderTime:performance.now()-A,data:L.data,dependencies:O.dependencies||[],cached:!0};if(F?.aborted)throw Error("Render aborted");try{let Q={...I};if(O.loader)Q={...Q,...await O.loader(I)};let U=await w(O.template,Q);return f(q,I,U,Q,O.cache),{html:U,renderTime:performance.now()-A,data:Q,dependencies:O.dependencies||[],cached:!1}}catch(Q){if(O.errorBoundary)return{html:await w(O.errorBoundary,{error:Q instanceof Error?Q.message:String(Q),...I}),renderTime:performance.now()-A,dependencies:O.dependencies||[],cached:!1};throw Q}}async function C(q,z={}){let A=performance.now(),{props:I={}}=z,F=W.get(q);if(!F)throw Error(`Client component "${q}" not found`);if(F.type!=="client")throw Error(`Component "${q}" is not a client component`);let J=F.component,O=`cc-${q}-${Math.random().toString(36).slice(2,9)}`,L=await w(J.template,I),Q={};if(J.clientProps){for(let _ of J.clientProps)if(_ in I)Q[_]=I[_]}let U=`<div data-client-component="${q}" data-component-id="${O}" data-priority="${J.priority||"lazy"}">
${L}
<script type="application/json" data-component-props="${O}">${JSON.stringify(Q)}</script>
</div>`,Z=J.clientScript?`<script type="module" data-component-script="${O}">${J.clientScript}</script>`:void 0;return{html:U,renderTime:performance.now()-A,data:I,dependencies:[],cached:!1,hydrationScript:Z}}async function E(q,z={}){let A=W.get(q);if(!A)throw Error(`Component "${q}" not found`);if(A.type==="server")return S(q,z);else return C(q,z)}var Y=new Map;function n(){for(let[q,z]of Y)if(z.status==="resolved"||z.status==="error")Y.delete(q)}function x(q,z){let A={id:q,status:"pending"};return Y.set(q,A),{wrap:async(I)=>{A.promise=I;try{return A.result=await I,A.status="resolved",A.result}catch(F){throw A.error=F instanceof Error?F:Error(String(F)),A.status="error",F}},getFallback:()=>z}}function t(q){return Y.get(q)}function e(q){if(q)Y.delete(q);else Y.clear()}function qq(q,z={}){return{renderToStream:()=>{return new ReadableStream({async start(A){for(let I of q)try{let F=await E(I,z);if(A.enqueue(F.html),F.hydrationScript)A.enqueue(F.hydrationScript)}catch(F){let J=F instanceof Error?F.message:String(F);A.enqueue(`<!-- Error rendering ${I}: ${J} -->`)}A.close()}})},renderToString:async()=>{let A=[];for(let I of q)try{let F=await E(I,z);if(A.push(F.html),F.hydrationScript)A.push(F.hydrationScript)}catch(F){let J=F instanceof Error?F.message:String(F);A.push(`<!-- Error rendering ${I}: ${J} -->`)}return A.join(`
`)}}}async function w(q,z){let A=q;return A=A.replace(/@foreach\s*\((\w+(?:\.\w+)*)\s+as\s+(\w+)\)([\s\S]*?)@endforeach/g,(I,F,J,O)=>{let L=B(z,F.trim());if(!Array.isArray(L))return"";return L.map((Q,U)=>{let Z={...z,[J]:Q,loop:{index:U,first:U===0,last:U===L.length-1}};return v(O,Z)}).join("")}),A=A.replace(/@if\s*\(([^)]+)\)([\s\S]*?)@endif/g,(I,F,J)=>{return g(F.trim(),z)?J:""}),A=A.replace(/\{\{([^}]+)\}\}/g,(I,F)=>{let J=F.trim();if(J.startsWith("await ")){let Q=J.slice(6).split("(")[0].trim();return String(z[Q]??I)}let O=J.split("."),L=z;for(let Q of O){if(L===null||L===void 0)break;L=L[Q]}if(L===void 0||L===null)return"";return G(String(L))}),A}function v(q,z){let A=q;return A=A.replace(/\{\{([^}]+)\}\}/g,(I,F)=>{let J=B(z,F.trim());if(J===void 0||J===null)return"";return G(String(J))}),A}function B(q,z){let A=z.split("."),I=q;for(let F of A){if(I===null||I===void 0)return;I=I[F]}return I}function g(q,z){let A=B(z,q);return Boolean(A)}function G(q){return q.replace(/&/g,"&amp;").replace(/</g,"&lt;").replace(/>/g,"&gt;").replace(/"/g,"&quot;").replace(/'/g,"&#039;")}var y={name:"serverComponent",hasEndTag:!0,handler:(q,z,A,I)=>{if(!z||z.length===0)throw Error("@serverComponent requires a name parameter");let F=z[0].replace(/['"`]/g,""),J=`sc-${F}-${Math.random().toString(36).slice(2,9)}`;return b({name:F,template:q}),`<div data-server-component="${F}" data-component-id="${J}">${q}</div>`}},u={name:"clientComponent",hasEndTag:!0,handler:(q,z,A,I)=>{if(!z||z.length===0)throw Error("@clientComponent requires a name parameter");let F=z[0].replace(/['"`]/g,""),J=z[1]?.replace(/['"`]/g,""),O=`cc-${F}-${Math.random().toString(36).slice(2,9)}`,L=q.match(/<script\b[^>]*>([\s\S]*?)<\/script>/i),Q=L?L[1]:void 0,U=L?q.replace(L[0],""):q;return T({name:F,template:U,clientScript:Q,priority:J||"lazy"}),`<div data-client-component="${F}" data-component-id="${O}" data-priority="${J||"lazy"}">
${U}
</div>`}},h={name:"suspense",hasEndTag:!0,handler:(q,z,A,I)=>{let F=z[0]?.replace(/['"`]/g,"")||"Loading...",J=`suspense-${Math.random().toString(36).slice(2,9)}`;return x(J,F),`<div data-suspense="${J}" data-fallback="${G(F)}">
${q}
</div>`}};function zq(){return[y,u,h]}function Aq(){return`
(function() {
  'use strict';

  const stxServerComponents = {
    components: new Map(),

    registerComponent(name, hydrator) {
      this.components.set(name, hydrator);
    },

    hydrateComponent(element) {
      const name = element.dataset.clientComponent;
      const id = element.dataset.componentId;
      const hydrator = this.components.get(name);

      if (!hydrator) {
        console.warn('[stx] No hydrator for component:', name);
        return;
      }

      const propsEl = element.querySelector('[data-component-props="' + id + '"]');
      const props = propsEl ? JSON.parse(propsEl.textContent || '{}') : {};

      try {
        hydrator(element, props);
        element.dataset.hydrated = 'true';
      }
catch (error) {
        console.error('[stx] Hydration error:', name, error);
      }
    },

    hydrateAll() {
      const components = document.querySelectorAll('[data-client-component]');
      const eager = [];
      const lazy = [];
      const idle = [];

      components.forEach(el => {
        const priority = el.dataset.priority || 'lazy';
        if (priority === 'eager') eager.push(el);
        else if (priority === 'idle') idle.push(el);
        else lazy.push(el);
      });

      // Hydrate eager immediately
      eager.forEach(el => this.hydrateComponent(el));

      // Hydrate lazy on intersection
      if (lazy.length && 'IntersectionObserver' in window) {
        const observer = new IntersectionObserver(entries => {
          entries.forEach(entry => {
            if (entry.isIntersecting) {
              observer.unobserve(entry.target);
              this.hydrateComponent(entry.target);
            }
          });
        }, { rootMargin: '50px' });
        lazy.forEach(el => observer.observe(el));
      }
else {
        lazy.forEach(el => this.hydrateComponent(el));
      }

      // Hydrate idle during browser idle
      if (idle.length && 'requestIdleCallback' in window) {
        requestIdleCallback(() => {
          idle.forEach(el => this.hydrateComponent(el));
        });
      }
else {
        setTimeout(() => {
          idle.forEach(el => this.hydrateComponent(el));
        }, 100);
      }
    }
  };

  window.__stxServerComponents = stxServerComponents;

  if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', () => stxServerComponents.hydrateAll());
  }
else {
    stxServerComponents.hydrateAll();
  }
})();`}export{h as suspenseDirective,y as serverComponentDirective,S as renderServerComponent,E as renderComponent,C as renderClientComponent,zq as registerServerComponentDirectives,b as registerServerComponent,T as registerClientComponent,p as hasComponent,t as getSuspenseState,r as getComponentNames,s as getComponent,Aq as generateServerComponentsRuntime,x as createSuspenseBoundary,qq as createStreamingRenderer,u as clientComponentDirective,e as clearSuspenseState,a as clearComponents,o as clearComponentCache,n as cleanupSuspenseStates};
