rari 0.15.15 → 0.15.17

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/image.mjs CHANGED
@@ -1 +1 @@
1
- import{a as e,i as t,n,r,t as i}from"./constants-BFdy-wPN.mjs";import{useCallback as a,useEffect as o,useRef as s,useState as c}from"react";import{jsx as l,jsxs as u}from"react/jsx-runtime";function d(e,t,n,r){let i=new URLSearchParams;return i.set(`url`,e),i.set(`w`,t.toString()),i.set(`q`,n.toString()),r&&i.set(`f`,r),`/_rari/image?${i}`}function f({src:e,alt:t,width:r,height:f,quality:p=75,preload:m=!1,loading:h=`lazy`,placeholder:g=`empty`,blurDataURL:_,fill:v=!1,sizes:y,style:b,className:x,onLoad:S,onError:C,unoptimized:w=!1,loader:T,overrideSrc:E,decoding:D}){let O=typeof e==`string`?e:e.src,k=r!=null&&r!==0?r:typeof e==`string`?void 0:e.width,A=f!=null&&f!==0?f:typeof e==`string`?void 0:e.height,j=_!=null&&_!==``?_:typeof e==`string`?void 0:e.blurDataURL,M=E!=null&&E!==``?E:O,N=m,P=D??(m?`sync`:`async`),[F,I]=c(!1),[L,R]=c(!1),z=s(null),B=s(S),V=s(null);o(()=>{B.current=S},[S]);let H=a(e=>{let t=e.currentTarget;t.src&&t.complete&&(g===`blur`&&I(!0),B.current&&B.current(e))},[g]),U=a(e=>{R(!0),g===`blur`&&I(!0),C&&C(e)},[g,C]);o(()=>{if(!N)return;let e=document.createElement(`link`);return e.rel=`preload`,e.as=`image`,e.href=T?T({src:M,width:k!=null&&k!==0?k:1920,quality:p}):w?M:d(M,k!=null&&k!==0?k:1920,p),y!=null&&y!==``&&e.setAttribute(`imagesizes`,y),document.head.appendChild(e),()=>{e.parentNode===document.head&&document.head.removeChild(e)}},[N,M,k,p,y,T,w]),o(()=>{if(N||w||h===`eager`)return;let e=z.current;if(!e)return;let t=new IntersectionObserver(n=>{n.forEach(n=>{n.isIntersecting&&t.unobserve(e)})},{rootMargin:`50px`});return t.observe(e),()=>{t.disconnect()}},[N,w,h]);let W={...b,...v&&{position:`absolute`,inset:0,width:`100%`,height:`100%`,objectFit:`cover`},...g===`blur`&&j!=null&&j!==``&&!F&&{backgroundImage:`url(${j})`,backgroundSize:`cover`,backgroundPosition:`center`,filter:`blur(20px)`,transition:`filter 0.3s ease-out`},...g===`blur`&&F&&{filter:`none`,transition:`filter 0.3s ease-out`}};if(w){let e=T?T({src:M,width:k!=null&&k!==0?k:1920,quality:p}):M;return l(`img`,{ref:z,src:e,alt:L?t:``,width:v?void 0:k,height:v?void 0:A,loading:N?`eager`:h,fetchPriority:N?`high`:`auto`,decoding:P,onLoad:H,onError:U,style:W,className:x})}let G=k!=null&&k!==0?k:1920,K=k!=null&&k!==0?[k]:i,q=e=>T?K.map(e=>`${T({src:M,width:e,quality:p})} ${e}w`).join(`, `):K.map(t=>`${d(M,t,p,e)} ${t}w`).join(`, `),J=T?T({src:M,width:G,quality:p}):d(M,G,p),Y=K.length>1||K[0]!==G,X=l(`img`,{ref:z,src:J,srcSet:Y?q():void 0,sizes:Y?y:void 0,alt:L?t:``,width:v?void 0:k,height:v?void 0:A,loading:N?`eager`:h,fetchPriority:N?`high`:`auto`,decoding:P,onLoad:H,onError:U,style:W,className:x});return Y?u(`picture`,{ref:V,children:[n.includes(`avif`)&&l(`source`,{type:`image/avif`,srcSet:q(`avif`),sizes:y}),n.includes(`webp`)&&l(`source`,{type:`image/webp`,srcSet:q(`webp`),sizes:y}),X]}):X}const p=typeof window>`u`,m=f;p&&(m.$$typeof=Symbol.for(`react.client.reference`),m.$$id=`rari/image#Image`);export{i as DEFAULT_DEVICE_SIZES,n as DEFAULT_FORMATS,r as DEFAULT_IMAGE_SIZES,t as DEFAULT_MINIMUM_CACHE_TTL,e as DEFAULT_QUALITY_LEVELS,m as Image};
1
+ import{a as e,i as t,n,r,t as i}from"./constants-BFdy-wPN.mjs";import{c as a}from"react/compiler-runtime";import{useEffect as o,useRef as s,useState as c}from"react";import{jsx as l,jsxs as ee}from"react/jsx-runtime";function u(e,t,n,r){let i=new URLSearchParams;return i.set(`url`,e),i.set(`w`,t.toString()),i.set(`q`,n.toString()),r&&i.set(`f`,r),`/_rari/image?${i}`}function d(e){let t=a(77),{src:r,alt:d,width:f,height:p,quality:te,preload:ne,loading:re,placeholder:ie,blurDataURL:m,fill:ae,sizes:h,style:g,className:_,onLoad:v,onError:y,unoptimized:oe,loader:b,overrideSrc:se,decoding:ce}=e,x=te===void 0?75:te,le=ne!==void 0&&ne,S=re===void 0?`lazy`:re,C=ie===void 0?`empty`:ie,w=ae!==void 0&&ae,T=oe!==void 0&&oe,ue=typeof r==`string`?r:r.src,E=f!=null&&f!==0?f:typeof r==`string`?void 0:r.width,D=p!=null&&p!==0?p:typeof r==`string`?void 0:r.height,O=m!=null&&m!==``?m:typeof r==`string`?void 0:r.blurDataURL,k=se!=null&&se!==``?se:ue,A=le,j=ce??(le?`sync`:`async`),[M,de]=c(!1),[N,fe]=c(!1),P=s(null),F=s(v),pe=s(null),I,L;t[0]===v?(I=t[1],L=t[2]):(I=()=>{F.current=v},L=[v],t[0]=v,t[1]=I,t[2]=L),o(I,L);let R;t[3]===C?R=t[4]:(R=e=>{let t=e.currentTarget;t.src&&t.complete&&(C===`blur`&&de(!0),F.current&&F.current(e))},t[3]=C,t[4]=R);let z=R,B;t[5]!==y||t[6]!==C?(B=e=>{fe(!0),C===`blur`&&de(!0),y&&y(e)},t[5]=y,t[6]=C,t[7]=B):B=t[7];let V=B,H,U;t[8]!==k||t[9]!==E||t[10]!==b||t[11]!==x||t[12]!==A||t[13]!==h||t[14]!==T?(H=()=>{if(!A)return;let e=document.createElement(`link`);return e.rel=`preload`,e.as=`image`,e.href=b?b({src:k,width:E!=null&&E!==0?E:1920,quality:x}):T?k:u(k,E!=null&&E!==0?E:1920,x),h!=null&&h!==``&&e.setAttribute(`imagesizes`,h),document.head.appendChild(e),()=>{e.parentNode===document.head&&document.head.removeChild(e)}},U=[A,k,E,x,h,b,T],t[8]=k,t[9]=E,t[10]=b,t[11]=x,t[12]=A,t[13]=h,t[14]=T,t[15]=H,t[16]=U):(H=t[15],U=t[16]),o(H,U);let W,G;t[17]!==S||t[18]!==A||t[19]!==T?(W=()=>{if(A||T||S===`eager`)return;let e=P.current;if(!e)return;let t=new IntersectionObserver(n=>{n.forEach(n=>{n.isIntersecting&&t.unobserve(e)})},{rootMargin:`50px`});return t.observe(e),()=>{t.disconnect()}},G=[A,T,S],t[17]=S,t[18]=A,t[19]=T,t[20]=W,t[21]=G):(W=t[20],G=t[21]),o(W,G);let K;t[22]===w?K=t[23]:(K=w&&{position:`absolute`,inset:0,width:`100%`,height:`100%`,objectFit:`cover`},t[22]=w,t[23]=K);let q;t[24]!==M||t[25]!==O||t[26]!==C?(q=C===`blur`&&O!=null&&O!==``&&!M&&{backgroundImage:`url(${O})`,backgroundSize:`cover`,backgroundPosition:`center`,filter:`blur(20px)`,transition:`filter 0.3s ease-out`},t[24]=M,t[25]=O,t[26]=C,t[27]=q):q=t[27];let J;t[28]!==M||t[29]!==C?(J=C===`blur`&&M&&{filter:`none`,transition:`filter 0.3s ease-out`},t[28]=M,t[29]=C,t[30]=J):J=t[30];let Y;t[31]!==g||t[32]!==K||t[33]!==q||t[34]!==J?(Y={...g,...K,...q,...J},t[31]=g,t[32]=K,t[33]=q,t[34]=J,t[35]=Y):Y=t[35];let X=Y;if(T){let e;t[36]!==k||t[37]!==E||t[38]!==b||t[39]!==x?(e=b?b({src:k,width:E!=null&&E!==0?E:1920,quality:x}):k,t[36]=k,t[37]=E,t[38]=b,t[39]=x,t[40]=e):e=t[40];let n=e,r=N?d:``,i=w?void 0:E,a=w?void 0:D,o=A?`eager`:S,s=A?`high`:`auto`,c;return t[41]!==_||t[42]!==n||t[43]!==V||t[44]!==z||t[45]!==j||t[46]!==X||t[47]!==r||t[48]!==i||t[49]!==a||t[50]!==o||t[51]!==s?(c=l(`img`,{ref:P,src:n,alt:r,width:i,height:a,loading:o,fetchPriority:s,decoding:j,onLoad:z,onError:V,style:X,className:_}),t[41]=_,t[42]=n,t[43]=V,t[44]=z,t[45]=j,t[46]=X,t[47]=r,t[48]=i,t[49]=a,t[50]=o,t[51]=s,t[52]=c):c=t[52],c}let Z=E!=null&&E!==0?E:1920,Q,$;if(t[53]!==d||t[54]!==_||t[55]!==Z||t[56]!==w||t[57]!==k||t[58]!==V||t[59]!==z||t[60]!==j||t[61]!==D||t[62]!==X||t[63]!==E||t[64]!==b||t[65]!==S||t[66]!==x||t[67]!==A||t[68]!==N||t[69]!==h){$=Symbol.for(`react.early_return_sentinel`);bb0:{let e=E!=null&&E!==0?[E]:i,r=t=>b?e.map(e=>`${b({src:k,width:e,quality:x})} ${e}w`).join(`, `):e.map(e=>`${u(k,e,x,t)} ${e}w`).join(`, `),a;t[72]!==Z||t[73]!==k||t[74]!==b||t[75]!==x?(a=b?b({src:k,width:Z,quality:x}):u(k,Z,x),t[72]=Z,t[73]=k,t[74]=b,t[75]=x,t[76]=a):a=t[76];let o=a,s=e.length>1||e[0]!==Z,c=l(`img`,{ref:P,src:o,srcSet:s?r():void 0,sizes:s?h:void 0,alt:N?d:``,width:w?void 0:E,height:w?void 0:D,loading:A?`eager`:S,fetchPriority:A?`high`:`auto`,decoding:j,onLoad:z,onError:V,style:X,className:_});if(!s){$=c;break bb0}Q=ee(`picture`,{ref:pe,children:[n.includes(`avif`)&&l(`source`,{type:`image/avif`,srcSet:r(`avif`),sizes:h}),n.includes(`webp`)&&l(`source`,{type:`image/webp`,srcSet:r(`webp`),sizes:h}),c]})}t[53]=d,t[54]=_,t[55]=Z,t[56]=w,t[57]=k,t[58]=V,t[59]=z,t[60]=j,t[61]=D,t[62]=X,t[63]=E,t[64]=b,t[65]=S,t[66]=x,t[67]=A,t[68]=N,t[69]=h,t[70]=Q,t[71]=$}else Q=t[70],$=t[71];return $===Symbol.for(`react.early_return_sentinel`)?Q:$}const f=typeof window>`u`,p=d;f&&(p.$$typeof=Symbol.for(`react.client.reference`),p.$$id=`rari/image#Image`);export{i as DEFAULT_DEVICE_SIZES,n as DEFAULT_FORMATS,r as DEFAULT_IMAGE_SIZES,t as DEFAULT_MINIMUM_CACHE_TTL,e as DEFAULT_QUALITY_LEVELS,p as Image};
package/dist/index.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as Sitemap, c as SitemapVideo, d as RouteContext, f as RouteHandler, i as RobotsRule, l as ApiResponse, n as FeedEntry, o as SitemapEntry, r as Robots, s as SitemapImage, t as Feed, u as ApiRouteHandlers } from "./types-BYob0lqv.mjs";
1
+ import { a as Sitemap, c as SitemapVideo, d as RouteContext, f as RouteHandler, i as RobotsRule, l as ApiResponse, n as FeedEntry, o as SitemapEntry, r as Robots, s as SitemapImage, t as Feed, u as ApiRouteHandlers } from "./types-0350HUwk.mjs";
2
2
  import { c as RariURL, d as RariResponse, n as ProxyConfig, r as ProxyFunction, s as RariFetchEvent } from "./types-DAdRjhuk.mjs";
3
3
  import { RariRequest } from "./proxy/RariRequest.mjs";
4
4
  import { a as ErrorProps, d as Metadata, l as LayoutProps, p as PageProps } from "./types-DCEyvFz7.mjs";
@@ -0,0 +1 @@
1
+ let e=null;function t(){return e}function n(t){if(typeof window>`u`){console.warn(`[rari] Router cannot register navigate in non-browser environment`);return}e&&typeof process<`u`&&process.env.NODE_ENV!==`production`&&console.warn(`[rari] Router: registerNavigate called multiple times, overwriting existing navigate function`,{previous:e,new:t}),e=t,window.dispatchEvent(new CustomEvent(`rari:register-navigate`,{detail:{navigate:t}}))}function r(){if(typeof window>`u`){console.warn(`[rari] Router cannot deregister navigate in non-browser environment`);return}e=null,window.dispatchEvent(new CustomEvent(`rari:deregister-navigate`))}async function i(t,n){if(typeof window>`u`){console.warn(`[rari] Router cannot navigate in non-browser environment`);return}if(!e){console.warn(`[rari] Router not initialized, falling back to window.location`),n?.replace?window.location.replace(t):window.location.href=t;return}return e(t,n)}export{n as i,t as n,i as r,r as t};
@@ -0,0 +1 @@
1
+ import{n as e}from"./navigate-DuyUa6qD.mjs";import{n as t,p as n}from"./type-guards-CTkEL8zw.mjs";import{c as r}from"react/compiler-runtime";import{createContext as i,use as a,useEffect as o,useRef as s,useState as c}from"react";import{jsx as l}from"react/jsx-runtime";function u(e){return n(e)&&typeof e.to==`string`}function d(e){return n(e)&&typeof e.navigate==`function`}const f=i(null);function p(n){let i=r(13),{children:a,initialPathname:p}=n,[y,b]=c(p),[x,S]=c(v),C=s(null),w,T;i[0]===Symbol.for(`react.memo_cache_sentinel`)?(w=()=>{let e=e=>{let n=t(e,u);n&&(b(n.to),S(new URLSearchParams(window.location.search)))};return window.addEventListener(`rari:navigate`,e),()=>{window.removeEventListener(`rari:navigate`,e)}},T=[],i[0]=w,i[1]=T):(w=i[0],T=i[1]),o(w,T);let E,D;i[2]===Symbol.for(`react.memo_cache_sentinel`)?(E=()=>{let n=e();n&&(C.current=n);let r=e=>{let n=t(e,d);n&&(C.current=n.navigate)},i=()=>{C.current=null};return window.addEventListener(`rari:register-navigate`,r),window.addEventListener(`rari:deregister-navigate`,i),()=>{window.removeEventListener(`rari:register-navigate`,r),window.removeEventListener(`rari:deregister-navigate`,i)}},D=[],i[2]=E,i[3]=D):(E=i[2],D=i[3]),o(E,D);let O;i[4]===Symbol.for(`react.memo_cache_sentinel`)?(O={},i[4]=O):O=i[4];let k,A;i[5]===Symbol.for(`react.memo_cache_sentinel`)?(k=async(e,t)=>{C.current?await C.current(e,t):(console.warn(`[rari] Router not ready, falling back to window.location`),window.location.href=e)},A=async(e,t)=>{C.current?await C.current(e,{...t,replace:!0}):(console.warn(`[rari] Router not ready, falling back to window.location`),window.location.replace(e))},i[5]=k,i[6]=A):(k=i[5],A=i[6]);let j;i[7]!==y||i[8]!==x?(j={pathname:y,params:O,searchParams:x,push:k,replace:A,back:_,forward:g,refresh:h,prefetch:m},i[7]=y,i[8]=x,i[9]=j):j=i[9];let M=j,N;return i[10]!==a||i[11]!==M?(N=l(f,{value:M,children:a}),i[10]=a,i[11]=M,i[12]=N):N=i[12],N}async function m(e){try{let t=new URL(e,window.location.origin);await fetch(t.pathname+t.search,{headers:{Accept:`text/x-component`},priority:`low`})}catch(e){console.warn(`[rari] Prefetch failed:`,e)}}function h(){window.dispatchEvent(new CustomEvent(`rari:app-router-rerender`))}function g(){window.history.forward()}function _(){window.history.back()}function v(){return typeof window<`u`?new URLSearchParams(window.location.search):new URLSearchParams}function y(){let e=a(f);if(!e)throw Error(`useRouter must be used within a RouterProvider`);return e}function b(){return y().pathname}function x(){return y().params}function S(){return y().searchParams}export{S as a,y as i,x as n,b as r,p as t};
package/dist/router.mjs CHANGED
@@ -1 +1 @@
1
- import{a as e,i as t,n,r,s as i,t as a}from"./router-D6mkoDqJ.mjs";export{a as RouterProvider,i as navigate,n as useParams,r as usePathname,t as useRouter,e as useSearchParams};
1
+ import{r as e}from"./navigate-DuyUa6qD.mjs";import{a as t,i as n,n as r,r as i,t as a}from"./router-D84JWQz7.mjs";export{a as RouterProvider,e as navigate,r as useParams,i as usePathname,n as useRouter,t as useSearchParams};
@@ -1 +1 @@
1
- "use client";import{n as e,p as t}from"../type-guards-CTkEL8zw.mjs";import{f as n}from"../regex-constants-Wm7xRA3u.mjs";import{a as r}from"../rari-global-5vGzhToD.mjs";import"./action-revalidation-kind.mjs";import{mergeFlightRefresh as i}from"./merge-flight-refresh.mjs";import{currentRouteLocation as a,flightRouteCache as o}from"./flight-route-cache.mjs";import{t as s}from"../preload-modules-QmSvKk0Q.mjs";import*as c from"react";import{useEffect as l,useRef as u,useState as d}from"react";import{Fragment as f,jsx as p,jsxs as m}from"react/jsx-runtime";import{createFromReadableStream as h}from"virtual:react-flight-client";const g=/"timestamp":(\d+)/;function _(e){return t(e)&&typeof e.then==`function`}function v(e){return e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||c.isValidElement(e)||Array.isArray(e)}function y(e){return t(e)&&typeof e.from==`string`&&typeof e.to==`string`&&typeof e.navigationId==`number`&&t(e.options)}function b(e){return t(e)&&`element`in e}function ee(e){return t(e)&&typeof e.navigationId==`number`&&typeof e.targetPath==`string`}function x({children:x,initialPayload:S,onNavigate:C}){let[w,T]=d(S),E=u(S),[te,D]=d(0),O=u({x:0,y:0}),k=u(new Map),A=u(new Set),j=u(C),M=u(0),N=u(new Map),P=u([]),F=u(null),I=u(0),[L,R]=d(null);l(()=>{j.current=C},[C]);let z=e=>{if(e==null||_(e))return;let{pathname:t,search:n}=a();o.set(t,n,e)};l(()=>{E.current=w,w?.element!=null&&z(w.element)},[w]),l(()=>{if(w?.element!=null){let e=w.element;if(t(e)&&`status`in e&&e.status===`rejected`){let t=e.reason;t!=null&&t!==``&&console.error(`[rari] AppRouter: Flight payload rejected:`,t)}}},[w]);let B=()=>{if(typeof document>`u`)return;let e=document.querySelectorAll(`form`);k.current.clear(),e.forEach((e,t)=>{let n=new FormData(e);k.current.set(`form-${t}`,n)})},V=()=>{typeof document>`u`||document.querySelectorAll(`form`).forEach((e,t)=>{let n=k.current.get(`form-${t}`);n&&n.forEach((t,n)=>{let r=e.elements.namedItem(n);r instanceof HTMLInputElement&&(r.type===`checkbox`||r.type===`radio`?r.checked=t===`on`:typeof t==`string`&&(r.value=t))})})},H=(e,t,n,r)=>{I.current+=1;let i={timestamp:Date.now(),error:e,type:t,details:n,filePath:r,consecutiveFailures:I.current};P.current.push(i),P.current.length>10&&P.current.shift(),I.current>=2&&R(i),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:hmr-failure`,{detail:i}))},U=()=>{setTimeout(()=>{window.location.reload()},1e3)},W=()=>{I.current>0&&(I.current=0)},G=e=>{if(F.current==null||F.current===``)return!1;if(e===F.current)return!0;let t=g.exec(e);if(t){let e=Number.parseInt(t[1],10);if(Date.now()-e>5e3)return!0}return!1},K=async e=>{await s(e,A.current);let t=new ReadableStream({start(t){t.enqueue(new TextEncoder().encode(e)),t.close()}}),n=await h(t);return{element:n,rawElement:n,flightProtocol:e}},q=async(e,t=!1)=>{let n=await e;if(!n.body)throw Error(`Response has no body stream`);if(t){let e=h(n.body);return{element:e,rawElement:e,flightProtocol:``}}let r=await n.clone().text();await s(r,A.current);let i=new Uint8Array(await n.arrayBuffer()),a=new ReadableStream({start(e){e.enqueue(i),e.close()}}),o=await h(a);return{element:o,rawElement:o,flightProtocol:r}},J=async(e,t)=>{let r=e!=null&&e!==``?e:window.location.pathname,i=M.current,a=`${i}:${r}${window.location.search}`,o=N.current.get(a);if(o)return o;let c=(async()=>{try{let e=(import.meta.env.RARI_SERVER_URL!=null&&import.meta.env.RARI_SERVER_URL!==``?import.meta.env.RARI_SERVER_URL:window.location.origin).replace(n,``)+r+window.location.search,a=await fetch(e,{headers:{Accept:`text/x-component`,"rari-navigation-id":String(M.current)},cache:`no-store`,signal:t});if(!a.ok){let t=Error(`Failed to fetch RSC data: ${a.status} ${a.statusText}`);throw H(t,`fetch`,`HTTP ${a.status} when fetching ${e}`,window.location.pathname),t}let o,c=``;try{if(c=await a.clone().text(),G(c)&&w)return w;await s(c,A.current);let e=new Uint8Array(await a.arrayBuffer()),t=new ReadableStream({start(t){t.enqueue(e),t.close()}}),n=await h(t);o={element:n,rawElement:n,flightProtocol:c}}catch(e){let t=e instanceof Error?e:Error(String(e));throw H(t,`parse`,`Failed to parse RSC Flight protocol: ${t.message}`,window.location.pathname),t}return M.current===i&&(T(o),F.current=c,W()),o}catch(e){throw e instanceof Error&&!e.message.includes(`Failed to fetch RSC data`)&&!e.message.includes(`Failed to parse`)&&H(e,`network`,`Network error: ${e.message}`,window.location.pathname),e}finally{N.current.delete(a)}})();return N.current.set(a,c),c},Y=u(K),X=u(q),Z=u(J);l(()=>{Y.current=K,X.current=q,Z.current=J}),l(()=>{if(typeof window>`u`)return;let t=async t=>{let n=e(t,y);if(!n||n.navigationId!==M.current)return;O.current={x:window.scrollX,y:window.scrollY},B();let r,i=null,a=!1;try{if(n.rscResponsePromise){let e=await n.rscResponsePromise;if(M.current!==n.navigationId||(a=e.headers.get(`x-render-mode`)===`streaming`,r=await X.current(Promise.resolve(e),a),M.current!==n.navigationId))return}else if(n.rscResponse){if(a=n.rscResponse.headers.get(`x-render-mode`)===`streaming`,r=await X.current(Promise.resolve(n.rscResponse),a),M.current!==n.navigationId)return}else n.rscFlightProtocol!=null&&n.rscFlightProtocol!==``?r=await Y.current(n.rscFlightProtocol):n.isStreaming||(r=await Z.current(n.to,n.abortSignal))}catch(e){if(e instanceof Error&&e.name===`AbortError`)return;i=e instanceof Error?e:Error(String(e))}if(i){console.error(`[rari] AppRouter: Navigation failed:`,i),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:n.from,to:n.to,error:i,navigationId:n.navigationId}})),I.current>=3&&U();return}if(!r&&n.isStreaming&&M.current===n.navigationId)return;r&&M.current===n.navigationId&&(a||n.options.historyKey!=null&&n.options.historyKey!==``?(T(r),D(e=>e+1),R(null)):c.startTransition(()=>{T(r),D(e=>e+1),R(null)}),n.rscFlightProtocol!=null&&n.rscFlightProtocol!==``&&(F.current=n.rscFlightProtocol),W(),j.current&&j.current(n));let o=typeof window<`u`&&window.location.hash.length>0;(n.options.historyKey==null||n.options.historyKey===``)&&!o&&requestAnimationFrame(()=>{n.options.scroll!==!1&&window.scrollTo(0,0)})},n=async()=>{O.current={x:window.scrollX,y:window.scrollY},B();try{await Z.current(),D(e=>e+1),R(null)}catch(e){console.error(`HMR refetch error:`,e instanceof Error?e.message:String(e)),I.current>=3&&U()}finally{requestAnimationFrame(()=>{window.scrollTo(O.current.x,O.current.y),V()})}},s=t=>{let n=e(t,b);if(!(n?.element==null||!v(n.element)&&!_(n.element))){O.current={x:window.scrollX,y:window.scrollY},B();try{let{pathname:e,search:t}=a();n.revalidationKind===1?o.clear():n.revalidatedPath!=null&&n.revalidatedPath!==``?o.invalidate(n.revalidatedPath,t):o.invalidate(e,t);let r=E.current?.element,s=o.getElement(e,t)??(r!=null&&_(r)?null:r??null),l=n.element,u=_(l)?l:i(s,l);c.startTransition(()=>{T({element:u,rawElement:u}),R(null)}),z(u),W()}catch(e){let t=e instanceof Error?e:Error(String(e));H(t,`parse`,`Action flight refresh failed: ${t.message}`,window.location.pathname),I.current>=3&&U()}finally{requestAnimationFrame(()=>{window.scrollTo(O.current.x,O.current.y),V()})}}},l=async()=>{try{await Z.current(),D(e=>e+1),R(null)}catch(e){console.error(`RSC invalidate error:`,e instanceof Error?e.message:String(e)),I.current>=3&&U()}},u=t=>{let n=e(t,ee);if(n&&(A.current.clear(),M.current=n.navigationId,typeof window<`u`)){let e=r();e&&(e.navigationId=n.navigationId)}},d=async()=>{try{await Z.current(),R(null)}catch(e){console.error(`Manifest update error:`,e instanceof Error?e.message:String(e)),I.current>=3&&U()}},f=e=>{t(e)},p=()=>{n()},m=()=>{l()},h=()=>{d()};return window.addEventListener(`rari:navigation-start`,u),window.addEventListener(`rari:navigate`,f),window.addEventListener(`rari:app-router-rerender`,p),window.addEventListener(`rari:action-flight-refresh`,s),window.addEventListener(`rari:rsc-invalidate`,m),window.addEventListener(`rari:app-router-manifest-updated`,h),()=>{window.removeEventListener(`rari:navigation-start`,u),window.removeEventListener(`rari:navigate`,f),window.removeEventListener(`rari:app-router-rerender`,p),window.removeEventListener(`rari:action-flight-refresh`,s),window.removeEventListener(`rari:rsc-invalidate`,m),window.removeEventListener(`rari:app-router-manifest-updated`,h)}},[]),l(()=>{if(!(typeof window>`u`)&&window.location.hash&&w){let e=window.location.hash.slice(1);requestAnimationFrame(()=>{requestAnimationFrame(()=>{let t=document.getElementById(e);t&&t.scrollIntoView({behavior:`instant`,block:`start`})})})}},[w]);let Q=()=>{window.location.reload()},ne=()=>{R(null)},$=x;if(w?.element!=null&&($=w.element),Array.isArray($)){let e=$;e.length===1&&c.isValidElement(e[0])?$=e[0]:e.length>0&&e.every(e=>c.isValidElement(e)||e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`)&&($=p(f,{children:e}))}return m(f,{children:[L&&m(`div`,{style:{position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,padding:`24px`,background:`rgba(220, 38, 38, 0.95)`,color:`white`,borderRadius:`8px`,fontSize:`14px`,zIndex:1e4,maxWidth:`500px`,boxShadow:`0 4px 6px rgba(0, 0, 0, 0.3)`},children:[p(`div`,{style:{marginBottom:`16px`,fontWeight:`bold`,fontSize:`16px`},children:`⚠️ HMR Update Failed`}),m(`div`,{style:{marginBottom:`12px`,opacity:.9},children:[L.type===`fetch`&&`Failed to fetch updated content from server.`,L.type===`parse`&&`Failed to parse server response.`,L.type===`stale`&&`Server returned stale content.`,L.type===`network`&&`Network error occurred.`]}),p(`div`,{style:{marginBottom:`16px`,fontSize:`12px`,opacity:.8,fontFamily:`monospace`},children:L.details}),m(`div`,{style:{marginBottom:`12px`,fontSize:`12px`,opacity:.7},children:[`Consecutive failures: `,L.consecutiveFailures,` / `,3]}),m(`div`,{style:{display:`flex`,gap:`8px`},children:[p(`button`,{onClick:Q,type:`button`,style:{padding:`8px 16px`,background:`white`,color:`#dc2626`,border:`none`,borderRadius:`4px`,cursor:`pointer`,fontWeight:`bold`,fontSize:`14px`},children:`Refresh Page`}),p(`button`,{onClick:ne,type:`button`,style:{padding:`8px 16px`,background:`rgba(255, 255, 255, 0.2)`,color:`white`,border:`1px solid rgba(255, 255, 255, 0.3)`,borderRadius:`4px`,cursor:`pointer`,fontSize:`14px`},children:`Dismiss`})]}),p(`div`,{style:{marginTop:`12px`,fontSize:`11px`,opacity:.6},children:`Check the console for detailed error logs.`})]}),$]})}export{x as AppRouterProvider};
1
+ "use client";import{n as e,p as t}from"../type-guards-CTkEL8zw.mjs";import{f as n}from"../regex-constants-Wm7xRA3u.mjs";import{a as r}from"../rari-global-5vGzhToD.mjs";import"./action-revalidation-kind.mjs";import{mergeFlightRefresh as i}from"./merge-flight-refresh.mjs";import{currentRouteLocation as a,flightRouteCache as o}from"./flight-route-cache.mjs";import{t as s}from"../preload-modules-QmSvKk0Q.mjs";import{c}from"react/compiler-runtime";import*as l from"react";import{useEffect as u,useLayoutEffect as d,useRef as f,useState as p}from"react";import{Fragment as m,jsx as h,jsxs as g}from"react/jsx-runtime";import{createFromReadableStream as _}from"virtual:react-flight-client";const ee={position:`fixed`,top:`50%`,left:`50%`,transform:`translate(-50%, -50%)`,padding:`24px`,background:`rgba(220, 38, 38, 0.95)`,color:`white`,borderRadius:`8px`,fontSize:`14px`,zIndex:1e4,maxWidth:`500px`,boxShadow:`0 4px 6px rgba(0, 0, 0, 0.3)`},v={padding:`8px 16px`,background:`white`,color:`#dc2626`,border:`none`,borderRadius:`4px`,cursor:`pointer`,fontWeight:`bold`,fontSize:`14px`},te={padding:`8px 16px`,background:`rgba(255, 255, 255, 0.2)`,color:`white`,border:`1px solid rgba(255, 255, 255, 0.3)`,borderRadius:`4px`,cursor:`pointer`,fontSize:`14px`},y={fetch:`Failed to fetch updated content from server.`,parse:`Failed to parse server response.`,stale:`Server returned stale content.`,network:`Network error occurred.`};function b(e){return y[e]}function x(e){let t=c(27),{failure:n,maxRetries:r,onRefresh:i,onDismiss:a}=e,o,s;t[0]===Symbol.for(`react.memo_cache_sentinel`)?(o=h(`div`,{style:{marginBottom:`16px`,fontWeight:`bold`,fontSize:`16px`},children:`⚠️ HMR Update Failed`}),s={marginBottom:`12px`,opacity:.9},t[0]=o,t[1]=s):(o=t[0],s=t[1]);let l;t[2]===n.type?l=t[3]:(l=b(n.type),t[2]=n.type,t[3]=l);let u;t[4]===l?u=t[5]:(u=h(`div`,{style:s,children:l}),t[4]=l,t[5]=u);let d;t[6]===Symbol.for(`react.memo_cache_sentinel`)?(d={marginBottom:`16px`,fontSize:`12px`,opacity:.8,fontFamily:`monospace`},t[6]=d):d=t[6];let f;t[7]===n.details?f=t[8]:(f=h(`div`,{style:d,children:n.details}),t[7]=n.details,t[8]=f);let p;t[9]===Symbol.for(`react.memo_cache_sentinel`)?(p={marginBottom:`12px`,fontSize:`12px`,opacity:.7},t[9]=p):p=t[9];let m;t[10]!==n.consecutiveFailures||t[11]!==r?(m=g(`div`,{style:p,children:[`Consecutive failures: `,n.consecutiveFailures,` / `,r]}),t[10]=n.consecutiveFailures,t[11]=r,t[12]=m):m=t[12];let _;t[13]===Symbol.for(`react.memo_cache_sentinel`)?(_={display:`flex`,gap:`8px`},t[13]=_):_=t[13];let y;t[14]===i?y=t[15]:(y=h(`button`,{onClick:i,type:`button`,style:v,children:`Refresh Page`}),t[14]=i,t[15]=y);let x;t[16]===a?x=t[17]:(x=h(`button`,{onClick:a,type:`button`,style:te,children:`Dismiss`}),t[16]=a,t[17]=x);let S;t[18]!==y||t[19]!==x?(S=g(`div`,{style:_,children:[y,x]}),t[18]=y,t[19]=x,t[20]=S):S=t[20];let C;t[21]===Symbol.for(`react.memo_cache_sentinel`)?(C=h(`div`,{style:{marginTop:`12px`,fontSize:`11px`,opacity:.6},children:`Check the console for detailed error logs.`}),t[21]=C):C=t[21];let w;return t[22]!==S||t[23]!==u||t[24]!==f||t[25]!==m?(w=g(`div`,{style:ee,children:[o,u,f,m,S,C]}),t[22]=S,t[23]=u,t[24]=f,t[25]=m,t[26]=w):w=t[26],w}function S(e){let{parsedPayload:t,shouldScrollToTop:n,navigationId:r,useTransition:i,currentNavigationIdRef:a,pendingScrollPayloadRef:o,setRenderKey:s,setRscPayload:c,clearHmrError:u}=e,d=()=>{s(e=>{let r=e+1;return o.current=n?{payload:t,commitKey:r}:null,r}),c(t),u()};i?l.startTransition(()=>{a.current===r&&d()}):d()}function C(e){return l.isValidElement(e)||e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`}function w(e){if(!Array.isArray(e))return e;let t=e;return t.length===1&&l.isValidElement(t[0])?t[0]:t.length>0&&t.every(C)?l.createElement(l.Fragment,null,...t):e}function ne(e,t,n){return e==null||e.commitKey!==n?{shouldScroll:!1,nextPending:null}:t===e.payload?{shouldScroll:!0,nextPending:null}:{shouldScroll:!1,nextPending:e}}const re=/"timestamp":(\d+)/;function T(e){return t(e)&&typeof e.then==`function`}function ie(e){return e==null||typeof e==`string`||typeof e==`number`||typeof e==`boolean`||typeof e==`bigint`||l.isValidElement(e)||Array.isArray(e)}function ae(e){return t(e)&&typeof e.from==`string`&&typeof e.to==`string`&&typeof e.navigationId==`number`&&t(e.options)}function oe(e){return t(e)&&`element`in e}function se(e){return t(e)&&typeof e.navigationId==`number`&&typeof e.targetPath==`string`}function ce(ee){let v=c(41),{children:te,initialPayload:y,onNavigate:b}=ee,[C,ce]=p(y),pe=f(y),[E,he]=p(0),D;v[0]===Symbol.for(`react.memo_cache_sentinel`)?(D={x:0,y:0},v[0]=D):D=v[0];let O=f(D),k=f(null),A;v[1]===Symbol.for(`react.memo_cache_sentinel`)?(A=new Map,v[1]=A):A=v[1];let ge=f(A),j;v[2]===Symbol.for(`react.memo_cache_sentinel`)?(j=new Set,v[2]=j):j=v[2];let M=f(j),_e=f(b),N=f(0),P;v[3]===Symbol.for(`react.memo_cache_sentinel`)?(P=new Map,v[3]=P):P=v[3];let F=f(P),I;v[4]===Symbol.for(`react.memo_cache_sentinel`)?(I=[],v[4]=I):I=v[4];let ve=f(I),L=f(null),R=f(0),[z,B]=p(null),V,H;v[5]===b?(V=v[6],H=v[7]):(V=()=>{_e.current=b},H=[b],v[5]=b,v[6]=V,v[7]=H),u(V,H);let U,W;v[8]!==E||v[9]!==C?(U=()=>{let{shouldScroll:e,nextPending:t}=ne(k.current,C,E);k.current=t,e&&window.scrollTo(0,0)},W=[C,E],v[8]=E,v[9]=C,v[10]=U,v[11]=W):(U=v[10],W=v[11]),d(U,W);let ye=me,G,K;v[12]===C?(G=v[13],K=v[14]):(G=()=>{pe.current=C,C?.element!=null&&ye(C.element)},K=[C],v[12]=C,v[13]=G,v[14]=K),u(G,K);let q,J;v[15]===C?(q=v[16],J=v[17]):(q=()=>{if(C?.element!=null){let e=C.element;if(t(e)&&`status`in e&&e.status===`rejected`){let t=e.reason;t!=null&&t!==``&&console.error(`[rari] AppRouter: Flight payload rejected:`,t)}}},J=[C],v[15]=C,v[16]=q,v[17]=J),u(q,J);let be;v[18]===Symbol.for(`react.memo_cache_sentinel`)?(be=()=>{if(typeof document>`u`)return;let e=document.querySelectorAll(`form`);ge.current.clear(),e.forEach((e,t)=>{let n=new FormData(e);ge.current.set(`form-${t}`,n)})},v[18]=be):be=v[18];let xe=be,Se;v[19]===Symbol.for(`react.memo_cache_sentinel`)?(Se=()=>{typeof document>`u`||document.querySelectorAll(`form`).forEach((e,t)=>{let n=ge.current.get(`form-${t}`);n&&n.forEach((t,n)=>{let r=e.elements.namedItem(n);r instanceof HTMLInputElement&&(r.type===`checkbox`||r.type===`radio`?r.checked=t===`on`:typeof t==`string`&&(r.value=t))})})},v[19]=Se):Se=v[19];let Ce=Se,we;v[20]===Symbol.for(`react.memo_cache_sentinel`)?(we=(e,t,n,r)=>{R.current+=1;let i={timestamp:Date.now(),error:e,type:t,details:n,filePath:r,consecutiveFailures:R.current};ve.current.push(i),ve.current.length>10&&ve.current.shift(),R.current>=2&&B(i),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:hmr-failure`,{detail:i}))},v[20]=we):we=v[20];let Te=we,Y=fe,Ee;v[21]===Symbol.for(`react.memo_cache_sentinel`)?(Ee=()=>{R.current>0&&(R.current=0)},v[21]=Ee):Ee=v[21];let De=Ee,Oe;v[22]===Symbol.for(`react.memo_cache_sentinel`)?(Oe=e=>{if(L.current==null||L.current===``)return!1;if(e===L.current)return!0;let t=re.exec(e);if(t){let e=Number.parseInt(t[1],10);if(Date.now()-e>5e3)return!0}return!1},v[22]=Oe):Oe=v[22];let ke=Oe,Ae;v[23]===Symbol.for(`react.memo_cache_sentinel`)?(Ae=async e=>{await s(e,M.current);let t=new ReadableStream({start(t){t.enqueue(new TextEncoder().encode(e)),t.close()}}),n=await _(t);return{element:n,rawElement:n,flightProtocol:e}},v[23]=Ae):Ae=v[23];let je=Ae,Me;v[24]===Symbol.for(`react.memo_cache_sentinel`)?(Me=async(e,t)=>{let n=t!==void 0&&t,r=await e;if(!r.body)throw Error(`Response has no body stream`);if(n){let e=_(r.body);return{element:e,rawElement:e,flightProtocol:``}}let i=await r.clone().text();await s(i,M.current);let a=new Uint8Array(await r.arrayBuffer()),o=new ReadableStream({start(e){e.enqueue(a),e.close()}}),c=await _(o);return{element:c,rawElement:c,flightProtocol:i}},v[24]=Me):Me=v[24];let Ne=Me,Pe;v[25]===C?Pe=v[26]:(Pe=async(e,t)=>{let r=e!=null&&e!==``?e:window.location.pathname,i=N.current,a=`${i}:${r}${window.location.search}`,o=F.current.get(a);if(o)return o;let c=(async()=>{let e;try{let o=(import.meta.env.RARI_SERVER_URL!=null&&import.meta.env.RARI_SERVER_URL!==``?import.meta.env.RARI_SERVER_URL:window.location.origin).replace(n,``)+r+window.location.search,c=await fetch(o,{headers:{Accept:`text/x-component`,"rari-navigation-id":String(N.current)},cache:`no-store`,signal:t});if(c.ok){let t,n=``;try{if(n=await c.clone().text(),ke(n)&&C)return F.current.delete(a),C;await s(n,M.current);let e=new Uint8Array(await c.arrayBuffer()),r=new ReadableStream({start(t){t.enqueue(e),t.close()}}),i=await _(r);t={element:i,rawElement:i,flightProtocol:n}}catch(t){let n=t,r=n instanceof Error?n:Error(String(n));Te(r,`parse`,`Failed to parse RSC Flight protocol: ${r.message}`,window.location.pathname),e=r}if(e==null)return N.current===i&&(ce(t),L.current=n,De()),F.current.delete(a),t}else{let t=Error(`Failed to fetch RSC data: ${c.status} ${c.statusText}`);Te(t,`fetch`,`HTTP ${c.status} when fetching ${o}`,window.location.pathname),e=t}}catch(t){let n=t;n instanceof Error&&!n.message.includes(`Failed to fetch RSC data`)&&!n.message.includes(`Failed to parse`)&&Te(n,`network`,`Network error: ${n.message}`,window.location.pathname),e=n}if(F.current.delete(a),e!=null)throw e instanceof Error?e:Error(typeof e==`string`?e:`Failed to fetch RSC payload`)})();return F.current.set(a,c),c},v[25]=C,v[26]=Pe);let Fe=Pe,Ie=f(je),Le=f(Ne),X=f(Fe),Re;v[27]===Fe?Re=v[28]:(Re=()=>{Ie.current=je,Le.current=Ne,X.current=Fe},v[27]=Fe,v[28]=Re),u(Re);let ze,Z;v[29]===Symbol.for(`react.memo_cache_sentinel`)?(ze=()=>{if(typeof window>`u`)return;let t=async t=>{let n=e(t,ae);if(!n||n.navigationId!==N.current)return;O.current={x:window.scrollX,y:window.scrollY},xe();let r,i=null,a=!1;try{if(n.rscResponsePromise){let e=await n.rscResponsePromise;if(N.current!==n.navigationId||(a=e.headers.get(`x-render-mode`)===`streaming`,r=await Le.current(Promise.resolve(e),a),N.current!==n.navigationId))return}else if(n.rscResponse){if(a=n.rscResponse.headers.get(`x-render-mode`)===`streaming`,r=await Le.current(Promise.resolve(n.rscResponse),a),N.current!==n.navigationId)return}else n.rscFlightProtocol!=null&&n.rscFlightProtocol!==``?r=await Ie.current(n.rscFlightProtocol):n.isStreaming||(r=await X.current(n.to,n.abortSignal))}catch(e){let t=e;if(t instanceof Error&&t.name===`AbortError`)return;i=t instanceof Error?t:Error(String(t))}if(i){console.error(`[rari] AppRouter: Navigation failed:`,i),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:n.from,to:n.to,error:i,navigationId:n.navigationId}})),R.current>=3&&Y();return}if(!(!r&&n.isStreaming&&N.current===n.navigationId)&&r&&N.current===n.navigationId){let e=window.location.hash.length>0,t=(n.options.historyKey==null||n.options.historyKey===``)&&!e&&n.options.scroll!==!1,i=n.navigationId,o=n.options.historyKey!=null&&n.options.historyKey!==``;S({parsedPayload:r,shouldScrollToTop:t,navigationId:i,useTransition:!a&&!o,currentNavigationIdRef:N,pendingScrollPayloadRef:k,setRenderKey:he,setRscPayload:ce,clearHmrError:()=>{B(null)}}),n.rscFlightProtocol!=null&&n.rscFlightProtocol!==``&&(L.current=n.rscFlightProtocol),De(),_e.current&&_e.current(n)}},n=async()=>{O.current={x:window.scrollX,y:window.scrollY},xe();try{await X.current(),he(de),B(null)}catch(e){let t=e;console.error(`HMR refetch error:`,t instanceof Error?t.message:String(t)),R.current>=3&&Y()}requestAnimationFrame(()=>{window.scrollTo(O.current.x,O.current.y),Ce()})},s=t=>{let n=e(t,oe);if(!(n?.element==null||!ie(n.element)&&!T(n.element))){O.current={x:window.scrollX,y:window.scrollY},xe();try{let{pathname:e,search:t}=a();n.revalidationKind===1?o.clear():n.revalidatedPath!=null&&n.revalidatedPath!==``?o.invalidate(n.revalidatedPath,t):o.invalidate(e,t);let r=pe.current?.element,s=o.getElement(e,t)??(r!=null&&T(r)?null:r??null),c=n.element,u=T(c)?c:i(s,c);l.startTransition(()=>{ce({element:u,rawElement:u}),B(null)}),ye(u),De()}catch(e){let t=e,n=t instanceof Error?t:Error(String(t));Te(n,`parse`,`Action flight refresh failed: ${n.message}`,window.location.pathname),R.current>=3&&Y()}requestAnimationFrame(()=>{window.scrollTo(O.current.x,O.current.y),Ce()})}},c=async()=>{try{await X.current(),he(ue),B(null)}catch(e){let t=e;console.error(`RSC invalidate error:`,t instanceof Error?t.message:String(t)),R.current>=3&&Y()}},u=t=>{let n=e(t,se);if(n&&(M.current.clear(),N.current=n.navigationId,k.current=null,typeof window<`u`)){let e=r();e&&(e.navigationId=n.navigationId)}},d=async()=>{try{await X.current(),B(null)}catch(e){let t=e;console.error(`Manifest update error:`,t instanceof Error?t.message:String(t)),R.current>=3&&Y()}},f=e=>{t(e)},p=()=>{n()},m=()=>{c()},h=()=>{d()};return window.addEventListener(`rari:navigation-start`,u),window.addEventListener(`rari:navigate`,f),window.addEventListener(`rari:app-router-rerender`,p),window.addEventListener(`rari:action-flight-refresh`,s),window.addEventListener(`rari:rsc-invalidate`,m),window.addEventListener(`rari:app-router-manifest-updated`,h),()=>{window.removeEventListener(`rari:navigation-start`,u),window.removeEventListener(`rari:navigate`,f),window.removeEventListener(`rari:app-router-rerender`,p),window.removeEventListener(`rari:action-flight-refresh`,s),window.removeEventListener(`rari:rsc-invalidate`,m),window.removeEventListener(`rari:app-router-manifest-updated`,h)}},Z=[],v[29]=ze,v[30]=Z):(ze=v[29],Z=v[30]),u(ze,Z);let Be,Ve;v[31]===C?(Be=v[32],Ve=v[33]):(Be=()=>{if(!(typeof window>`u`)&&window.location.hash&&C){let e=window.location.hash.slice(1);requestAnimationFrame(()=>{requestAnimationFrame(()=>{let t=document.getElementById(e);t&&t.scrollIntoView({behavior:`instant`,block:`start`})})})}},Ve=[C],v[31]=C,v[32]=Be,v[33]=Ve),u(Be,Ve);let He=C?.element??te,Ue;v[34]===He?Ue=v[35]:(Ue=w(He),v[34]=He,v[35]=Ue);let We=Ue,Q;v[36]===z?Q=v[37]:(Q=z&&h(x,{failure:z,maxRetries:3,onRefresh:le,onDismiss:()=>{B(null)}}),v[36]=z,v[37]=Q);let $;return v[38]!==We||v[39]!==Q?($=g(m,{children:[Q,We]}),v[38]=We,v[39]=Q,v[40]=$):$=v[40],$}function le(){window.location.reload()}function ue(e){return e+1}function de(e){return e+1}function fe(){setTimeout(pe,1e3)}function pe(){window.location.reload()}function me(e){if(e==null||T(e))return;let{pathname:t,search:n}=a();o.set(t,n,e)}export{ce as AppRouterProvider};
@@ -0,0 +1,10 @@
1
+ import * as React from "react";
2
+ //#region src/router/navigation/client-router.d.ts
3
+ interface ClientRouterProps {
4
+ readonly children: React.ReactNode;
5
+ readonly initialRoute: string;
6
+ readonly staleWindowMs?: number;
7
+ }
8
+ declare function ClientRouter({ children, initialRoute, staleWindowMs }: ClientRouterProps): React.ReactNode;
9
+ //#endregion
10
+ export { ClientRouter, ClientRouterProps };
@@ -0,0 +1 @@
1
+ "use client";import{i as e,t}from"../navigate-DuyUa6qD.mjs";import{d as n,g as r,p as i}from"../type-guards-CTkEL8zw.mjs";import{a}from"../rari-global-5vGzhToD.mjs";import{c as o}from"react/compiler-runtime";import{useEffect as s,useLayoutEffect as c,useRef as l,useState as u}from"react";function d(e,t,n={}){let r=null,i=0,a=0,o=null,s=null,{leading:c=!1,trailing:l=!0,maxWait:u}=n;function d(t){let n=o,r=s;o=null,s=null,a=t,e.apply(r,n)}function f(e){let n=e-i,r=e-a;return i===0||n>=t||n<0||u!==void 0&&r>=u}function p(){let e=Date.now();if(f(e)){h(e);return}let n=e-i,o=e-a,s=t-n,c=u===void 0?1/0:u-o;r=setTimeout(p,Math.min(s,c))}function m(e){a=e,r=setTimeout(p,t),c&&d(e)}function h(e){if(r=null,l&&o){d(e);return}o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){r!==null&&h(Date.now())}function v(){return r!==null}function y(...e){let n=Date.now(),a=f(n);if(o=e,s=this,i=n,a){if(r===null){m(i);return}if(u!==void 0){r=setTimeout(p,t),d(i);return}}r??=setTimeout(p,t)}return y.cancel=g,y.flush=_,y.pending=v,y}const f=/fetch|networkerror|load failed/i;function p(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function m(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function h(e,t,n){if(t===404)return{type:`not-found`,message:`Page not found`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!1};if(t>=500)return{type:`server-error`,message:`Server error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!0};let r=t===408||t===429;return{type:`fetch-error`,message:`HTTP error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:r}}function g(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function _(e,t){return{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function v(e,t){return{type:`fetch-error`,message:e instanceof Error?e.message:`Unknown error occurred`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function y(e,t){if(e instanceof Error&&e.name===`AbortError`)return p(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return m(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?h(e,n,t):v(e,t)}return e instanceof TypeError&&f.test(e.message)?g(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?_(e,t):v(e,t)}var ee=class{options;retryCount;constructor(e={}){this.options={timeout:e.timeout??1e4,maxRetries:e.maxRetries??3,onError:e.onError??(()=>{}),onRetry:e.onRetry??(()=>{})},this.retryCount=new Map}handleError(e,t){let n=y(e,t);return this.options.onError(n),console.error(`[rari] Navigation:`,n.type,n.message,{url:n.url,statusCode:n.statusCode,retryable:n.retryable}),n}canRetry(e,t){return e.retryable?(this.retryCount.get(t)??0)<this.options.maxRetries:!1}incrementRetry(e){let t=(this.retryCount.get(e)??0)+1;return this.retryCount.set(e,t),this.options.onRetry(t,{type:`fetch-error`,message:`Retry attempt ${t}`,url:e,timestamp:Date.now(),retryable:!0}),t}resetRetry(e){this.retryCount.delete(e)}getRetryCount(e){return this.retryCount.get(e)??0}clearRetries(){this.retryCount.clear()}};function b(e){if(!e||e===`/`)return`/`;let t=e;for(;t.endsWith(`/`)&&t.length>1;)t=t.slice(0,-1);return t.startsWith(`/`)||(t=`/${t}`),t}function te(e,t){try{return new URL(e,t!=null&&t!==``?t:window.location.origin).origin!==(t!=null&&t!==``?t:window.location.origin)}catch{return!1}}function ne(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}const re=new class{cache=new Map;pendingRequests=new Map;async get(e){let t=this.cache.get(e);if(t)return t;let n=this.pendingRequests.get(e);if(n)return n;let r=this.fetchRouteInfo(e);this.pendingRequests.set(e,r);try{let t=await r;return this.cache.set(e,t),t}finally{this.pendingRequests.delete(e)}}parseRouteInfoResponse(e){let t=r(e);if(!t||!this.isRouteInfoResponse(t))throw Error(`Failed to parse route info response`);return t}isRouteInfoResponse(e){return i(e)&&typeof e.exists==`boolean`&&Array.isArray(e.layouts)&&(e.loading===null||typeof e.loading==`string`)&&typeof e.isDynamic==`boolean`}async fetchRouteInfo(e){let t=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})});if(!t.ok){let e;try{let n=await t.text(),i=r(n);i&&typeof i.error==`string`&&i.error!==``&&(e=i.error)}catch{}throw Error(e!=null&&e!==``?e:`Failed to fetch route info: ${t.status} ${t.statusText}`)}let n=t.clone();try{let e=await t.text();return this.parseRouteInfoResponse(e)}catch(t){try{let e=await n.text();return this.parseRouteInfoResponse(e)}catch(n){throw console.error(`[RouteInfo] Failed to parse response:`,{error:t,parseError:n,path:e}),Error(`Failed to parse route info response`)}}}clear(){this.cache.clear(),this.pendingRequests.clear()}invalidate(e){this.cache.delete(e)}};if(typeof window<`u`){let e=a();e.routeInfoCache=re}var ie=class{stateHistory;routeAccessOrder;maxHistorySize;scrollableSelector;constructor(e={}){this.stateHistory=new Map,this.routeAccessOrder=[],this.maxHistorySize=e.maxHistorySize!=null&&e.maxHistorySize!==0?e.maxHistorySize:50,this.scrollableSelector=e.scrollableSelector!=null&&e.scrollableSelector!==``?e.scrollableSelector:`[data-scrollable], .scrollable, [style*="overflow"]`}captureState(e){let t={scrollPositions:this.captureScrollPositions(),formData:this.captureFormData(),focusedElement:this.captureFocusedElement()};return this.storeState(e,t),t}captureScrollPositions(){let e=new Map;try{e.set(`window`,{x:window.scrollX,y:window.scrollY,element:`window`}),document.querySelectorAll(this.scrollableSelector).forEach((t,n)=>{if(t instanceof HTMLElement){let r=t.id||`scrollable-${n}`;(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)&&e.set(r,{x:t.scrollLeft,y:t.scrollTop,element:r})}})}catch{}return e}captureFormData(){let e=new Map;try{document.querySelectorAll(`form`).forEach((t,n)=>{let r=t.id||t.name||`form-${n}`,i=new FormData(t);i.entries().next().done||e.set(r,i)})}catch{}return e}captureFocusedElement(){try{let e=document.activeElement;if(e&&e!==document.body){if(e.id)return`#${e.id}`;if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.name)return`[name="${e.name}"]`}}catch{}return null}storeState(e,t){let n=this.routeAccessOrder.indexOf(e);for(n!==-1&&this.routeAccessOrder.splice(n,1),this.routeAccessOrder.push(e),this.stateHistory.set(e,t);this.routeAccessOrder.length>this.maxHistorySize;){let e=this.routeAccessOrder.shift();e!=null&&e!==``&&this.stateHistory.delete(e)}}getHistorySize(){return this.stateHistory.size}hasState(e){return this.stateHistory.has(e)}getState(e){return this.stateHistory.get(e)}clearAll(){this.stateHistory.clear(),this.routeAccessOrder=[]}clearState(e){this.stateHistory.delete(e);let t=this.routeAccessOrder.indexOf(e);t!==-1&&this.routeAccessOrder.splice(t,1)}restoreState(e){let t=this.stateHistory.get(e);if(!t)return!1;let n=!0;return this.restoreScrollPositions(t.scrollPositions)||(n=!1),this.restoreFormData(t.formData)||(n=!1),t.focusedElement!=null&&t.focusedElement!==``&&this.restoreFocus(t.focusedElement),n}restoreScrollPositions(e){let t=!0;try{e.forEach((e,n)=>{try{if(n===`window`)window.scrollTo(e.x,e.y);else{let r=document.getElementById(n)??document.querySelector(`[data-scrollable-id="${n}"]`);r instanceof HTMLElement?(r.scrollLeft=e.x,r.scrollTop=e.y):t=!1}}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore scroll positions:`,e),t=!1}return t}restoreFormData(e){let t=!0;try{e.forEach((e,n)=>{try{let r=document.getElementById(n),i=r instanceof HTMLFormElement?r:document.querySelector(`form[name="${n}"]`)??document.querySelectorAll(`form`)[Number.parseInt(n.replace(`form-`,``),10)];i instanceof HTMLFormElement?e.forEach((e,n)=>{try{let t=i.elements.namedItem(n);t instanceof RadioNodeList?t.forEach(t=>{t instanceof HTMLInputElement&&(t.type===`radio`||t.type===`checkbox`?t.checked=t.value===e:typeof e==`string`&&(t.value=e))}):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&(t instanceof HTMLInputElement&&(t.type===`checkbox`||t.type===`radio`)?t.checked=t.value===e:typeof e==`string`&&(t.value=e))}catch{t=!1}}):t=!1}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore form data:`,e),t=!1}return t}restoreFocus(e){try{let t=document.querySelector(e);t instanceof HTMLElement&&requestAnimationFrame(()=>{try{t.focus()}catch{}})}catch{}}};function x(e,t){let n=document.querySelector(e);if(n)t.content&&n.setAttribute(`content`,t.content);else{n=document.createElement(`meta`);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);document.head.appendChild(n)}}function S(e){let t=document.querySelector(e);t&&t.remove()}function C(e){e.title!=null&&e.title!==``&&(document.title=e.title),e.description!=null&&e.description!==``?x(`meta[name="description"]`,{name:`description`,content:e.description}):S(`meta[name="description"]`),e.keywords&&e.keywords.length>0?x(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):S(`meta[name="keywords"]`),e.viewport!=null&&e.viewport!==``&&x(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function w(e){let t=document.querySelector(`link[rel="canonical"]`);if(e===void 0){t&&t.remove();return}if(t)t.setAttribute(`href`,e);else{let t=document.createElement(`link`);t.setAttribute(`rel`,`canonical`),t.setAttribute(`href`,e),document.head.appendChild(t)}}function ae(e){if(e===void 0){S(`meta[name="robots"]`);return}let t=[];e.index!==void 0&&t.push(e.index?`index`:`noindex`),e.follow!==void 0&&t.push(e.follow?`follow`:`nofollow`),e.nocache&&t.push(`nocache`),t.length>0?x(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):S(`meta[name="robots"]`)}function T(e){if(e===void 0){S(`meta[property="og:title"]`),S(`meta[property="og:description"]`),S(`meta[property="og:url"]`),S(`meta[property="og:site_name"]`),S(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>{e.remove()});return}if(e.title!=null&&e.title!==``?x(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):S(`meta[property="og:title"]`),e.description!=null&&e.description!==``?x(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):S(`meta[property="og:description"]`),e.url!=null&&e.url!==``?x(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):S(`meta[property="og:url"]`),e.siteName!=null&&e.siteName!==``?x(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):S(`meta[property="og:site_name"]`),e.type!=null&&e.type!==``?x(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):S(`meta[property="og:type"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>{e.remove()});for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`property`,`og:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>{e.remove()})}function E(e){if(e===void 0){S(`meta[name="twitter:card"]`),S(`meta[name="twitter:site"]`),S(`meta[name="twitter:creator"]`),S(`meta[name="twitter:title"]`),S(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>{e.remove()});return}if(e.card!=null&&e.card!==``?x(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):S(`meta[name="twitter:card"]`),e.site!=null&&e.site!==``?x(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):S(`meta[name="twitter:site"]`),e.creator!=null&&e.creator!==``?x(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):S(`meta[name="twitter:creator"]`),e.title!=null&&e.title!==``?x(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):S(`meta[name="twitter:title"]`),e.description!=null&&e.description!==``?x(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):S(`meta[name="twitter:description"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>{e.remove()});for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`name`,`twitter:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>{e.remove()})}function D(e){C(e),w(e.canonical),ae(e.robots),T(e.openGraph),E(e.twitter)}function O(e){return i(e)}function k(r){let i=o(40),{children:a,initialRoute:f,staleWindowMs:p}=r,m=p===void 0?3e4:p,h;i[0]===f?h=i[1]:(h=()=>({currentRoute:b(f),navigationId:0,error:null}),i[0]=f,i[1]=h);let[g,_]=u(h),v=l(null),y=l(!0),x;i[2]===f?x=i[3]:(x=b(f),i[2]=f,i[3]=x);let S=l(x),C=l(0),w;i[4]===Symbol.for(`react.memo_cache_sentinel`)?(w=new ee({timeout:1e4,maxRetries:3,onError:fe,onRetry:de}),i[4]=w):w=i[4];let ae=l(w),T;i[5]===Symbol.for(`react.memo_cache_sentinel`)?(T=new Map,i[5]=T):T=i[5];let E=l(T),D;i[6]===Symbol.for(`react.memo_cache_sentinel`)?(D=[],i[6]=D):D=i[6];let O=l(D),k;i[7]===Symbol.for(`react.memo_cache_sentinel`)?(k=new ie({maxHistorySize:50}),i[7]=k):k=i[7];let A=l(k),pe=l(null),me=l(m),he=ue,j;i[8]===Symbol.for(`react.memo_cache_sentinel`)?(j=()=>{v.current&&=(v.current.abort(),null)},i[8]=j):j=i[8];let ge=j,M;i[9]===Symbol.for(`react.memo_cache_sentinel`)?(M=()=>{for(let[,e]of E.current.entries())e.abortController.abort();E.current.clear()},i[9]=M):M=i[9];let _e=M,N;i[10]===g?N=i[11]:(N=(e,t)=>{E.current.delete(e),y.current&&g.navigationId===t&&_(le)},i[10]=g,i[11]=N);let P=N,F=l(null),ve=ce,ye=se,I;i[12]===Symbol.for(`react.memo_cache_sentinel`)?(I=(e,t,n,r,i,a)=>{C.current===r&&window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:t,to:n,navigationId:r,options:i,abortSignal:a.signal,rscResponsePromise:e}}))},i[12]=I):I=i[12];let be=I,L;if(i[13]===Symbol.for(`react.memo_cache_sentinel`)){let e=(e,t,n)=>{n.historyKey!=null&&n.historyKey!==``?requestAnimationFrame(()=>{A.current.restoreState(e)}):t&&requestAnimationFrame(()=>{let e=n=>{let r=n===void 0?0:n,i=document.getElementById(t);i?i.scrollIntoView({behavior:`smooth`,block:`start`}):r<10&&setTimeout(e,50,r+1)};e()})};L=(t,n,r,i)=>{y.current&&C.current===i&&(S.current=t,_(e=>({...e,currentRoute:t,navigationId:i,error:null})),ae.current.resetRetry(t),e(t,n,r))},i[13]=L}else L=i[13];let xe=L,R;i[14]===P?R=i[15]:(R=(e,t,n,r)=>{if(e instanceof Error&&e.name===`AbortError`){P(t,n);return}let i=ae.current.handleError(e,t);y.current&&(_(e=>({...e,error:i})),window.history.replaceState(window.history.state,``,r)),E.current.delete(t),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:r,to:t,error:i,navigationId:n}})),F.current?.()},i[14]=P,i[15]=R);let Se=R,z;i[16]!==P||i[17]!==Se?(z=async(e,t)=>{let n=t===void 0?{}:t;if(!e||typeof e!=`string`)return;let[r,i]=e.includes(`#`)?e.split(`#`):[e,``],a=b(r);if(a===S.current&&!n.replace){ve(a,i);return}let o=E.current.get(a);if(o)return o.promise;_e(),ge();let s=new AbortController;v.current=s,C.current+=1;let c=C.current;window.dispatchEvent(new CustomEvent(`rari:navigation-start`,{detail:{navigationId:c,targetPath:a}}));let l=(async()=>{let e=S.current;try{(n.historyKey==null||n.historyKey===``)&&A.current.captureState(e);let t=n.historyKey!=null&&n.historyKey!==``?n.historyKey:he(),r=window.location.origin+a,o=i?`${a}#${i}`:a,l={route:a,navigationId:c,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:t};n.replace?window.history.replaceState(l,``,o):window.history.pushState(l,``,o);let u=await fetch(r,{headers:{Accept:`text/x-component`,"rari-navigation-id":String(c)},signal:s.signal}).then(oe);if(s.signal.aborted){P(a,c);return}let d=new URL(u.url).pathname;if(d!==a){let e=i?`${d}#${i}`:d;window.history.replaceState({...l,route:d},``,e)}be(Promise.resolve(u),e,d,c,n,s),ye(u),xe(d,i,n,c),E.current.delete(a),F.current?.()}catch(t){Se(t,a,c,e)}})();return E.current.set(a,{targetPath:a,navigationId:c,promise:l,abortController:s}),l},i[16]=P,i[17]=Se,i[18]=z):z=i[18];let B=z,V;i[19]===B?V=i[20]:(V=async()=>{if(O.current.length===0)return;let e=O.current.at(-1);e&&(O.current=[],await B(e.path,e.options))},i[19]=B,i[20]=V);let Ce=V,H=l(B),U;i[21]!==B||i[22]!==Ce?(U=()=>(F.current=Ce,H.current=B,()=>{F.current=null,H.current=null}),i[21]=B,i[22]=Ce,i[23]=U):U=i[23],c(U);let we=l(null),W,G;i[24]===Symbol.for(`react.memo_cache_sentinel`)?(W=()=>{we.current??=d((e,t)=>{H.current?.(e,t)},50,{leading:!0,trailing:!0,maxWait:200})},G=[],i[24]=W,i[25]=G):(W=i[24],G=i[25]),c(W,G);let K;i[26]===Symbol.for(`react.memo_cache_sentinel`)?(K=e=>{if(e.button!==0||e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)return;let t=e.target instanceof Element?e.target:null;for(;t&&!(t instanceof HTMLAnchorElement);)t=t.parentElement;if(!(t instanceof HTMLAnchorElement))return;let n=t;if(n.target&&n.target!==`_self`||n.hasAttribute(`download`))return;let r=n.getAttribute(`href`);if(r==null||r===``||te(r))return;if(r.startsWith(`#`)){e.preventDefault();let t=r.slice(1),n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,r));return}e.preventDefault();let i=ne(r);we.current?.(i,{replace:!1})},i[26]=K):K=i[26];let Te=K,q;i[27]===Symbol.for(`react.memo_cache_sentinel`)?(q=e=>{let t=window.location.pathname,r=n(e.state)?e.state:null;H.current&&H.current(t,{replace:!0,scroll:!1,historyKey:r?.key})},i[27]=q):q=i[27];let Ee=q,J,Y;i[28]===f?(J=i[29],Y=i[30]):(J=()=>{let e=n(window.history.state)?window.history.state:null;if(e?.key==null||e.key===``){let e={route:b(f),navigationId:0,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:he()};window.history.replaceState(e,``,window.location.pathname+window.location.search+window.location.hash)}},Y=[f],i[28]=f,i[29]=J,i[30]=Y),s(J,Y);let X;i[31]===Symbol.for(`react.memo_cache_sentinel`)?(X=e=>{if(e.persisted){let e=window.location.pathname;A.current.captureState(e)}},i[31]=X):X=i[31];let De=X,Z;i[32]===Symbol.for(`react.memo_cache_sentinel`)?(Z=e=>{if(e.persisted){let e=window.location.pathname,t=n(window.history.state)?window.history.state:null;requestAnimationFrame(()=>{A.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}},i[32]=Z):Z=i[32];let Oe=Z,Q,ke;i[33]===Symbol.for(`react.memo_cache_sentinel`)?(Q=()=>(document.addEventListener(`click`,Te),window.addEventListener(`popstate`,Ee),window.addEventListener(`pagehide`,De),window.addEventListener(`pageshow`,Oe),()=>{document.removeEventListener(`click`,Te),window.removeEventListener(`popstate`,Ee),window.removeEventListener(`pagehide`,De),window.removeEventListener(`pageshow`,Oe)}),ke=[],i[33]=Q,i[34]=ke):(Q=i[33],ke=i[34]),s(Q,ke);let Ae,je;i[35]===m?(Ae=i[36],je=i[37]):(Ae=()=>{me.current=m;let e=()=>{document.hidden?pe.current=Date.now():pe.current!==null&&Date.now()-pe.current>me.current&&re.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},je=[m],i[35]=m,i[36]=Ae,i[37]=je),s(Ae,je);let Me,$;return i[38]===Symbol.for(`react.memo_cache_sentinel`)?(Me=()=>(y.current=!0,e(async(e,t)=>H.current?.(e,t)??Promise.resolve()),()=>{y.current=!1,t(),ge(),_e(),we.current?.cancel()}),$=[],i[38]=Me,i[39]=$):(Me=i[38],$=i[39]),s(Me,$),a}function oe(e){if(!e.ok&&e.status!==404)throw Error(`Failed to fetch: ${e.status}`);return e}function se(e){try{let t=e.headers.get(`x-rari-metadata`);if(t!=null&&t!==``){let e=r(decodeURIComponent(t));e&&O(e)&&D(e)}}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}}function ce(e,t){if(!t)return;let n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${e}#${t}`))}function le(e){return{...e}}function ue(){return`${Date.now()}-${Math.random().toString(36).substring(2,9)}`}function de(){}function fe(e){console.error(`[rari] Router: Navigation error:`,e)}export{k as ClientRouter};
@@ -1,5 +1,5 @@
1
- import{c as e,o as t,t as n}from"../router-D6mkoDqJ.mjs";import{d as r,g as i,n as a,p as o}from"../type-guards-CTkEL8zw.mjs";import{a as s,i as c,n as l,r as u}from"../rari-global-5vGzhToD.mjs";import{t as d}from"../get-client-component-CLpyIcLJ.mjs";import{t as f}from"../preload-modules-QmSvKk0Q.mjs";import*as p from"react";import{useEffect as m,useLayoutEffect as h,useRef as g,useState as _}from"react";import{createFromReadableStream as v}from"virtual:react-flight-client";import{createRoot as y,hydrateRoot as b}from"react-dom/client";import{AppRouterProvider as x}from"virtual:app-router-provider";import"virtual:rsc-integration.ts";function S(e,t,n={}){let r=null,i=0,a=0,o=null,s=null,{leading:c=!1,trailing:l=!0,maxWait:u}=n;function d(t){let n=o,r=s;o=null,s=null,a=t,e.apply(r,n)}function f(e){let n=e-i,r=e-a;return i===0||n>=t||n<0||u!==void 0&&r>=u}function p(){let e=Date.now();if(f(e)){h(e);return}let n=e-i,o=e-a,s=t-n,c=u===void 0?1/0:u-o;r=setTimeout(p,Math.min(s,c))}function m(e){a=e,r=setTimeout(p,t),c&&d(e)}function h(e){if(r=null,l&&o){d(e);return}o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){r!==null&&h(Date.now())}function v(){return r!==null}function y(...e){let n=Date.now(),a=f(n);if(o=e,s=this,i=n,a){if(r===null){m(i);return}if(u!==void 0){r=setTimeout(p,t),d(i);return}}r??=setTimeout(p,t)}return y.cancel=g,y.flush=_,y.pending=v,y}const C=/fetch|networkerror|load failed/i;function w(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function T(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function E(e,t,n){if(t===404)return{type:`not-found`,message:`Page not found`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!1};if(t>=500)return{type:`server-error`,message:`Server error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:!0};let r=t===408||t===429;return{type:`fetch-error`,message:`HTTP error: ${t}`,originalError:e,statusCode:t,url:n,timestamp:Date.now(),retryable:r}}function D(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function O(e,t){return{type:`parse-error`,message:`Failed to parse server response`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function k(e,t){return{type:`fetch-error`,message:e instanceof Error?e.message:`Unknown error occurred`,originalError:e instanceof Error?e:void 0,url:t,timestamp:Date.now(),retryable:!1}}function A(e,t){if(e instanceof Error&&e.name===`AbortError`)return w(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return T(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?E(e,n,t):k(e,t)}return e instanceof TypeError&&C.test(e.message)?D(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?O(e,t):k(e,t)}var j=class{options;retryCount;constructor(e={}){this.options={timeout:e.timeout??1e4,maxRetries:e.maxRetries??3,onError:e.onError??(()=>{}),onRetry:e.onRetry??(()=>{})},this.retryCount=new Map}handleError(e,t){let n=A(e,t);return this.options.onError(n),console.error(`[rari] Navigation:`,n.type,n.message,{url:n.url,statusCode:n.statusCode,retryable:n.retryable}),n}canRetry(e,t){return e.retryable?(this.retryCount.get(t)??0)<this.options.maxRetries:!1}incrementRetry(e){let t=(this.retryCount.get(e)??0)+1;return this.retryCount.set(e,t),this.options.onRetry(t,{type:`fetch-error`,message:`Retry attempt ${t}`,url:e,timestamp:Date.now(),retryable:!0}),t}resetRetry(e){this.retryCount.delete(e)}getRetryCount(e){return this.retryCount.get(e)??0}clearRetries(){this.retryCount.clear()}};function M(e){if(!e||e===`/`)return`/`;let t=e;for(;t.endsWith(`/`)&&t.length>1;)t=t.slice(0,-1);return t.startsWith(`/`)||(t=`/${t}`),t}function ee(e,t){try{return new URL(e,t!=null&&t!==``?t:window.location.origin).origin!==(t!=null&&t!==``?t:window.location.origin)}catch{return!1}}function te(e){try{let t=new URL(e,window.location.origin);return t.pathname+t.hash}catch{return e}}const N=new class{cache=new Map;pendingRequests=new Map;async get(e){let t=this.cache.get(e);if(t)return t;let n=this.pendingRequests.get(e);if(n)return n;let r=this.fetchRouteInfo(e);this.pendingRequests.set(e,r);try{let t=await r;return this.cache.set(e,t),t}finally{this.pendingRequests.delete(e)}}parseRouteInfoResponse(e){let t=i(e);if(!t||!this.isRouteInfoResponse(t))throw Error(`Failed to parse route info response`);return t}isRouteInfoResponse(e){return o(e)&&typeof e.exists==`boolean`&&Array.isArray(e.layouts)&&(e.loading===null||typeof e.loading==`string`)&&typeof e.isDynamic==`boolean`}async fetchRouteInfo(e){let t=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({path:e})});if(!t.ok){let e;try{let n=await t.text(),r=i(n);r&&typeof r.error==`string`&&r.error!==``&&(e=r.error)}catch{}throw Error(e!=null&&e!==``?e:`Failed to fetch route info: ${t.status} ${t.statusText}`)}let n=t.clone();try{let e=await t.text();return this.parseRouteInfoResponse(e)}catch(t){try{let e=await n.text();return this.parseRouteInfoResponse(e)}catch(n){throw console.error(`[RouteInfo] Failed to parse response:`,{error:t,parseError:n,path:e}),Error(`Failed to parse route info response`)}}}clear(){this.cache.clear(),this.pendingRequests.clear()}invalidate(e){this.cache.delete(e)}};if(typeof window<`u`){let e=s();e.routeInfoCache=N}var ne=class{stateHistory;routeAccessOrder;maxHistorySize;scrollableSelector;constructor(e={}){this.stateHistory=new Map,this.routeAccessOrder=[],this.maxHistorySize=e.maxHistorySize!=null&&e.maxHistorySize!==0?e.maxHistorySize:50,this.scrollableSelector=e.scrollableSelector!=null&&e.scrollableSelector!==``?e.scrollableSelector:`[data-scrollable], .scrollable, [style*="overflow"]`}captureState(e){let t={scrollPositions:this.captureScrollPositions(),formData:this.captureFormData(),focusedElement:this.captureFocusedElement()};return this.storeState(e,t),t}captureScrollPositions(){let e=new Map;try{e.set(`window`,{x:window.scrollX,y:window.scrollY,element:`window`}),document.querySelectorAll(this.scrollableSelector).forEach((t,n)=>{if(t instanceof HTMLElement){let r=t.id||`scrollable-${n}`;(t.scrollHeight>t.clientHeight||t.scrollWidth>t.clientWidth)&&e.set(r,{x:t.scrollLeft,y:t.scrollTop,element:r})}})}catch{}return e}captureFormData(){let e=new Map;try{document.querySelectorAll(`form`).forEach((t,n)=>{let r=t.id||t.name||`form-${n}`,i=new FormData(t);i.entries().next().done||e.set(r,i)})}catch{}return e}captureFocusedElement(){try{let e=document.activeElement;if(e&&e!==document.body){if(e.id)return`#${e.id}`;if((e instanceof HTMLInputElement||e instanceof HTMLTextAreaElement)&&e.name)return`[name="${e.name}"]`}}catch{}return null}storeState(e,t){let n=this.routeAccessOrder.indexOf(e);for(n!==-1&&this.routeAccessOrder.splice(n,1),this.routeAccessOrder.push(e),this.stateHistory.set(e,t);this.routeAccessOrder.length>this.maxHistorySize;){let e=this.routeAccessOrder.shift();e!=null&&e!==``&&this.stateHistory.delete(e)}}getHistorySize(){return this.stateHistory.size}hasState(e){return this.stateHistory.has(e)}getState(e){return this.stateHistory.get(e)}clearAll(){this.stateHistory.clear(),this.routeAccessOrder=[]}clearState(e){this.stateHistory.delete(e);let t=this.routeAccessOrder.indexOf(e);t!==-1&&this.routeAccessOrder.splice(t,1)}restoreState(e){let t=this.stateHistory.get(e);if(!t)return!1;let n=!0;return this.restoreScrollPositions(t.scrollPositions)||(n=!1),this.restoreFormData(t.formData)||(n=!1),t.focusedElement!=null&&t.focusedElement!==``&&this.restoreFocus(t.focusedElement),n}restoreScrollPositions(e){let t=!0;try{e.forEach((e,n)=>{try{if(n===`window`)window.scrollTo(e.x,e.y);else{let r=document.getElementById(n)??document.querySelector(`[data-scrollable-id="${n}"]`);r instanceof HTMLElement?(r.scrollLeft=e.x,r.scrollTop=e.y):t=!1}}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore scroll positions:`,e),t=!1}return t}restoreFormData(e){let t=!0;try{e.forEach((e,n)=>{try{let r=document.getElementById(n),i=r instanceof HTMLFormElement?r:document.querySelector(`form[name="${n}"]`)??document.querySelectorAll(`form`)[Number.parseInt(n.replace(`form-`,``),10)];i instanceof HTMLFormElement?e.forEach((e,n)=>{try{let t=i.elements.namedItem(n);t instanceof RadioNodeList?t.forEach(t=>{t instanceof HTMLInputElement&&(t.type===`radio`||t.type===`checkbox`?t.checked=t.value===e:typeof e==`string`&&(t.value=e))}):(t instanceof HTMLInputElement||t instanceof HTMLTextAreaElement||t instanceof HTMLSelectElement)&&(t instanceof HTMLInputElement&&(t.type===`checkbox`||t.type===`radio`)?t.checked=t.value===e:typeof e==`string`&&(t.value=e))}catch{t=!1}}):t=!1}catch{t=!1}})}catch(e){console.error(`[rari] Router: Failed to restore form data:`,e),t=!1}return t}restoreFocus(e){try{let t=document.querySelector(e);t instanceof HTMLElement&&requestAnimationFrame(()=>{try{t.focus()}catch{}})}catch{}}};function P(e,t){let n=document.querySelector(e);if(n)t.content&&n.setAttribute(`content`,t.content);else{n=document.createElement(`meta`);for(let[e,r]of Object.entries(t))n.setAttribute(e,r);document.head.appendChild(n)}}function F(e){let t=document.querySelector(e);t&&t.remove()}function I(e){e.title!=null&&e.title!==``&&(document.title=e.title),e.description!=null&&e.description!==``?P(`meta[name="description"]`,{name:`description`,content:e.description}):F(`meta[name="description"]`),e.keywords&&e.keywords.length>0?P(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):F(`meta[name="keywords"]`),e.viewport!=null&&e.viewport!==``&&P(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function L(e){let t=document.querySelector(`link[rel="canonical"]`);if(e===void 0){t&&t.remove();return}if(t)t.setAttribute(`href`,e);else{let t=document.createElement(`link`);t.setAttribute(`rel`,`canonical`),t.setAttribute(`href`,e),document.head.appendChild(t)}}function R(e){if(e===void 0){F(`meta[name="robots"]`);return}let t=[];e.index!==void 0&&t.push(e.index?`index`:`noindex`),e.follow!==void 0&&t.push(e.follow?`follow`:`nofollow`),e.nocache&&t.push(`nocache`),t.length>0?P(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):F(`meta[name="robots"]`)}function z(e){if(e===void 0){F(`meta[property="og:title"]`),F(`meta[property="og:description"]`),F(`meta[property="og:url"]`),F(`meta[property="og:site_name"]`),F(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>{e.remove()});return}if(e.title!=null&&e.title!==``?P(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):F(`meta[property="og:title"]`),e.description!=null&&e.description!==``?P(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):F(`meta[property="og:description"]`),e.url!=null&&e.url!==``?P(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):F(`meta[property="og:url"]`),e.siteName!=null&&e.siteName!==``?P(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):F(`meta[property="og:site_name"]`),e.type!=null&&e.type!==``?P(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):F(`meta[property="og:type"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>{e.remove()});for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`property`,`og:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>{e.remove()})}function B(e){if(e===void 0){F(`meta[name="twitter:card"]`),F(`meta[name="twitter:site"]`),F(`meta[name="twitter:creator"]`),F(`meta[name="twitter:title"]`),F(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>{e.remove()});return}if(e.card!=null&&e.card!==``?P(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):F(`meta[name="twitter:card"]`),e.site!=null&&e.site!==``?P(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):F(`meta[name="twitter:site"]`),e.creator!=null&&e.creator!==``?P(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):F(`meta[name="twitter:creator"]`),e.title!=null&&e.title!==``?P(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):F(`meta[name="twitter:title"]`),e.description!=null&&e.description!==``?P(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):F(`meta[name="twitter:description"]`),e.images&&e.images.length>0){document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>{e.remove()});for(let t of e.images){let e=document.createElement(`meta`);e.setAttribute(`name`,`twitter:image`),e.setAttribute(`content`,t),document.head.appendChild(e)}}else document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>{e.remove()})}function re(e){I(e),L(e.canonical),R(e.robots),z(e.openGraph),B(e.twitter)}function ie(e){return o(e)}function V({children:n,initialRoute:a,staleWindowMs:o=3e4}){let[s,c]=_(()=>({currentRoute:M(a),navigationId:0,error:null})),l=g(null),u=g(!0),d=g(M(a)),f=g(0),p=g(new j({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),v=g(new Map),y=g([]),b=g(new ne({maxHistorySize:50})),x=g(null),C=g(o),w=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,T=()=>{l.current&&=(l.current.abort(),null)},E=()=>{for(let[,e]of v.current.entries())e.abortController.abort();v.current.clear()},D=(e,t)=>{v.current.delete(e),u.current&&s.navigationId===t&&c(e=>({...e}))},O=g(null),k=(e,t)=>{if(!t)return;let n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,`${e}#${t}`))},A=e=>{try{let t=e.headers.get(`x-rari-metadata`);if(t!=null&&t!==``){let e=i(decodeURIComponent(t));e&&ie(e)&&re(e)}}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}},P=(e,t,n,r,i,a)=>{f.current===r&&window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:t,to:n,navigationId:r,options:i,abortSignal:a.signal,rscResponsePromise:e}}))},F=(e,t,n)=>{n.historyKey!=null&&n.historyKey!==``?requestAnimationFrame(()=>{b.current.restoreState(e)}):t&&requestAnimationFrame(()=>{let e=(n=0)=>{let r=document.getElementById(t);r?r.scrollIntoView({behavior:`smooth`,block:`start`}):n<10&&setTimeout(e,50,n+1)};e()})},I=(e,t,n,r)=>{u.current&&f.current===r&&(d.current=e,c(t=>({...t,currentRoute:e,navigationId:r,error:null})),p.current.resetRetry(e),F(e,t,n))},L=(e,t,n,r)=>{if(e instanceof Error&&e.name===`AbortError`){D(t,n);return}let i=p.current.handleError(e,t);u.current&&(c(e=>({...e,error:i})),window.history.replaceState(window.history.state,``,r)),v.current.delete(t),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:r,to:t,error:i,navigationId:n}})),O.current?.()},R=async(e,t={})=>{if(!e||typeof e!=`string`)return;let[n,r]=e.includes(`#`)?e.split(`#`):[e,``],i=M(n);if(i===d.current&&!t.replace){k(i,r);return}let a=v.current.get(i);if(a)return a.promise;E(),T();let o=new AbortController;l.current=o,f.current+=1;let s=f.current;window.dispatchEvent(new CustomEvent(`rari:navigation-start`,{detail:{navigationId:s,targetPath:i}}));let c=(async()=>{let e=d.current;try{(t.historyKey==null||t.historyKey===``)&&b.current.captureState(e);let n=t.historyKey!=null&&t.historyKey!==``?t.historyKey:w(),a=window.location.origin+i,c=r?`${i}#${r}`:i,l={route:i,navigationId:s,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n};t.replace?window.history.replaceState(l,``,c):window.history.pushState(l,``,c);let u=await fetch(a,{headers:{Accept:`text/x-component`,"rari-navigation-id":String(s)},signal:o.signal}).then(e=>{if(!e.ok&&e.status!==404)throw Error(`Failed to fetch: ${e.status}`);return e});if(o.signal.aborted){D(i,s);return}let d=new URL(u.url).pathname;if(d!==i){let e=r?`${d}#${r}`:d;window.history.replaceState({...l,route:d},``,e)}P(Promise.resolve(u),e,d,s,t,o),A(u),I(d,r,t,s),v.current.delete(i),O.current?.()}catch(t){L(t,i,s,e)}})();return v.current.set(i,{targetPath:i,navigationId:s,promise:c,abortController:o}),c},z=async()=>{if(y.current.length===0)return;let e=y.current.at(-1);e&&(y.current=[],await R(e.path,e.options))},B=g(R);h(()=>(O.current=z,B.current=R,()=>{O.current=null,B.current=null}));let V=g(null);V.current??=S((e,t)=>{B.current?.(e,t)},50,{leading:!0,trailing:!0,maxWait:200});let H=e=>{if(e.button!==0||e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)return;let t=e.target instanceof Element?e.target:null;for(;t&&!(t instanceof HTMLAnchorElement);)t=t.parentElement;if(!(t instanceof HTMLAnchorElement))return;let n=t;if(n.target&&n.target!==`_self`||n.hasAttribute(`download`))return;let r=n.getAttribute(`href`);if(r==null||r===``||ee(r))return;if(r.startsWith(`#`)){e.preventDefault();let t=r.slice(1),n=document.getElementById(t);n&&(n.scrollIntoView({behavior:`smooth`,block:`start`}),window.history.pushState(window.history.state,``,r));return}e.preventDefault();let i=te(r);V.current&&V.current(i,{replace:!1})},U=e=>{let t=window.location.pathname,n=r(e.state)?e.state:null;B.current&&B.current(t,{replace:!0,scroll:!1,historyKey:n?.key})};m(()=>{let e=r(window.history.state)?window.history.state:null;if(e?.key==null||e.key===``){let e={route:M(a),navigationId:0,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:w()};window.history.replaceState(e,``,window.location.pathname+window.location.search+window.location.hash)}},[a]);let W=e=>{if(e.persisted){let e=window.location.pathname;b.current.captureState(e)}},G=e=>{if(e.persisted){let e=window.location.pathname,t=r(window.history.state)?window.history.state:null;requestAnimationFrame(()=>{b.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}};return m(()=>(document.addEventListener(`click`,H),window.addEventListener(`popstate`,U),window.addEventListener(`pagehide`,W),window.addEventListener(`pageshow`,G),()=>{document.removeEventListener(`click`,H),window.removeEventListener(`popstate`,U),window.removeEventListener(`pagehide`,W),window.removeEventListener(`pageshow`,G)}),[]),m(()=>{C.current=o;let e=()=>{document.hidden?x.current=Date.now():x.current!==null&&Date.now()-x.current>C.current&&N.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[o]),m(()=>(u.current=!0,e(async(e,t)=>B.current?.(e,t)??Promise.resolve()),()=>{u.current=!1,t(),T(),E(),V.current?.cancel&&V.current.cancel()}),[]),n}function H(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;t.nextNode();){let e=t.currentNode;if(e.nodeType===8&&`data`in e){let t=e.data;if(t===`$`||t===`$?`||t===`/$`)return!0}}return!!(e.querySelector(`[data-reactroot]`)||e.querySelectorAll(`template[data-rri]`).length>0)}function U(e){if(H(e))return!0;let t=e.firstElementChild;return t===null||t.tagName===`SCRIPT`?!1:!t.classList.contains(`rari-error`)}function W(e){return H(e)}function G(e){e.querySelectorAll(`.rari-error:not([data-rari-hydration-failure])`).forEach(e=>{e.remove()})}function K(e,t,n){return p.createElement(e,t,n)}function ae(e,t){if(e.querySelector(`.rari-error[data-rari-hydration-failure]`))return;let n=document.createElement(`div`);n.className=`rari-error`,n.setAttribute(`data-rari-hydration-failure`,`true`),n.setAttribute(`role`,`alert`),n.style.cssText=`color:red;border:1px solid red;padding:10px;border-radius:4px;background-color:#fff5f5;margin:10px 0;`;let r=document.createElement(`strong`);r.textContent=`Failed to load page: `,n.append(r,document.createTextNode(t)),e.prepend(n)}function oe(){Reflect.set(globalThis,`__rari_client_ready`,!0),window.dispatchEvent(new CustomEvent(`rari:client-ready`))}function q(e,t){W(e)?(G(e),b(e,t,{onRecoverableError(e){import.meta.env.DEV&&console.warn(`[rari] Hydration mismatch:`,e)}})):y(e).render(t),oe()}const J=c();J.AppRouterProvider=x,J.ClientRouter=V,J.getClientComponent=d;async function Y(e){try{await d(e)}catch(t){console.error(`[rari] Failed to preload component ${e}:`,t)}}
1
+ import{n as e,p as t}from"../type-guards-CTkEL8zw.mjs";import{t as n}from"../router-D84JWQz7.mjs";import{a as r,i,n as a,r as o}from"../rari-global-5vGzhToD.mjs";import{t as s}from"../get-client-component-CLpyIcLJ.mjs";import{t as c}from"../preload-modules-QmSvKk0Q.mjs";import*as l from"react";import{createFromReadableStream as u}from"virtual:react-flight-client";import{createRoot as d,hydrateRoot as f}from"react-dom/client";import{AppRouterProvider as p}from"virtual:app-router-provider";import{ClientRouter as m}from"virtual:client-router";import"virtual:rsc-integration.ts";function h(e,t){if(e.querySelector(`.rari-error[data-rari-hydration-failure]`))return;let n=document.createElement(`div`);n.className=`rari-error`,n.setAttribute(`data-rari-hydration-failure`,`true`),n.setAttribute(`role`,`alert`),n.style.cssText=`color:red;border:1px solid red;padding:10px;border-radius:4px;background-color:#fff5f5;margin:10px 0;`;let r=document.createElement(`strong`);r.textContent=`Failed to load page: `,n.append(r,document.createTextNode(t)),e.prepend(n)}function g(e){let t=document.createTreeWalker(e,NodeFilter.SHOW_COMMENT);for(;t.nextNode();){let e=t.currentNode;if(e.nodeType===8&&`data`in e){let t=e.data;if(t===`$`||t===`$?`||t===`/$`)return!0}}return!!(e.querySelector(`[data-reactroot]`)||e.querySelectorAll(`template[data-rri]`).length>0)}function _(e){if(g(e))return!0;let t=e.firstElementChild;return t===null||t.tagName===`SCRIPT`?!1:!t.classList.contains(`rari-error`)}function v(e){return g(e)}function y(e){e.querySelectorAll(`.rari-error:not([data-rari-hydration-failure])`).forEach(e=>{e.remove()})}function b(e,t,n){return l.createElement(e,t,n)}function x(){Reflect.set(globalThis,`__rari_client_ready`,!0),window.dispatchEvent(new CustomEvent(`rari:client-ready`))}function S(e,t){v(e)?(y(e),f(e,t,{onRecoverableError(e){import.meta.env.DEV&&console.warn(`[rari] Hydration mismatch:`,e)}})):d(e).render(t),x()}const C=i();C.AppRouterProvider=p,C.ClientRouter=m,C.getClientComponent=s;async function w(e){try{await s(e)}catch(t){console.error(`[rari] Failed to preload component ${e}:`,t)}}
2
2
  /*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */
3
- J.preloadClientComponent=Y,u(),l();
3
+ C.preloadClientComponent=w,o(),a();
4
4
  /*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */
5
- function X(){let e=Reflect.get(globalThis,`__rari_f`);if(Array.isArray(e))return e}function Z(e){return o(e)&&typeof e.rscRow==`string`}function se(e){return Array.isArray(e)&&typeof e[1]==`string`}function ce(){return!!X()?.some(e=>e!==0)}function le(){let e=X();if(e?.length==null||e.length===0)return null;let t=``,n=[];for(let r of e)r!==0&&(typeof r==`string`?t+=r:se(r)&&n.push(r[1]));if(n.length>0){let e=n.map(e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0))),t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t),i=0;for(let t of e)r.set(t,i),i+=t.length;return r}return t?new TextEncoder().encode(t):null}async function Q(e,t){let n=new TextDecoder().decode(e);await f(n);let r=s(),i=r.streaming,o=!!(i?.bufferedRows&&i.bufferedRows.length>0);if(t.streaming&&(i?.complete===void 0||o)){let t=new ReadableStream({start(t){let n=!1;t.enqueue(e);let i=e=>{if(n)return;let r=a(e,Z);r&&t.enqueue(new TextEncoder().encode(`\n${r.rscRow}`))},o=()=>{n||(n=!0,t.close(),window.removeEventListener(`rari:html-stream-row`,i),window.removeEventListener(`rari:stream-complete`,o))};if(window.addEventListener(`rari:html-stream-row`,i),window.addEventListener(`rari:stream-complete`,o),r.streaming?.bufferedRows){let e=[...r.streaming.bufferedRows];for(let n of e)t.enqueue(new TextEncoder().encode(`\n${n}`));r.streaming.bufferedRows=[]}r.streaming?.complete&&o()}});return v(t)}let c=new ReadableStream({start(t){t.enqueue(e),t.close()}});return v(c)}async function $(){let e=document.getElementById(`root`);if(!e){console.error(`[rari] Root element not found`);return}let t=ce(),r=le(),i=U(e)||H(e),o=s().streaming,c=!!(o?.bufferedRows&&o.bufferedRows.length>0);try{let o,l=!t&&!c&&!i;if(i&&t&&r){let t=`Could not load interactive page data.`;try{o=await Q(r,{streaming:!1})}catch(e){t=e instanceof Error?e.message:`Failed to parse embedded RSC payload.`;try{let e=window.location.pathname+window.location.search,n=import.meta.env.DEV?import.meta.env.RARI_SERVER_URL!=null&&import.meta.env.RARI_SERVER_URL!==``?import.meta.env.RARI_SERVER_URL:`http://localhost:${import.meta.env.VITE_RSC_PORT!=null&&import.meta.env.VITE_RSC_PORT!==``?import.meta.env.VITE_RSC_PORT:`3000`}`:window.location.origin,r=await fetch(n+e,{headers:{Accept:`text/x-component`},cache:`no-store`});if(r.ok){let e=new Uint8Array(await r.arrayBuffer()),t=new ReadableStream({start(t){t.enqueue(e),t.close()}});o=await v(t)}else t=`Failed to fetch RSC payload fallback: HTTP ${r.status}.`}catch(e){t=e instanceof Error?e.message:`Failed to fetch RSC payload fallback.`,console.error(`[rari] Failed to fetch RSC payload fallback:`,e)}}if(o!=null){let t=p.createElement(x,{initialPayload:{element:o}});t=K(V,{initialRoute:window.location.pathname},t),t=K(n,{initialPathname:window.location.pathname},t),q(e,t)}else ae(e,`${t} Try refreshing the page.`),console.error(`[rari] Hydration skipped: failed to load RSC payload`);return}if(l)try{let e=window.location.pathname+window.location.search,t=(import.meta.env.DEV?import.meta.env.RARI_SERVER_URL!=null&&import.meta.env.RARI_SERVER_URL!==``?import.meta.env.RARI_SERVER_URL:`http://localhost:${import.meta.env.VITE_RSC_PORT!=null&&import.meta.env.VITE_RSC_PORT!==``?import.meta.env.VITE_RSC_PORT:`3000`}`:window.location.origin)+e,n=await fetch(t,{headers:{Accept:`text/x-component`},cache:`no-store`});if(!n.ok&&n.status!==404)throw Error(`Failed to fetch RSC data: ${n.status}`);if(!n.body)throw Error(`RSC response has no body`);o=await v(n.body)}catch(e){if(e instanceof Promise)throw e;console.error(`[rari] Failed to fetch initial RSC data:`,e),o=null}else if(t&&r)try{o=await Q(r,{streaming:!0})}catch(e){console.error(`[rari] Failed to parse embedded RSC payload:`,e),console.error(`[rari] Error stack:`,e instanceof Error?e.stack:`no stack`),o=null}else if(c)try{let e=new ReadableStream({start(e){let t=t=>{let n=a(t,Z);n&&e.enqueue(new TextEncoder().encode(`${n.rscRow}\n`))},n=()=>{e.close(),window.removeEventListener(`rari:html-stream-row`,t),window.removeEventListener(`rari:stream-complete`,n)};window.addEventListener(`rari:html-stream-row`,t),window.addEventListener(`rari:stream-complete`,n);let r=s();if(r.streaming?.bufferedRows){let t=[...r.streaming.bufferedRows];r.streaming.bufferedRows=[];for(let n of t)e.enqueue(new TextEncoder().encode(`${n}\n`))}r.streaming?.complete&&n()}});o=await v(e)}catch(e){console.error(`[rari] Failed to process streaming RSC payload:`,e),o=null}if(o==null)throw Error(`No RSC data available for hydration`);let u=p.createElement(x,{initialPayload:{element:o}});u=K(V,{initialRoute:window.location.pathname},u),u=K(n,{initialPathname:window.location.pathname},u),q(e,u)}catch(e){console.error(`[rari] Error rendering app:`,e)}}function ue(){let e=import.meta.hot;if(!e)return{};let t=e.data;return o(t)?{hasRendered:t.hasRendered===!0}:{}}function de(){let e=import.meta.hot;if(!e)return;let t=e.data;o(t)&&(t.hasRendered=!0)}(!import.meta.hot||ue().hasRendered!==!0)&&($().catch(e=>{console.error(`[rari] Fatal error:`,e)}),de());export{Y as preloadClientComponent,$ as renderApp};
5
+ function T(){let e=Reflect.get(globalThis,`__rari_f`);if(Array.isArray(e))return e}function E(e){return t(e)&&typeof e.rscRow==`string`}function D(e){return Array.isArray(e)&&typeof e[1]==`string`}function O(){return!!T()?.some(e=>e!==0)}function k(){let e=T();if(e?.length==null||e.length===0)return null;let t=``,n=[];for(let r of e)r!==0&&(typeof r==`string`?t+=r:D(r)&&n.push(r[1]));if(n.length>0){let e=n.map(e=>Uint8Array.from(atob(e),e=>e.charCodeAt(0))),t=e.reduce((e,t)=>e+t.length,0),r=new Uint8Array(t),i=0;for(let t of e)r.set(t,i),i+=t.length;return r}return t?new TextEncoder().encode(t):null}async function A(t,n){let i=new TextDecoder().decode(t);await c(i);let a=r(),o=a.streaming,s=!!(o?.bufferedRows&&o.bufferedRows.length>0);if(n.streaming&&(o?.complete===void 0||s)){let n=new ReadableStream({start(n){let r=!1;n.enqueue(t);let i=t=>{if(r)return;let i=e(t,E);i&&n.enqueue(new TextEncoder().encode(`\n${i.rscRow}`))},o=()=>{r||(r=!0,n.close(),window.removeEventListener(`rari:html-stream-row`,i),window.removeEventListener(`rari:stream-complete`,o))};if(window.addEventListener(`rari:html-stream-row`,i),window.addEventListener(`rari:stream-complete`,o),a.streaming?.bufferedRows){let e=[...a.streaming.bufferedRows];for(let t of e)n.enqueue(new TextEncoder().encode(`\n${t}`));a.streaming.bufferedRows=[]}a.streaming?.complete&&o()}});return u(n)}let l=new ReadableStream({start(e){e.enqueue(t),e.close()}});return u(l)}async function j(){let t=document.getElementById(`root`);if(!t){console.error(`[rari] Root element not found`);return}let i=O(),a=k(),o=_(t)||g(t),s=r().streaming,c=!!(s?.bufferedRows&&s.bufferedRows.length>0);try{let s,d=!i&&!c&&!o;if(o&&i&&a){let e=`Could not load interactive page data.`;try{s=await A(a,{streaming:!1})}catch(t){e=t instanceof Error?t.message:`Failed to parse embedded RSC payload.`;try{let t=window.location.pathname+window.location.search,n=import.meta.env.DEV?import.meta.env.RARI_SERVER_URL!=null&&import.meta.env.RARI_SERVER_URL!==``?import.meta.env.RARI_SERVER_URL:`http://localhost:${import.meta.env.VITE_RSC_PORT!=null&&import.meta.env.VITE_RSC_PORT!==``?import.meta.env.VITE_RSC_PORT:`3000`}`:window.location.origin,r=await fetch(n+t,{headers:{Accept:`text/x-component`},cache:`no-store`});if(r.ok){let e=new Uint8Array(await r.arrayBuffer()),t=new ReadableStream({start(t){t.enqueue(e),t.close()}});s=await u(t)}else e=`Failed to fetch RSC payload fallback: HTTP ${r.status}.`}catch(t){e=t instanceof Error?t.message:`Failed to fetch RSC payload fallback.`,console.error(`[rari] Failed to fetch RSC payload fallback:`,t)}}if(s!=null){let e=l.createElement(p,{initialPayload:{element:s}});e=b(m,{initialRoute:window.location.pathname},e),e=b(n,{initialPathname:window.location.pathname},e),S(t,e)}else h(t,`${e} Try refreshing the page.`),console.error(`[rari] Hydration skipped: failed to load RSC payload`);return}if(d)try{let e=window.location.pathname+window.location.search,t=(import.meta.env.DEV?import.meta.env.RARI_SERVER_URL!=null&&import.meta.env.RARI_SERVER_URL!==``?import.meta.env.RARI_SERVER_URL:`http://localhost:${import.meta.env.VITE_RSC_PORT!=null&&import.meta.env.VITE_RSC_PORT!==``?import.meta.env.VITE_RSC_PORT:`3000`}`:window.location.origin)+e,n=await fetch(t,{headers:{Accept:`text/x-component`},cache:`no-store`});if(!n.ok&&n.status!==404)throw Error(`Failed to fetch RSC data: ${n.status}`);if(!n.body)throw Error(`RSC response has no body`);s=await u(n.body)}catch(e){if(e instanceof Promise)throw e;console.error(`[rari] Failed to fetch initial RSC data:`,e),s=null}else if(i&&a)try{s=await A(a,{streaming:!0})}catch(e){console.error(`[rari] Failed to parse embedded RSC payload:`,e),console.error(`[rari] Error stack:`,e instanceof Error?e.stack:`no stack`),s=null}else if(c)try{let t=new ReadableStream({start(t){let n=n=>{let r=e(n,E);r&&t.enqueue(new TextEncoder().encode(`${r.rscRow}\n`))},i=()=>{t.close(),window.removeEventListener(`rari:html-stream-row`,n),window.removeEventListener(`rari:stream-complete`,i)};window.addEventListener(`rari:html-stream-row`,n),window.addEventListener(`rari:stream-complete`,i);let a=r();if(a.streaming?.bufferedRows){let e=[...a.streaming.bufferedRows];a.streaming.bufferedRows=[];for(let n of e)t.enqueue(new TextEncoder().encode(`${n}\n`))}a.streaming?.complete&&i()}});s=await u(t)}catch(e){console.error(`[rari] Failed to process streaming RSC payload:`,e),s=null}if(s==null)throw Error(`No RSC data available for hydration`);let f=l.createElement(p,{initialPayload:{element:s}});f=b(m,{initialRoute:window.location.pathname},f),f=b(n,{initialPathname:window.location.pathname},f),S(t,f)}catch(e){console.error(`[rari] Error rendering app:`,e)}}function M(){let e=import.meta.hot;if(!e)return{};let n=e.data;return t(n)?{hasRendered:n.hasRendered===!0}:{}}function N(){let e=import.meta.hot;if(!e)return;let n=e.data;t(n)&&(n.hasRendered=!0)}(!import.meta.hot||M().hasRendered!==!0)&&(j().catch(e=>{console.error(`[rari] Fatal error:`,e)}),N());export{w as preloadClientComponent,j as renderApp};
@@ -22,6 +22,28 @@ declare module 'virtual:react-flight-client' {
22
22
  readonly signal?: AbortSignal;
23
23
  }>): Promise<FormData | string>;
24
24
  }
25
+ declare module 'virtual:client-router' {
26
+ import type * as React from 'react';
27
+ export interface ClientRouterProps {
28
+ readonly children: React.ReactNode;
29
+ readonly initialRoute: string;
30
+ readonly staleWindowMs?: number;
31
+ }
32
+ export function ClientRouter(props: ClientRouterProps): React.ReactNode;
33
+ }
34
+ declare module 'virtual:app-router-provider' {
35
+ import type * as React from 'react';
36
+ export interface AppRouterProviderProps {
37
+ readonly children?: React.ReactNode;
38
+ readonly initialPayload?: {
39
+ readonly element: unknown;
40
+ readonly rawElement?: unknown;
41
+ readonly flightProtocol?: string;
42
+ };
43
+ readonly onNavigate?: (detail: Readonly<Record<string, unknown>>) => void;
44
+ }
45
+ export function AppRouterProvider(props: AppRouterProviderProps): React.ReactNode;
46
+ }
25
47
  declare module 'react-server-dom-webpack/client' {
26
48
  export type { Thenable } from 'virtual:react-flight-client';
27
49
  export { createFromReadableStream, createServerReference, encodeReply } from 'virtual:react-flight-client';
package/dist/vite.d.mts CHANGED
@@ -1,4 +1,4 @@
1
- import { a as Sitemap, c as SitemapVideo, d as RouteContext, f as RouteHandler, i as RobotsRule, l as ApiResponse, o as SitemapEntry, r as Robots, s as SitemapImage, u as ApiRouteHandlers } from "./types-BYob0lqv.mjs";
1
+ import { a as Sitemap, c as SitemapVideo, d as RouteContext, f as RouteHandler, i as RobotsRule, l as ApiResponse, o as SitemapEntry, r as Robots, s as SitemapImage, u as ApiRouteHandlers } from "./types-0350HUwk.mjs";
2
2
  import { a as ProxyModule, c as RariURL, i as ProxyMatcher, l as RequestCookies, n as ProxyConfig, o as ProxyResult, r as ProxyFunction, s as RariFetchEvent, t as CookieOptions, u as ResponseCookies } from "./types-DAdRjhuk.mjs";
3
3
  import { a as ErrorProps, c as LayoutEntry, d as Metadata, f as NotFoundEntry, g as TemplateEntry, h as RouteSegmentType, i as ErrorEntry, l as LayoutProps, m as RouteSegment, n as AppRouteManifest, o as GenerateMetadata, p as PageProps, r as AppRouteMatch, s as GenerateStaticParams, t as AppRouteEntry, u as LoadingEntry } from "./types-DCEyvFz7.mjs";
4
4
  import { UserConfig } from "vite-plus";
package/dist/vite.mjs CHANGED
@@ -1,4 +1,4 @@
1
- import{t as e}from"./api-routes-ChRr3O5-.mjs";import{g as t,h as n,m as r,o as i,p as a,r as o,t as s,y as c}from"./type-guards-CTkEL8zw.mjs";import{a as l,n as u,r as d,t as f}from"./constants-BFdy-wPN.mjs";import{a as p,c as m,d as h,g,h as _,i as v,m as y,n as b,o as ee,p as te,r as ne,s as re,t as x,u as ie}from"./regex-constants-Wm7xRA3u.mjs";import{a as ae,i as oe,n as se,o as ce,r as le,t as S}from"./alias-resolver-Cigam7Y7.mjs";import{t as ue}from"./timer-Duul5JHq.mjs";import{t as de}from"./names-N6JRDeT1.mjs";import{builtinModules as C,createRequire as w}from"node:module";import{Buffer as fe}from"node:buffer";import{spawn as pe,spawnSync as me}from"node:child_process";import T,{promises as E}from"node:fs";import D from"node:path";import O from"node:process";import{fileURLToPath as k,pathToFileURL as A}from"node:url";import j from"node:crypto";import{build as he}from"rolldown";function ge(e){return e.map(e=>e)}function _e(e){return e}function ve(e={}){let{root:t=O.cwd(),srcDir:n=`src`,proxyFileName:r=`proxy`,extensions:i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.mjs`],verbose:a=!1}=e,o=null,s=e=>{a&&console.warn(`[rari] Proxy: ${e}`)};async function c(){for(let e of i){let n=`${r}${e}`,i=D.join(t,n);try{return await E.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=D.join(t,n);try{await E.access(e);for(let t of i){let i=`${r}${t}`,a=D.join(e,i);try{return await E.access(a),s(`Found proxy file: ${D.join(n,i)}`),{filePath:a,exists:!0,relativePath:D.join(n,i)}}catch{}}}catch{}return null}return _e({name:`rari:proxy`,async buildStart(){o=await c(),s(o?`Proxy enabled: ${o.relativePath}`:`No proxy file found`)},configureServer(e){o&&(e.watcher.add(o.filePath),e.watcher.on(`change`,t=>{t===o?.filePath&&(s(`Proxy file changed, reloading...`),e.ws.send({type:`custom`,event:`rari:proxy-reload`}))}))},handleHotUpdate({file:e,server:t}){if(e===o?.filePath)return s(`Hot reloading proxy...`),t.ws.send({type:`custom`,event:`rari:proxy-reload`,data:{file:o.relativePath}}),[]}})}function ye(e){if(e==null||e===``)return null;let t=Number(e);return Number.isFinite(t)?t:null}function M(){let{SERVER_PORT:e,PORT:t,RSC_PORT:n}=O.env;return ye(e)??ye(t)??ye(n)??3e3}function be(){return`http://localhost:${M()}`}const xe=6e4;async function Se(e){let t=A(e).href,n=`
1
+ import{t as e}from"./api-routes-ChRr3O5-.mjs";import{g as t,h as n,m as r,o as i,p as a,r as o,t as s,y as c}from"./type-guards-CTkEL8zw.mjs";import{a as l,n as u,r as d,t as f}from"./constants-BFdy-wPN.mjs";import{a as p,c as m,d as h,g,h as _,i as v,m as y,n as b,o as ee,p as te,r as ne,s as re,t as x,u as ie}from"./regex-constants-Wm7xRA3u.mjs";import{a as ae,i as oe,n as se,o as ce,r as le,t as S}from"./alias-resolver-Cigam7Y7.mjs";import{t as ue}from"./timer-Duul5JHq.mjs";import{t as de}from"./names-N6JRDeT1.mjs";import{builtinModules as C,createRequire as fe}from"node:module";import{Buffer as pe}from"node:buffer";import{spawn as me,spawnSync as he}from"node:child_process";import w,{promises as T}from"node:fs";import E from"node:path";import D from"node:process";import{fileURLToPath as O,pathToFileURL as k}from"node:url";import A from"node:crypto";import{build as j}from"rolldown";function ge(e){return e.map(e=>e)}function _e(e){return e}function ve(e={}){let{root:t=D.cwd(),srcDir:n=`src`,proxyFileName:r=`proxy`,extensions:i=[`.ts`,`.tsx`,`.js`,`.jsx`,`.mts`,`.mjs`],verbose:a=!1}=e,o=null,s=e=>{a&&console.warn(`[rari] Proxy: ${e}`)};async function c(){for(let e of i){let n=`${r}${e}`,i=E.join(t,n);try{return await T.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=E.join(t,n);try{await T.access(e);for(let t of i){let i=`${r}${t}`,a=E.join(e,i);try{return await T.access(a),s(`Found proxy file: ${E.join(n,i)}`),{filePath:a,exists:!0,relativePath:E.join(n,i)}}catch{}}}catch{}return null}return _e({name:`rari:proxy`,async buildStart(){o=await c(),s(o?`Proxy enabled: ${o.relativePath}`:`No proxy file found`)},configureServer(e){o&&(e.watcher.add(o.filePath),e.watcher.on(`change`,t=>{t===o?.filePath&&(s(`Proxy file changed, reloading...`),e.ws.send({type:`custom`,event:`rari:proxy-reload`}))}))},handleHotUpdate({file:e,server:t}){if(e===o?.filePath)return s(`Hot reloading proxy...`),t.ws.send({type:`custom`,event:`rari:proxy-reload`,data:{file:o.relativePath}}),[]}})}function ye(e){if(e==null||e===``)return null;let t=Number(e);return Number.isFinite(t)?t:null}function M(){let{SERVER_PORT:e,PORT:t,RSC_PORT:n}=D.env;return ye(e)??ye(t)??ye(n)??3e3}function be(){return`http://localhost:${M()}`}const xe=6e4;async function Se(e){let t=k(e).href,n=`
2
2
  import { registerHooks } from "node:module";
3
3
  registerHooks({
4
4
  resolve(specifier, context, nextResolve) {
@@ -16,8 +16,8 @@ const result =
16
16
  process.send(result, () => {
17
17
  process.disconnect();
18
18
  });
19
- `;return new Promise((t,r)=>{let i=pe(O.execPath,[`--conditions=react-server`,`--input-type=module`,`--eval`,n],{stdio:[`ignore`,`pipe`,`pipe`,`ipc`],env:O.env}),a=``,o=``,s=!1,c=!1,l,u,d,f=()=>{u!==void 0&&clearTimeout(u),d!==void 0&&clearTimeout(d),u=void 0,d=void 0};u=setTimeout(()=>{s||(s=!0,u!==void 0&&clearTimeout(u),u=void 0,i.kill(`SIGTERM`),d=setTimeout(()=>{i.kill(`SIGKILL`)},1e3),r(Error(`generateStaticParams timed out after ${xe}ms for ${e}`)))},xe),i.stdout?.setEncoding(`utf8`),i.stderr?.setEncoding(`utf8`),i.stdout?.on(`data`,e=>{a+=e}),i.stderr?.on(`data`,e=>{o+=e}),i.on(`message`,e=>{c=!0,l=e}),i.on(`error`,e=>{s||(s=!0,f(),r(e))}),i.on(`close`,n=>{if(f(),s)return;s=!0;let i=[o.trim(),a.trim()].filter(Boolean).join(`
20
- `);if(n!==0){r(Error(i||`generateStaticParams worker exited with code ${n}`));return}if(!c){r(Error(i||`generateStaticParams worker exited without an IPC result for ${e}`));return}t(l)})})}const N={PAGE:`page`,LAYOUT:`layout`,LOADING:`loading`,ERROR:`error`,NOT_FOUND:`not-found`,TEMPLATE:`template`,DEFAULT:`default`,ROUTE:`route`,OG_IMAGE:`opengraph-image`,TWITTER_IMAGE:`twitter-image`,ICON:`icon`,APPLE_ICON:`apple-icon`},Ce={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},we=[{pattern:Ce.OPTIONAL_CATCH_ALL,type:`optional-catch-all`,format:e=>`[[...${e}]]`},{pattern:Ce.CATCH_ALL,type:`catch-all`,format:e=>`[...${e}]`},{pattern:Ce.DYNAMIC,type:`dynamic`,format:e=>`[${e}]`}],Te=/^\([^/]+\)$/;function Ee(e){return Te.test(e)}function De(e){return e?e.replace(x,`/`).split(`/`).filter(Boolean).some(Ee):!1}function Oe(e){for(let t of we){let n=e.match(t.pattern);if(n)return{type:t.type,param:n[1],format:t.format}}}function ke(e){let t=Oe(e);return t?t.format(t.param):e}function Ae(e){let t=Oe(e);return t?{type:t.type,value:e,param:t.param}:{type:`static`,value:e}}const je=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,Me=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,Ne=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var Pe=class{appDir;extensions;verbose;constructor(e){this.appDir=D.resolve(e.appDir),this.extensions=[...e.extensions??[`.tsx`,`.jsx`,`.ts`,`.js`]],this.verbose=e.verbose??!1}async generateManifest(){this.verbose&&console.warn(`[rari] Router: Scanning app directory: ${this.appDir}`);let e=[],t=[],n=[],r=[],i=[],a=[],o=[],s=[];await this.scanDirectory(``,e,t,n,r,i,a,o,s);for(let o of[t,n,r,i,a,s])this.finalizeGroupEntries(e,o);return this.assertNoDuplicateRoutes(e),this.assertNoDuplicateRoutes(o),this.verbose&&(console.warn(`[rari] Router: Found ${e.length} routes`),console.warn(`[rari] Router: Found ${t.length} layouts`),console.warn(`[rari] Router: Found ${n.length} loading components`),console.warn(`[rari] Router: Found ${r.length} error boundaries`),console.warn(`[rari] Router: Found ${a.length} templates`),console.warn(`[rari] Router: Found ${o.length} API routes`),console.warn(`[rari] Router: Found ${s.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,templates:this.sortTemplates(a),apiRoutes:this.sortApiRoutes(o),ogImages:s,generated:new Date().toISOString()}}finalizeGroupEntries(e,t){for(let n=t.length-1;n>=0;n--){let r=t[n],i=D.dirname(r.filePath).replace(x,`/`);if(!De(i))continue;let a=e.filter(e=>{let t=D.dirname(e.filePath).replace(x,`/`);return t===i||t.startsWith(`${i}/`)}).map(e=>e.path);if(a.length===0){t.splice(n,1);continue}let o=Array.from(new Set(a)).sort();r.path=o[0],o.length>1&&(r.additionalPaths=o.slice(1))}}assertNoDuplicateRoutes(e){let t=new Map;for(let n of e){let e=t.get(n.path);if(e!=null&&e!==``)throw Error(`[rari] Route conflict: path '${n.path}' is defined by both '${e}' and '${n.filePath}'.`);t.set(n.path,n.filePath)}}async scanDirectory(e,t,n,r,i,a,o,s,c){let l=D.join(this.appDir,e),u;try{u=await E.readdir(l)}catch{return}let d=[],f=[];for(let e of u){let t=D.join(l,e),n=await E.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&f.push(e):n.isFile()&&d.push(e)}await this.processSpecialFiles(e,d,t,n,r,i,a,o,s,c);for(let l of f){let u=e?D.join(e,l):l;await this.scanDirectory(u,t,n,r,i,a,o,s,c)}}async processSpecialFiles(e,t,n,r,i,a,o,s,c,l){let u=this.pathToRoute(e),d=this.findFile(t,N.PAGE);if(d!=null&&d!==``){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:u,filePath:D.join(e,d).replace(x,`/`),segments:t,params:r,isDynamic:r.length>0})}let f=this.findFile(t,N.LAYOUT);if(f!=null&&f!==``){let t=this.getParentPath(e);r.push({path:u,filePath:D.join(e,f).replace(x,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let p=this.findFile(t,N.LOADING);p!=null&&p!==``&&i.push({path:u,filePath:D.join(e,p).replace(x,`/`)});let m=this.findFile(t,N.ERROR);m!=null&&m!==``&&a.push({path:u,filePath:D.join(e,m).replace(x,`/`)});let h=this.findFile(t,N.NOT_FOUND);h!=null&&h!==``&&o.push({path:u,filePath:D.join(e,h).replace(x,`/`)});let g=this.findFile(t,N.TEMPLATE);if(g!=null&&g!==``){let t=this.getParentPath(e);s.push({path:u,filePath:D.join(e,g).replace(x,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let _=this.findFile(t,N.OG_IMAGE);if(_!=null&&_!==``){let t=D.join(e,_).replace(x,`/`),n=D.join(this.appDir,t),r,i,a;try{let e=await E.readFile(n,`utf-8`),t=je.exec(e);t&&(r=Number.parseInt(t[1],10),i=Number.parseInt(t[2],10));let o=Me.exec(e);o&&(a=o[1])}catch{}l.push({path:u,filePath:t,width:r,height:i,contentType:a})}let v=this.findFile(t,N.ROUTE);if(v!=null&&v!==``){let t=await this.processApiRouteFile(e,v);c.push(t)}}findFile(e,t){for(let n of this.extensions){let r=`${t}${n}`;if(e.includes(r))return r}}pathToRoute(e){return e?`/${e.replace(x,`/`).split(`/`).filter(Boolean).filter(e=>!Ee(e)).map(ke).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(h).filter(Boolean).filter(e=>!Ee(e)).map(Ae):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(h).filter(Boolean);return t.length===0?null:t.slice(0,-1).join(`/`)}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!e.startsWith(`_`)&&!e.startsWith(`.`)}sortRoutes(e){return e.sort((e,t)=>{let n=e=>{if(!e.isDynamic)return 0;let t=e.segments.some(e=>e.type===`catch-all`);return e.segments.some(e=>e.type===`optional-catch-all`)?3:t?2:1},r=n(e),i=n(t);if(r!==i)return r-i;let a=e.path.split(`/`).length,o=t.path.split(`/`).length;return a===o?e.path.localeCompare(t.path):o-a})}sortApiRoutes(e){return e.sort((e,t)=>{if(!e.isDynamic&&t.isDynamic)return-1;if(e.isDynamic&&!t.isDynamic)return 1;let n=e.path.split(`/`).length,r=t.path.split(`/`).length;return n===r?e.path.localeCompare(t.path):n-r})}sortLayouts(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}sortTemplates(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}async detectHttpMethods(e){let t=D.join(this.appDir,e),n=await E.readFile(t,`utf-8`),r=[];for(let e of Ne){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||i.test(n))&&r.push(e)}return r}async processApiRouteFile(e,t){let n=D.join(e,t).replace(x,`/`),r=this.pathToRoute(e),i=this.parseRouteSegments(e),a=this.extractParams(i),o=await this.detectHttpMethods(n);return{path:r,filePath:n,segments:i,params:a,isDynamic:a.length>0,methods:o}}};async function Fe(e,t={}){return new Pe({appDir:e,...t}).generateManifest()}const Ie=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,Le=/title\s*:\s*['"]([^'"]+)['"]/,Re=/description\s*:\s*['"]([^'"]+)['"]/,ze=/keywords\s*:\s*\[([\s\S]*?)\]/,Be={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function Ve(e){switch(D.basename(e).replace(_,``)){case`page`:return`page`;case`layout`:return`layout`;case`template`:return`template`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function He(e){return/^\([^/]+\)$/.test(e)}function Ue(e){if(!e||e===`/`)return`/`;let t=e.replace(x,`/`).split(`/`).filter(e=>!!e&&!He(e));return t.length>0?`/${t.join(`/`)}`:`/`}function We(e,t){let n=D.relative(t,D.dirname(e));return!n||n===`.`?`/`:Ue(`/${n.replace(x,`/`).split(`/`).filter(Boolean).join(`/`)}`)}function Ge(e,t,n){if(t===`page`)return[e];let r=`${e}${e===`/`?``:`/`}`,i=n.filter(t=>t===e||t.startsWith(r));return i.length>0?i:[e]}function Ke(e){try{let t=Ie.exec(e);if(!t)return null;let n=t[1],r={},i=Le.exec(n);i&&(r.title=i[1]);let a=Re.exec(n);a&&(r.description=a[1]);let o=ze.exec(n);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(te,``)).filter(Boolean));for(let e of[`author`,`viewport`,`themeColor`,`robots`,`openGraph`,`twitter`]){let t=RegExp(`${e}\\s*:\\s*['"]([^'"]+)['"]`,`m`),i=n.match(t);i&&(r[e]=i[1])}return Object.keys(r).length>0?r:null}catch(e){return console.error(`[rari] Router: Failed to extract metadata:`,e),null}}function qe(e){let t=[];for(let n of[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]){let r=RegExp(`export\\s+(?:async\\s+)?function\\s+${n}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${n}\\s*=`);(r.test(e)||i.test(e))&&t.push(n)}return t}function Je(e){return a(e)&&Array.isArray(e.routes)}async function Ye(e){try{let n=await fetch(`${be()}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate-api-route`,filePath:e})});if(!n.ok){console.error(`[rari] Router: Failed to invalidate API route cache: ${n.statusText}`);return}let r=t(await n.text());if(r?.success!==!0){let e=typeof r?.error==`string`&&r.error!==``?r.error:`Unknown error`;console.error(`[rari] HMR: Failed to invalidate API route cache: ${e}`)}}catch(e){console.error(`[rari] Router: Failed to notify API route invalidation:`,e)}}function Xe(e={}){let n={...Be,...e},i=null,a=new Map,o=null,s=new Set,l=e=>[...e].toSorted().join(`|`),u=async e=>{let t=new Set,r=async e=>{try{let i=await E.readdir(e,{withFileTypes:!0});for(let a of i){let i=D.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&n.extensions.some(e=>a.name.endsWith(e))&&Ve(i)&&t.add(i)}}catch{}};return await r(e),t},d=async(e,t=!1)=>{let r=D.resolve(e,n.appDir);try{await E.access(r)}catch{return null}try{let a=await u(r),c=l(a);if(!t&&o===c&&i!=null&&i!==``)return i;let d=await Fe(r,{extensions:n.extensions}),f=JSON.stringify(d),p=D.resolve(e,n.outDir);await E.mkdir(p,{recursive:!0});let m=D.join(p,`server`);return await E.mkdir(m,{recursive:!0}),await E.writeFile(D.join(m,`routes.json`),f,`utf-8`),o=c,s.clear(),a.forEach(e=>{s.add(e)}),f}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},f=e=>{let t=D.resolve(e.config.root,n.appDir);e.watcher.on(`all`,(r,i)=>{(async()=>{if(i.startsWith(t)&&n.extensions.some(e=>i.endsWith(e)))try{let t=Ve(i)!==null,a=r===`add`||r===`unlink`,o=t&&!s.has(i);(a||o)&&(await d(e.config.root,!0),i.includes(n.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})()})},p;return _e({name:`rari-router`,configResolved(e){p=e.root;let t=e.logger.warn.bind(e.logger);e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`The above dynamic import cannot be analyzed`)&&e.includes(`packages/rari/dist/`)||t(e,n)}},async writeBundle(){let e=p||O.cwd();i=await d(e,!0)},configureServer(e){f(e)},async handleHotUpdate(e){let{file:r,server:o}=e,c=D.resolve(o.config.root,n.appDir);if(r.startsWith(c)&&n.extensions.some(e=>r.endsWith(e))){let e=Ve(r);if(e){let n=a.get(r);n&&clearTimeout(n);let l=setTimeout(()=>{(async()=>{a.delete(r);let n=!s.has(r),l=i;i=await d(o.config.root,n);let u=l!==i,f=We(r,c),p=[f];if(i!=null&&i!==``)try{let e=t(i);e&&Je(e)&&(p=e.routes.map(e=>e.path))}catch(e){console.error(`[rari] Router: Failed to parse manifest for affected routes:`,e)}let m=Ge(f,e,p),h,g=!1,_;if(e===`page`||e===`layout`)try{let e=Ke(await E.readFile(r,`utf-8`));e&&(h=e,g=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{_=qe(await E.readFile(r,`utf-8`)),await Ye(D.relative(c,r))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let v={fileType:e,filePath:D.relative(o.config.root,r),routePath:f,affectedRoutes:m,manifestUpdated:u,timestamp:Date.now(),metadata:h,metadataChanged:g,methods:_};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:v})})()},200);return a.set(r,l),[]}return i=await d(o.config.root),[]}},async closeBundle(){for(let e of a.values())clearTimeout(e);a.clear();let e=p||O.cwd(),i=D.resolve(e,n.outDir,`server`),o=D.join(i,`routes.json`);try{let e=await E.readFile(o,`utf-8`),n=t(e);if(!n||!Je(n))return;let a=n,s=a.routes.flatMap(e=>{if(!e.isDynamic)return[];let t=e.componentId;return t==null||t===``?[]:[{route:e,componentId:t}]}),l=Math.min(8,Math.max(1,s.length)),u=s.map(()=>!1),d=0,f=0;await new Promise(e=>{let t=()=>{for(;f<l&&d<s.length;){let n=d++,{route:a,componentId:o}=s[n],l=D.join(i,`${o}.js`);f++,(async()=>{try{let e=await Se(l);if(e==null)return;r(e)?(a.staticParams=e,u[n]=!0):c(o)}catch(e){console.warn(`[rari] Failed to evaluate generateStaticParams for ${o}:`,e)}finally{f--,d>=s.length&&f===0?e():t()}})()}s.length===0&&e()};t()}),u.some(Boolean)&&await E.writeFile(o,JSON.stringify(a),`utf-8`)}catch(e){console.warn(`[rari] Failed to enrich routes manifest with static params:`,e)}}})}function Ze(e,t,n,r){let i=e.indexOf(t);if(i===-1)throw Error(`Failed to patch flight browser client: anchor for ${r} not found. The react-server-dom-webpack sources likely changed shape after a version bump; update the anchors in patch-flight-browser-client.ts.`);if(e.includes(t,i+1))throw Error(`Failed to patch flight browser client: anchor for ${r} matched more than once. Update the anchors in patch-flight-browser-client.ts to be unambiguous.`);return e.slice(0,i)+n+e.slice(i+t.length)}function Qe(e,t){let n=t.indexOf(`var boundCache = new WeakMap();`),r=t.indexOf(`function createBoundServerReference`,n);if(n===-1||r===-1)throw Error(`Failed to locate edge client form-action helpers for browser patch`);return Ze(e,`function registerBoundServerReference(reference, id, bound) {
19
+ `;return new Promise((t,r)=>{let i=me(D.execPath,[`--conditions=react-server`,`--input-type=module`,`--eval`,n],{stdio:[`ignore`,`pipe`,`pipe`,`ipc`],env:D.env}),a=``,o=``,s=!1,c=!1,l,u,d,f=()=>{u!==void 0&&clearTimeout(u),d!==void 0&&clearTimeout(d),u=void 0,d=void 0};u=setTimeout(()=>{s||(s=!0,u!==void 0&&clearTimeout(u),u=void 0,i.kill(`SIGTERM`),d=setTimeout(()=>{i.kill(`SIGKILL`)},1e3),r(Error(`generateStaticParams timed out after ${xe}ms for ${e}`)))},xe),i.stdout?.setEncoding(`utf8`),i.stderr?.setEncoding(`utf8`),i.stdout?.on(`data`,e=>{a+=e}),i.stderr?.on(`data`,e=>{o+=e}),i.on(`message`,e=>{c=!0,l=e}),i.on(`error`,e=>{s||(s=!0,f(),r(e))}),i.on(`close`,n=>{if(f(),s)return;s=!0;let i=[o.trim(),a.trim()].filter(Boolean).join(`
20
+ `);if(n!==0){r(Error(i||`generateStaticParams worker exited with code ${n}`));return}if(!c){r(Error(i||`generateStaticParams worker exited without an IPC result for ${e}`));return}t(l)})})}const N={PAGE:`page`,LAYOUT:`layout`,LOADING:`loading`,ERROR:`error`,NOT_FOUND:`not-found`,TEMPLATE:`template`,DEFAULT:`default`,ROUTE:`route`,OG_IMAGE:`opengraph-image`,TWITTER_IMAGE:`twitter-image`,ICON:`icon`,APPLE_ICON:`apple-icon`},Ce={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},we=[{pattern:Ce.OPTIONAL_CATCH_ALL,type:`optional-catch-all`,format:e=>`[[...${e}]]`},{pattern:Ce.CATCH_ALL,type:`catch-all`,format:e=>`[...${e}]`},{pattern:Ce.DYNAMIC,type:`dynamic`,format:e=>`[${e}]`}],Te=/^\([^/]+\)$/;function Ee(e){return Te.test(e)}function De(e){return e?e.replace(x,`/`).split(`/`).filter(Boolean).some(Ee):!1}function Oe(e){for(let t of we){let n=e.match(t.pattern);if(n)return{type:t.type,param:n[1],format:t.format}}}function ke(e){let t=Oe(e);return t?t.format(t.param):e}function Ae(e){let t=Oe(e);return t?{type:t.type,value:e,param:t.param}:{type:`static`,value:e}}const je=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,Me=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,Ne=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var Pe=class{appDir;extensions;verbose;constructor(e){this.appDir=E.resolve(e.appDir),this.extensions=[...e.extensions??[`.tsx`,`.jsx`,`.ts`,`.js`]],this.verbose=e.verbose??!1}async generateManifest(){this.verbose&&console.warn(`[rari] Router: Scanning app directory: ${this.appDir}`);let e=[],t=[],n=[],r=[],i=[],a=[],o=[],s=[];await this.scanDirectory(``,e,t,n,r,i,a,o,s);for(let o of[t,n,r,i,a,s])this.finalizeGroupEntries(e,o);return this.assertNoDuplicateRoutes(e),this.assertNoDuplicateRoutes(o),this.verbose&&(console.warn(`[rari] Router: Found ${e.length} routes`),console.warn(`[rari] Router: Found ${t.length} layouts`),console.warn(`[rari] Router: Found ${n.length} loading components`),console.warn(`[rari] Router: Found ${r.length} error boundaries`),console.warn(`[rari] Router: Found ${a.length} templates`),console.warn(`[rari] Router: Found ${o.length} API routes`),console.warn(`[rari] Router: Found ${s.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,templates:this.sortTemplates(a),apiRoutes:this.sortApiRoutes(o),ogImages:s,generated:new Date().toISOString()}}finalizeGroupEntries(e,t){for(let n=t.length-1;n>=0;n--){let r=t[n],i=E.dirname(r.filePath).replace(x,`/`);if(!De(i))continue;let a=e.filter(e=>{let t=E.dirname(e.filePath).replace(x,`/`);return t===i||t.startsWith(`${i}/`)}).map(e=>e.path);if(a.length===0){t.splice(n,1);continue}let o=Array.from(new Set(a)).sort();r.path=o[0],o.length>1&&(r.additionalPaths=o.slice(1))}}assertNoDuplicateRoutes(e){let t=new Map;for(let n of e){let e=t.get(n.path);if(e!=null&&e!==``)throw Error(`[rari] Route conflict: path '${n.path}' is defined by both '${e}' and '${n.filePath}'.`);t.set(n.path,n.filePath)}}async scanDirectory(e,t,n,r,i,a,o,s,c){let l=E.join(this.appDir,e),u;try{u=await T.readdir(l)}catch{return}let d=[],f=[];for(let e of u){let t=E.join(l,e),n=await T.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&f.push(e):n.isFile()&&d.push(e)}await this.processSpecialFiles(e,d,t,n,r,i,a,o,s,c);for(let l of f){let u=e?E.join(e,l):l;await this.scanDirectory(u,t,n,r,i,a,o,s,c)}}async processSpecialFiles(e,t,n,r,i,a,o,s,c,l){let u=this.pathToRoute(e),d=this.findFile(t,N.PAGE);if(d!=null&&d!==``){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:u,filePath:E.join(e,d).replace(x,`/`),segments:t,params:r,isDynamic:r.length>0})}let f=this.findFile(t,N.LAYOUT);if(f!=null&&f!==``){let t=this.getParentPath(e);r.push({path:u,filePath:E.join(e,f).replace(x,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let p=this.findFile(t,N.LOADING);p!=null&&p!==``&&i.push({path:u,filePath:E.join(e,p).replace(x,`/`)});let m=this.findFile(t,N.ERROR);m!=null&&m!==``&&a.push({path:u,filePath:E.join(e,m).replace(x,`/`)});let h=this.findFile(t,N.NOT_FOUND);h!=null&&h!==``&&o.push({path:u,filePath:E.join(e,h).replace(x,`/`)});let g=this.findFile(t,N.TEMPLATE);if(g!=null&&g!==``){let t=this.getParentPath(e);s.push({path:u,filePath:E.join(e,g).replace(x,`/`),parentPath:t===null?void 0:this.pathToRoute(t)})}let _=this.findFile(t,N.OG_IMAGE);if(_!=null&&_!==``){let t=E.join(e,_).replace(x,`/`),n=E.join(this.appDir,t),r,i,a;try{let e=await T.readFile(n,`utf-8`),t=je.exec(e);t&&(r=Number.parseInt(t[1],10),i=Number.parseInt(t[2],10));let o=Me.exec(e);o&&(a=o[1])}catch{}l.push({path:u,filePath:t,width:r,height:i,contentType:a})}let v=this.findFile(t,N.ROUTE);if(v!=null&&v!==``){let t=await this.processApiRouteFile(e,v);c.push(t)}}findFile(e,t){for(let n of this.extensions){let r=`${t}${n}`;if(e.includes(r))return r}}pathToRoute(e){return e?`/${e.replace(x,`/`).split(`/`).filter(Boolean).filter(e=>!Ee(e)).map(ke).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(h).filter(Boolean).filter(e=>!Ee(e)).map(Ae):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(h).filter(Boolean);return t.length===0?null:t.slice(0,-1).join(`/`)}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!e.startsWith(`_`)&&!e.startsWith(`.`)}sortRoutes(e){return e.sort((e,t)=>{let n=e=>{if(!e.isDynamic)return 0;let t=e.segments.some(e=>e.type===`catch-all`);return e.segments.some(e=>e.type===`optional-catch-all`)?3:t?2:1},r=n(e),i=n(t);if(r!==i)return r-i;let a=e.path.split(`/`).length,o=t.path.split(`/`).length;return a===o?e.path.localeCompare(t.path):o-a})}sortApiRoutes(e){return e.sort((e,t)=>{if(!e.isDynamic&&t.isDynamic)return-1;if(e.isDynamic&&!t.isDynamic)return 1;let n=e.path.split(`/`).length,r=t.path.split(`/`).length;return n===r?e.path.localeCompare(t.path):n-r})}sortLayouts(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}sortTemplates(e){return e.sort((e,t)=>e.path===`/`&&t.path!==`/`?-1:t.path===`/`&&e.path!==`/`?1:e.path.split(`/`).length-t.path.split(`/`).length)}async detectHttpMethods(e){let t=E.join(this.appDir,e),n=await T.readFile(t,`utf-8`),r=[];for(let e of Ne){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||i.test(n))&&r.push(e)}return r}async processApiRouteFile(e,t){let n=E.join(e,t).replace(x,`/`),r=this.pathToRoute(e),i=this.parseRouteSegments(e),a=this.extractParams(i),o=await this.detectHttpMethods(n);return{path:r,filePath:n,segments:i,params:a,isDynamic:a.length>0,methods:o}}};async function Fe(e,t={}){return new Pe({appDir:e,...t}).generateManifest()}const Ie=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,Le=/title\s*:\s*['"]([^'"]+)['"]/,Re=/description\s*:\s*['"]([^'"]+)['"]/,ze=/keywords\s*:\s*\[([\s\S]*?)\]/,Be={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function Ve(e){switch(E.basename(e).replace(_,``)){case`page`:return`page`;case`layout`:return`layout`;case`template`:return`template`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function He(e){return/^\([^/]+\)$/.test(e)}function Ue(e){if(!e||e===`/`)return`/`;let t=e.replace(x,`/`).split(`/`).filter(e=>!!e&&!He(e));return t.length>0?`/${t.join(`/`)}`:`/`}function We(e,t){let n=E.relative(t,E.dirname(e));return!n||n===`.`?`/`:Ue(`/${n.replace(x,`/`).split(`/`).filter(Boolean).join(`/`)}`)}function Ge(e,t,n){if(t===`page`)return[e];let r=`${e}${e===`/`?``:`/`}`,i=n.filter(t=>t===e||t.startsWith(r));return i.length>0?i:[e]}function Ke(e){try{let t=Ie.exec(e);if(!t)return null;let n=t[1],r={},i=Le.exec(n);i&&(r.title=i[1]);let a=Re.exec(n);a&&(r.description=a[1]);let o=ze.exec(n);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(te,``)).filter(Boolean));for(let e of[`author`,`viewport`,`themeColor`,`robots`,`openGraph`,`twitter`]){let t=RegExp(`${e}\\s*:\\s*['"]([^'"]+)['"]`,`m`),i=n.match(t);i&&(r[e]=i[1])}return Object.keys(r).length>0?r:null}catch(e){return console.error(`[rari] Router: Failed to extract metadata:`,e),null}}function qe(e){let t=[];for(let n of[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`]){let r=RegExp(`export\\s+(?:async\\s+)?function\\s+${n}\\s*\\(`),i=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${n}\\s*=`);(r.test(e)||i.test(e))&&t.push(n)}return t}function Je(e){return a(e)&&Array.isArray(e.routes)}async function Ye(e){try{let n=await fetch(`${be()}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate-api-route`,filePath:e})});if(!n.ok){console.error(`[rari] Router: Failed to invalidate API route cache: ${n.statusText}`);return}let r=t(await n.text());if(r?.success!==!0){let e=typeof r?.error==`string`&&r.error!==``?r.error:`Unknown error`;console.error(`[rari] HMR: Failed to invalidate API route cache: ${e}`)}}catch(e){console.error(`[rari] Router: Failed to notify API route invalidation:`,e)}}function Xe(e={}){let n={...Be,...e},i=null,a=new Map,o=null,s=new Set,l=e=>[...e].toSorted().join(`|`),u=async e=>{let t=new Set,r=async e=>{try{let i=await T.readdir(e,{withFileTypes:!0});for(let a of i){let i=E.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&n.extensions.some(e=>a.name.endsWith(e))&&Ve(i)&&t.add(i)}}catch{}};return await r(e),t},d=async(e,t=!1)=>{let r=E.resolve(e,n.appDir);try{await T.access(r)}catch{return null}try{let a=await u(r),c=l(a);if(!t&&o===c&&i!=null&&i!==``)return i;let d=await Fe(r,{extensions:n.extensions}),f=JSON.stringify(d),p=E.resolve(e,n.outDir);await T.mkdir(p,{recursive:!0});let m=E.join(p,`server`);return await T.mkdir(m,{recursive:!0}),await T.writeFile(E.join(m,`routes.json`),f,`utf-8`),o=c,s.clear(),a.forEach(e=>{s.add(e)}),f}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},f=e=>{let t=E.resolve(e.config.root,n.appDir);e.watcher.on(`all`,(r,i)=>{(async()=>{if(i.startsWith(t)&&n.extensions.some(e=>i.endsWith(e)))try{let t=Ve(i)!==null,a=r===`add`||r===`unlink`,o=t&&!s.has(i);(a||o)&&(await d(e.config.root,!0),i.includes(n.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})()})},p;return _e({name:`rari-router`,configResolved(e){p=e.root;let t=e.logger.warn.bind(e.logger);e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`The above dynamic import cannot be analyzed`)&&e.includes(`packages/rari/dist/`)||t(e,n)}},async writeBundle(){let e=p||D.cwd();i=await d(e,!0)},configureServer(e){f(e)},async handleHotUpdate(e){let{file:r,server:o}=e,c=E.resolve(o.config.root,n.appDir);if(r.startsWith(c)&&n.extensions.some(e=>r.endsWith(e))){let e=Ve(r);if(e){let n=a.get(r);n&&clearTimeout(n);let l=setTimeout(()=>{(async()=>{a.delete(r);let n=!s.has(r),l=i;i=await d(o.config.root,n);let u=l!==i,f=We(r,c),p=[f];if(i!=null&&i!==``)try{let e=t(i);e&&Je(e)&&(p=e.routes.map(e=>e.path))}catch(e){console.error(`[rari] Router: Failed to parse manifest for affected routes:`,e)}let m=Ge(f,e,p),h,g=!1,_;if(e===`page`||e===`layout`)try{let e=Ke(await T.readFile(r,`utf-8`));e&&(h=e,g=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{_=qe(await T.readFile(r,`utf-8`)),await Ye(E.relative(c,r))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let v={fileType:e,filePath:E.relative(o.config.root,r),routePath:f,affectedRoutes:m,manifestUpdated:u,timestamp:Date.now(),metadata:h,metadataChanged:g,methods:_};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:v})})()},200);return a.set(r,l),[]}return i=await d(o.config.root),[]}},async closeBundle(){for(let e of a.values())clearTimeout(e);a.clear();let e=p||D.cwd(),i=E.resolve(e,n.outDir,`server`),o=E.join(i,`routes.json`);try{let e=await T.readFile(o,`utf-8`),n=t(e);if(!n||!Je(n))return;let a=n,s=a.routes.flatMap(e=>{if(!e.isDynamic)return[];let t=e.componentId;return t==null||t===``?[]:[{route:e,componentId:t}]}),l=Math.min(8,Math.max(1,s.length)),u=s.map(()=>!1),d=0,f=0;await new Promise(e=>{let t=()=>{for(;f<l&&d<s.length;){let n=d++,{route:a,componentId:o}=s[n],l=E.join(i,`${o}.js`);f++,(async()=>{try{let e=await Se(l);if(e==null)return;r(e)?(a.staticParams=e,u[n]=!0):c(o)}catch(e){console.warn(`[rari] Failed to evaluate generateStaticParams for ${o}:`,e)}finally{f--,d>=s.length&&f===0?e():t()}})()}s.length===0&&e()};t()}),u.some(Boolean)&&await T.writeFile(o,JSON.stringify(a),`utf-8`)}catch(e){console.warn(`[rari] Failed to enrich routes manifest with static params:`,e)}}})}function Ze(e,t,n,r){let i=e.indexOf(t);if(i===-1)throw Error(`Failed to patch flight browser client: anchor for ${r} not found. The react-server-dom-webpack sources likely changed shape after a version bump; update the anchors in patch-flight-browser-client.ts.`);if(e.includes(t,i+1))throw Error(`Failed to patch flight browser client: anchor for ${r} matched more than once. Update the anchors in patch-flight-browser-client.ts to be unambiguous.`);return e.slice(0,i)+n+e.slice(i+t.length)}function Qe(e,t){let n=t.indexOf(`var boundCache = new WeakMap();`),r=t.indexOf(`function createBoundServerReference`,n);if(n===-1||r===-1)throw Error(`Failed to locate edge client form-action helpers for browser patch`);return Ze(e,`function registerBoundServerReference(reference, id, bound) {
21
21
  knownServerReferences.has(reference) ||
22
22
  knownServerReferences.set(reference, {
23
23
  id: id,
@@ -44,8 +44,8 @@ process.send(result, () => {
44
44
  encType: "multipart/form-data",
45
45
  action: resolveRariFormActionUrl(),
46
46
  data: data
47
- };`,`edge $$FORM_ACTION return block`),`browser registerBoundServerReference`)}function P(e,t=8){return j.createHash(`sha256`).update(e).digest(`hex`).slice(0,t)}function $e(e,t=O.cwd()){let n=D.isAbsolute(e)?e:D.resolve(t,e),r=D.relative(t,n);return D.isAbsolute(r)?n.replace(x,`/`):r.replace(x,`/`)}function et(e){return e.replace(_,``).replace(b,`_`).replace(y,``)}function tt(e,t=O.cwd()){let n=$e(e,t);return`${et(n)}_${P(n)}`}const nt=new Set([`return`,`throw`,`case`,`typeof`,`instanceof`,`new`,`delete`,`void`,`in`,`of`]),rt=8232,it=8233;function F(e){return e===32||e===9||e===13||e===10||e===rt||e===it||e===65279}function I(e){return e===13||e===10||e===rt||e===it}function L(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function at(e){return e>=97&&e<=122||e>=65&&e<=90||e===95||e===36}function ot(e,t,n){for(;t<n&&F(e.charCodeAt(t));)t++;return t}function R(e,t,n){for(;t<n;){let r=ot(e,t,n);if(r!==t){t=r;continue}let i=e.charCodeAt(t);if(i===47&&e.charCodeAt(t+1)===47){t=z(e,t,n);continue}if(i===47&&e.charCodeAt(t+1)===42){t=B(e,t,n);continue}break}return t}function z(e,t,n){for(;t<n&&!I(e.charCodeAt(t));)t++;return t}function B(e,t,n){for(t+=2;t<n-1&&(e.charCodeAt(t)!==42||e.charCodeAt(t+1)!==47);)t++;return t+2}function V(e,t,n,r){for(t++;t<n;){let n=e.charCodeAt(t);if(n===92){t+=2;continue}if(n===r)return t+1;t++}return t}function st(e,t,n){t++;let r=e.charCodeAt(t)===47;for(r&&t++;t<n;){let n=e.charCodeAt(t);if(L(n)||n===46||n===45)t++;else break}let i=+!r;for(;t<n&&i>0;){let a=e.charCodeAt(t);if(a===39||a===34||a===96){t=V(e,t,n,a);continue}if(a===123){t++;let r=1;for(;t<n&&r>0;){let i=e.charCodeAt(t);if(i===39||i===34||i===96){t=V(e,t,n,i);continue}i===123&&r++,i===125&&r--,t++}continue}if(a===47&&e.charCodeAt(t+1)===62){i--,t+=2;continue}if(a===62){t++,r&&i--;continue}if(a===60){let r=e.charCodeAt(t+1);if(r===47||r===46||r===62||at(r)){for(r===47?(i--,t++):r!==33&&i++,t++;t<n;){let n=e.charCodeAt(t);if(L(n)||n===46||n===45)t++;else break}continue}t++;continue}t++}return t}function ct(e,t,n){for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;return!0}function H(e,t,n){if(t+n.length>e.length)return!1;for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;let r=t>0?e.charCodeAt(t-1):-1,i=t+n.length,a=i<e.length?e.charCodeAt(i):-1;return!(r!==-1&&L(r)||a!==-1&&L(a))}function U(e,t,n){let r=R(e,t,n);if(r>=n)return null;let i=e.charCodeAt(r);if(i!==39&&i!==34)return null;let a=r+1,o=V(e,r,n,i);return o<=a?null:{source:e.slice(a,o-1),end:o}}function lt(e,t,n){if(!H(e,t,`import`))return{sources:[],end:t+6};let r=t+6;if(r=R(e,r,n),H(e,r,`type`)&&(r=R(e,r+4,n)),e.charCodeAt(r)===46){for(r++;r<n&&L(e.charCodeAt(r));)r++;for(;r<n&&e.charCodeAt(r)===46;)for(r++;r<n&&L(e.charCodeAt(r));)r++;return{sources:[],end:r}}if(e.charCodeAt(r)===40){r++;let t=U(e,r,n);return t?{sources:[t.source],end:t.end}:{sources:[],end:r}}let i=U(e,r,n);if(i)return{sources:[i.source],end:i.end};let a=0;for(;r<n&&(r=R(e,r,n),!(r>=n));){let t=e.charCodeAt(r);if(a===0&&H(e,r,`from`)){let t=U(e,r+4,n);if(t)return{sources:[t.source],end:t.end};break}if(t===39||t===34||t===96){r=V(e,r,n,t);continue}t===123||t===40||t===91?a++:(t===125||t===41||t===93)&&(a=Math.max(0,a-1)),r++}return{sources:[],end:r}}function ut(e,t){return e.charCodeAt(t)===101&&e.charCodeAt(t+1)===120&&e.charCodeAt(t+2)===112&&e.charCodeAt(t+3)===111&&e.charCodeAt(t+4)===114&&e.charCodeAt(t+5)===116}function dt(e,t){return e.charCodeAt(t)===100&&e.charCodeAt(t+1)===101&&e.charCodeAt(t+2)===102&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===117&&e.charCodeAt(t+5)===108&&e.charCodeAt(t+6)===116}function W(e){let t={hasUseClient:!1,hasUseServer:!1},n=!1,r=!1,i=!1,a=!1,o=[],s=!0,c=!1,l=0,u=e.length;for(;l<u;){let d=e.charCodeAt(l);if(s&&(d===39||d===34)){let i=l+1,a=V(e,l,u,d);if(a<=i){s=!1,l++;continue}let o=a-1-i,f=o===10&&ct(e,i,`use client`),p=o===10&&ct(e,i,`use server`);c||(c=!0,n=f,r=p),f&&(t.hasUseClient=!0),p&&(t.hasUseServer=!0);let m=a,h=!1;for(;m<u;){let t=e.charCodeAt(m);if(F(t)&&!I(t)){m++;continue}if(I(t)||t===59){h=!0,l=m+1;break}if(t===47&&e.charCodeAt(m+1)===47){m=z(e,m,u);continue}if(t===47&&e.charCodeAt(m+1)===42){m=B(e,m,u);continue}s=!1,h=!1;break}if(!h){m>=u&&(s=!1),l=s?a:m;continue}continue}let f=K(e,l,u);if(f!==-1){s&&!Dt(e,l)&&(s=!1),l=f;continue}if(s=!1,H(e,l,`import`)){let t=lt(e,l,u);for(let e of t.sources)o.push(e);l=t.end;continue}if(ut(e,l)){let t=l+6;if(t<u){let n=e.charCodeAt(t);if(F(n)||n===123||n===47&&(e.charCodeAt(t+1)===47||e.charCodeAt(t+1)===42)){let n=R(e,t,u);if(dt(e,n)){i=!0,a=!0;let r=n+7;if(r>=u||!L(e.charCodeAt(r))){l=t;continue}}if(e.charCodeAt(n)===123){let t=n+1;for(;t<u&&(t=R(e,t,u),e.charCodeAt(t)!==125);){let n=t;for(;t<u&&L(e.charCodeAt(t));)t++;let r=t-n;if(r===0)break;t=R(e,t,u);let o=!1;if(e.charCodeAt(t)===97&&e.charCodeAt(t+1)===115){o=!0;let n=t+2;if(n<u&&!L(e.charCodeAt(n))){t=R(e,n,u);let r=t;for(;t<u&&L(e.charCodeAt(t));)t++;t-r===7&&dt(e,r)&&(i=!0,a=!0)}}if(!o&&r===7&&dt(e,n)&&(i=!0,a=!0),e.charCodeAt(t)===44){t++;continue}if(e.charCodeAt(t)===125)break;t++}}else(H(e,n,`async`)||H(e,n,`function`)||H(e,n,`class`))&&(a=!0)}}}l++}return{directives:t,topLevelUseClient:n,topLevelUseServer:r,hasDefaultExport:i,hasComponentExport:a,importSources:[...new Set(o)]}}function G(e,t,n){if(t>=n||!at(e.charCodeAt(t)))return null;let r=t+1;for(;r<n&&L(e.charCodeAt(r));)r++;return{name:e.slice(t,r),end:r}}function ft(e,t,n){let r=t;for(;r<n;){let t=e.charCodeAt(r);if(t===32||t===9){r++;continue}if(t===59)return r+1;break}return t}function pt(e,t,n){let r=[],i=t+1;for(;;){if(i=R(e,i,n),i>=n)return null;if(e.charCodeAt(i)===125)return{named:r,end:i+1};let t=!1;if(H(e,i,`type`)){let r=R(e,i+4,n),a=e.charCodeAt(r);(a===39||a===34||G(e,r,n)!==null)&&!H(e,r,`as`)&&(t=!0,i=r)}let a,o=e.charCodeAt(i);if(o===39||o===34){let t=V(e,i,n,o);a=e.slice(i+1,t-1),i=t}else{let t=G(e,i,n);if(!t)return null;a=t.name,i=t.end}i=R(e,i,n);let s=a;if(H(e,i,`as`)){i=R(e,i+2,n);let t=G(e,i,n);if(!t)return null;s=t.name,i=R(e,t.end,n)}r.push({imported:a,local:s,typeOnly:t});let c=e.charCodeAt(i);if(c===44){i++;continue}return c===125?{named:r,end:i+1}:null}}function mt(e,t,n){let r=R(e,t+6,n);if(r>=n)return null;let i=e.charCodeAt(r);if(i===40||i===46)return null;if(i===39||i===34){let i=U(e,r,n);return i?{start:t,end:ft(e,i.end,n),source:i.source,typeOnly:!1,sideEffectOnly:!0,defaultBinding:null,namespaceBinding:null,named:[]}:null}let a=!1;if(H(e,r,`type`)){let t=R(e,r+4,n);!H(e,t,`from`)&&e.charCodeAt(t)!==44&&(a=!0,r=t)}let o=null,s=null,c=[],l=e.charCodeAt(r);if(l!==123&&l!==42){let t=G(e,r,n);if(!t)return null;o=t.name,r=R(e,t.end,n),e.charCodeAt(r)===44?(r=R(e,r+1,n),l=e.charCodeAt(r)):l=-1}if(l===42){if(r=R(e,r+1,n),!H(e,r,`as`))return null;r=R(e,r+2,n);let t=G(e,r,n);if(!t)return null;s=t.name,r=t.end}else if(l===123){let t=pt(e,r,n);if(!t)return null;c=t.named,r=t.end}if(r=R(e,r,n),!H(e,r,`from`))return null;let u=U(e,r+4,n);return u?{start:t,end:ft(e,u.end,n),source:u.source,typeOnly:a,sideEffectOnly:!1,defaultBinding:o,namespaceBinding:s,named:c}:null}function ht(e){let t=[],n=0,r=e.length;for(;n<r;){let i=K(e,n,r);if(i!==-1){n=i;continue}if(H(e,n,`import`)){let i=mt(e,n,r);if(i){t.push(i),n=i.end;continue}n+=6;continue}n++}return t}function gt(e){let t=new Set,n=0,r=e.length;for(;n<r;){let i=K(e,n,r);if(i!==-1){n=i;continue}if(!H(e,n,`export`)){n++;continue}let a=R(e,n+6,r);if(H(e,a,`type`)||H(e,a,`interface`)){n=a+1;continue}if(e.charCodeAt(a)===42){let i=R(e,a+1,r);if(H(e,i,`as`)){i=R(e,i+2,r);let a=G(e,i,r);a&&t.add(a.name),n=a?.end??i+1}else n=a+1;continue}if(H(e,a,`default`)){t.add(`default`),n=a+7;continue}if(e.charCodeAt(a)===123){let i=_t(e,a,r),o=e.slice(a+1,i-1);for(let e of o.split(`,`)){let n=e.trim();if(!n||n.startsWith(`type `)||n.startsWith(`typeof `))continue;let r=(n.split(/\s+as\s+/).at(-1)??``).trim();r!==``&&r!==`type`&&t.add(r)}n=i;continue}if(H(e,a,`async`)&&(a=R(e,a+5,r)),H(e,a,`function`)||H(e,a,`class`)||H(e,a,`const`)||H(e,a,`let`)||H(e,a,`var`)){let i=H(e,a,`function`)?8:H(e,a,`class`)||H(e,a,`const`)?5:3,o=R(e,a+i,r);e.charCodeAt(o)===42&&(o=R(e,o+1,r));let s=G(e,o,r);s&&t.add(s.name),n=s?.end??o+1;continue}n++}return[...t]}function _t(e,t,n){let r=t,i=0;for(;r<n;){let t=e.charCodeAt(r);if(t===39||t===34||t===96){r=V(e,r,n,t);continue}if(t===47&&e.charCodeAt(r+1)===47){r=z(e,r,n);continue}if(t===47&&e.charCodeAt(r+1)===42){r=B(e,r,n);continue}if(t===123){i++,r++;continue}if(t===125){if(i--,r++,i===0)return r;continue}r++}return r}function vt(e){return W(e).hasDefaultExport}function yt(e){return e===40||e===91||e===123||e===44||e===59||e===61||e===58||e===63||e===33||e===43||e===45||e===42||e===37||e===38||e===124||e===94||e===126||e===60||e===62}function bt(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(F(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}break}if(n<0||!L(e.charCodeAt(n)))return;let r=n;for(;n>=0&&L(e.charCodeAt(n));)n--;return e.slice(n+1,r+1)}function xt(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(F(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return-1;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}return t}return-1}function St(e,t){let n=xt(e,t);if(n===-1||yt(n))return!0;let r=bt(e,t);return r!=null&&r!==``&&nt.has(r)}const Ct=new Set([`return`,`throw`,`case`,`default`,`else`,`do`,`typeof`,`void`,`yield`,`await`,`delete`]);function wt(e,t){let n=xt(e,t);if(n===-1)return!0;if(L(n)||n>=48&&n<=57){let n=bt(e,t);return n!=null&&n!==``&&Ct.has(n)}return n!==41&&n!==93&&n!==125}function Tt(e,t,n){if(!wt(e,t))return-1;let r=e.charCodeAt(t+1);if(r!==47&&r!==46&&r!==62&&!at(r))return-1;let i=st(e,t,n);return i<n&&e.charCodeAt(i)===62&&i++,i>t&&e.charCodeAt(i-1)===62?i:-1}function Et(e,t,n){t++;let r=!1;for(;t<n;){let i=e.charCodeAt(t);if(i===92){t+=2;continue}if(r){i===93&&(r=!1),t++;continue}if(i===91){r=!0,t++;continue}if(i===47){for(t++;t<n&&L(e.charCodeAt(t));)t++;return t}if(I(i))return t;t++}return t}function K(e,t,n){if(t>=n)return-1;let r=e.charCodeAt(t);if(F(r))return t+1;if(r===47&&e.charCodeAt(t+1)===47)return z(e,t,n);if(r===47&&e.charCodeAt(t+1)===42)return B(e,t,n);if(r===39||r===34||r===96)return V(e,t,n,r);if(r===47&&e.charCodeAt(t+1)!==47&&e.charCodeAt(t+1)!==42&&St(e,t))return Et(e,t,n);if(r===60){let r=Tt(e,t,n);if(r!==-1)return r}return-1}function Dt(e,t){let n=e.charCodeAt(t);return F(n)?!0:n===47&&(e.charCodeAt(t+1)===47||e.charCodeAt(t+1)===42)}function Ot(e){let t=e.length,n=0;for(;n<t;){let r=K(e,n,t);if(r!==-1){n=r;continue}if(H(e,n,`export`)){let r=R(e,n+6,t);if(!H(e,r,`default`)){n++;continue}let i=R(e,r+7,t),a=i,o=null;if(H(e,a,`async`)){let n=R(e,a+5,t);H(e,n,`function`)&&(a=n)}if(H(e,a,`function`)||H(e,a,`class`)){let n=H(e,a,`function`)?8:5,r=R(e,a+n,t);e.charCodeAt(r)===42&&(r=R(e,r+1,t));let i=G(e,r,t);i&&(o=i.name)}let s=jt(e,i,t),c=ft(e,s,t);return{exportStart:n,valueStart:i,valueEnd:s,statementEnd:c,bindingName:o}}n++}return null}function kt(e,t,n){if(t>=n)return!1;let r=e.charCodeAt(t),i=t+1<n?e.charCodeAt(t+1):-1;return r===46||r===63&&i===46||r===40||r===91||r===96||r===61&&i===62||r===43||r===45||r===42||r===47||r===37||r===38||r===124||r===94||r===60||r===62||r===61||r===33||r===63||r===58||r===44||r===126||H(e,t,`instanceof`)||H(e,t,`in`)||H(e,t,`of`)||H(e,t,`as`)}const At=new Set([`typeof`,`void`,`delete`,`await`,`yield`,`new`]);function jt(e,t,n){let r=t,i=0,a=0,o=0,s=!1;for(;r<n;){let t=e.charCodeAt(r);if(t===39||t===34||t===96){r=V(e,r,n,t),s=!0;continue}if(t===47&&e.charCodeAt(r+1)===47){r=z(e,r,n);continue}if(t===47&&e.charCodeAt(r+1)===42){r=B(e,r,n);continue}if(t===47&&e.charCodeAt(r+1)!==47&&e.charCodeAt(r+1)!==42&&St(e,r)){r=Et(e,r,n),s=!0;continue}if(t===60&&i===0&&a===0&&o===0){let t=Tt(e,r,n);if(t!==-1){r=t,s=!0;continue}}if(t===40){i++,s=!1,r++;continue}if(t===41){i=Math.max(0,i-1),s=!0,r++;continue}if(t===123){a++,s=!1,r++;continue}if(t===125){if(a=Math.max(0,a-1),s=!0,r++,i===0&&a===0&&o===0)return r;continue}if(t===91){o++,s=!1,r++;continue}if(t===93){o=Math.max(0,o-1),s=!0,r++;continue}if(i===0&&a===0&&o===0){if(t===59)return r;if(I(t)){let t=R(e,r+1,n);if(!s||kt(e,t,n)){r++;continue}return r}}if(at(t)){let t=G(e,r,n);if(t){s=!At.has(t.name),r=t.end;continue}}if(t>=48&&t<=57){for(s=!0,r++;r<n;){let t=e.charCodeAt(r);if(t>=48&&t<=57||t===46||t===110||t===101||t===69){r++;continue}break}continue}if(t===61&&e.charCodeAt(r+1)===62){s=!1,r+=2;continue}if(t===46||t===44||t===58||t===63||t===61||t===43||t===45||t===42||t===47||t===37||t===38||t===124||t===94||t===33||t===126||t===60||t===62){s=!1,r++;continue}r++}return r}function Mt(e,t){let n=Ot(e);if(n==null||n.bindingName!=null)return null;let r=`const ${t} = ${e.slice(n.valueStart,n.valueEnd).trimEnd()};\nexport default ${t}${e.slice(n.statementEnd)}`;return e.slice(0,n.exportStart)+r}const Nt=new Set([`node_modules`,`.git`,`.cache`,`dist`]);function Pt(e,t){let n=new Set,r=e=>{if(!T.existsSync(e))return;let i=T.readdirSync(e,{withFileTypes:!0});for(let a of i){let i=D.join(e,a.name);if(a.isDirectory()){if(Nt.has(a.name))continue;r(i)}else if(a.isFile()&&_.test(a.name)){if(n.has(i))continue;n.add(i),t(i)}}};for(let t of e)t&&T.existsSync(t)&&r(t)}function Ft(e){let t=[];return Pt(e,e=>{t.push(e)}),t}function It(e,t=[]){let n=[e],r=D.resolve(e);for(let e of t){if(!e)continue;let t=D.resolve(e);if(t===r)continue;let i=D.relative(r,t);if(!(i===``||!i.startsWith(`..`)&&!D.isAbsolute(i)))try{T.statSync(e).isDirectory()&&n.push(e)}catch{}}return n}const Lt=new Set(C);function q(e){return Lt.has(e)}function Rt(e){for(let t of e.importSources)if(t.startsWith(`node:`)||q(t))return!0;return!1}function zt(e,t=Lt){let n=[];for(let r of e)!r.startsWith(`.`)&&!r.startsWith(`/`)&&!r.startsWith(`@/`)&&!r.startsWith(`node:`)&&!t.has(r)&&n.push(r);return[...new Set(n)]}function Bt(e){let t=[];for(let n of e)(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`@/`))&&t.push(n);return t}function J(e){try{return T.realpathSync(e)}catch{return D.resolve(e)}}function Vt(e,t){e.delete(t);try{e.delete(T.realpathSync(t))}catch{e.delete(D.resolve(t))}}function Ht(e,t){let n=[];for(let r of Ft(e))try{t.get(r).directives.hasUseClient&&n.push(r)}catch{}return n}var Ut=class{cache=new Map;get(e,t){let n=J(e),r=this.cache.get(n);if(t!==void 0){if(r?.source===t)return r.analysis}else if(r){let e=this.readMtimeMs(n);if(e>=0&&r.mtimeMs===e)return r.analysis}t??=T.readFileSync(n,`utf-8`);let i=this.readMtimeMs(n),a=W(t);return this.cache.set(n,{mtimeMs:i,source:t,analysis:a}),a}getSource(e){return this.get(e),this.cache.get(J(e)).source}invalidate(e){Vt(this.cache,e)}clear(){this.cache.clear()}readMtimeMs(e){try{return T.statSync(e).mtimeMs}catch{return-1}}},Wt=class extends Error{status;statusText;bodyPreview;constructor(e,t,n){super(`HTTP ${e}: ${t}`),this.name=`HttpError`,this.status=e,this.statusText=t,this.bodyPreview=n}};async function Gt(e){if(!e.ok){let t;try{t=await e.text()}catch{t=`<unable to read response body>`}let n=t.length>200?`${t.slice(0,200)}...`:t;throw new Wt(e.status,e.statusText,n)}}var Kt=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer=ue(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=ue(this.resetTimer)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.reset()}};function qt(e,t,n){let r=new Set(t),i=new Set,a=[...t];for(;a.length>0;){let t=a.pop();if(t==null)break;let o=e.get(t);if(o)for(let e of o)r.has(e)||(r.add(e),a.push(e),(n==null||n(e))&&i.add(e))}return i}function Jt(e){return a(e)&&e.success===!0&&typeof e.componentId==`string`&&typeof e.filePath==`string`&&typeof e.relativePath==`string`}function Yt(e){return a(e)&&e.success===!1&&typeof e.filePath==`string`&&typeof e.relativePath==`string`&&e.error instanceof Error}function Xt(e){return e===`info`||e===`success`||e===`warning`||e===`error`}var Zt=class{serverComponentBuilder;rustServerUrl;pendingUpdates=new Map;pendingFiles=new Set;batchTimer=null;DEBOUNCE_DELAY=200;errorHandler;logBatch=[];logBatchTimer=null;LOG_BATCH_DELAY=500;constructor(e,t=M()){this.serverComponentBuilder=e,this.rustServerUrl=`http://localhost:${t}`,this.errorHandler=new Kt({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=D.relative(O.cwd(),e);try{let r=t.moduleGraph.getModuleById(e);r?(t.moduleGraph.invalidateModule(r),this.errorHandler.reset()):this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}return Promise.resolve()}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);return n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(()=>{(async()=>{let e=[...this.pendingFiles];if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=this.collectDependentPageComponents(e);for(let e of n)this.serverComponentBuilder.invalidateBuildCacheFor(e);let r=[...e,...n],i=await Promise.allSettled(r.map(async e=>{let t=D.relative(O.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error!=null&&n.error!==``?n.error:`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),a=[],o=[];if(i.forEach(e=>{e.status===`fulfilled`&&Jt(e.value)?a.push(e.value):e.status===`fulfilled`&&Yt(e.value)?o.push(e.value):e.status===`rejected`&&o.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),a.length>0){let e=Date.now();a.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(o.length>0){let e=Date.now();o.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack!=null&&r.stack!==``?r.stack:``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}})()},this.DEBOUNCE_DELAY),Promise.resolve()}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});await Gt(n);let r=await n.text(),i;try{i=JSON.parse(r)}catch(e){throw Error(`Failed to parse server response (status ${n.status}): ${e instanceof Error?e.message:String(e)}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`)}if(!a(i))throw Error(`Invalid server response (status ${n.status}): expected object, got ${typeof i}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`);if(i.success!==!0){let e=typeof i.message==`string`&&i.message!==``?i.message:typeof i.error==`string`&&i.error!==``?i.error:`Component reload failed`;throw Error(e)}}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}collectDependentPageComponents(e){return[...qt(this.serverComponentBuilder.getImportGraph(),e,e=>e.includes(`/app/`)||e.includes(`\\app\\`))]}detectComponentType(e){try{return this.serverComponentBuilder.getModuleAnalysis(e).topLevelUseClient?`client`:`server`}catch{return`unknown`}}queueLog(e,t){this.logBatch.push({type:e,message:t,timestamp:Date.now()}),this.logBatchTimer&&clearTimeout(this.logBatchTimer),this.logBatchTimer=setTimeout(()=>{this.flushLogs()},this.LOG_BATCH_DELAY)}flushLogs(){if(this.logBatch.length===0)return;let e=this.logBatch.reduce((e,t)=>(e[t.type]??=[],e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(Xt(t)){if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
48
- • `);this.outputLog(t,`${n.length} updates:\n • ${e}`)}}this.logBatch=[],this.logBatchTimer=null}outputLog(e,t){let n=`[rari] HMR:`;switch(e){case`success`:console.warn(`\x1B[32m${n}\x1B[0m ${t}`);break;case`warning`:console.warn(`\x1B[33m${n}\x1B[0m ${t}`);break;case`error`:console.error(`\x1B[31m${n}\x1B[0m ${t}`);break;default:console.warn(`${n} ${t}`)}}dispose(){this.logBatchTimer&&(clearTimeout(this.logBatchTimer),this.flushLogs()),this.batchTimer&&=(clearTimeout(this.batchTimer),null);for(let e of this.pendingUpdates.values())clearTimeout(e);this.pendingUpdates.clear(),this.pendingFiles.clear(),this.errorHandler.dispose()}};function Qt(e){let t=e.replace(x,`/`);return t===`rari/mdx/registry`||t.startsWith(`rari/mdx/registry?`)?!0:t.endsWith(`/mdx/registry.ts`)||t.endsWith(`/mdx/registry.mts`)||t.endsWith(`/mdx/registry.mjs`)||t.endsWith(`/mdx/registry.js`)||t.endsWith(`/mdx/registry`)?t.includes(`/node_modules/rari/`)||t.includes(`/packages/rari/`):!1}function $t(e,t){let n=e=>{if(T.existsSync(e))for(let r of T.readdirSync(e,{withFileTypes:!0})){let i=D.join(e,r.name);if(r.isDirectory()){if(r.name===`node_modules`||r.name===`.git`||r.name===`dist`)continue;n(i)}else r.isFile()&&r.name.endsWith(`.mdx`)&&t(i)}};for(let t of e)t&&T.existsSync(t)&&n(t)}function en(e){let t=new Set;return $t(e,e=>{try{let n=T.readFileSync(e,`utf-8`);for(let e of de(n))t.add(e)}catch{}}),t}function tn(e,t){try{if(t.get(e).hasDefaultExport)return D.basename(e,D.extname(e));let n=t.getSource(e).match(ee);if(n?.[1]!=null&&n[1]!==``)return n[1]}catch{}return D.basename(e,D.extname(e))}function nn(e){let t=en(e.contentDirs.map(t=>D.join(e.projectRoot,t)));if(t.size===0)return[];let n=Ht(e.componentScanDirs,e.cache),r=[],i=new Set;for(let a of n){let n=tn(a,e.cache);if(n==null||n===``||!t.has(n))continue;let o=$e(a,e.projectRoot).replace(x,`/`),s=o.startsWith(`/`)?o:`/${o}`,c=n.replace(/[^\w$]/g,`_`);i.has(c)&&(c=`${c}_${r.length}`),i.add(c),r.push({name:n,binding:c,importPath:s,moduleId:o,client:!0})}return r.sort((e,t)=>e.name.localeCompare(t.name))}function rn(e){let t=on(e.projectRoot,e.mdxOptions),n=e.srcDir??D.join(e.projectRoot,`src`),r=sn(e.projectRoot,t.componentsDir,It(n,Object.values(e.alias??{})));return nn({projectRoot:e.projectRoot,componentsDir:t.componentsDir,contentDirs:t.contentDirs,cache:e.cache,componentScanDirs:r})}function an(e,t={}){let n=t.importStyle??`root-absolute`,r=t.mode??`vite`;return e.length===0?`import { defineMdxComponents } from 'rari/mdx/define'
47
+ };`,`edge $$FORM_ACTION return block`),`browser registerBoundServerReference`)}function P(e,t=8){return A.createHash(`sha256`).update(e).digest(`hex`).slice(0,t)}function $e(e,t=D.cwd()){let n=E.isAbsolute(e)?e:E.resolve(t,e),r=E.relative(t,n);return E.isAbsolute(r)?n.replace(x,`/`):r.replace(x,`/`)}function et(e){return e.replace(_,``).replace(b,`_`).replace(y,``)}function tt(e,t=D.cwd()){let n=$e(e,t);return`${et(n)}_${P(n)}`}const nt=new Set([`return`,`throw`,`case`,`typeof`,`instanceof`,`new`,`delete`,`void`,`in`,`of`]),rt=8232,it=8233;function F(e){return e===32||e===9||e===13||e===10||e===rt||e===it||e===65279}function I(e){return e===13||e===10||e===rt||e===it}function L(e){return e>=97&&e<=122||e>=65&&e<=90||e>=48&&e<=57||e===95||e===36}function at(e){return e>=97&&e<=122||e>=65&&e<=90||e===95||e===36}function ot(e,t,n){for(;t<n&&F(e.charCodeAt(t));)t++;return t}function R(e,t,n){for(;t<n;){let r=ot(e,t,n);if(r!==t){t=r;continue}let i=e.charCodeAt(t);if(i===47&&e.charCodeAt(t+1)===47){t=z(e,t,n);continue}if(i===47&&e.charCodeAt(t+1)===42){t=B(e,t,n);continue}break}return t}function z(e,t,n){for(;t<n&&!I(e.charCodeAt(t));)t++;return t}function B(e,t,n){for(t+=2;t<n-1&&(e.charCodeAt(t)!==42||e.charCodeAt(t+1)!==47);)t++;return t+2}function V(e,t,n,r){for(t++;t<n;){let n=e.charCodeAt(t);if(n===92){t+=2;continue}if(n===r)return t+1;t++}return t}function st(e,t,n){t++;let r=e.charCodeAt(t)===47;for(r&&t++;t<n;){let n=e.charCodeAt(t);if(L(n)||n===46||n===45)t++;else break}let i=+!r;for(;t<n&&i>0;){let a=e.charCodeAt(t);if(a===39||a===34||a===96){t=V(e,t,n,a);continue}if(a===123){t++;let r=1;for(;t<n&&r>0;){let i=e.charCodeAt(t);if(i===39||i===34||i===96){t=V(e,t,n,i);continue}i===123&&r++,i===125&&r--,t++}continue}if(a===47&&e.charCodeAt(t+1)===62){i--,t+=2;continue}if(a===62){t++,r&&i--;continue}if(a===60){let r=e.charCodeAt(t+1);if(r===47||r===46||r===62||at(r)){for(r===47?(i--,t++):r!==33&&i++,t++;t<n;){let n=e.charCodeAt(t);if(L(n)||n===46||n===45)t++;else break}continue}t++;continue}t++}return t}function ct(e,t,n){for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;return!0}function H(e,t,n){if(t+n.length>e.length)return!1;for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;let r=t>0?e.charCodeAt(t-1):-1,i=t+n.length,a=i<e.length?e.charCodeAt(i):-1;return!(r!==-1&&L(r)||a!==-1&&L(a))}function U(e,t,n){let r=R(e,t,n);if(r>=n)return null;let i=e.charCodeAt(r);if(i!==39&&i!==34)return null;let a=r+1,o=V(e,r,n,i);return o<=a?null:{source:e.slice(a,o-1),end:o}}function lt(e,t,n){if(!H(e,t,`import`))return{sources:[],end:t+6};let r=t+6;if(r=R(e,r,n),H(e,r,`type`)&&(r=R(e,r+4,n)),e.charCodeAt(r)===46){for(r++;r<n&&L(e.charCodeAt(r));)r++;for(;r<n&&e.charCodeAt(r)===46;)for(r++;r<n&&L(e.charCodeAt(r));)r++;return{sources:[],end:r}}if(e.charCodeAt(r)===40){r++;let t=U(e,r,n);return t?{sources:[t.source],end:t.end}:{sources:[],end:r}}let i=U(e,r,n);if(i)return{sources:[i.source],end:i.end};let a=0;for(;r<n&&(r=R(e,r,n),!(r>=n));){let t=e.charCodeAt(r);if(a===0&&H(e,r,`from`)){let t=U(e,r+4,n);if(t)return{sources:[t.source],end:t.end};break}if(t===39||t===34||t===96){r=V(e,r,n,t);continue}t===123||t===40||t===91?a++:(t===125||t===41||t===93)&&(a=Math.max(0,a-1)),r++}return{sources:[],end:r}}function ut(e,t){return e.charCodeAt(t)===101&&e.charCodeAt(t+1)===120&&e.charCodeAt(t+2)===112&&e.charCodeAt(t+3)===111&&e.charCodeAt(t+4)===114&&e.charCodeAt(t+5)===116}function dt(e,t){return e.charCodeAt(t)===100&&e.charCodeAt(t+1)===101&&e.charCodeAt(t+2)===102&&e.charCodeAt(t+3)===97&&e.charCodeAt(t+4)===117&&e.charCodeAt(t+5)===108&&e.charCodeAt(t+6)===116}function W(e){let t={hasUseClient:!1,hasUseServer:!1},n=!1,r=!1,i=!1,a=!1,o=[],s=!0,c=!1,l=0,u=e.length;for(;l<u;){let d=e.charCodeAt(l);if(s&&(d===39||d===34)){let i=l+1,a=V(e,l,u,d);if(a<=i){s=!1,l++;continue}let o=a-1-i,f=o===10&&ct(e,i,`use client`),p=o===10&&ct(e,i,`use server`);c||(c=!0,n=f,r=p),f&&(t.hasUseClient=!0),p&&(t.hasUseServer=!0);let m=a,h=!1;for(;m<u;){let t=e.charCodeAt(m);if(F(t)&&!I(t)){m++;continue}if(I(t)||t===59){h=!0,l=m+1;break}if(t===47&&e.charCodeAt(m+1)===47){m=z(e,m,u);continue}if(t===47&&e.charCodeAt(m+1)===42){m=B(e,m,u);continue}s=!1,h=!1;break}if(!h){m>=u&&(s=!1),l=s?a:m;continue}continue}let f=K(e,l,u);if(f!==-1){s&&!Dt(e,l)&&(s=!1),l=f;continue}if(s=!1,H(e,l,`import`)){let t=lt(e,l,u);for(let e of t.sources)o.push(e);l=t.end;continue}if(ut(e,l)){let t=l+6;if(t<u){let n=e.charCodeAt(t);if(F(n)||n===123||n===47&&(e.charCodeAt(t+1)===47||e.charCodeAt(t+1)===42)){let n=R(e,t,u);if(dt(e,n)){i=!0,a=!0;let r=n+7;if(r>=u||!L(e.charCodeAt(r))){l=t;continue}}if(e.charCodeAt(n)===123){let t=n+1;for(;t<u&&(t=R(e,t,u),e.charCodeAt(t)!==125);){let n=t;for(;t<u&&L(e.charCodeAt(t));)t++;let r=t-n;if(r===0)break;t=R(e,t,u);let o=!1;if(e.charCodeAt(t)===97&&e.charCodeAt(t+1)===115){o=!0;let n=t+2;if(n<u&&!L(e.charCodeAt(n))){t=R(e,n,u);let r=t;for(;t<u&&L(e.charCodeAt(t));)t++;t-r===7&&dt(e,r)&&(i=!0,a=!0)}}if(!o&&r===7&&dt(e,n)&&(i=!0,a=!0),e.charCodeAt(t)===44){t++;continue}if(e.charCodeAt(t)===125)break;t++}}else(H(e,n,`async`)||H(e,n,`function`)||H(e,n,`class`))&&(a=!0)}}}l++}return{directives:t,topLevelUseClient:n,topLevelUseServer:r,hasDefaultExport:i,hasComponentExport:a,importSources:[...new Set(o)]}}function G(e,t,n){if(t>=n||!at(e.charCodeAt(t)))return null;let r=t+1;for(;r<n&&L(e.charCodeAt(r));)r++;return{name:e.slice(t,r),end:r}}function ft(e,t,n){let r=t;for(;r<n;){let t=e.charCodeAt(r);if(t===32||t===9){r++;continue}if(t===59)return r+1;break}return t}function pt(e,t,n){let r=[],i=t+1;for(;;){if(i=R(e,i,n),i>=n)return null;if(e.charCodeAt(i)===125)return{named:r,end:i+1};let t=!1;if(H(e,i,`type`)){let r=R(e,i+4,n),a=e.charCodeAt(r);(a===39||a===34||G(e,r,n)!==null)&&!H(e,r,`as`)&&(t=!0,i=r)}let a,o=e.charCodeAt(i);if(o===39||o===34){let t=V(e,i,n,o);a=e.slice(i+1,t-1),i=t}else{let t=G(e,i,n);if(!t)return null;a=t.name,i=t.end}i=R(e,i,n);let s=a;if(H(e,i,`as`)){i=R(e,i+2,n);let t=G(e,i,n);if(!t)return null;s=t.name,i=R(e,t.end,n)}r.push({imported:a,local:s,typeOnly:t});let c=e.charCodeAt(i);if(c===44){i++;continue}return c===125?{named:r,end:i+1}:null}}function mt(e,t,n){let r=R(e,t+6,n);if(r>=n)return null;let i=e.charCodeAt(r);if(i===40||i===46)return null;if(i===39||i===34){let i=U(e,r,n);return i?{start:t,end:ft(e,i.end,n),source:i.source,typeOnly:!1,sideEffectOnly:!0,defaultBinding:null,namespaceBinding:null,named:[]}:null}let a=!1;if(H(e,r,`type`)){let t=R(e,r+4,n);!H(e,t,`from`)&&e.charCodeAt(t)!==44&&(a=!0,r=t)}let o=null,s=null,c=[],l=e.charCodeAt(r);if(l!==123&&l!==42){let t=G(e,r,n);if(!t)return null;o=t.name,r=R(e,t.end,n),e.charCodeAt(r)===44?(r=R(e,r+1,n),l=e.charCodeAt(r)):l=-1}if(l===42){if(r=R(e,r+1,n),!H(e,r,`as`))return null;r=R(e,r+2,n);let t=G(e,r,n);if(!t)return null;s=t.name,r=t.end}else if(l===123){let t=pt(e,r,n);if(!t)return null;c=t.named,r=t.end}if(r=R(e,r,n),!H(e,r,`from`))return null;let u=U(e,r+4,n);return u?{start:t,end:ft(e,u.end,n),source:u.source,typeOnly:a,sideEffectOnly:!1,defaultBinding:o,namespaceBinding:s,named:c}:null}function ht(e){let t=[],n=0,r=e.length;for(;n<r;){let i=K(e,n,r);if(i!==-1){n=i;continue}if(H(e,n,`import`)){let i=mt(e,n,r);if(i){t.push(i),n=i.end;continue}n+=6;continue}n++}return t}function gt(e){let t=new Set,n=0,r=e.length;for(;n<r;){let i=K(e,n,r);if(i!==-1){n=i;continue}if(!H(e,n,`export`)){n++;continue}let a=R(e,n+6,r);if(H(e,a,`type`)||H(e,a,`interface`)){n=a+1;continue}if(e.charCodeAt(a)===42){let i=R(e,a+1,r);if(H(e,i,`as`)){i=R(e,i+2,r);let a=G(e,i,r);a&&t.add(a.name),n=a?.end??i+1}else n=a+1;continue}if(H(e,a,`default`)){t.add(`default`),n=a+7;continue}if(e.charCodeAt(a)===123){let i=_t(e,a,r),o=e.slice(a+1,i-1);for(let e of o.split(`,`)){let n=e.trim();if(!n||n.startsWith(`type `)||n.startsWith(`typeof `))continue;let r=(n.split(/\s+as\s+/).at(-1)??``).trim();r!==``&&r!==`type`&&t.add(r)}n=i;continue}if(H(e,a,`async`)&&(a=R(e,a+5,r)),H(e,a,`function`)||H(e,a,`class`)||H(e,a,`const`)||H(e,a,`let`)||H(e,a,`var`)){let i=H(e,a,`function`)?8:H(e,a,`class`)||H(e,a,`const`)?5:3,o=R(e,a+i,r);e.charCodeAt(o)===42&&(o=R(e,o+1,r));let s=G(e,o,r);s&&t.add(s.name),n=s?.end??o+1;continue}n++}return[...t]}function _t(e,t,n){let r=t,i=0;for(;r<n;){let t=e.charCodeAt(r);if(t===39||t===34||t===96){r=V(e,r,n,t);continue}if(t===47&&e.charCodeAt(r+1)===47){r=z(e,r,n);continue}if(t===47&&e.charCodeAt(r+1)===42){r=B(e,r,n);continue}if(t===123){i++,r++;continue}if(t===125){if(i--,r++,i===0)return r;continue}r++}return r}function vt(e){return W(e).hasDefaultExport}function yt(e){return e===40||e===91||e===123||e===44||e===59||e===61||e===58||e===63||e===33||e===43||e===45||e===42||e===37||e===38||e===124||e===94||e===126||e===60||e===62}function bt(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(F(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}break}if(n<0||!L(e.charCodeAt(n)))return;let r=n;for(;n>=0&&L(e.charCodeAt(n));)n--;return e.slice(n+1,r+1)}function xt(e,t){let n=t-1;for(;n>=0;){let t=e.charCodeAt(n);if(F(t)){n--;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===42){for(n-=2;n>=1;){if(e.charCodeAt(n)===42&&e.charCodeAt(n-1)===47){n-=2;break}n--}if(n<0)return-1;continue}if(n>=1&&t===47&&e.charCodeAt(n-1)===47){n-=2;continue}let r=n;for(;r>=0&&e.charCodeAt(r)!==10&&e.charCodeAt(r)!==13;)r--;let i=r+1;for(;i<n&&(e.charCodeAt(i)===32||e.charCodeAt(i)===9);)i++;if(i<n&&e.charCodeAt(i)===47&&e.charCodeAt(i+1)===47){n=i-1;continue}return t}return-1}function St(e,t){let n=xt(e,t);if(n===-1||yt(n))return!0;let r=bt(e,t);return r!=null&&r!==``&&nt.has(r)}const Ct=new Set([`return`,`throw`,`case`,`default`,`else`,`do`,`typeof`,`void`,`yield`,`await`,`delete`]);function wt(e,t){let n=xt(e,t);if(n===-1)return!0;if(L(n)||n>=48&&n<=57){let n=bt(e,t);return n!=null&&n!==``&&Ct.has(n)}return n!==41&&n!==93&&n!==125}function Tt(e,t,n){if(!wt(e,t))return-1;let r=e.charCodeAt(t+1);if(r!==47&&r!==46&&r!==62&&!at(r))return-1;let i=st(e,t,n);return i<n&&e.charCodeAt(i)===62&&i++,i>t&&e.charCodeAt(i-1)===62?i:-1}function Et(e,t,n){t++;let r=!1;for(;t<n;){let i=e.charCodeAt(t);if(i===92){t+=2;continue}if(r){i===93&&(r=!1),t++;continue}if(i===91){r=!0,t++;continue}if(i===47){for(t++;t<n&&L(e.charCodeAt(t));)t++;return t}if(I(i))return t;t++}return t}function K(e,t,n){if(t>=n)return-1;let r=e.charCodeAt(t);if(F(r))return t+1;if(r===47&&e.charCodeAt(t+1)===47)return z(e,t,n);if(r===47&&e.charCodeAt(t+1)===42)return B(e,t,n);if(r===39||r===34||r===96)return V(e,t,n,r);if(r===47&&e.charCodeAt(t+1)!==47&&e.charCodeAt(t+1)!==42&&St(e,t))return Et(e,t,n);if(r===60){let r=Tt(e,t,n);if(r!==-1)return r}return-1}function Dt(e,t){let n=e.charCodeAt(t);return F(n)?!0:n===47&&(e.charCodeAt(t+1)===47||e.charCodeAt(t+1)===42)}function Ot(e){let t=e.length,n=0;for(;n<t;){let r=K(e,n,t);if(r!==-1){n=r;continue}if(H(e,n,`export`)){let r=R(e,n+6,t);if(!H(e,r,`default`)){n++;continue}let i=R(e,r+7,t),a=i,o=null;if(H(e,a,`async`)){let n=R(e,a+5,t);H(e,n,`function`)&&(a=n)}if(H(e,a,`function`)||H(e,a,`class`)){let n=H(e,a,`function`)?8:5,r=R(e,a+n,t);e.charCodeAt(r)===42&&(r=R(e,r+1,t));let i=G(e,r,t);i&&(o=i.name)}let s=jt(e,i,t),c=ft(e,s,t);return{exportStart:n,valueStart:i,valueEnd:s,statementEnd:c,bindingName:o}}n++}return null}function kt(e,t,n){if(t>=n)return!1;let r=e.charCodeAt(t),i=t+1<n?e.charCodeAt(t+1):-1;return r===46||r===63&&i===46||r===40||r===91||r===96||r===61&&i===62||r===43||r===45||r===42||r===47||r===37||r===38||r===124||r===94||r===60||r===62||r===61||r===33||r===63||r===58||r===44||r===126||H(e,t,`instanceof`)||H(e,t,`in`)||H(e,t,`of`)||H(e,t,`as`)}const At=new Set([`typeof`,`void`,`delete`,`await`,`yield`,`new`]);function jt(e,t,n){let r=t,i=0,a=0,o=0,s=!1;for(;r<n;){let t=e.charCodeAt(r);if(t===39||t===34||t===96){r=V(e,r,n,t),s=!0;continue}if(t===47&&e.charCodeAt(r+1)===47){r=z(e,r,n);continue}if(t===47&&e.charCodeAt(r+1)===42){r=B(e,r,n);continue}if(t===47&&e.charCodeAt(r+1)!==47&&e.charCodeAt(r+1)!==42&&St(e,r)){r=Et(e,r,n),s=!0;continue}if(t===60&&i===0&&a===0&&o===0){let t=Tt(e,r,n);if(t!==-1){r=t,s=!0;continue}}if(t===40){i++,s=!1,r++;continue}if(t===41){i=Math.max(0,i-1),s=!0,r++;continue}if(t===123){a++,s=!1,r++;continue}if(t===125){if(a=Math.max(0,a-1),s=!0,r++,i===0&&a===0&&o===0)return r;continue}if(t===91){o++,s=!1,r++;continue}if(t===93){o=Math.max(0,o-1),s=!0,r++;continue}if(i===0&&a===0&&o===0){if(t===59)return r;if(I(t)){let t=R(e,r+1,n);if(!s||kt(e,t,n)){r++;continue}return r}}if(at(t)){let t=G(e,r,n);if(t){s=!At.has(t.name),r=t.end;continue}}if(t>=48&&t<=57){for(s=!0,r++;r<n;){let t=e.charCodeAt(r);if(t>=48&&t<=57||t===46||t===110||t===101||t===69){r++;continue}break}continue}if(t===61&&e.charCodeAt(r+1)===62){s=!1,r+=2;continue}if(t===46||t===44||t===58||t===63||t===61||t===43||t===45||t===42||t===47||t===37||t===38||t===124||t===94||t===33||t===126||t===60||t===62){s=!1,r++;continue}r++}return r}function Mt(e,t){let n=Ot(e);if(n==null||n.bindingName!=null)return null;let r=`const ${t} = ${e.slice(n.valueStart,n.valueEnd).trimEnd()};\nexport default ${t}${e.slice(n.statementEnd)}`;return e.slice(0,n.exportStart)+r}const Nt=new Set([`node_modules`,`.git`,`.cache`,`dist`]);function Pt(e,t){let n=new Set,r=e=>{if(!w.existsSync(e))return;let i=w.readdirSync(e,{withFileTypes:!0});for(let a of i){let i=E.join(e,a.name);if(a.isDirectory()){if(Nt.has(a.name))continue;r(i)}else if(a.isFile()&&_.test(a.name)){if(n.has(i))continue;n.add(i),t(i)}}};for(let t of e)t&&w.existsSync(t)&&r(t)}function Ft(e){let t=[];return Pt(e,e=>{t.push(e)}),t}function It(e,t=[]){let n=[e],r=E.resolve(e);for(let e of t){if(!e)continue;let t=E.resolve(e);if(t===r)continue;let i=E.relative(r,t);if(!(i===``||!i.startsWith(`..`)&&!E.isAbsolute(i)))try{w.statSync(e).isDirectory()&&n.push(e)}catch{}}return n}const Lt=new Set(C);function Rt(e){return Lt.has(e)}function zt(e){for(let t of e.importSources)if(t.startsWith(`node:`)||Rt(t))return!0;return!1}function Bt(e,t=Lt){let n=[];for(let r of e)!r.startsWith(`.`)&&!r.startsWith(`/`)&&!r.startsWith(`@/`)&&!r.startsWith(`node:`)&&!t.has(r)&&n.push(r);return[...new Set(n)]}function Vt(e){let t=[];for(let n of e)(n.startsWith(`./`)||n.startsWith(`../`)||n.startsWith(`@/`))&&t.push(n);return t}function q(e){try{return w.realpathSync(e)}catch{return E.resolve(e)}}function Ht(e,t){e.delete(t);try{e.delete(w.realpathSync(t))}catch{e.delete(E.resolve(t))}}function Ut(e,t){let n=[];for(let r of Ft(e))try{t.get(r).directives.hasUseClient&&n.push(r)}catch{}return n}var Wt=class{cache=new Map;get(e,t){let n=q(e),r=this.cache.get(n);if(t!==void 0){if(r?.source===t)return r.analysis}else if(r){let e=this.readMtimeMs(n);if(e>=0&&r.mtimeMs===e)return r.analysis}t??=w.readFileSync(n,`utf-8`);let i=this.readMtimeMs(n),a=W(t);return this.cache.set(n,{mtimeMs:i,source:t,analysis:a}),a}getSource(e){return this.get(e),this.cache.get(q(e)).source}invalidate(e){Ht(this.cache,e)}clear(){this.cache.clear()}readMtimeMs(e){try{return w.statSync(e).mtimeMs}catch{return-1}}},Gt=class extends Error{status;statusText;bodyPreview;constructor(e,t,n){super(`HTTP ${e}: ${t}`),this.name=`HttpError`,this.status=e,this.statusText=t,this.bodyPreview=n}};async function Kt(e){if(!e.ok){let t;try{t=await e.text()}catch{t=`<unable to read response body>`}let n=t.length>200?`${t.slice(0,200)}...`:t;throw new Gt(e.status,e.statusText,n)}}var qt=class{errorCount=0;maxErrors;resetTimeout;resetTimer=null;lastError=null;constructor(e={}){this.maxErrors=e.maxErrors??5,this.resetTimeout=e.resetTimeout??3e4}recordError(e){this.errorCount++,this.lastError=e,this.resetTimer=ue(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=ue(this.resetTimer)}getErrorCount(){return this.errorCount}getLastError(){return this.lastError}hasReachedMaxErrors(){return this.errorCount>=this.maxErrors}handleMaxErrorsReached(){console.error(`[rari] HMR: Maximum error count (${this.maxErrors}) reached. Consider restarting the dev server if issues persist.`)}dispose(){this.reset()}};function Jt(e,t,n){let r=new Set(t),i=new Set,a=[...t];for(;a.length>0;){let t=a.pop();if(t==null)break;let o=e.get(t);if(o)for(let e of o)r.has(e)||(r.add(e),a.push(e),(n==null||n(e))&&i.add(e))}return i}function Yt(e){return a(e)&&e.success===!0&&typeof e.componentId==`string`&&typeof e.filePath==`string`&&typeof e.relativePath==`string`}function Xt(e){return a(e)&&e.success===!1&&typeof e.filePath==`string`&&typeof e.relativePath==`string`&&e.error instanceof Error}function Zt(e){return e===`info`||e===`success`||e===`warning`||e===`error`}var Qt=class{serverComponentBuilder;rustServerUrl;pendingUpdates=new Map;pendingFiles=new Set;batchTimer=null;DEBOUNCE_DELAY=200;errorHandler;logBatch=[];logBatchTimer=null;LOG_BATCH_DELAY=500;constructor(e,t=M()){this.serverComponentBuilder=e,this.rustServerUrl=`http://localhost:${t}`,this.errorHandler=new qt({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=E.relative(D.cwd(),e);try{let r=t.moduleGraph.getModuleById(e);r?(t.moduleGraph.invalidateModule(r),this.errorHandler.reset()):this.queueLog(`warning`,`Client component module not found in graph: ${n}`)}catch(e){let t=e instanceof Error?e.message:String(e);this.queueLog(`error`,`Failed to update client component: ${n} - ${t}`),this.errorHandler.recordError(e instanceof Error?e:Error(t))}return Promise.resolve()}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);return n&&(clearTimeout(n),this.pendingUpdates.delete(e)),this.batchTimer&&clearTimeout(this.batchTimer),this.batchTimer=setTimeout(()=>{(async()=>{let e=[...this.pendingFiles];if(this.pendingFiles.clear(),this.batchTimer=null,e.length===0)return;let n=this.collectDependentPageComponents(e);for(let e of n)this.serverComponentBuilder.invalidateBuildCacheFor(e);let r=[...e,...n],i=await Promise.allSettled(r.map(async e=>{let t=E.relative(D.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw Error(n.error!=null&&n.error!==``?n.error:`Build failed`);return await this.notifyRustServer(n.componentId,n.bundlePath),{success:!0,componentId:n.componentId,filePath:e,relativePath:t}}catch(n){return{success:!1,filePath:e,relativePath:t,error:n instanceof Error?n:Error(String(n))}}})),a=[],o=[];if(i.forEach(e=>{e.status===`fulfilled`&&Yt(e.value)?a.push(e.value):e.status===`fulfilled`&&Xt(e.value)?o.push(e.value):e.status===`rejected`&&o.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),a.length>0){let e=Date.now();a.forEach(({componentId:n})=>{t.hot.send(`rari:server-component-updated`,{id:n,t:e})}),this.errorHandler.reset(),t.ws.send({type:`custom`,event:`rari:hmr-error-cleared`,data:{t:e}})}if(o.length>0){let e=Date.now();o.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(r.stack!=null&&r.stack!==``?r.stack:``).substring(0,500);this.queueLog(`error`,`Failed to rebuild: ${n} - ${i}`),this.errorHandler.recordError(r),t.ws.send({type:`custom`,event:`rari:hmr-error`,data:{msg:i,stack:a,file:n,t:e,count:this.errorHandler.getErrorCount(),max:5}})}),this.errorHandler.hasReachedMaxErrors()&&this.queueLog(`error`,`Maximum error count reached (${this.errorHandler.getErrorCount()}). Consider restarting the dev server if issues persist.`)}})()},this.DEBOUNCE_DELAY),Promise.resolve()}async notifyRustServer(e,t){try{let n=await fetch(`${this.rustServerUrl}/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`reload-component`,component_id:e,bundle_path:t})});await Kt(n);let r=await n.text(),i;try{i=JSON.parse(r)}catch(e){throw Error(`Failed to parse server response (status ${n.status}): ${e instanceof Error?e.message:String(e)}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`)}if(!a(i))throw Error(`Invalid server response (status ${n.status}): expected object, got ${typeof i}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`);if(i.success!==!0){let e=typeof i.message==`string`&&i.message!==``?i.message:typeof i.error==`string`&&i.error!==``?i.error:`Component reload failed`;throw Error(e)}}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}collectDependentPageComponents(e){return[...Jt(this.serverComponentBuilder.getImportGraph(),e,e=>e.includes(`/app/`)||e.includes(`\\app\\`))]}detectComponentType(e){try{return this.serverComponentBuilder.getModuleAnalysis(e).topLevelUseClient?`client`:`server`}catch{return`unknown`}}queueLog(e,t){this.logBatch.push({type:e,message:t,timestamp:Date.now()}),this.logBatchTimer&&clearTimeout(this.logBatchTimer),this.logBatchTimer=setTimeout(()=>{this.flushLogs()},this.LOG_BATCH_DELAY)}flushLogs(){if(this.logBatch.length===0)return;let e=this.logBatch.reduce((e,t)=>(e[t.type]??=[],e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(Zt(t)){if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
48
+ • `);this.outputLog(t,`${n.length} updates:\n • ${e}`)}}this.logBatch=[],this.logBatchTimer=null}outputLog(e,t){let n=`[rari] HMR:`;switch(e){case`success`:console.warn(`\x1B[32m${n}\x1B[0m ${t}`);break;case`warning`:console.warn(`\x1B[33m${n}\x1B[0m ${t}`);break;case`error`:console.error(`\x1B[31m${n}\x1B[0m ${t}`);break;default:console.warn(`${n} ${t}`)}}dispose(){this.logBatchTimer&&(clearTimeout(this.logBatchTimer),this.flushLogs()),this.batchTimer&&=(clearTimeout(this.batchTimer),null);for(let e of this.pendingUpdates.values())clearTimeout(e);this.pendingUpdates.clear(),this.pendingFiles.clear(),this.errorHandler.dispose()}};function $t(e){let t=e.replace(x,`/`);return t===`rari/mdx/registry`||t.startsWith(`rari/mdx/registry?`)?!0:t.endsWith(`/mdx/registry.ts`)||t.endsWith(`/mdx/registry.mts`)||t.endsWith(`/mdx/registry.mjs`)||t.endsWith(`/mdx/registry.js`)||t.endsWith(`/mdx/registry`)?t.includes(`/node_modules/rari/`)||t.includes(`/packages/rari/`):!1}function en(e,t){let n=e=>{if(w.existsSync(e))for(let r of w.readdirSync(e,{withFileTypes:!0})){let i=E.join(e,r.name);if(r.isDirectory()){if(r.name===`node_modules`||r.name===`.git`||r.name===`dist`)continue;n(i)}else r.isFile()&&r.name.endsWith(`.mdx`)&&t(i)}};for(let t of e)t&&w.existsSync(t)&&n(t)}function tn(e){let t=new Set;return en(e,e=>{try{let n=w.readFileSync(e,`utf-8`);for(let e of de(n))t.add(e)}catch{}}),t}function nn(e,t){try{if(t.get(e).hasDefaultExport)return E.basename(e,E.extname(e));let n=t.getSource(e).match(ee);if(n?.[1]!=null&&n[1]!==``)return n[1]}catch{}return E.basename(e,E.extname(e))}function rn(e){let t=tn(e.contentDirs.map(t=>E.join(e.projectRoot,t)));if(t.size===0)return[];let n=Ut(e.componentScanDirs,e.cache),r=[],i=new Set;for(let a of n){let n=nn(a,e.cache);if(n==null||n===``||!t.has(n))continue;let o=$e(a,e.projectRoot).replace(x,`/`),s=o.startsWith(`/`)?o:`/${o}`,c=n.replace(/[^\w$]/g,`_`);i.has(c)&&(c=`${c}_${r.length}`),i.add(c),r.push({name:n,binding:c,importPath:s,moduleId:o,client:!0})}return r.sort((e,t)=>e.name.localeCompare(t.name))}function an(e){let t=sn(e.projectRoot,e.mdxOptions),n=e.srcDir??E.join(e.projectRoot,`src`),r=cn(e.projectRoot,t.componentsDir,It(n,Object.values(e.alias??{})));return rn({projectRoot:e.projectRoot,componentsDir:t.componentsDir,contentDirs:t.contentDirs,cache:e.cache,componentScanDirs:r})}function on(e,t={}){let n=t.importStyle??`root-absolute`,r=t.mode??`vite`;return e.length===0?`import { defineMdxComponents } from 'rari/mdx/define'
49
49
 
50
50
  export const getMDXComponents = defineMdxComponents([])
51
51
  `:r===`production`?`import { defineMdxComponents } from 'rari/mdx/define'
@@ -62,15 +62,15 @@ export const getMDXComponents = defineMdxComponents([
62
62
  ${e.map(e=>` { name: ${JSON.stringify(e.name)}, component: ${e.binding}, id: ${JSON.stringify(e.moduleId)}, client: ${e.client} }`).join(`,
63
63
  `)},
64
64
  ])
65
- `}function on(e,t){return{componentsDir:t?.componentsDir??`src/components`,contentDirs:t?.contentDirs??[`public/content`,`content`]}}function sn(e,t,n){let r=D.join(e,t),i=new Set(n);return T.existsSync(r)&&i.add(r),[...i]}function cn(e,t,n){if(n.length===0)return e;let r=ht(e).find(e=>e.source===t&&!e.typeOnly&&!e.sideEffectOnly),i=new Map;if(r!=null)for(let e of r.named)e.typeOnly||i.set(e.imported,e.local);for(let e of n)i.has(e)||i.set(e,e);let a=[...i.entries()].map(([e,t])=>e===t?e:`${e} as ${t}`);if(r?.namespaceBinding!=null||r?.named.some(e=>e.typeOnly)){let i=n.filter(e=>!r.named.some(t=>!t.typeOnly&&t.imported===e));return i.length===0?e:`${`import { ${[...new Set(i)].join(`, `)} } from ${JSON.stringify(t)};`}\n${e}`}let o=`import ${r?.defaultBinding==null?``:`${r.defaultBinding}, `}{ ${a.join(`, `)} } from ${JSON.stringify(t)};`;return r==null?`${o}\n\n${e}`:e.slice(0,r.start)+o+e.slice(r.end)}function ln(e,t){return`const ${e} = createClientModuleProxy(${JSON.stringify(t)});`}function un(e,t,n){return`const ${e} = registerClientReference(
65
+ `}function sn(e,t){return{componentsDir:t?.componentsDir??`src/components`,contentDirs:t?.contentDirs??[`public/content`,`content`]}}function cn(e,t,n){let r=E.join(e,t),i=new Set(n);return w.existsSync(r)&&i.add(r),[...i]}function ln(e,t,n){if(n.length===0)return e;let r=ht(e).find(e=>e.source===t&&!e.typeOnly&&!e.sideEffectOnly),i=new Map;if(r!=null)for(let e of r.named)e.typeOnly||i.set(e.imported,e.local);for(let e of n)i.has(e)||i.set(e,e);let a=[...i.entries()].map(([e,t])=>e===t?e:`${e} as ${t}`);if(r?.namespaceBinding!=null||r?.named.some(e=>e.typeOnly)){let i=n.filter(e=>!r.named.some(t=>!t.typeOnly&&t.imported===e));return i.length===0?e:`${`import { ${[...new Set(i)].join(`, `)} } from ${JSON.stringify(t)};`}\n${e}`}let o=`import ${r?.defaultBinding==null?``:`${r.defaultBinding}, `}{ ${a.join(`, `)} } from ${JSON.stringify(t)};`;return r==null?`${o}\n\n${e}`:e.slice(0,r.start)+o+e.slice(r.end)}function un(e,t){return`const ${e} = createClientModuleProxy(${JSON.stringify(t)});`}function dn(e,t,n){return`const ${e} = registerClientReference(
66
66
  function() {
67
67
  throw new Error("Attempted to call ${e} from the server but it's on the client. It can only be rendered as a Component or passed to props of a Client Component.");
68
68
  },
69
69
  ${JSON.stringify(t)},
70
70
  ${JSON.stringify(n)}
71
- );`}function dn(e,t){let n=[],r=new Set;e.namespaceBinding!=null&&(r.add(`createClientModuleProxy`),n.push(ln(e.namespaceBinding,t))),e.defaultBinding!=null&&(r.add(`registerClientReference`),n.push(un(e.defaultBinding,t,`default`)));for(let i of e.named)i.typeOnly||(r.add(`registerClientReference`),n.push(un(i.local,t,i.imported)));return n.length===0?{code:``,helpers:[]}:{code:n.join(`
72
- `),helpers:[...r]}}function fn(e,t){let n=t.length>0?t:[`default`],r=[`import { registerClientReference } from ${JSON.stringify(`react-server-dom-rari/server`)};`];for(let t of n)t==="default"?r.push(`export default registerClientReference(null, ${JSON.stringify(e)}, "default");`):r.push(`export const ${t} = registerClientReference(null, ${JSON.stringify(e)}, ${JSON.stringify(t)});`);return`${r.join(`
73
- `)}\n`}function pn(e,t,n){let r=n==="default"?`if (Component && typeof Component === 'object' && Component.default) {
71
+ );`}function fn(e,t){let n=[],r=new Set;e.namespaceBinding!=null&&(r.add(`createClientModuleProxy`),n.push(un(e.namespaceBinding,t))),e.defaultBinding!=null&&(r.add(`registerClientReference`),n.push(dn(e.defaultBinding,t,`default`)));for(let i of e.named)i.typeOnly||(r.add(`registerClientReference`),n.push(dn(i.local,t,i.imported)));return n.length===0?{code:``,helpers:[]}:{code:n.join(`
72
+ `),helpers:[...r]}}function pn(e,t){let n=t.length>0?t:[`default`],r=[`import { registerClientReference } from ${JSON.stringify(`react-server-dom-rari/server`)};`];for(let t of n)t==="default"?r.push(`export default registerClientReference(null, ${JSON.stringify(e)}, "default");`):r.push(`export const ${t} = registerClientReference(null, ${JSON.stringify(e)}, ${JSON.stringify(t)});`);return`${r.join(`
73
+ `)}\n`}function mn(e,t,n){let r=n==="default"?`if (Component && typeof Component === 'object' && Component.default) {
74
74
  Component = Component.default;
75
75
  }`:`if (Component && typeof Component === 'object') {
76
76
  Component = Component[${JSON.stringify(n)}] ?? Component.default?.[${JSON.stringify(n)}];
@@ -90,16 +90,16 @@ const ${e} = (props) => {
90
90
  }
91
91
 
92
92
  return Component(props);
93
- }`}function mn(e,t){return`// Component namespace reference: ${t}
93
+ }`}function hn(e,t){return`// Component namespace reference: ${t}
94
94
  const ${e} = globalThis['~clientComponents']?.[${JSON.stringify(t)}]?.component
95
95
  || globalThis[${JSON.stringify(t)}]
96
- || {};`}const hn=/import\s*\(\s*["']([^"']+)["']\s*\)|import\s+["']([^"']+)["']/g,gn=/<script\b[^>]*>/gi;function _n(e,t,n){n?.startsWith(`/src/`)&&e.add(J(D.join(t,n.slice(1))))}function vn(e){return/\btype\s*=\s*["']module["']/i.test(e)?/\bsrc\s*=\s*["']([^"']+)["']/i.exec(e)?.[1]??null:null}function yn(e){let t=new Set,n=D.join(e,`index.html`);if(!T.existsSync(n))return t;try{let r=T.readFileSync(n,`utf-8`);for(let n of r.matchAll(hn))_n(t,e,n[1]||n[2]);for(let n of r.matchAll(gn))_n(t,e,vn(n[0]))}catch{}return t}const bn=/(?:^|[\n\r;])\s*import\s*\{[^}]*\bregisterServerReference\b[^}]*\}\s*from\s*["'][^"'\n]+["']/;function xn(e){return bn.test(e)}const Sn=new Set(`undefined.NaN.Infinity.arguments.Object.Array.String.Number.Boolean.Symbol.BigInt.Math.Date.JSON.Promise.Error.TypeError.RangeError.Map.Set.WeakMap.WeakSet.RegExp.Proxy.Reflect.Function.console.fetch.process.Buffer.globalThis.global.window.document.navigator.location.crypto.TextEncoder.TextDecoder.URL.URLSearchParams.FormData.Headers.Request.Response.AbortController.AbortSignal.setTimeout.clearTimeout.setInterval.clearInterval.queueMicrotask.structuredClone.atob.btoa.React.jsx.jsxs.Fragment`.split(`.`)),Cn=new Set(`await.return.throw.if.else.for.while.do.switch.case.break.continue.new.typeof.instanceof.void.delete.yield.class.extends.super.this.try.catch.finally.with.debugger.default.of.in.from.as.import.export.async.function.const.let.var.true.false.null.static.get.set.typeof`.split(`.`));function wn(e){return e>=97&&e<=122||e>=65&&e<=90||e===95||e===36}function Tn(e){return wn(e)||e>=48&&e<=57}function Y(e,t){let n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(r===32||r===9||r===10||r===13||r===65279){t++;continue}if(r===47&&e.charCodeAt(t+1)===47){for(t+=2;t<n&&e.charCodeAt(t)!==10&&e.charCodeAt(t)!==13;)t++;continue}if(r===47&&e.charCodeAt(t+1)===42){for(t+=2;t<n-1&&(e.charCodeAt(t)!==42||e.charCodeAt(t+1)!==47);)t++;t+=2;continue}break}return t}function En(e,t,n){t++;let r=e.length;for(;t<r;){let r=e.charCodeAt(t);if(r===92){t+=2;continue}if(r===n)return t+1;t++}return t}function X(e,t,n,r){let i=t,a=0,o=e.length;for(;i<o;){let t=K(e,i,o);if(t!==-1){i=t;continue}let s=e.charCodeAt(i);if(s===n)a++;else if(s===r&&(a--,a===0))return i+1;i++}return i}function Dn(e,t,n){for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;return!0}function On(e,t,n){let r=Y(e,t+1);if(r>=n)return!1;let i=e.charCodeAt(r);if(i!==39&&i!==34)return!1;let a=r+1,o=En(e,r,i);if(o-1-a!=10||!Dn(e,a,`use server`))return!1;for(r=o;r<n;){let t=e.charCodeAt(r);if(t===32||t===9){r++;continue}return t===59||t===10||t===13||t===47&&e.charCodeAt(r+1)===47||t===47&&e.charCodeAt(r+1)===42}return!0}function kn(e,t,n){let r=Y(e,t+1),i=e.charCodeAt(r);return i!==39&&i!==34?e.slice(t+1,n):(r=Y(e,En(e,r,i)),e.charCodeAt(r)===59&&r++,r=Y(e,r),e.slice(r,n))}function An(e,t){if(!wn(e.charCodeAt(t)))return null;let n=t+1;for(;n<e.length&&Tn(e.charCodeAt(n));)n++;return{name:e.slice(t,n),end:n}}function jn(e,t,n){if(!Dn(e,t,n))return!1;let r=t>0?e.charCodeAt(t-1):-1,i=t+n.length<e.length?e.charCodeAt(t+n.length):-1;return!(r!==-1&&Tn(r)||i!==-1&&Tn(i))}function Mn(e){let t=new Set,n=0,r=e.length;for(;n<r&&(n=Y(e,n),!(n>=r));){let r=e.charCodeAt(n);if(r===123||r===91){let i=X(e,n,r,r===123?125:93);for(let r of e.slice(n,i).matchAll(/[a-z_$][\w$]*/gi))r[0]!==`as`&&t.add(r[0]);n=i;continue}if(r===46&&e.charCodeAt(n+1)===46&&e.charCodeAt(n+2)===46){n+=3,n=Y(e,n);let r=An(e,n);r&&(t.add(r.name),n=r.end);continue}let i=An(e,n);if(i){t.add(i.name),n=i.end;continue}n++}return t}function Nn(e){let t=new Set;for(let n of e.matchAll(/\b(?:const|let|var|function|class|async\s+function)\s+([A-Za-z_$][\w$]*)/g))t.add(n[1]);return t}function Pn(e){let t=new Set;for(let n of e.matchAll(/\b(?:import|export)\s+(?:type\s+)?(?:\{([^}]+)\}|(\*\s+as\s+[A-Za-z_$][\w$]*)|([A-Za-z_$][\w$]*))/g)){if(n[1])for(let e of n[1].split(`,`)){let n=e.trim();if(!n||n.startsWith(`type `))continue;let r=(n.split(/\s+as\s+/).at(-1)??``).trim();r&&t.add(r)}if(n[2]){let e=/as\s+([A-Za-z_$][\w$]*)/.exec(n[2]);e&&t.add(e[1])}n[3]&&n[3]!==`type`&&n[3]!==`async`&&n[3]!==`function`&&n[3]!==`class`&&t.add(n[3])}for(let n of e.matchAll(/(?:^|\n)\s*(?:export\s+)?(?:async\s+)?(?:function|class|const|let|var)\s+([A-Za-z_$][\w$]*)/g))t.add(n[1]);return t}function Fn(e,t,n){let r=new Set([...Mn(t),...Nn(e),...n,...Sn,...Cn]),i=new Set,a=0,o=e.length;for(;a<o;){let t=K(e,a,o);if(t!==-1){a=t;continue}if(!wn(e.charCodeAt(a))){a++;continue}let n=An(e,a);if(n==null){a++;continue}if(a>0&&e.charCodeAt(a-1)===46){a=n.end;continue}if(In(e,a,n.end)){a=n.end;continue}r.has(n.name)||i.add(n.name),a=n.end}return[...i]}function Z(e,t){for(;t>0;){let n=e.charCodeAt(t-1);if(n===32||n===9||n===10||n===13||n===65279)t--;else break}return t}function Q(e,t,n){let r=t-n.length;return r<0||!jn(e,r,n)?null:r}function In(e,t,n){let r=Y(e,n);if(e.charCodeAt(r)!==58)return!1;let i=Z(e,t);if(i===0)return!1;let a=e.charCodeAt(i-1);return a===123||a===44}function Ln(e,t){let n=Z(e,t),r=Q(e,n,`default`);if(r!=null){n=Z(e,r);let t=Q(e,n,`export`);if(t!=null)return{start:t,exportKind:`default`,bindingName:null}}if(n>0&&e.charCodeAt(n-1)===61){let r=Z(e,n-1),i=r;for(;i>0&&Tn(e.charCodeAt(i-1));)i--;if(i<r&&wn(e.charCodeAt(i))){let n=e.slice(i,r),a=Z(e,i),o=Q(e,a,`const`)??Q(e,a,`let`)??Q(e,a,`var`);if(o!=null)return Q(e,Z(e,o),`export`)==null?{start:t,exportKind:null,bindingName:n}:{start:t,exportKind:`named`,bindingName:n}}}let i=Q(e,n,`export`);return i==null?{start:t,exportKind:null,bindingName:null}:{start:i,exportKind:`named`,bindingName:null}}function Rn(e){let t=[],n=e.length,r=0;for(;r<n;){let n=e.charCodeAt(r);if(n===39||n===34||n===96){r=En(e,r,n);continue}if(n===47&&(e.charCodeAt(r+1)===47||e.charCodeAt(r+1)===42)){r=Y(e,r);continue}if(jn(e,r,`async`)||jn(e,r,`function`)){let n=r,i=r,a=!1;if(jn(e,i,`async`)&&(a=!0,i=Y(e,i+5)),jn(e,i,`function`)){i=Y(e,i+8),e.charCodeAt(i)===42&&(i=Y(e,i+1));let o=null,s=An(e,i);if(s&&(o=s.name,i=Y(e,s.end)),e.charCodeAt(i)!==40){r++;continue}let c=X(e,i,40,41),l=e.slice(i+1,c-1);if(i=Y(e,c),e.charCodeAt(i)!==123){r++;continue}let u=X(e,i,123,125)-1;On(e,i,u)?(t.push({start:n,end:u+1,bodyOpen:i,bodyClose:u,paramsRaw:l,isAsync:a,name:o,kind:o==null?`expression`:`declaration`}),r=u+1):r=i+1;continue}if(a&&e.charCodeAt(i)===40){let a=X(e,i,40,41),o=e.slice(i+1,a-1),s=Y(e,a);if(e.charCodeAt(s)===61&&e.charCodeAt(s+1)===62&&(s=Y(e,s+2),e.charCodeAt(s)===123)){let i=X(e,s,123,125)-1;On(e,s,i)?(t.push({start:n,end:i+1,bodyOpen:s,bodyClose:i,paramsRaw:o,isAsync:!0,name:null,kind:`arrow`}),r=i+1):r=s+1;continue}}}if(e.charCodeAt(r)===40){let n=X(e,r,40,41),i=Y(e,n);if(e.charCodeAt(i)===61&&e.charCodeAt(i+1)===62&&(i=Y(e,i+2),e.charCodeAt(i)===123)){let a=X(e,i,123,125)-1;On(e,i,a)?(t.push({start:r,end:a+1,bodyOpen:i,bodyClose:a,paramsRaw:e.slice(r+1,n-1),isAsync:!1,name:null,kind:`arrow`}),r=a+1):r=i+1;continue}}r++}return t}function zn(e,t){let n=Rn(e);if(n.length===0)return null;let r=Pn(e),i=[],a=[],o=e,s=[],c=!1,l=[...n].sort((e,t)=>t.start-e.start),u=n.length-1;for(let e of l){let n=e.name??`anonymous_server_function`,l=`$$ACTION_${u}_${n.replace(/\W/g,`_`)}`;u--,i.unshift(l);let d=kn(o,e.bodyOpen,e.bodyClose),f=Fn(d,e.paramsRaw,r),p=[...f,e.paramsRaw.trim()].filter(e=>e!==``).join(`, `),m=e.isAsync?`async `:``,h=f.length>0?`${l}.bind(null, ${f.join(`, `)})`:l,{start:g,exportKind:_,bindingName:v}=Ln(o,e.start),y=h,b=null;_==="default"?(b=`default`,y=`export default registerServerReference(${h}, ${JSON.stringify(t)}, "default")`):_===`named`&&e.name!=null?(b=e.name,y=`export const ${e.name} = registerServerReference(${h}, ${JSON.stringify(t)}, ${JSON.stringify(e.name)})`):_===`named`&&v!=null?(b=v,y=`registerServerReference(${h}, ${JSON.stringify(t)}, ${JSON.stringify(v)})`):e.kind===`declaration`&&e.name!=null&&(y=`const ${e.name} = ${h}`),b==null?s.unshift(`${m}function ${l}(${p}) {\n${d}\n}`,`registerServerReference(${l}, ${JSON.stringify(t)}, ${JSON.stringify(l)});`):(s.unshift(`${m}function ${l}(${p}) {\n${d}\n}`),a.unshift(b)),c=!0,o=o.slice(0,g)+y+o.slice(e.end)}let d=c?`import { registerServerReference } from ${JSON.stringify(`react-server-dom-rari/server`)};\n`:``;return{code:`${c&&!xn(o)?d:``}${o}\n\n${s.join(`
97
- `)}\n`,actionNames:i,rewrittenExportNames:a}}let Bn;async function Vn(){if(Bn!==void 0)return Bn;try{let e=(await import(`@rari/use-cache`)).transformUseCacheModule;return Bn=typeof e==`function`?e:null,Bn}catch{return Bn=null,null}}const Hn=/^proxy\.(?:tsx?|jsx?|mts|mjs)$/,Un=/\/components\/(\w+)(?:\.tsx?|\.jsx?)?$/,Wn=/[/\\]components[/\\]\w+(?:\.tsx?|\.jsx?)?$/,Gn=/^(?:robots|sitemap|feed)\.(?:tsx?|jsx?)$/,Kn=/^[./@~#]/,qn=/^node:/,Jn=`[hash]_[local]`;function Yn(e){if(e.startsWith(`@`)){let t=e.split(`/`);return t.length>=2?`${t[0]}/${t[1]}`:e}return e.split(`/`)[0]??e}function Xn(e,t){let n=Yn(t),r=e;for(;;){let e=D.join(r,`node_modules`,...n.split(`/`));if(T.existsSync(D.join(e,`package.json`)))return!0;let t=D.dirname(r);if(t===r)return!1;r=t}}const Zn=[{componentId:`rari/image`,devSourceSegments:[`src`,`image`,`image.tsx`],publishedExport:`rari/image`,exports:[`Image`]}],Qn=D.dirname(k(import.meta.url)),$=D.dirname(Qn);function $n(e){return e.startsWith($)}function er(e,t){return $n(e)?D.join($,`src`):D.join(t,`src`)}function tr(){let e=D.join($,`src`,`runtime`,`boundaries`,`error-boundary-wrapper.tsx`);if(T.existsSync(e))return e;try{let e=k(import.meta.resolve(`rari/runtime/ErrorBoundaryWrapper`));if(T.existsSync(e))return e}catch{}return null}function nr(e){let t=e.replace(x,`/`);return t.includes(`ErrorBoundaryWrapper`)||t.includes(`/boundaries/error-boundary-wrapper`)||t.endsWith(`/error-boundary-wrapper.tsx`)}function rr(e,t){if(nr(e))return`virtual:error-boundary-wrapper.tsx`;let n=D.relative(t,e).replace(x,`/`);return n.startsWith(`..`)||D.isAbsolute(n)?e.replace(x,`/`):n}function ir(e,t){if(nr(e))return`error_boundary_wrapper_${P(`virtual:error-boundary-wrapper.tsx`)}`;if($n(e)){let t=D.relative($,e).replace(x,`/`);return`${et(t)}_${P(t)}`}return tt(e,t)}let ar=null;async function or(){return ar||=(await import(`lightningcss`)).transform,ar}function sr(e){return a(e)&&a(e.components)}function cr(e,t,n,r){return e.includes(`node_modules`)||n.has(r??J(e))?!1:!t.directives.hasUseClient&&!t.directives.hasUseServer}var lr=class{serverComponents=new Map;serverActions=new Map;options;projectRoot;buildCache=new Map;useCacheBuildId=null;htmlOnlyImports=new Set;fileImporters=new Map;moduleAnalysisCache;discoveredExternalClientComponents=new Set;clientComponentFiles=new Map;recordClientComponent(e,t){this.clientComponentFiles.set(e,t)}getClientComponentFiles(){return[...this.clientComponentFiles.entries()].map(([e,t])=>({filePath:e,code:t}))}getClientComponentPaths(){return[...this.clientComponentFiles.keys()]}getModuleAnalysisCache(){return this.moduleAnalysisCache}clearClientComponentFiles(){this.clientComponentFiles.clear()}getComponentCount(){return this.serverComponents.size+this.serverActions.size}hasComponent(e){return this.serverComponents.has(e)||this.serverActions.has(e)}removeComponent(e){this.serverComponents.delete(e),this.serverActions.delete(e),this.moduleAnalysisCache.invalidate(e)}getImportGraph(){let e=new Map;for(let[t,n]of this.fileImporters)e.set(t,new Set(n));return e}getHtmlOnlyImports(){return new Set(this.htmlOnlyImports)}async writeComponentCssAsset(e,t){if(t.length===0)return[];let n=D.join(this.options.outDir,`assets`,`server`);await T.promises.mkdir(n,{recursive:!0});let r=`${t.join(`
98
- `)}\n`,i=`${P(e+r,12)}.css`,a=D.join(n,i);return await T.promises.writeFile(a,r,`utf-8`),[`/assets/server/${i}`]}getComponentIdFromRouteManifestPath(e){return this.getComponentId(D.join(this.projectRoot,`src`,`app`,e))}getComponentReferenceId(e){return this.getReadableComponentId(this.getProjectRelativePath(e))}async writeRouteCssEntries(e){let t=D.join(this.options.outDir,this.options.rscDir,`routes.json`);if(!T.existsSync(t))return;let n=await T.promises.readFile(t,`utf-8`),r=JSON.parse(n);if(!a(r))return;let i=r,o=t=>{if(Array.isArray(t))for(let n of t){if(!a(n))continue;let t=n.filePath;if(typeof t!=`string`||t===``)continue;let r=this.getComponentIdFromRouteManifestPath(t);n.componentId=r;let i=e.components[r]?.css??[];i.length?n.css=i:delete n.css}};o(i.routes),o(i.layouts),o(i.loading),o(i.errors),o(i.notFound),o(i.templates);let s=i.apiRoutes;if(Array.isArray(s))for(let e of s){if(!a(e))continue;let t=e.filePath;typeof t==`string`&&t!==``&&(e.componentId=this.getComponentIdFromRouteManifestPath(t))}await T.promises.writeFile(t,JSON.stringify(i),`utf-8`)}constructor(e,t={}){this.projectRoot=e,this.moduleAnalysisCache=t.moduleAnalysisCache??new Ut;let n=t.rscDir!=null&&t.rscDir!==``?t.rscDir:`server`;this.options={outDir:t.outDir!=null&&t.outDir!==``?t.outDir:D.join(e,`dist`),rscDir:n,manifestPath:t.manifestPath!=null&&t.manifestPath!==``?t.manifestPath:D.join(n,`manifest.json`),serverConfigPath:t.serverConfigPath!=null&&t.serverConfigPath!==``?t.serverConfigPath:D.join(n,`config.json`),minify:t.minify??O.env.NODE_ENV===`production`,alias:t.alias??{},define:t.define,csp:t.csp,cacheControl:t.cacheControl,cache:t.cache,action:t.action,jsPoolSize:t.jsPoolSize,origin:t.origin,htmlLimitedBots:t.htmlLimitedBots,experimental:t.experimental,mdx:t.mdx},this.parseHtmlImports()}parseHtmlImports(){for(let e of yn(this.projectRoot))this.htmlOnlyImports.add(e)}getModuleAnalysis(e,t){return this.moduleAnalysisCache.get(e,t)}isServerComponent(e,t){try{return cr(e,this.moduleAnalysisCache.get(e,t),this.htmlOnlyImports)}catch{return!1}}isClientComponent(e,t){try{return this.moduleAnalysisCache.get(e,t).directives.hasUseClient}catch{return!1}}resolveImportedFilePath(e,t){let n=null;if(t.startsWith(`./`)||t.startsWith(`../`)){let r=D.dirname(e);n=D.resolve(r,t)}else if(n=S(t,this.options.alias,this.projectRoot),(n==null||n===``)&&t.startsWith(`@/`)){let e=t.slice(2);n=D.join(this.projectRoot,`src`,e)}return n==null||n===``?null:ce(n,[``,`.ts`,`.tsx`,`.js`,`.jsx`])}populateImportGraphFromFiles(e){this.fileImporters.clear();for(let{filePath:t,analysis:n}of e)for(let e of Bt(n.importSources)){let n=this.resolveImportedFilePath(t,e);n!=null&&n!==``&&(this.fileImporters.has(n)||this.fileImporters.set(n,new Set),this.fileImporters.get(n).add(t))}}buildImportGraph(e){let t=ur(this,[e]);this.populateImportGraphFromFiles(t)}isOnlyImportedByClientComponents(e){let t=this.fileImporters.get(e);if(!t||t.size===0)return!1;for(let e of t)if(!this.isClientComponent(e)&&!this.isOnlyImportedByClientComponents(e))return!1;return!0}addServerComponent(e,t,n){let r=t??T.readFileSync(e,`utf-8`),i=n??this.moduleAnalysisCache.get(e,r),a=zt(i.importSources),o=Rt(i);if(i.directives.hasUseServer){this.serverActions.set(e,{filePath:e,originalCode:r,dependencies:a,hasNodeImports:o});return}cr(e,i,this.htmlOnlyImports)&&this.serverComponents.set(e,{filePath:e,originalCode:r,dependencies:a,hasNodeImports:o})}isServerAction(e,t){return t!=null&&t!==``?this.moduleAnalysisCache.get(t,e).directives.hasUseServer:W(e).directives.hasUseServer}extractDependencies(e,t){return zt((t!=null&&t!==``?this.moduleAnalysisCache.get(t,e):W(e)).importSources)}hasNodeImports(e,t){return Rt(t!=null&&t!==``?this.moduleAnalysisCache.get(t,e):W(e))}async getTransformedComponentsForDevelopment(e){let t=[];for(let[n]of this.serverComponents){if(e&&!e(n))continue;let r=D.relative(this.projectRoot,n),i=this.getComponentId(r),a=await this.buildComponentCodeOnly(n);t.push({id:i,code:a,isAction:!1})}for(let[n]of this.serverActions){if(e&&!e(n))continue;let r=D.relative(this.projectRoot,n),i=this.getComponentId(r),a=await this.buildComponentCodeOnly(n);t.push({id:i,code:a,isAction:!0})}return t}resolveComponentsDirClientImport(e){if(!e.startsWith(`.`)&&!e.startsWith(`@`)&&!e.startsWith(`~`)&&!e.startsWith(`#`))return null;if(e.startsWith(`.`)){if(!e.includes(`/components/`))return null;let t=Un.exec(e);if(!t)return null;let n=t[1],r=[D.resolve(this.projectRoot,`src`,`components`,`${n}.tsx`),D.resolve(this.projectRoot,`src`,`components`,`${n}.ts`),D.resolve(this.projectRoot,`src`,`components`,`${n}.jsx`),D.resolve(this.projectRoot,`src`,`components`,`${n}.js`)];for(let e of r)if(T.existsSync(e)&&this.isClientComponent(e))return{registryKey:`components/${n}`,absolutePath:e};return null}let t=null;for(let[n,r]of Object.entries(this.options.alias))if(e.startsWith(`${n}/`)||e===n){let i=e.slice(n.length).replace(/^\/+/,``);t=D.join(r,i);break}if(t==null||t===``||!Wn.exec(t))return null;let n=D.isAbsolute(t)?t:D.resolve(this.projectRoot,t),r=[n,`${n}.tsx`,`${n}.ts`,`${n}.jsx`,`${n}.js`];for(let e of r)if(T.existsSync(e)&&this.isClientComponent(e))return{registryKey:this.getComponentReferenceId(e),absolutePath:e};return null}transformComponentImportsToGlobal(e){let t=[];for(let n of ht(e)){if(n.typeOnly||n.sideEffectOnly)continue;let e=this.resolveComponentsDirClientImport(n.source);if(e==null)continue;let r=[];n.namespaceBinding!=null&&r.push(mn(n.namespaceBinding,e.registryKey)),n.defaultBinding!=null&&r.push(pn(n.defaultBinding,e.registryKey,`default`));for(let t of n.named)t.typeOnly||r.push(pn(t.local,e.registryKey,t.imported));r.length!==0&&t.push({start:n.start,end:n.end,replacement:r.join(`
99
- `)})}if(t.length===0)return e;let n=e;for(let{start:e,end:r,replacement:i}of[...t].sort((e,t)=>t.start-e.start))n=n.slice(0,e)+i+n.slice(r);return n}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}createRolldownModuleInfoPlugin(e){let t=new Set;return{name:`rari-rolldown-module-info`,moduleParsed(e){for(let n of e.importedIds)!n.startsWith(`.`)&&!n.startsWith(`/`)&&!n.startsWith(`node:`)&&!q(n)&&t.add(n);for(let n of e.dynamicallyImportedIds)!n.startsWith(`.`)&&!n.startsWith(`/`)&&!n.startsWith(`node:`)&&!q(n)&&t.add(n)},buildEnd:()=>{if(t.size===0)return;let n=[...t].sort(),r=this.serverComponents.get(e)??this.serverActions.get(e);r&&(r.dependencies=n);let i=this.buildCache.get(e);i&&(i.bundledDependencies=n)}}}createBuildPlugins(e,t,n,r,i=!1,a){let o=D.dirname(r),s=Hn.test(D.basename(r)),c=new Map,l=new Map;return[{name:`virtual-module`,resolveId(t,n){if(t===e)return t;if(n===e&&(t.startsWith(`./`)||t.startsWith(`../`))){if(t.endsWith(`.module.css`))return null;let e=D.resolve(o,t);for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`,``]){let n=e+t;if(T.existsSync(n)&&T.statSync(n).isFile())return n}for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=D.join(e,`index${t}`);if(T.existsSync(n))return n}return e}return null},load(r){return r===e?{code:t,moduleType:n}:null}},{name:`resolve-client-server-boundaries`,enforce:`pre`,resolveId:(t,n)=>{if(n==null||n===``||n.includes(`node_modules`)||$n(n)||t.startsWith(`node:`)||q(t)||t===`react`||t===`react-dom`||t===`react/jsx-runtime`||t===`react/jsx-dev-runtime`)return null;let r=null,i=this.options.alias;if(r=S(t,i,this.projectRoot),(r==null||r===``)&&(t.startsWith(`./`)||t.startsWith(`../`))){let i=n===e?o:D.dirname(n);r=D.resolve(i,t)}if((r==null||r===``)&&D.isAbsolute(t)&&(r=t),r!==``)for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=r+e;if(T.existsSync(t)&&T.statSync(t).isFile()){if(this.isClientComponent(t)){let e=D.relative(this.projectRoot,t),n=(e.startsWith(`..`)?t:e).replace(x,`/`);return c.set(t,n),e.startsWith(`..`)&&this.discoveredExternalClientComponents.add(t),{id:`\0client-ref:${t}`}}try{let e=this.moduleAnalysisCache.get(t);if(e.directives.hasUseServer){let n=this.getComponentId(t);return l.set(t,{actionId:n,hasDefaultExport:e.hasDefaultExport}),{id:`\0server-action:${t}`}}}catch(e){console.error(`[rari] Failed to read file for server action detection: ${t}`,e)}break}}return null},load:e=>{if(e.startsWith(`\0client-ref:`)){let t=e.slice(12),n=D.relative(this.projectRoot,t),r=(c.get(t)??(n.startsWith(`..`)?t:n)).replace(x,`/`);return{code:this.generateClientReferenceStub(t,r),moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15),n=l.get(t)?.actionId??this.getComponentId(t);return{code:this.generateServerActionRuntimeModule(t,n),moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!i)return null;if(e.startsWith(`file://`)){let t=e.replace(m,``);return T.existsSync(t)?{id:`\0transformed:${t}`}:null}let n=null,r=this.options.alias;n=S(e,r,this.projectRoot);let a=t?.startsWith(`\0`)?o:t!=null&&t!==``?D.dirname(t):o;if((n==null||n===``)&&(e.startsWith(`./`)||e.startsWith(`../`))&&(n=D.resolve(a,e)),n==null||n===``||a.includes(`node_modules`))return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=n+e;if(T.existsSync(t)&&T.statSync(t).isFile()){if(this.isClientComponent(t)||this.isServerActionFile(t))return null;let e=D.join(this.projectRoot,`src`);if(!t.startsWith(e))return null;let n=this.getComponentId(t),r=D.join(this.options.outDir,this.options.rscDir,`${n}.js`);if(T.existsSync(r))return{id:`\0transformed:${r}`};break}}return null},load(e){if(e.startsWith(`\0transformed:`)){let t=e.slice(13);return{code:T.readFileSync(t,`utf-8`),moduleType:`js`}}return null}},{name:`resolve-aliases`,resolveId:e=>{if(e.startsWith(`\0`))return null;let t=S(e,this.options.alias,this.projectRoot);if(t==null||t===``)return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let n=t+e;if(T.existsSync(n)&&T.statSync(n).isFile()){if(this.isServerActionFile(n)){let e=this.getComponentId(n);return l.set(n,{actionId:e,hasDefaultExport:this.moduleAnalysisCache.get(n).hasDefaultExport}),{id:`\0server-action:${n}`}}return n}}for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=D.join(t,`index${e}`);if(T.existsSync(n)){if(this.isServerActionFile(n)){let e=this.getComponentId(n);return l.set(n,{actionId:e,hasDefaultExport:this.moduleAnalysisCache.get(n).hasDefaultExport}),{id:`\0server-action:${n}`}}return n}}return t}},{name:`resolve-rari-proxy`,resolveId:e=>{if(s&&e===`rari`){let e=D.join(Qn,`proxy/RariResponse.mjs`);if(T.existsSync(e))return e;let t=D.join($,`src/proxy/http/response.ts`);if(T.existsSync(t))return t}return null}},{name:`css-modules`,resolveId:(e,t)=>{if(e.endsWith(`.module.css`)){let n=t!=null&&t!==``&&!t.startsWith(`\0`)?D.dirname(t):o,r=D.resolve(n,e);if(T.existsSync(r))return{id:`\0css-module:${r}`}}return null},load:async e=>{if(!e.startsWith(`\0css-module:`))return null;let t=e.slice(12);try{let e=await or(),n=T.readFileSync(t),r=e({filename:D.relative(this.projectRoot,t),code:n,cssModules:{pattern:Jn}});a&&a.push(new TextDecoder().decode(r.code));let i={};if(r.exports)for(let[e,t]of Object.entries(r.exports))i[e]=t.name;return{code:`export default ${JSON.stringify(i)}`,moduleType:`js`}}catch(t){throw Error(`[rari] Failed to process CSS module ${e}: ${t instanceof Error?t.message:String(t)}`)}}},{name:`externalize-deps`,resolveId:(e,t)=>{if(e.startsWith(`\0`))return null;if(e.startsWith(`node:`)||q(e)||[`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`rari/image`].includes(e)||e in{"rari/runtime/cache-wrapper":`node_modules/rari/dist/runtime/cache-wrapper.mjs`,"react-server-dom-rari/server":`node_modules/rari/dist/runtime/rsc-references.mjs`})return{id:e,external:!0};if(e===`rari`||S(e,this.options.alias,this.projectRoot)!=null)return null;if(!e.startsWith(`.`)&&!e.startsWith(`/`)){if(Xn(this.projectRoot,e))return{id:e,external:!0};let n=[t!=null&&t!==``&&!t.startsWith(`\0`)?t:null,r].filter(e=>!!e);for(let t of n)try{return{id:w(t).resolve(e)}}catch{try{let n=import.meta.resolve(e,A(t).href);return{id:k(n)}}catch{}}return null}return null}},this.createRolldownModuleInfoPlugin(r),{name:`use-cache`,transform:async(e,t)=>{if(!this.options.experimental?.useCache&&!this.options.experimental?.useCacheRemote)return null;let n=await Vn();return n?n(e,t,{hashSalt:`${this.useCacheBuildId??`development`}:rari-use-cache-v1`}):null}}]}async buildComponentCodeOnly(e){let t=await T.promises.readFile(e,`utf-8`),n=zn(t,this.getComponentId(e))?.code??t,r=this.transformClientImports(n,e),i=this.isPageComponent(e),a=i?this.transformComponentImportsToGlobal(r):r,o=D.extname(e),s;s=o===`.tsx`?`tsx`:o===`.ts`?`ts`:o===`.jsx`?`jsx`:`js`;let c=`\0virtual:${e}`,l=await he({input:c,platform:`node`,write:!1,external:[qn,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${s}`]:s},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(O.env.NODE_ENV!=null&&O.env.NODE_ENV!==``?O.env.NODE_ENV:`production`),...this.options.define}},plugins:this.createBuildPlugins(c,a,s,e,i,[])});if(l.output.length===0)throw Error(`No output generated from Rolldown`);let u=l.output.find(e=>e.type===`chunk`&&e.isEntry);if(u?.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let d=u.code;return d=`// Built: ${new Date().toISOString()}\n${d}`,d}async buildComponentBatch(e,t,n){let r=0,i=0,a=[];if(await new Promise(o=>{let s=()=>{for(;r<n&&i<e.length;){let[n,c]=e[i++],l=D.relative(this.projectRoot,n),u=this.getComponentId(n),d=D.join(this.options.rscDir,`${u}.js`),f=D.join(this.options.outDir,d);r++,(async()=>{try{let e=D.dirname(f);await T.promises.mkdir(e,{recursive:!0});let r=await this.buildSingleComponent(n,f),i=await this.writeComponentCssAsset(u,r.css),a=A(D.resolve(this.projectRoot,f)).href;t.components[u]={id:u,filePath:n,relativePath:l,bundlePath:d,moduleSpecifier:a,dependencies:[...c.dependencies],hasNodeImports:c.hasNodeImports,css:i}}catch(e){a.push(e instanceof Error?e:Error(String(e)))}finally{r--,i>=e.length&&r===0?o():s()}})()}e.length===0&&o()};s()}),a.length>0)throw a[0]}async buildServerComponents(){let e=D.join(this.options.outDir,this.options.rscDir);await T.promises.mkdir(e,{recursive:!0});let t={components:{},buildTime:new Date().toISOString()},n=this.options.experimental?.useCache===!0||this.options.experimental?.useCacheRemote!=null,r=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),i=[...this.serverComponents.entries()].filter(([e])=>!this.isPageComponent(e)),a=[...this.serverComponents.entries()].filter(([e])=>this.isPageComponent(e)),s=[...this.serverActions.entries()];await Promise.all([this.buildComponentBatch(i,t,r),this.buildComponentBatch(s,t,r)]),await this.buildComponentBatch(a,t,r),n&&(this.useCacheBuildId=P(JSON.stringify(t.components),16),t.useCacheBuildId=this.useCacheBuildId);let c=D.join(this.options.outDir,this.options.manifestPath);await T.promises.writeFile(c,JSON.stringify(t),`utf-8`),await this.writeRouteCssEntries(t);let l={};this.options.csp&&(l.csp=this.options.csp),this.options.cacheControl&&(l.cacheControl=this.options.cacheControl),this.options.cache&&(l.cache=this.options.cache),this.options.action&&(l.action=this.options.action),this.options.jsPoolSize!=null&&(l.jsPoolSize=this.options.jsPoolSize);let u=this.options.origin?.trim().replace(/\/+$/,``);u!=null&&u!==``&&(l.origin=u),this.options.htmlLimitedBots!=null&&(l.htmlLimitedBots=this.options.htmlLimitedBots),(this.options.experimental?.useCacheRemote!=null||this.useCacheBuildId!=null&&this.useCacheBuildId!==``)&&(l.useCache={...this.options.experimental?.useCacheRemote?{remote:this.options.experimental.useCacheRemote}:{},...this.useCacheBuildId!=null&&this.useCacheBuildId!==``?{buildId:this.useCacheBuildId}:{}},!this.options.experimental?.useCache&&this.options.experimental?.useCacheRemote&&console.warn(`[server-build] experimental.useCacheRemote is set without experimental.useCache; the 'use cache' transform will still run because useCacheRemote is configured.`));let d=D.join(this.options.outDir,this.options.serverConfigPath);if(Object.keys(l).length===0)try{await T.promises.unlink(d)}catch(e){o(e)!==`ENOENT`&&console.warn(`Failed to remove server config file:`,e)}else await T.promises.writeFile(d,JSON.stringify(l),`utf-8`);return t}async buildMdxRegistry(e){let n=rn({projectRoot:this.projectRoot,mdxOptions:e,alias:this.options.alias,cache:this.moduleAnalysisCache}),r=D.join(this.options.outDir,this.options.manifestPath),i;if(T.existsSync(r)){let e=await T.promises.readFile(r,`utf-8`),n=t(e);i=n&&sr(n)?n:{components:{},buildTime:new Date().toISOString()}}else i={components:{},buildTime:new Date().toISOString()};i.mdxRegistry=n.map(e=>({name:e.name,id:e.moduleId,client:e.client})),await T.promises.writeFile(r,JSON.stringify(i),`utf-8`)}async buildSSRClientComponents(){let e=D.join(this.options.outDir,`ssr`);await T.promises.mkdir(e,{recursive:!0});let t=[...this.getClientComponentFiles()];for(let e of this.discoveredExternalClientComponents)if(!t.some(t=>t.filePath===e))try{let n=T.readFileSync(e,`utf-8`);t.push({filePath:e,code:n})}catch{}try{let e=tr();if(e!=null&&e!==``){let n=T.readFileSync(e,`utf-8`);t.push({filePath:e,code:n})}}catch{}if(t.length===0){let t={};await this.buildExternalClientComponents(t,new Map),await this.writeClientReferenceManifest(e,t);return}let n=new Map;for(let{filePath:e}of t){let t=ir(e,this.projectRoot);n.set(D.resolve(e),`file:///ssr/${t}.js`)}let r={},i=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),a=0,o=0;await new Promise(e=>{let s=()=>{for(;a<i&&o<t.length;){let{filePath:i,code:c}=t[o++],l=rr(i,this.projectRoot),u=`ssr/${ir(i,this.projectRoot)}.js`,d=D.join(this.options.outDir,u);a++,(async()=>{try{let e=D.dirname(d);await T.promises.mkdir(e,{recursive:!0}),await this.buildSSRSingleClient(i,d,n);let t=this.extractExportNames(c);r[l]={id:l,filePath:i,bundlePath:u,exports:t}}catch(e){console.warn(`[rari] SSR build failed for ${l}:`,e instanceof Error?e.message:e)}finally{a--,o>=t.length&&a===0?e():s()}})()}t.length===0&&e()};s()}),await this.buildExternalClientComponents(r,n),await this.writeClientReferenceManifest(e,r)}async writeClientReferenceManifest(e,t){let n=D.join(e,`manifest.json`);await T.promises.writeFile(n,JSON.stringify(t),`utf-8`);let r={};for(let[e,n]of Object.entries(t))for(let t of n.exports){let i=`${e}#${t}`;r[i]={id:i,chunks:`/${n.bundlePath}`,name:t}}let i=D.join(this.options.outDir,`server`);await T.promises.mkdir(i,{recursive:!0});let a=D.join(i,`client-reference-manifest.json`);await T.promises.writeFile(a,JSON.stringify(r),`utf-8`)}resolveExternalClientSourcePath(e,t){let n=D.join($,...e);if(T.existsSync(n))return n;try{let e=k(import.meta.resolve(t));if(T.existsSync(e))return e}catch{}return null}async buildExternalClientComponents(e,t){for(let{componentId:n,devSourceSegments:r,publishedExport:i,exports:a}of Zn){let o=this.resolveExternalClientSourcePath(r,i);if(o!=null&&o!==``)try{let r=`ssr/${`external_${P(n)}`}.js`,i=D.join(this.options.outDir,r);await T.promises.mkdir(D.dirname(i),{recursive:!0}),await this.buildSSRSingleClient(o,i,t),e[n]={id:n,filePath:o,bundlePath:r,exports:[...a]}}catch(e){console.warn(`[rari] SSR build failed for ${n}:`,e instanceof Error?e.message:e)}}}extractExportNames(e){return gt(e)}generateClientReferenceStub(e,t){let n=[`default`];try{n=gt(T.readFileSync(e,`utf-8`))}catch{}return fn(t,n)}isServerActionFile(e){try{let t=T.readFileSync(e,`utf-8`);return this.isServerAction(t,e)}catch{return!1}}generateServerActionRuntimeModule(e,t){let n=T.readFileSync(e,`utf-8`),r=this.extractExportNames(n),i=[`const __rariActionMod = globalThis.__rari_rsc_require__(${JSON.stringify(t)});`,`if (!__rariActionMod) throw new Error("Server action module ${t} is not registered");`];for(let e of r)e==="default"?i.push(`export default __rariActionMod.default;`):i.push(`export const ${e} = __rariActionMod.${e};`);return`${i.join(`
100
- `)}\n`}generateServerActionReferenceModule(e){let t=T.readFileSync(e,`utf-8`),n=this.extractExportNames(t),r=this.getComponentId(e),i=`import { createServerReference } from 'react-server-dom-webpack/client';
96
+ || {};`}const gn=/import\s*\(\s*["']([^"']+)["']\s*\)|import\s+["']([^"']+)["']/g,_n=/<script\b[^>]*>/gi;function vn(e,t,n){n?.startsWith(`/src/`)&&e.add(q(E.join(t,n.slice(1))))}function yn(e){return/\btype\s*=\s*["']module["']/i.test(e)?/\bsrc\s*=\s*["']([^"']+)["']/i.exec(e)?.[1]??null:null}function bn(e){let t=new Set,n=E.join(e,`index.html`);if(!w.existsSync(n))return t;try{let r=w.readFileSync(n,`utf-8`);for(let n of r.matchAll(gn))vn(t,e,n[1]||n[2]);for(let n of r.matchAll(_n))vn(t,e,yn(n[0]))}catch{}return t}const xn=/(?:^|[\n\r;])\s*import\s*\{[^}]*\bregisterServerReference\b[^}]*\}\s*from\s*["'][^"'\n]+["']/;function Sn(e){return xn.test(e)}const Cn=new Set(`undefined.NaN.Infinity.arguments.Object.Array.String.Number.Boolean.Symbol.BigInt.Math.Date.JSON.Promise.Error.TypeError.RangeError.Map.Set.WeakMap.WeakSet.RegExp.Proxy.Reflect.Function.console.fetch.process.Buffer.globalThis.global.window.document.navigator.location.crypto.TextEncoder.TextDecoder.URL.URLSearchParams.FormData.Headers.Request.Response.AbortController.AbortSignal.setTimeout.clearTimeout.setInterval.clearInterval.queueMicrotask.structuredClone.atob.btoa.React.jsx.jsxs.Fragment`.split(`.`)),wn=new Set(`await.return.throw.if.else.for.while.do.switch.case.break.continue.new.typeof.instanceof.void.delete.yield.class.extends.super.this.try.catch.finally.with.debugger.default.of.in.from.as.import.export.async.function.const.let.var.true.false.null.static.get.set.typeof`.split(`.`));function Tn(e){return e>=97&&e<=122||e>=65&&e<=90||e===95||e===36}function En(e){return Tn(e)||e>=48&&e<=57}function J(e,t){let n=e.length;for(;t<n;){let r=e.charCodeAt(t);if(r===32||r===9||r===10||r===13||r===65279){t++;continue}if(r===47&&e.charCodeAt(t+1)===47){for(t+=2;t<n&&e.charCodeAt(t)!==10&&e.charCodeAt(t)!==13;)t++;continue}if(r===47&&e.charCodeAt(t+1)===42){for(t+=2;t<n-1&&(e.charCodeAt(t)!==42||e.charCodeAt(t+1)!==47);)t++;t+=2;continue}break}return t}function Dn(e,t,n){t++;let r=e.length;for(;t<r;){let r=e.charCodeAt(t);if(r===92){t+=2;continue}if(r===n)return t+1;t++}return t}function Y(e,t,n,r){let i=t,a=0,o=e.length;for(;i<o;){let t=K(e,i,o);if(t!==-1){i=t;continue}let s=e.charCodeAt(i);if(s===n)a++;else if(s===r&&(a--,a===0))return i+1;i++}return i}function On(e,t,n){for(let r=0;r<n.length;r++)if(e.charCodeAt(t+r)!==n.charCodeAt(r))return!1;return!0}function kn(e,t,n){let r=J(e,t+1);if(r>=n)return!1;let i=e.charCodeAt(r);if(i!==39&&i!==34)return!1;let a=r+1,o=Dn(e,r,i);if(o-1-a!=10||!On(e,a,`use server`))return!1;for(r=o;r<n;){let t=e.charCodeAt(r);if(t===32||t===9){r++;continue}return t===59||t===10||t===13||t===47&&e.charCodeAt(r+1)===47||t===47&&e.charCodeAt(r+1)===42}return!0}function An(e,t,n){let r=J(e,t+1),i=e.charCodeAt(r);return i!==39&&i!==34?e.slice(t+1,n):(r=J(e,Dn(e,r,i)),e.charCodeAt(r)===59&&r++,r=J(e,r),e.slice(r,n))}function jn(e,t){if(!Tn(e.charCodeAt(t)))return null;let n=t+1;for(;n<e.length&&En(e.charCodeAt(n));)n++;return{name:e.slice(t,n),end:n}}function Mn(e,t,n){if(!On(e,t,n))return!1;let r=t>0?e.charCodeAt(t-1):-1,i=t+n.length<e.length?e.charCodeAt(t+n.length):-1;return!(r!==-1&&En(r)||i!==-1&&En(i))}function Nn(e){let t=new Set,n=0,r=e.length;for(;n<r&&(n=J(e,n),!(n>=r));){let r=e.charCodeAt(n);if(r===123||r===91){let i=Y(e,n,r,r===123?125:93);for(let r of e.slice(n,i).matchAll(/[a-z_$][\w$]*/gi))r[0]!==`as`&&t.add(r[0]);n=i;continue}if(r===46&&e.charCodeAt(n+1)===46&&e.charCodeAt(n+2)===46){n+=3,n=J(e,n);let r=jn(e,n);r&&(t.add(r.name),n=r.end);continue}let i=jn(e,n);if(i){t.add(i.name),n=i.end;continue}n++}return t}function Pn(e){let t=new Set;for(let n of e.matchAll(/\b(?:const|let|var|function|class|async\s+function)\s+([A-Za-z_$][\w$]*)/g))t.add(n[1]);return t}function Fn(e){let t=new Set;for(let n of e.matchAll(/\b(?:import|export)\s+(?:type\s+)?(?:\{([^}]+)\}|(\*\s+as\s+[A-Za-z_$][\w$]*)|([A-Za-z_$][\w$]*))/g)){if(n[1])for(let e of n[1].split(`,`)){let n=e.trim();if(!n||n.startsWith(`type `))continue;let r=(n.split(/\s+as\s+/).at(-1)??``).trim();r&&t.add(r)}if(n[2]){let e=/as\s+([A-Za-z_$][\w$]*)/.exec(n[2]);e&&t.add(e[1])}n[3]&&n[3]!==`type`&&n[3]!==`async`&&n[3]!==`function`&&n[3]!==`class`&&t.add(n[3])}for(let n of e.matchAll(/(?:^|\n)\s*(?:export\s+)?(?:async\s+)?(?:function|class|const|let|var)\s+([A-Za-z_$][\w$]*)/g))t.add(n[1]);return t}function In(e,t,n){let r=new Set([...Nn(t),...Pn(e),...n,...Cn,...wn]),i=new Set,a=0,o=e.length;for(;a<o;){let t=K(e,a,o);if(t!==-1){a=t;continue}if(!Tn(e.charCodeAt(a))){a++;continue}let n=jn(e,a);if(n==null){a++;continue}if(a>0&&e.charCodeAt(a-1)===46){a=n.end;continue}if(Ln(e,a,n.end)){a=n.end;continue}r.has(n.name)||i.add(n.name),a=n.end}return[...i]}function X(e,t){for(;t>0;){let n=e.charCodeAt(t-1);if(n===32||n===9||n===10||n===13||n===65279)t--;else break}return t}function Z(e,t,n){let r=t-n.length;return r<0||!Mn(e,r,n)?null:r}function Ln(e,t,n){let r=J(e,n);if(e.charCodeAt(r)!==58)return!1;let i=X(e,t);if(i===0)return!1;let a=e.charCodeAt(i-1);return a===123||a===44}function Rn(e,t){let n=X(e,t),r=Z(e,n,`default`);if(r!=null){n=X(e,r);let t=Z(e,n,`export`);if(t!=null)return{start:t,exportKind:`default`,bindingName:null}}if(n>0&&e.charCodeAt(n-1)===61){let r=X(e,n-1),i=r;for(;i>0&&En(e.charCodeAt(i-1));)i--;if(i<r&&Tn(e.charCodeAt(i))){let n=e.slice(i,r),a=X(e,i),o=Z(e,a,`const`)??Z(e,a,`let`)??Z(e,a,`var`);if(o!=null)return Z(e,X(e,o),`export`)==null?{start:t,exportKind:null,bindingName:n}:{start:t,exportKind:`named`,bindingName:n}}}let i=Z(e,n,`export`);return i==null?{start:t,exportKind:null,bindingName:null}:{start:i,exportKind:`named`,bindingName:null}}function zn(e){let t=[],n=e.length,r=0;for(;r<n;){let n=e.charCodeAt(r);if(n===39||n===34||n===96){r=Dn(e,r,n);continue}if(n===47&&(e.charCodeAt(r+1)===47||e.charCodeAt(r+1)===42)){r=J(e,r);continue}if(Mn(e,r,`async`)||Mn(e,r,`function`)){let n=r,i=r,a=!1;if(Mn(e,i,`async`)&&(a=!0,i=J(e,i+5)),Mn(e,i,`function`)){i=J(e,i+8),e.charCodeAt(i)===42&&(i=J(e,i+1));let o=null,s=jn(e,i);if(s&&(o=s.name,i=J(e,s.end)),e.charCodeAt(i)!==40){r++;continue}let c=Y(e,i,40,41),l=e.slice(i+1,c-1);if(i=J(e,c),e.charCodeAt(i)!==123){r++;continue}let u=Y(e,i,123,125)-1;kn(e,i,u)?(t.push({start:n,end:u+1,bodyOpen:i,bodyClose:u,paramsRaw:l,isAsync:a,name:o,kind:o==null?`expression`:`declaration`}),r=u+1):r=i+1;continue}if(a&&e.charCodeAt(i)===40){let a=Y(e,i,40,41),o=e.slice(i+1,a-1),s=J(e,a);if(e.charCodeAt(s)===61&&e.charCodeAt(s+1)===62&&(s=J(e,s+2),e.charCodeAt(s)===123)){let i=Y(e,s,123,125)-1;kn(e,s,i)?(t.push({start:n,end:i+1,bodyOpen:s,bodyClose:i,paramsRaw:o,isAsync:!0,name:null,kind:`arrow`}),r=i+1):r=s+1;continue}}}if(e.charCodeAt(r)===40){let n=Y(e,r,40,41),i=J(e,n);if(e.charCodeAt(i)===61&&e.charCodeAt(i+1)===62&&(i=J(e,i+2),e.charCodeAt(i)===123)){let a=Y(e,i,123,125)-1;kn(e,i,a)?(t.push({start:r,end:a+1,bodyOpen:i,bodyClose:a,paramsRaw:e.slice(r+1,n-1),isAsync:!1,name:null,kind:`arrow`}),r=a+1):r=i+1;continue}}r++}return t}function Bn(e,t){let n=zn(e);if(n.length===0)return null;let r=Fn(e),i=[],a=[],o=e,s=[],c=!1,l=[...n].sort((e,t)=>t.start-e.start),u=n.length-1;for(let e of l){let n=e.name??`anonymous_server_function`,l=`$$ACTION_${u}_${n.replace(/\W/g,`_`)}`;u--,i.unshift(l);let d=An(o,e.bodyOpen,e.bodyClose),f=In(d,e.paramsRaw,r),p=[...f,e.paramsRaw.trim()].filter(e=>e!==``).join(`, `),m=e.isAsync?`async `:``,h=f.length>0?`${l}.bind(null, ${f.join(`, `)})`:l,{start:g,exportKind:_,bindingName:v}=Rn(o,e.start),y=h,b=null;_==="default"?(b=`default`,y=`export default registerServerReference(${h}, ${JSON.stringify(t)}, "default")`):_===`named`&&e.name!=null?(b=e.name,y=`export const ${e.name} = registerServerReference(${h}, ${JSON.stringify(t)}, ${JSON.stringify(e.name)})`):_===`named`&&v!=null?(b=v,y=`registerServerReference(${h}, ${JSON.stringify(t)}, ${JSON.stringify(v)})`):e.kind===`declaration`&&e.name!=null&&(y=`const ${e.name} = ${h}`),b==null?s.unshift(`${m}function ${l}(${p}) {\n${d}\n}`,`registerServerReference(${l}, ${JSON.stringify(t)}, ${JSON.stringify(l)});`):(s.unshift(`${m}function ${l}(${p}) {\n${d}\n}`),a.unshift(b)),c=!0,o=o.slice(0,g)+y+o.slice(e.end)}let d=c?`import { registerServerReference } from ${JSON.stringify(`react-server-dom-rari/server`)};\n`:``;return{code:`${c&&!Sn(o)?d:``}${o}\n\n${s.join(`
97
+ `)}\n`,actionNames:i,rewrittenExportNames:a}}let Vn;async function Hn(){if(Vn!==void 0)return Vn;try{let e=(await import(`@rari/use-cache`)).transformUseCacheModule;return Vn=typeof e==`function`?e:null,Vn}catch{return Vn=null,null}}const Un=/^proxy\.(?:tsx?|jsx?|mts|mjs)$/,Wn=/\/components\/(\w+)(?:\.tsx?|\.jsx?)?$/,Gn=/[/\\]components[/\\]\w+(?:\.tsx?|\.jsx?)?$/,Kn=/^(?:robots|sitemap|feed)\.(?:tsx?|jsx?)$/,qn=/^[./@~#]/,Jn=/^node:/,Yn=`[hash]_[local]`;function Xn(e){if(e.startsWith(`@`)){let t=e.split(`/`);return t.length>=2?`${t[0]}/${t[1]}`:e}return e.split(`/`)[0]??e}function Zn(e,t){let n=Xn(t),r=e;for(;;){let e=E.join(r,`node_modules`,...n.split(`/`));if(w.existsSync(E.join(e,`package.json`)))return!0;let t=E.dirname(r);if(t===r)return!1;r=t}}const Qn=[{componentId:`rari/image`,devSourceSegments:[`src`,`image`,`image.tsx`],publishedExport:`rari/image`,exports:[`Image`]}],$n=E.dirname(O(import.meta.url)),Q=E.dirname($n);function er(e){return e.startsWith(Q)}function tr(e,t){return er(e)?E.join(Q,`src`):E.join(t,`src`)}function nr(){let e=E.join(Q,`src`,`runtime`,`boundaries`,`error-boundary-wrapper.tsx`);if(w.existsSync(e))return e;try{let e=O(import.meta.resolve(`rari/runtime/ErrorBoundaryWrapper`));if(w.existsSync(e))return e}catch{}return null}function rr(e){let t=e.replace(x,`/`);return t.includes(`ErrorBoundaryWrapper`)||t.includes(`/boundaries/error-boundary-wrapper`)||t.endsWith(`/error-boundary-wrapper.tsx`)}function ir(e,t){if(rr(e))return`virtual:error-boundary-wrapper.tsx`;let n=E.relative(t,e).replace(x,`/`);return n.startsWith(`..`)||E.isAbsolute(n)?e.replace(x,`/`):n}function ar(e,t){if(rr(e))return`error_boundary_wrapper_${P(`virtual:error-boundary-wrapper.tsx`)}`;if(er(e)){let t=E.relative(Q,e).replace(x,`/`);return`${et(t)}_${P(t)}`}return tt(e,t)}let or=null;async function sr(){return or||=(await import(`lightningcss`)).transform,or}function cr(e){return a(e)&&a(e.components)}function lr(e,t,n,r){return e.includes(`node_modules`)||n.has(r??q(e))?!1:!t.directives.hasUseClient&&!t.directives.hasUseServer}var ur=class{serverComponents=new Map;serverActions=new Map;options;projectRoot;buildCache=new Map;useCacheBuildId=null;htmlOnlyImports=new Set;fileImporters=new Map;moduleAnalysisCache;discoveredExternalClientComponents=new Set;clientComponentFiles=new Map;recordClientComponent(e,t){this.clientComponentFiles.set(e,t)}getClientComponentFiles(){return[...this.clientComponentFiles.entries()].map(([e,t])=>({filePath:e,code:t}))}getClientComponentPaths(){return[...this.clientComponentFiles.keys()]}getModuleAnalysisCache(){return this.moduleAnalysisCache}clearClientComponentFiles(){this.clientComponentFiles.clear()}getComponentCount(){return this.serverComponents.size+this.serverActions.size}hasComponent(e){return this.serverComponents.has(e)||this.serverActions.has(e)}removeComponent(e){this.serverComponents.delete(e),this.serverActions.delete(e),this.moduleAnalysisCache.invalidate(e)}getImportGraph(){let e=new Map;for(let[t,n]of this.fileImporters)e.set(t,new Set(n));return e}getHtmlOnlyImports(){return new Set(this.htmlOnlyImports)}async writeComponentCssAsset(e,t){if(t.length===0)return[];let n=E.join(this.options.outDir,`assets`,`server`);await w.promises.mkdir(n,{recursive:!0});let r=`${t.join(`
98
+ `)}\n`,i=`${P(e+r,12)}.css`,a=E.join(n,i);return await w.promises.writeFile(a,r,`utf-8`),[`/assets/server/${i}`]}getComponentIdFromRouteManifestPath(e){return this.getComponentId(E.join(this.projectRoot,`src`,`app`,e))}getComponentReferenceId(e){return this.getReadableComponentId(this.getProjectRelativePath(e))}async writeRouteCssEntries(e){let t=E.join(this.options.outDir,this.options.rscDir,`routes.json`);if(!w.existsSync(t))return;let n=await w.promises.readFile(t,`utf-8`),r=JSON.parse(n);if(!a(r))return;let i=r,o=t=>{if(Array.isArray(t))for(let n of t){if(!a(n))continue;let t=n.filePath;if(typeof t!=`string`||t===``)continue;let r=this.getComponentIdFromRouteManifestPath(t);n.componentId=r;let i=e.components[r]?.css??[];i.length?n.css=i:delete n.css}};o(i.routes),o(i.layouts),o(i.loading),o(i.errors),o(i.notFound),o(i.templates);let s=i.apiRoutes;if(Array.isArray(s))for(let e of s){if(!a(e))continue;let t=e.filePath;typeof t==`string`&&t!==``&&(e.componentId=this.getComponentIdFromRouteManifestPath(t))}await w.promises.writeFile(t,JSON.stringify(i),`utf-8`)}constructor(e,t={}){this.projectRoot=e,this.moduleAnalysisCache=t.moduleAnalysisCache??new Wt;let n=t.rscDir!=null&&t.rscDir!==``?t.rscDir:`server`;this.options={outDir:t.outDir!=null&&t.outDir!==``?t.outDir:E.join(e,`dist`),rscDir:n,manifestPath:t.manifestPath!=null&&t.manifestPath!==``?t.manifestPath:E.join(n,`manifest.json`),serverConfigPath:t.serverConfigPath!=null&&t.serverConfigPath!==``?t.serverConfigPath:E.join(n,`config.json`),minify:t.minify??D.env.NODE_ENV===`production`,alias:t.alias??{},define:t.define,csp:t.csp,cacheControl:t.cacheControl,cache:t.cache,action:t.action,jsPoolSize:t.jsPoolSize,origin:t.origin,htmlLimitedBots:t.htmlLimitedBots,experimental:t.experimental,mdx:t.mdx},this.parseHtmlImports()}parseHtmlImports(){for(let e of bn(this.projectRoot))this.htmlOnlyImports.add(e)}getModuleAnalysis(e,t){return this.moduleAnalysisCache.get(e,t)}isServerComponent(e,t){try{return lr(e,this.moduleAnalysisCache.get(e,t),this.htmlOnlyImports)}catch{return!1}}isClientComponent(e,t){try{return this.moduleAnalysisCache.get(e,t).directives.hasUseClient}catch{return!1}}resolveImportedFilePath(e,t){let n=null;if(t.startsWith(`./`)||t.startsWith(`../`)){let r=E.dirname(e);n=E.resolve(r,t)}else if(n=S(t,this.options.alias,this.projectRoot),(n==null||n===``)&&t.startsWith(`@/`)){let e=t.slice(2);n=E.join(this.projectRoot,`src`,e)}return n==null||n===``?null:ce(n,[``,`.ts`,`.tsx`,`.js`,`.jsx`])}populateImportGraphFromFiles(e){this.fileImporters.clear();for(let{filePath:t,analysis:n}of e)for(let e of Vt(n.importSources)){let n=this.resolveImportedFilePath(t,e);n!=null&&n!==``&&(this.fileImporters.has(n)||this.fileImporters.set(n,new Set),this.fileImporters.get(n).add(t))}}buildImportGraph(e){let t=dr(this,[e]);this.populateImportGraphFromFiles(t)}isOnlyImportedByClientComponents(e){let t=this.fileImporters.get(e);if(!t||t.size===0)return!1;for(let e of t)if(!this.isClientComponent(e)&&!this.isOnlyImportedByClientComponents(e))return!1;return!0}addServerComponent(e,t,n){let r=t??w.readFileSync(e,`utf-8`),i=n??this.moduleAnalysisCache.get(e,r),a=Bt(i.importSources),o=zt(i);if(i.directives.hasUseServer){this.serverActions.set(e,{filePath:e,originalCode:r,dependencies:a,hasNodeImports:o});return}lr(e,i,this.htmlOnlyImports)&&this.serverComponents.set(e,{filePath:e,originalCode:r,dependencies:a,hasNodeImports:o})}isServerAction(e,t){return t!=null&&t!==``?this.moduleAnalysisCache.get(t,e).directives.hasUseServer:W(e).directives.hasUseServer}extractDependencies(e,t){return Bt((t!=null&&t!==``?this.moduleAnalysisCache.get(t,e):W(e)).importSources)}hasNodeImports(e,t){return zt(t!=null&&t!==``?this.moduleAnalysisCache.get(t,e):W(e))}async getTransformedComponentsForDevelopment(e){let t=[];for(let[n]of this.serverComponents){if(e&&!e(n))continue;let r=E.relative(this.projectRoot,n),i=this.getComponentId(r),a=await this.buildComponentCodeOnly(n);t.push({id:i,code:a,isAction:!1})}for(let[n]of this.serverActions){if(e&&!e(n))continue;let r=E.relative(this.projectRoot,n),i=this.getComponentId(r),a=await this.buildComponentCodeOnly(n);t.push({id:i,code:a,isAction:!0})}return t}resolveComponentsDirClientImport(e){if(!e.startsWith(`.`)&&!e.startsWith(`@`)&&!e.startsWith(`~`)&&!e.startsWith(`#`))return null;if(e.startsWith(`.`)){if(!e.includes(`/components/`))return null;let t=Wn.exec(e);if(!t)return null;let n=t[1],r=[E.resolve(this.projectRoot,`src`,`components`,`${n}.tsx`),E.resolve(this.projectRoot,`src`,`components`,`${n}.ts`),E.resolve(this.projectRoot,`src`,`components`,`${n}.jsx`),E.resolve(this.projectRoot,`src`,`components`,`${n}.js`)];for(let e of r)if(w.existsSync(e)&&this.isClientComponent(e))return{registryKey:`components/${n}`,absolutePath:e};return null}let t=null;for(let[n,r]of Object.entries(this.options.alias))if(e.startsWith(`${n}/`)||e===n){let i=e.slice(n.length).replace(/^\/+/,``);t=E.join(r,i);break}if(t==null||t===``||!Gn.exec(t))return null;let n=E.isAbsolute(t)?t:E.resolve(this.projectRoot,t),r=[n,`${n}.tsx`,`${n}.ts`,`${n}.jsx`,`${n}.js`];for(let e of r)if(w.existsSync(e)&&this.isClientComponent(e))return{registryKey:this.getComponentReferenceId(e),absolutePath:e};return null}transformComponentImportsToGlobal(e){let t=[];for(let n of ht(e)){if(n.typeOnly||n.sideEffectOnly)continue;let e=this.resolveComponentsDirClientImport(n.source);if(e==null)continue;let r=[];n.namespaceBinding!=null&&r.push(hn(n.namespaceBinding,e.registryKey)),n.defaultBinding!=null&&r.push(mn(n.defaultBinding,e.registryKey,`default`));for(let t of n.named)t.typeOnly||r.push(mn(t.local,e.registryKey,t.imported));r.length!==0&&t.push({start:n.start,end:n.end,replacement:r.join(`
99
+ `)})}if(t.length===0)return e;let n=e;for(let{start:e,end:r,replacement:i}of[...t].sort((e,t)=>t.start-e.start))n=n.slice(0,e)+i+n.slice(r);return n}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}createRolldownModuleInfoPlugin(e){let t=new Set;return{name:`rari-rolldown-module-info`,moduleParsed(e){for(let n of e.importedIds)!n.startsWith(`.`)&&!n.startsWith(`/`)&&!n.startsWith(`node:`)&&!Rt(n)&&t.add(n);for(let n of e.dynamicallyImportedIds)!n.startsWith(`.`)&&!n.startsWith(`/`)&&!n.startsWith(`node:`)&&!Rt(n)&&t.add(n)},buildEnd:()=>{if(t.size===0)return;let n=[...t].sort(),r=this.serverComponents.get(e)??this.serverActions.get(e);r&&(r.dependencies=n);let i=this.buildCache.get(e);i&&(i.bundledDependencies=n)}}}createBuildPlugins(e,t,n,r,i=!1,a){let o=E.dirname(r),s=Un.test(E.basename(r)),c=new Map,l=new Map;return[{name:`virtual-module`,resolveId(t,n){if(t===e)return t;if(n===e&&(t.startsWith(`./`)||t.startsWith(`../`))){if(t.endsWith(`.module.css`))return null;let e=E.resolve(o,t);for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`,``]){let n=e+t;if(w.existsSync(n)&&w.statSync(n).isFile())return n}for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=E.join(e,`index${t}`);if(w.existsSync(n))return n}return e}return null},load(r){return r===e?{code:t,moduleType:n}:null}},{name:`resolve-client-server-boundaries`,enforce:`pre`,resolveId:(t,n)=>{if(n==null||n===``||n.includes(`node_modules`)||er(n)||t.startsWith(`node:`)||Rt(t)||t===`react`||t===`react-dom`||t===`react/jsx-runtime`||t===`react/jsx-dev-runtime`)return null;let r=null,i=this.options.alias;if(r=S(t,i,this.projectRoot),(r==null||r===``)&&(t.startsWith(`./`)||t.startsWith(`../`))){let i=n===e?o:E.dirname(n);r=E.resolve(i,t)}if((r==null||r===``)&&E.isAbsolute(t)&&(r=t),r!==``)for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=r+e;if(w.existsSync(t)&&w.statSync(t).isFile()){if(this.isClientComponent(t)){let e=E.relative(this.projectRoot,t),n=(e.startsWith(`..`)?t:e).replace(x,`/`);return c.set(t,n),e.startsWith(`..`)&&this.discoveredExternalClientComponents.add(t),{id:`\0client-ref:${t}`}}try{let e=this.moduleAnalysisCache.get(t);if(e.directives.hasUseServer){let n=this.getComponentId(t);return l.set(t,{actionId:n,hasDefaultExport:e.hasDefaultExport}),{id:`\0server-action:${t}`}}}catch(e){console.error(`[rari] Failed to read file for server action detection: ${t}`,e)}break}}return null},load:e=>{if(e.startsWith(`\0client-ref:`)){let t=e.slice(12),n=E.relative(this.projectRoot,t),r=(c.get(t)??(n.startsWith(`..`)?t:n)).replace(x,`/`);return{code:this.generateClientReferenceStub(t,r),moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15),n=l.get(t)?.actionId??this.getComponentId(t);return{code:this.generateServerActionRuntimeModule(t,n),moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!i)return null;if(e.startsWith(`file://`)){let t=e.replace(m,``);return w.existsSync(t)?{id:`\0transformed:${t}`}:null}let n=null,r=this.options.alias;n=S(e,r,this.projectRoot);let a=t?.startsWith(`\0`)?o:t!=null&&t!==``?E.dirname(t):o;if((n==null||n===``)&&(e.startsWith(`./`)||e.startsWith(`../`))&&(n=E.resolve(a,e)),n==null||n===``||a.includes(`node_modules`))return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=n+e;if(w.existsSync(t)&&w.statSync(t).isFile()){if(this.isClientComponent(t)||this.isServerActionFile(t))return null;let e=E.join(this.projectRoot,`src`);if(!t.startsWith(e))return null;let n=this.getComponentId(t),r=E.join(this.options.outDir,this.options.rscDir,`${n}.js`);if(w.existsSync(r))return{id:`\0transformed:${r}`};break}}return null},load(e){if(e.startsWith(`\0transformed:`)){let t=e.slice(13);return{code:w.readFileSync(t,`utf-8`),moduleType:`js`}}return null}},{name:`resolve-aliases`,resolveId:e=>{if(e.startsWith(`\0`))return null;let t=S(e,this.options.alias,this.projectRoot);if(t==null||t===``)return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let n=t+e;if(w.existsSync(n)&&w.statSync(n).isFile()){if(this.isServerActionFile(n)){let e=this.getComponentId(n);return l.set(n,{actionId:e,hasDefaultExport:this.moduleAnalysisCache.get(n).hasDefaultExport}),{id:`\0server-action:${n}`}}return n}}for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=E.join(t,`index${e}`);if(w.existsSync(n)){if(this.isServerActionFile(n)){let e=this.getComponentId(n);return l.set(n,{actionId:e,hasDefaultExport:this.moduleAnalysisCache.get(n).hasDefaultExport}),{id:`\0server-action:${n}`}}return n}}return t}},{name:`resolve-rari-proxy`,resolveId:e=>{if(s&&e===`rari`){let e=E.join($n,`proxy/RariResponse.mjs`);if(w.existsSync(e))return e;let t=E.join(Q,`src/proxy/http/response.ts`);if(w.existsSync(t))return t}return null}},{name:`css-modules`,resolveId:(e,t)=>{if(e.endsWith(`.module.css`)){let n=t!=null&&t!==``&&!t.startsWith(`\0`)?E.dirname(t):o,r=E.resolve(n,e);if(w.existsSync(r))return{id:`\0css-module:${r}`}}return null},load:async e=>{if(!e.startsWith(`\0css-module:`))return null;let t=e.slice(12);try{let e=await sr(),n=w.readFileSync(t),r=e({filename:E.relative(this.projectRoot,t),code:n,cssModules:{pattern:Yn}});a&&a.push(new TextDecoder().decode(r.code));let i={};if(r.exports)for(let[e,t]of Object.entries(r.exports))i[e]=t.name;return{code:`export default ${JSON.stringify(i)}`,moduleType:`js`}}catch(t){throw Error(`[rari] Failed to process CSS module ${e}: ${t instanceof Error?t.message:String(t)}`)}}},{name:`externalize-deps`,resolveId:(e,t)=>{if(e.startsWith(`\0`))return null;if(e.startsWith(`node:`)||Rt(e)||[`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`rari/image`].includes(e)||e in{"rari/runtime/cache-wrapper":`node_modules/rari/dist/runtime/cache-wrapper.mjs`,"react-server-dom-rari/server":`node_modules/rari/dist/runtime/rsc-references.mjs`})return{id:e,external:!0};if(e===`rari`||S(e,this.options.alias,this.projectRoot)!=null)return null;if(!e.startsWith(`.`)&&!e.startsWith(`/`)){if(Zn(this.projectRoot,e))return{id:e,external:!0};let n=[t!=null&&t!==``&&!t.startsWith(`\0`)?t:null,r].filter(e=>!!e);for(let t of n)try{return{id:fe(t).resolve(e)}}catch{try{let n=import.meta.resolve(e,k(t).href);return{id:O(n)}}catch{}}return null}return null}},this.createRolldownModuleInfoPlugin(r),{name:`use-cache`,transform:async(e,t)=>{if(!this.options.experimental?.useCache&&!this.options.experimental?.useCacheRemote)return null;let n=await Hn();return n?n(e,t,{hashSalt:`${this.useCacheBuildId??`development`}:rari-use-cache-v1`}):null}}]}async buildComponentCodeOnly(e){let t=await w.promises.readFile(e,`utf-8`),n=Bn(t,this.getComponentId(e))?.code??t,r=this.transformClientImports(n,e),i=this.isPageComponent(e),a=i?this.transformComponentImportsToGlobal(r):r,o=E.extname(e),s;s=o===`.tsx`?`tsx`:o===`.ts`?`ts`:o===`.jsx`?`jsx`:`js`;let c=`\0virtual:${e}`,l=await j({input:c,platform:`node`,write:!1,external:[Jn,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${s}`]:s},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(D.env.NODE_ENV!=null&&D.env.NODE_ENV!==``?D.env.NODE_ENV:`production`),...this.options.define}},plugins:this.createBuildPlugins(c,a,s,e,i,[])});if(l.output.length===0)throw Error(`No output generated from Rolldown`);let u=l.output.find(e=>e.type===`chunk`&&e.isEntry);if(u?.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let d=u.code;return d=`// Built: ${new Date().toISOString()}\n${d}`,d}async buildComponentBatch(e,t,n){let r=0,i=0,a=[];if(await new Promise(o=>{let s=()=>{for(;r<n&&i<e.length;){let[n,c]=e[i++],l=E.relative(this.projectRoot,n),u=this.getComponentId(n),d=E.join(this.options.rscDir,`${u}.js`),f=E.join(this.options.outDir,d);r++,(async()=>{try{let e=E.dirname(f);await w.promises.mkdir(e,{recursive:!0});let r=await this.buildSingleComponent(n,f),i=await this.writeComponentCssAsset(u,r.css),a=k(E.resolve(this.projectRoot,f)).href;t.components[u]={id:u,filePath:n,relativePath:l,bundlePath:d,moduleSpecifier:a,dependencies:[...c.dependencies],hasNodeImports:c.hasNodeImports,css:i}}catch(e){a.push(e instanceof Error?e:Error(String(e)))}finally{r--,i>=e.length&&r===0?o():s()}})()}e.length===0&&o()};s()}),a.length>0)throw a[0]}async buildServerComponents(){let e=E.join(this.options.outDir,this.options.rscDir);await w.promises.mkdir(e,{recursive:!0});let t={components:{},buildTime:new Date().toISOString()},n=this.options.experimental?.useCache===!0||this.options.experimental?.useCacheRemote!=null,r=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),i=[...this.serverComponents.entries()].filter(([e])=>!this.isPageComponent(e)),a=[...this.serverComponents.entries()].filter(([e])=>this.isPageComponent(e)),s=[...this.serverActions.entries()];await Promise.all([this.buildComponentBatch(i,t,r),this.buildComponentBatch(s,t,r)]),await this.buildComponentBatch(a,t,r),n&&(this.useCacheBuildId=P(JSON.stringify(t.components),16),t.useCacheBuildId=this.useCacheBuildId);let c=E.join(this.options.outDir,this.options.manifestPath);await w.promises.writeFile(c,JSON.stringify(t),`utf-8`),await this.writeRouteCssEntries(t);let l={};this.options.csp&&(l.csp=this.options.csp),this.options.cacheControl&&(l.cacheControl=this.options.cacheControl),this.options.cache&&(l.cache=this.options.cache),this.options.action&&(l.action=this.options.action),this.options.jsPoolSize!=null&&(l.jsPoolSize=this.options.jsPoolSize);let u=this.options.origin?.trim().replace(/\/+$/,``);u!=null&&u!==``&&(l.origin=u),this.options.htmlLimitedBots!=null&&(l.htmlLimitedBots=this.options.htmlLimitedBots),(this.options.experimental?.useCacheRemote!=null||this.useCacheBuildId!=null&&this.useCacheBuildId!==``)&&(l.useCache={...this.options.experimental?.useCacheRemote?{remote:this.options.experimental.useCacheRemote}:{},...this.useCacheBuildId!=null&&this.useCacheBuildId!==``?{buildId:this.useCacheBuildId}:{}},!this.options.experimental?.useCache&&this.options.experimental?.useCacheRemote&&console.warn(`[server-build] experimental.useCacheRemote is set without experimental.useCache; the 'use cache' transform will still run because useCacheRemote is configured.`));let d=E.join(this.options.outDir,this.options.serverConfigPath);if(Object.keys(l).length===0)try{await w.promises.unlink(d)}catch(e){o(e)!==`ENOENT`&&console.warn(`Failed to remove server config file:`,e)}else await w.promises.writeFile(d,JSON.stringify(l),`utf-8`);return t}async buildMdxRegistry(e){let n=an({projectRoot:this.projectRoot,mdxOptions:e,alias:this.options.alias,cache:this.moduleAnalysisCache}),r=E.join(this.options.outDir,this.options.manifestPath),i;if(w.existsSync(r)){let e=await w.promises.readFile(r,`utf-8`),n=t(e);i=n&&cr(n)?n:{components:{},buildTime:new Date().toISOString()}}else i={components:{},buildTime:new Date().toISOString()};i.mdxRegistry=n.map(e=>({name:e.name,id:e.moduleId,client:e.client})),await w.promises.writeFile(r,JSON.stringify(i),`utf-8`)}async buildSSRClientComponents(){let e=E.join(this.options.outDir,`ssr`);await w.promises.mkdir(e,{recursive:!0});let t=[...this.getClientComponentFiles()];for(let e of this.discoveredExternalClientComponents)if(!t.some(t=>t.filePath===e))try{let n=w.readFileSync(e,`utf-8`);t.push({filePath:e,code:n})}catch{}try{let e=nr();if(e!=null&&e!==``){let n=w.readFileSync(e,`utf-8`);t.push({filePath:e,code:n})}}catch{}if(t.length===0){let t={};await this.buildExternalClientComponents(t,new Map),await this.writeClientReferenceManifest(e,t);return}let n=new Map;for(let{filePath:e}of t){let t=ar(e,this.projectRoot);n.set(E.resolve(e),`file:///ssr/${t}.js`)}let r={},i=Math.min(8,Math.max(1,(await import(`node:os`)).cpus().length)),a=0,o=0;await new Promise(e=>{let s=()=>{for(;a<i&&o<t.length;){let{filePath:i,code:c}=t[o++],l=ir(i,this.projectRoot),u=`ssr/${ar(i,this.projectRoot)}.js`,d=E.join(this.options.outDir,u);a++,(async()=>{try{let e=E.dirname(d);await w.promises.mkdir(e,{recursive:!0}),await this.buildSSRSingleClient(i,d,n);let t=this.extractExportNames(c);r[l]={id:l,filePath:i,bundlePath:u,exports:t}}catch(e){console.warn(`[rari] SSR build failed for ${l}:`,e instanceof Error?e.message:e)}finally{a--,o>=t.length&&a===0?e():s()}})()}t.length===0&&e()};s()}),await this.buildExternalClientComponents(r,n),await this.writeClientReferenceManifest(e,r)}async writeClientReferenceManifest(e,t){let n=E.join(e,`manifest.json`);await w.promises.writeFile(n,JSON.stringify(t),`utf-8`);let r={};for(let[e,n]of Object.entries(t))for(let t of n.exports){let i=`${e}#${t}`;r[i]={id:i,chunks:`/${n.bundlePath}`,name:t}}let i=E.join(this.options.outDir,`server`);await w.promises.mkdir(i,{recursive:!0});let a=E.join(i,`client-reference-manifest.json`);await w.promises.writeFile(a,JSON.stringify(r),`utf-8`)}resolveExternalClientSourcePath(e,t){let n=E.join(Q,...e);if(w.existsSync(n))return n;try{let e=O(import.meta.resolve(t));if(w.existsSync(e))return e}catch{}return null}async buildExternalClientComponents(e,t){for(let{componentId:n,devSourceSegments:r,publishedExport:i,exports:a}of Qn){let o=this.resolveExternalClientSourcePath(r,i);if(o!=null&&o!==``)try{let r=`ssr/${`external_${P(n)}`}.js`,i=E.join(this.options.outDir,r);await w.promises.mkdir(E.dirname(i),{recursive:!0}),await this.buildSSRSingleClient(o,i,t),e[n]={id:n,filePath:o,bundlePath:r,exports:[...a]}}catch(e){console.warn(`[rari] SSR build failed for ${n}:`,e instanceof Error?e.message:e)}}}extractExportNames(e){return gt(e)}generateClientReferenceStub(e,t){let n=[`default`];try{n=gt(w.readFileSync(e,`utf-8`))}catch{}return pn(t,n)}isServerActionFile(e){try{let t=w.readFileSync(e,`utf-8`);return this.isServerAction(t,e)}catch{return!1}}generateServerActionRuntimeModule(e,t){let n=w.readFileSync(e,`utf-8`),r=this.extractExportNames(n),i=[`const __rariActionMod = globalThis.__rari_rsc_require__(${JSON.stringify(t)});`,`if (!__rariActionMod) throw new Error("Server action module ${t} is not registered");`];for(let e of r)e==="default"?i.push(`export default __rariActionMod.default;`):i.push(`export const ${e} = __rariActionMod.${e};`);return`${i.join(`
100
+ `)}\n`}generateServerActionReferenceModule(e){let t=w.readFileSync(e,`utf-8`),n=this.extractExportNames(t),r=this.getComponentId(e),i=`import { createServerReference } from 'react-server-dom-webpack/client';
101
101
  `;i+=`import { callServer } from 'rari/runtime/call-server';
102
- `;for(let e of n){let t=`${r}#${e}`;i+=e==="default"?`export default createServerReference(${JSON.stringify(t)}, callServer);\n`:`export const ${e} = createServerReference(${JSON.stringify(t)}, callServer);\n`}return i}async buildSSRSingleClient(e,t,n){let r=(await T.promises.readFile(e,`utf-8`)).replace(/^['"]use client['"];?\s*/m,``),i=D.extname(e),a;a=i===`.tsx`?`tsx`:i===`.ts`?`ts`:i===`.jsx`?`jsx`:`js`;let o=`\0ssr-virtual:${e}`,s=this.projectRoot,c=er(e,s),l=e=>this.generateServerActionReferenceModule(e),u=e=>this.isServerActionFile(e),d=(await he({input:o,platform:`node`,write:!1,external:[qn,`react`,`react-dom`,/^react\//,/^rari/,`react-server-dom-webpack/client`,/^react-server-dom-webpack\//],output:{format:`esm`,minify:!1},moduleTypes:{[`.${a}`]:a},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react-jsx`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(O.env.NODE_ENV!=null&&O.env.NODE_ENV!==``?O.env.NODE_ENV:`production`)}},plugins:[{name:`ssr-client-virtual`,resolveId(e){return e===o?e:null},load(e){if(e===o)return{code:r,moduleType:a};if(e.startsWith(`\0server-action-ref:`)){let t=e.slice(19);return{code:l(t),moduleType:`js`}}return null}},{name:`ssr-client-resolve`,resolveId(t,r){if(t.startsWith(`\0server-action-ref:`))return t;if(t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`@/`)){let i=t;t.startsWith(`@/`)?i=D.join(c,t.slice(2)):r===o?i=D.resolve(D.dirname(e),t):r!=null&&r!==``&&(i=D.resolve(D.dirname(r.replace(`\0ssr-virtual:`,``).replace(`\0server-action-ref:`,``)),t));let a=ae(i,[`.mjs`,`.mts`,`.ts`,`.tsx`,`.js`,`.jsx`]),s=a!=null&&a!==``?a:oe(i,[`.mjs`,`.mts`,`.ts`,`.tsx`,`.js`,`.jsx`]);if(s!=null&&s!==``&&u(s))return`\0server-action-ref:${D.resolve(s)}`;if(s!=null&&s!==``&&n!=null){let t=D.resolve(s),r=n.get(t);if(r!=null&&r!==``&&t!==D.resolve(e))return{id:r,external:!0}}return s!=null&&s!==``?s:null}return null}}]})).output[0],f=typeof d==`object`&&`code`in d?d.code:``;return await T.promises.writeFile(t,f,`utf-8`),{code:f}}async buildSingleComponent(e,t){let n=await T.promises.readFile(e,`utf-8`),r=zn(n,this.getComponentId(e))?.code??n,i=this.transformClientImports(r,e),a=this.isPageComponent(e),o=a?this.transformComponentImportsToGlobal(i):i,s=D.extname(e),c;c=s===`.tsx`?`tsx`:s===`.ts`?`ts`:s===`.jsx`?`jsx`:`js`;let l=`\0virtual:${e}`,u=[],d=await he({input:l,platform:`node`,write:!1,external:[qn,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${c}`]:c},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(O.env.NODE_ENV!=null&&O.env.NODE_ENV!==``?O.env.NODE_ENV:`production`),...this.options.define}},plugins:this.createBuildPlugins(l,o,c,e,a,u)});if(d.output.length===0)throw Error(`No output generated from Rolldown`);let f=d.output.find(e=>e.type===`chunk`&&e.isEntry);if(f?.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let p=f.code;p=`// Built: ${new Date().toISOString()}\n${p}`,await T.promises.writeFile(t,p,`utf-8`);let m=await T.promises.open(t,`r+`);return await m.sync(),await m.close(),{code:p,css:u}}transformClientImports(e,t){let n=Zn.map(e=>e.componentId),r=[],i=!1,a=!1;for(let o of ht(e)){if(o.typeOnly||o.sideEffectOnly)continue;let e=!1,s=o.source;if(n.includes(o.source))e=!0;else if(Kn.test(o.source)||Object.keys(this.options.alias).some(e=>o.source===e||o.source.startsWith(`${e}/`))){let n=this.resolveImportPath(o.source,t);this.isClientComponent(n)&&(e=!0,s=D.relative(this.projectRoot,n).replace(x,`/`))}if(!e)continue;let c=[];o.namespaceBinding!=null&&(a=!0,c.push(`const ${o.namespaceBinding} = createClientModuleProxy(${JSON.stringify(s)});`)),o.defaultBinding!=null&&(i=!0,c.push(`const ${o.defaultBinding} = registerClientReference(
102
+ `;for(let e of n){let t=`${r}#${e}`;i+=e==="default"?`export default createServerReference(${JSON.stringify(t)}, callServer);\n`:`export const ${e} = createServerReference(${JSON.stringify(t)}, callServer);\n`}return i}async buildSSRSingleClient(e,t,n){let r=(await w.promises.readFile(e,`utf-8`)).replace(/^['"]use client['"];?\s*/m,``),i=E.extname(e),a;a=i===`.tsx`?`tsx`:i===`.ts`?`ts`:i===`.jsx`?`jsx`:`js`;let o=`\0ssr-virtual:${e}`,s=this.projectRoot,c=tr(e,s),l=e=>this.generateServerActionReferenceModule(e),u=e=>this.isServerActionFile(e),d=(await j({input:o,platform:`node`,write:!1,external:[Jn,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react/compiler-runtime`,/^rari/,`react-server-dom-webpack/client`,/^react-server-dom-webpack\//],output:{format:`esm`,minify:!1},moduleTypes:{[`.${a}`]:a},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`,`.mjs`]},transform:{jsx:`react-jsx`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(D.env.NODE_ENV!=null&&D.env.NODE_ENV!==``?D.env.NODE_ENV:`production`)}},plugins:[{name:`ssr-client-virtual`,resolveId(e){return e===o?e:null},load(e){if(e===o)return{code:r,moduleType:a};if(e.startsWith(`\0server-action-ref:`)){let t=e.slice(19);return{code:l(t),moduleType:`js`}}return null}},{name:`ssr-client-resolve`,resolveId(t,r){if(t.startsWith(`\0server-action-ref:`))return t;if(t.startsWith(`.`)||t.startsWith(`/`)||t.startsWith(`@/`)){let i=t;t.startsWith(`@/`)?i=E.join(c,t.slice(2)):r===o?i=E.resolve(E.dirname(e),t):r!=null&&r!==``&&(i=E.resolve(E.dirname(r.replace(`\0ssr-virtual:`,``).replace(`\0server-action-ref:`,``)),t));let a=ae(i,[`.mjs`,`.mts`,`.ts`,`.tsx`,`.js`,`.jsx`]),s=a!=null&&a!==``?a:oe(i,[`.mjs`,`.mts`,`.ts`,`.tsx`,`.js`,`.jsx`]);if(s!=null&&s!==``&&u(s))return`\0server-action-ref:${E.resolve(s)}`;if(s!=null&&s!==``&&n!=null){let t=E.resolve(s),r=n.get(t);if(r!=null&&r!==``&&t!==E.resolve(e))return{id:r,external:!0}}return s!=null&&s!==``?s:null}return null}}]})).output[0],f=typeof d==`object`&&`code`in d?d.code:``;return await w.promises.writeFile(t,f,`utf-8`),{code:f}}async buildSingleComponent(e,t){let n=await w.promises.readFile(e,`utf-8`),r=Bn(n,this.getComponentId(e))?.code??n,i=this.transformClientImports(r,e),a=this.isPageComponent(e),o=a?this.transformComponentImportsToGlobal(i):i,s=E.extname(e),c;c=s===`.tsx`?`tsx`:s===`.ts`?`ts`:s===`.jsx`?`jsx`:`js`;let l=`\0virtual:${e}`,u=[],d=await j({input:l,platform:`node`,write:!1,external:[Jn,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${c}`]:c},resolve:{mainFields:[`module`,`main`],conditionNames:[`import`,`module`,`default`],extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]},transform:{jsx:`react`,define:{global:`globalThis`,"process.env.NODE_ENV":JSON.stringify(D.env.NODE_ENV!=null&&D.env.NODE_ENV!==``?D.env.NODE_ENV:`production`),...this.options.define}},plugins:this.createBuildPlugins(l,o,c,e,a,u)});if(d.output.length===0)throw Error(`No output generated from Rolldown`);let f=d.output.find(e=>e.type===`chunk`&&e.isEntry);if(f?.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let p=f.code;p=`// Built: ${new Date().toISOString()}\n${p}`,await w.promises.writeFile(t,p,`utf-8`);let m=await w.promises.open(t,`r+`);return await m.sync(),await m.close(),{code:p,css:u}}transformClientImports(e,t){let n=Qn.map(e=>e.componentId),r=[],i=!1,a=!1;for(let o of ht(e)){if(o.typeOnly||o.sideEffectOnly)continue;let e=!1,s=o.source;if(n.includes(o.source))e=!0;else if(qn.test(o.source)||Object.keys(this.options.alias).some(e=>o.source===e||o.source.startsWith(`${e}/`))){let n=this.resolveImportPath(o.source,t);this.isClientComponent(n)&&(e=!0,s=E.relative(this.projectRoot,n).replace(x,`/`))}if(!e)continue;let c=[];o.namespaceBinding!=null&&(a=!0,c.push(`const ${o.namespaceBinding} = createClientModuleProxy(${JSON.stringify(s)});`)),o.defaultBinding!=null&&(i=!0,c.push(`const ${o.defaultBinding} = registerClientReference(
103
103
  null,
104
104
  ${JSON.stringify(s)},
105
105
  "default"
@@ -108,19 +108,19 @@ const ${e} = globalThis['~clientComponents']?.[${JSON.stringify(t)}]?.component
108
108
  ${JSON.stringify(s)},
109
109
  ${JSON.stringify(e.imported)}
110
110
  );`));c.length!==0&&r.push({start:o.start,end:o.end,replacement:c.join(`
111
- `)})}if(r.length===0)return e;let o=e;for(let{start:e,end:t,replacement:n}of[...r].sort((e,t)=>t.start-e.start))o=o.slice(0,e)+n+o.slice(t);let s=[...i?[`registerClientReference`]:[],...a?[`createClientModuleProxy`]:[]];return cn(o,`react-server-dom-rari/server`,s)}resolveImportPath(e,t){let n=e,r=this.options.alias;for(let[t,i]of Object.entries(r))if(e.startsWith(`${t}/`)||e===t){let r=e.slice(t.length).replace(/^\/+/,``);n=D.join(i,r);break}D.isAbsolute(n)||(n=D.resolve(D.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`],a=ae(n,i);if(a!=null&&a!==``)return a;let o=oe(n,i);return o!=null&&o!==``?o:`${n}.tsx`}getProjectRelativePath(e){return $e(e,this.projectRoot)}getReadableComponentId(e){return et(e)}getComponentId(e){return tt(e,this.projectRoot)}async rebuildComponent(e){let t=this.getComponentId(e),n=await T.promises.readFile(e,`utf-8`),r=this.extractDependencies(n,e),i={filePath:e,originalCode:n,dependencies:r,hasNodeImports:this.hasNodeImports(n,e)};this.isServerAction(n,e)?(this.serverActions.set(e,i),this.serverComponents.delete(e)):(this.serverComponents.set(e,i),this.serverActions.delete(e));let a=D.join(this.options.rscDir,`${t}.js`),o=D.join(this.options.outDir,a),s=this.buildCache.get(e),c=(await T.promises.stat(e)).mtimeMs;if(s&&s.timestamp>=c&&JSON.stringify(s.sourceDependencies)===JSON.stringify(r)){let n=this.serverActions.get(e)??this.serverComponents.get(e);return n&&s.bundledDependencies.length>0&&(n.dependencies=s.bundledDependencies),await T.promises.writeFile(o,s.code,`utf-8`),await this.updateManifestForComponent(t,e,a,s.css),{componentId:t,bundlePath:D.join(this.options.outDir,a),success:!0}}let l=D.dirname(o);await T.promises.mkdir(l,{recursive:!0});let u=await this.buildSingleComponent(e,o),d=await this.writeComponentCssAsset(t,u.css),f=this.serverActions.get(e)??this.serverComponents.get(e);return this.buildCache.set(e,{code:u.code,css:d,timestamp:Date.now(),sourceDependencies:r,bundledDependencies:f?.dependencies??r}),await this.updateManifestForComponent(t,e,a,d),{componentId:t,bundlePath:D.join(this.options.outDir,a),success:!0}}manifestCache=null;async updateManifestForComponent(e,n,r,i=[]){let a=D.join(this.options.outDir,this.options.manifestPath),o;if(this.manifestCache)o=this.manifestCache;else if(T.existsSync(a)){let e=await T.promises.readFile(a,`utf-8`),n=t(e);n&&sr(n)?(o=n,this.manifestCache=o):(o={components:{},buildTime:new Date().toISOString()},this.manifestCache=o)}else o={components:{},buildTime:new Date().toISOString()},this.manifestCache=o;let s=this.serverComponents.get(n)??this.serverActions.get(n),c=D.join(this.options.outDir,r),l=A(D.resolve(this.projectRoot,c)).href;if(s)o.components[e]={id:e,filePath:n,relativePath:D.relative(this.projectRoot,n),bundlePath:r,moduleSpecifier:l,dependencies:[...s.dependencies],hasNodeImports:s.hasNodeImports,css:i};else{let t=await T.promises.readFile(n,`utf-8`);o.components[e]={id:e,filePath:n,relativePath:D.relative(this.projectRoot,n),bundlePath:r,moduleSpecifier:l,dependencies:this.extractDependencies(t,n),hasNodeImports:this.hasNodeImports(t,n),css:i}}o.buildTime=new Date().toISOString(),await T.promises.writeFile(a,JSON.stringify(o),`utf-8`),await this.writeRouteCssEntries(o),this.manifestCache=o}clearCache(){this.buildCache.clear(),this.manifestCache=null}invalidateBuildCacheFor(e){this.buildCache.delete(e)}async getTransformedComponentCode(e){return this.buildComponentCodeOnly(e)}};function ur(e,t){let n=[];for(let r of Ft(t))try{let t=J(r),i=T.readFileSync(r,`utf-8`),a=e.getModuleAnalysis(r,i);n.push({filePath:r,cacheKey:t,code:i,analysis:a})}catch(e){console.warn(`[server-build] Error reading ${r}:`,e instanceof Error?e.message:e)}return n}function dr(e,t){return(t??W(e)).hasComponentExport||p.test(e)||v.test(e)||ne.test(e)}function fr(e,t,n,r,i){let a=D.basename(e);if(Gn.test(a)||a.endsWith(`.d.ts`))return!1;let o=r??n.getModuleAnalysis(e,t);return o.directives.hasUseClient?!1:o.directives.hasUseServer?!0:!n.isOnlyImportedByClientComponents(e)&&cr(e,o,n.getHtmlOnlyImports(),i)&&dr(t,o)}function pr(e,t,n=[]){let r=ur(t,It(e,n));t.clearClientComponentFiles(),t.populateImportGraphFromFiles(r);let i=[],a=[];for(let{filePath:e,cacheKey:n,code:o,analysis:s}of r)s.directives.hasUseClient&&(a.push(e),t.recordClientComponent(e,o)),fr(e,o,t,s,n)&&(t.addServerComponent(e,o,s),i.push(e));return{serverComponentPaths:i,clientComponentPaths:a}}function mr(e={}){let t=null,n,r=!1,i={};return{name:`rari-server-build`,configResolved(a){n=a.root,r=a.command===`serve`;let o=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react/compiler-runtime`,`react-dom/client`]),s={},c=a.resolve.alias;Array.isArray(c)?c.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!o.has(e.find)&&(s[e.find]=e.replacement)}):typeof c==`object`&&Object.entries(c).forEach(([e,t])=>{typeof t==`string`&&!o.has(e)&&(s[e]=t)}),i=s,t=new lr(n,{...e,alias:s})},buildStart(){if(!t)return;let e=O.env.NODE_ENV===`production`,r=[D.join(n,`dist`,`cache`,`og`),D.join(n,`dist`,`cache`,`images`)];e&&r.push(`/tmp/rari-og-cache`,`/tmp/rari-image-cache`);for(let e of r)try{T.existsSync(e)&&T.rmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[rari] Failed to clear cache ${e}:`,t)}let a=D.join(n,`src`);T.existsSync(a)&&pr(a,t,Object.values(i))},async closeBundle(){if(t){await t.buildServerComponents(),await t.buildSSRClientComponents();try{await t.buildMdxRegistry(e.mdx)}catch(e){console.warn(`[rari] Failed to build MDX component registry:`,e)}try{let{generateRobotsFile:e}=await import(`./robots-BGCTYwKN.mjs`);await e({appDir:D.join(n,`src`,`app`),outDir:D.join(n,`dist`)})}catch(e){console.warn(`[rari] Failed to generate robots.txt:`,e)}try{let{generateSitemapFiles:e}=await import(`./sitemap-1n5BIACA.mjs`);await e({appDir:D.join(n,`src`,`app`),outDir:D.join(n,`dist`),aliases:i})}catch(e){console.warn(`[rari] Failed to generate sitemap:`,e)}try{let{generateFeedFile:e}=await import(`./feed-Ixvy9L12.mjs`);await e({appDir:D.join(n,`src`,`app`),outDir:D.join(n,`dist`),aliases:i})}catch(e){console.warn(`[rari] Failed to generate feed:`,e)}}},async handleHotUpdate({file:e}){if(!t||!r)return;let i=D.relative(n,e).replace(x,`/`);if(!(!i.startsWith(`src/`)||!_.test(i)))try{let n=await T.promises.readFile(e,`utf-8`),r=t.getModuleAnalysis(e,n),i=t.hasComponent(e);if(!fr(e,n,t,r)){i&&t.removeComponent(e);return}i||t.addServerComponent(e,n,r),await t.rebuildComponent(e)}catch(e){console.error(`[rari] Build: Error rebuilding ${i}:`,e)}}}}const hr=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g,gr=/import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g,_r=/import\s+(\w+)\s*,\s*\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g,vr=/defineMdxComponents\s*\(\s*\{([\s\S]*?)\}\s*\)/;function yr(e,t,n){for(let r of t.split(`,`)){let t=r.trim();if(!t||(t=t.replace(/^type\s+/i,``).trim(),!t))continue;let i=t.split(/\s+as\s+/i),a=(i[1]??i[0]).trim();a&&n.set(a,e)}}function br(e){let t=new Map;for(let n of e.matchAll(_r))t.set(n[1],n[3]),yr(n[3],n[2],t);for(let n of e.matchAll(hr))t.set(n[1],n[2]);for(let n of e.matchAll(gr))yr(n[2],n[1],t);return t}function xr(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(!e)continue;let r=e.indexOf(`:`);if(r===-1){t.push({name:e,binding:e});continue}let i=e.slice(0,r).trim(),a=e.slice(r+1).trim();i&&a&&t.push({name:i,binding:a})}return t}function Sr(e){try{return W(T.readFileSync(e,`utf-8`)).topLevelUseClient}catch{return!1}}function Cr(e){let{code:t,id:n,projectRoot:r,resolvedAlias:i}=e;if(!t.includes(`defineMdxComponents`)||t.includes(`__RARI_MDX_RESOLVED__`))return null;let a=vr.exec(t);if(!a)return null;let o=br(t),s=xr(a[1]);if(s.length===0)return null;let c=`defineMdxComponents(/* __RARI_MDX_RESOLVED__ */[\n${s.map(({name:e,binding:t})=>{let a=o.get(t);if(a==null||a===``)throw Error(`[rari/mdx] Could not resolve import for MDX component "${e}" (binding "${t}") in ${n}`);let s=le(a,n,i),c=$e(s,r).replace(x,`/`),l=Sr(s);return` { name: ${JSON.stringify(e)}, component: ${t}, id: ${JSON.stringify(c)}, client: ${l} }`}).join(`,
112
- `)},\n])`;return t.replace(vr,c)}const wr=/forwardRef|memo|\b(?:[A-Z]|use[A-Z0-9])/,Tr=/\.[cm]?[jt]sx?$/,Er=/\?.*$/,Dr=/['"]use memo['"]/;function Or(e){return{...e===!0?{}:e,target:`19`}}function kr(e,t){return t.compilationMode===`annotation`?Dr.test(e):wr.test(e)}function Ar(e){if(e.startsWith(`\0`)||e.includes(`virtual:`))return!1;let t=e.replace(Er,``);return Tr.test(t)&&!t.includes(`/node_modules/`)}function jr(e){let t=Or(e),n,r=!0,i=!1,a=!1,o=async e=>{if(n)return n;try{return n=await import(`oxc-transform-react`),n}catch(t){return e(`React Compiler requires the optional \`oxc-transform-react\` package. Install it before enabling \`rari({ compiler: true })\`.${t instanceof Error?`\n${t.message}`:``}`)}};return{name:`rari:react-compiler`,enforce:`pre`,async config(e,{command:t}){return await o(e=>this.error(e)),a=t===`serve`,{oxc:{jsx:{refresh:!1}},optimizeDeps:{include:[`react/compiler-runtime`]}}},configResolved(e){r=e.command!==`build`||e.build.sourcemap!==!1,i=!e.isProduction,a=!e.isProduction&&e.command===`serve`&&e.server.hmr!==!1},async transform(e,s){if(!Ar(s)||this.environment.config.consumer===`server`)return null;let{transform:c}=n??await o(e=>this.error(e)),l=s.replace(Er,``),u=kr(e,t),d=await c(l,e,{jsx:{runtime:`automatic`,development:i,importSource:`react`,refresh:a},reactCompiler:u?t:!1,sourcemap:r}),f=d.errors.map(e=>{let t=e.codeframe;return t!=null&&t!==``?`${e.message}\n${t}`:e.message});if(d.fatal){let e=f.join(`
111
+ `)})}if(r.length===0)return e;let o=e;for(let{start:e,end:t,replacement:n}of[...r].sort((e,t)=>t.start-e.start))o=o.slice(0,e)+n+o.slice(t);let s=[...i?[`registerClientReference`]:[],...a?[`createClientModuleProxy`]:[]];return ln(o,`react-server-dom-rari/server`,s)}resolveImportPath(e,t){let n=e,r=this.options.alias;for(let[t,i]of Object.entries(r))if(e.startsWith(`${t}/`)||e===t){let r=e.slice(t.length).replace(/^\/+/,``);n=E.join(i,r);break}E.isAbsolute(n)||(n=E.resolve(E.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`],a=ae(n,i);if(a!=null&&a!==``)return a;let o=oe(n,i);return o!=null&&o!==``?o:`${n}.tsx`}getProjectRelativePath(e){return $e(e,this.projectRoot)}getReadableComponentId(e){return et(e)}getComponentId(e){return tt(e,this.projectRoot)}async rebuildComponent(e){let t=this.getComponentId(e),n=await w.promises.readFile(e,`utf-8`),r=this.extractDependencies(n,e),i={filePath:e,originalCode:n,dependencies:r,hasNodeImports:this.hasNodeImports(n,e)};this.isServerAction(n,e)?(this.serverActions.set(e,i),this.serverComponents.delete(e)):(this.serverComponents.set(e,i),this.serverActions.delete(e));let a=E.join(this.options.rscDir,`${t}.js`),o=E.join(this.options.outDir,a),s=this.buildCache.get(e),c=(await w.promises.stat(e)).mtimeMs;if(s&&s.timestamp>=c&&JSON.stringify(s.sourceDependencies)===JSON.stringify(r)){let n=this.serverActions.get(e)??this.serverComponents.get(e);return n&&s.bundledDependencies.length>0&&(n.dependencies=s.bundledDependencies),await w.promises.writeFile(o,s.code,`utf-8`),await this.updateManifestForComponent(t,e,a,s.css),{componentId:t,bundlePath:E.join(this.options.outDir,a),success:!0}}let l=E.dirname(o);await w.promises.mkdir(l,{recursive:!0});let u=await this.buildSingleComponent(e,o),d=await this.writeComponentCssAsset(t,u.css),f=this.serverActions.get(e)??this.serverComponents.get(e);return this.buildCache.set(e,{code:u.code,css:d,timestamp:Date.now(),sourceDependencies:r,bundledDependencies:f?.dependencies??r}),await this.updateManifestForComponent(t,e,a,d),{componentId:t,bundlePath:E.join(this.options.outDir,a),success:!0}}manifestCache=null;async updateManifestForComponent(e,n,r,i=[]){let a=E.join(this.options.outDir,this.options.manifestPath),o;if(this.manifestCache)o=this.manifestCache;else if(w.existsSync(a)){let e=await w.promises.readFile(a,`utf-8`),n=t(e);n&&cr(n)?(o=n,this.manifestCache=o):(o={components:{},buildTime:new Date().toISOString()},this.manifestCache=o)}else o={components:{},buildTime:new Date().toISOString()},this.manifestCache=o;let s=this.serverComponents.get(n)??this.serverActions.get(n),c=E.join(this.options.outDir,r),l=k(E.resolve(this.projectRoot,c)).href;if(s)o.components[e]={id:e,filePath:n,relativePath:E.relative(this.projectRoot,n),bundlePath:r,moduleSpecifier:l,dependencies:[...s.dependencies],hasNodeImports:s.hasNodeImports,css:i};else{let t=await w.promises.readFile(n,`utf-8`);o.components[e]={id:e,filePath:n,relativePath:E.relative(this.projectRoot,n),bundlePath:r,moduleSpecifier:l,dependencies:this.extractDependencies(t,n),hasNodeImports:this.hasNodeImports(t,n),css:i}}o.buildTime=new Date().toISOString(),await w.promises.writeFile(a,JSON.stringify(o),`utf-8`),await this.writeRouteCssEntries(o),this.manifestCache=o}clearCache(){this.buildCache.clear(),this.manifestCache=null}invalidateBuildCacheFor(e){this.buildCache.delete(e)}async getTransformedComponentCode(e){return this.buildComponentCodeOnly(e)}};function dr(e,t){let n=[];for(let r of Ft(t))try{let t=q(r),i=w.readFileSync(r,`utf-8`),a=e.getModuleAnalysis(r,i);n.push({filePath:r,cacheKey:t,code:i,analysis:a})}catch(e){console.warn(`[server-build] Error reading ${r}:`,e instanceof Error?e.message:e)}return n}function fr(e,t){return(t??W(e)).hasComponentExport||p.test(e)||v.test(e)||ne.test(e)}function pr(e,t,n,r,i){let a=E.basename(e);if(Kn.test(a)||a.endsWith(`.d.ts`))return!1;let o=r??n.getModuleAnalysis(e,t);return o.directives.hasUseClient?!1:o.directives.hasUseServer?!0:!n.isOnlyImportedByClientComponents(e)&&lr(e,o,n.getHtmlOnlyImports(),i)&&fr(t,o)}function mr(e,t,n=[]){let r=dr(t,It(e,n));t.clearClientComponentFiles(),t.populateImportGraphFromFiles(r);let i=[],a=[];for(let{filePath:e,cacheKey:n,code:o,analysis:s}of r)s.directives.hasUseClient&&(a.push(e),t.recordClientComponent(e,o)),pr(e,o,t,s,n)&&(t.addServerComponent(e,o,s),i.push(e));return{serverComponentPaths:i,clientComponentPaths:a}}function hr(e={}){let t=null,n,r=!1,i={};return{name:`rari-server-build`,configResolved(a){n=a.root,r=a.command===`serve`;let o=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react/compiler-runtime`,`react-dom/client`]),s={},c=a.resolve.alias;Array.isArray(c)?c.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!o.has(e.find)&&(s[e.find]=e.replacement)}):typeof c==`object`&&Object.entries(c).forEach(([e,t])=>{typeof t==`string`&&!o.has(e)&&(s[e]=t)}),i=s,t=new ur(n,{...e,alias:s})},buildStart(){if(!t)return;let e=D.env.NODE_ENV===`production`,r=[E.join(n,`dist`,`cache`,`og`),E.join(n,`dist`,`cache`,`images`)];e&&r.push(`/tmp/rari-og-cache`,`/tmp/rari-image-cache`);for(let e of r)try{w.existsSync(e)&&w.rmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[rari] Failed to clear cache ${e}:`,t)}let a=E.join(n,`src`);w.existsSync(a)&&mr(a,t,Object.values(i))},async closeBundle(){if(t){await t.buildServerComponents(),await t.buildSSRClientComponents();try{await t.buildMdxRegistry(e.mdx)}catch(e){console.warn(`[rari] Failed to build MDX component registry:`,e)}try{let{generateRobotsFile:e}=await import(`./robots-BGCTYwKN.mjs`);await e({appDir:E.join(n,`src`,`app`),outDir:E.join(n,`dist`)})}catch(e){console.warn(`[rari] Failed to generate robots.txt:`,e)}try{let{generateSitemapFiles:e}=await import(`./sitemap-1n5BIACA.mjs`);await e({appDir:E.join(n,`src`,`app`),outDir:E.join(n,`dist`),aliases:i})}catch(e){console.warn(`[rari] Failed to generate sitemap:`,e)}try{let{generateFeedFile:e}=await import(`./feed-Ixvy9L12.mjs`);await e({appDir:E.join(n,`src`,`app`),outDir:E.join(n,`dist`),aliases:i})}catch(e){console.warn(`[rari] Failed to generate feed:`,e)}}},async handleHotUpdate({file:e}){if(!t||!r)return;let i=E.relative(n,e).replace(x,`/`);if(!(!i.startsWith(`src/`)||!_.test(i)))try{let n=await w.promises.readFile(e,`utf-8`),r=t.getModuleAnalysis(e,n),i=t.hasComponent(e);if(!pr(e,n,t,r)){i&&t.removeComponent(e);return}i||t.addServerComponent(e,n,r),await t.rebuildComponent(e)}catch(e){console.error(`[rari] Build: Error rebuilding ${i}:`,e)}}}}const gr=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g,_r=/import\s+\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g,vr=/import\s+(\w+)\s*,\s*\{([^}]+)\}\s+from\s+['"]([^'"]+)['"]/g,yr=/defineMdxComponents\s*\(\s*\{([\s\S]*?)\}\s*\)/;function br(e,t,n){for(let r of t.split(`,`)){let t=r.trim();if(!t||(t=t.replace(/^type\s+/i,``).trim(),!t))continue;let i=t.split(/\s+as\s+/i),a=(i[1]??i[0]).trim();a&&n.set(a,e)}}function xr(e){let t=new Map;for(let n of e.matchAll(vr))t.set(n[1],n[3]),br(n[3],n[2],t);for(let n of e.matchAll(gr))t.set(n[1],n[2]);for(let n of e.matchAll(_r))br(n[2],n[1],t);return t}function Sr(e){let t=[];for(let n of e.split(`,`)){let e=n.trim();if(!e)continue;let r=e.indexOf(`:`);if(r===-1){t.push({name:e,binding:e});continue}let i=e.slice(0,r).trim(),a=e.slice(r+1).trim();i&&a&&t.push({name:i,binding:a})}return t}function Cr(e){try{return W(w.readFileSync(e,`utf-8`)).topLevelUseClient}catch{return!1}}function wr(e){let{code:t,id:n,projectRoot:r,resolvedAlias:i}=e;if(!t.includes(`defineMdxComponents`)||t.includes(`__RARI_MDX_RESOLVED__`))return null;let a=yr.exec(t);if(!a)return null;let o=xr(t),s=Sr(a[1]);if(s.length===0)return null;let c=`defineMdxComponents(/* __RARI_MDX_RESOLVED__ */[\n${s.map(({name:e,binding:t})=>{let a=o.get(t);if(a==null||a===``)throw Error(`[rari/mdx] Could not resolve import for MDX component "${e}" (binding "${t}") in ${n}`);let s=le(a,n,i),c=$e(s,r).replace(x,`/`),l=Cr(s);return` { name: ${JSON.stringify(e)}, component: ${t}, id: ${JSON.stringify(c)}, client: ${l} }`}).join(`,
112
+ `)},\n])`;return t.replace(yr,c)}const Tr=/forwardRef|memo|\b(?:[A-Z]|use[A-Z0-9])/,Er=/\.[cm]?[jt]sx?$/,Dr=/\?.*$/,Or=/['"]use memo['"]/;function kr(e){return{...e===!0?{}:e,target:`19`}}function Ar(e,t){return t.compilationMode===`annotation`?Or.test(e):Tr.test(e)}function jr(e){if(e.startsWith(`\0`)||e.includes(`virtual:`))return!1;let t=e.replace(Dr,``);return!/\.d\.[cm]?ts$/.test(t)&&Er.test(t)&&!t.includes(`/node_modules/`)}const Mr=/\.[jt]sx$/;function Nr(e,t=`app`){let n=kr(e),r,i=!0,a=!1,o=!1,s=async e=>{if(r)return r;try{return r=await import(`oxc-transform-react`),r}catch(t){return e(`React Compiler requires the optional \`oxc-transform-react\` package. Install it before enabling \`rari({ compiler: true })\`.${t instanceof Error?`\n${t.message}`:``}`)}};return{name:t===`library`?`rari:react-compiler-library`:`rari:react-compiler`,enforce:`pre`,async config(e,{command:n}){return await s(e=>this.error(e)),t===`library`?(o=!1,a=!1,{}):(o=n===`serve`,{oxc:{jsx:{refresh:!1}},optimizeDeps:{include:[`react/compiler-runtime`]}})},configResolved(e){if(t===`library`){i=e.build.sourcemap!==!1,a=!1,o=!1;return}i=e.command!==`build`||e.build.sourcemap!==!1,a=!e.isProduction,o=!e.isProduction&&e.command===`serve`&&e.server.hmr!==!1},async transform(e,c){if(!jr(c))return null;let l=c.replace(Dr,``);if(t===`library`&&!Mr.test(l)||t===`app`&&this.environment.config.consumer===`server`)return null;let{transform:u}=r??await s(e=>this.error(e)),d=Ar(e,n),f=await u(l,e,{jsx:{runtime:`automatic`,development:a,importSource:`react`,refresh:o},reactCompiler:d?n:!1,sourcemap:i}),p=f.errors.map(e=>{let t=e.codeframe;return t!=null&&t!==``?`${e.message}\n${t}`:e.message});if(f.fatal){let e=p.join(`
113
113
 
114
- `);this.error(e===``?`React Compiler transform failed.`:e)}for(let e of f)this.warn(e);return{code:d.code,map:d.map}}}}function Mr(e){return a(e)}function Nr(e){return a(e)}async function Pr(e){let t=await import(e);return Mr(t)?t:{}}function Fr(e,t){e&&(e.notFound&&(t.notFound=!0),e.redirect!=null&&(t.redirect=typeof e.redirect==`string`?e.redirect:e.redirect.destination),e.revalidate!==void 0&&(t.revalidate=e.revalidate),e.props&&(t.props={...t.props,...e.props}))}async function Ir(e,t,n,r){typeof e.getData==`function`&&Fr(await e.getData({params:t,searchParams:n}),r)}async function Lr(e,t,n,r){typeof e.getServerSideProps==`function`&&Fr(await e.getServerSideProps({params:t,searchParams:n}),r)}async function Rr(e,t,n){typeof e.getStaticProps==`function`&&Fr(await e.getStaticProps({params:t}),n)}async function zr(e,t,n){try{let r=await Pr(e),i={props:{}};return await Ir(r,t,n,i),await Lr(r,t,n,i),await Rr(r,t,i),i}catch(t){return console.error(`[rari] Router: Failed to extract server props from ${e}:`,t),{props:{}}}}async function Br(e,t,n){try{let r=await Pr(e);if(typeof r.generateMetadata==`function`){let e=await r.generateMetadata({params:t,searchParams:n});if(Nr(e))return e}return Nr(r.metadata)?r.metadata:{}}catch(t){return console.error(`[rari] Router: Failed to extract metadata from ${e}:`,t),{}}}async function Vr(e){try{let t=await Se(e);return t==null?[]:r(t)?t:(c(e),[])}catch(t){return console.error(`[rari] Router: Failed to extract static params from ${e}:`,t),[]}}async function Hr(e){try{let t=await Pr(e);return!!(t.getData??t.getServerSideProps??t.getStaticProps??t.generateMetadata??t.generateStaticParams)}catch{return!1}}const Ur=new Map;async function Wr(e,t,n,r=6e4){let i=`${e}:${JSON.stringify(t)}:${JSON.stringify(n)}`,a=Ur.get(i);if(a&&Date.now()-a.timestamp<r)return a.result;let o=await zr(e,t,n);return Ur.set(i,{result:o,timestamp:Date.now()}),o}function Gr(){Ur.clear()}function Kr(e){for(let t of Ur.keys())t.startsWith(e)&&Ur.delete(t)}const qr="[rari] Runtime dist not built. Run `pnpm build` in the rari package first.",Jr=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Yr=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Xr=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Zr=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Qr=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,$r=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ei=/import\s+["']\.\.?\/([^"']+)["'];?/g,ti=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,ni=/^['"]use client['"];?\s*$/gm,ri=/import\s+["']([^"']+)["']/g,ii=/^[./@~#]/;function ai(e,t){for(let n of Object.keys(t))if(e===n||e.startsWith(`${n}/`))return!0;return!1}function oi(e){let t=o(e);return t===`ENOENT`||t===`ERR_PACKAGE_PATH_NOT_EXPORTED`||t===`ERR_MODULE_NOT_FOUND`}function si(e){return e===`react`||e instanceof RegExp&&e.source===`^react$`&&e.flags===``}const ci=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,li=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,ui=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,di=/import\s+["']([^"']+)["']/g,fi=/from(\s*)(['"])(?:\.\/vendor\/react-flight-client\/index|rari\/runtime\/vendor\/react-flight-client\/index)\.mjs\2/g,pi=/\bJSX\b/,mi=/\{([^}]*)\}/,hi=/^['"]use client['"];?\s*\n/,gi={remotePatterns:[],localPatterns:[],deviceSizes:f,imageSizes:d,formats:u,qualityAllowlist:l,minimumCacheTTL:60},_i=new Map;async function vi(e){let t=_i.get(e);if(t!=null&&t!==``)return t;let n=import.meta.url,r=k(n),i=D.dirname(r),a=[D.join(i,`runtime`,e),D.join(i,`../runtime`,e)];for(let t of a)try{let n=await T.promises.readFile(t,`utf-8`);return t.endsWith(`.ts`)&&(n=n.replace(Jr,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(Yr,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(Xr,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(Zr,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(Qr,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace($r,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(ei,(e,t)=>`import "rari/${t}";`)),_i.set(e,n),n}catch(e){let n=o(e);n!==`ENOENT`&&n!==`EISDIR`&&console.warn(`[rari] Unexpected error reading ${t}:`,e)}throw Error(`Could not find ${e}. Tried: ${a.join(`, `)}`)}const yi=D.dirname(k(import.meta.url)),bi=D.dirname(yi);function xi(e){let t=[D.join(yi,`runtime`,e),D.join(yi,`../runtime`,e)];for(let e of t)if(T.existsSync(e))return e;return null}function Si(e){return e.startsWith(bi)}async function Ci(){return vi(`rsc-client-runtime.mjs`)}async function wi(e,t){return(await vi(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function Ti(){return vi(`rsc-references.mjs`)}async function Ei(e,t){let r=D.join(e,`src`),{getBinaryPath:i}=await import(`./platform.mjs`),a=i(),o=me(a,[`scan-images`,`--src`,r],{encoding:`utf8`,cwd:e,shell:!1,timeout:6e4});if(o.error)throw Error(`Failed to scan for image usage: ${o.error.message}`);if(o.signal)throw Error(`Failed to scan for image usage: process terminated by signal ${o.signal}`);if(o.status!==0)throw Error(`Failed to scan for image usage: ${o.stderr||o.stdout||`exit code ${o.status}`}`);let s;try{s={images:n(o.stdout,`images`)??[]}}catch(e){let t=e instanceof SyntaxError||e instanceof Error?e.message:String(e),n=(o.stdout||o.stderr||`(empty)`).slice(0,500);throw Error(`Failed to parse image scanner output as JSON: ${t}. Scanner output: ${n}`,{cause:e})}let c={...gi,...t.images,preoptimizeManifest:s.images},l=D.join(e,`dist`),u=D.join(l,`server`);T.existsSync(u)||T.mkdirSync(u,{recursive:!0});let d=D.join(u,`image.json`);T.writeFileSync(d,JSON.stringify(c))}function Di(e){return e}function Oi(e={}){if(e.jsPoolSize!=null){let t=e.jsPoolSize;if(!Number.isInteger(t)||t<1||!Number.isFinite(t))throw Error(`jsPoolSize must be a finite positive integer; received ${String(t)}`)}let n=new Map,r=new Set,c=new Ut,l=null,u=null,d=null,f={},p=null;function m(){p=null}function h(){return p!=null&&p!==``||(p=an(rn({projectRoot:e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd(),mdxOptions:e.mdx,alias:f,cache:c}))),p}function v(e){return n.get(J(e))}function y(e,t){n.set(J(e),t)}function b(e){Vt(n,e)}function te(e){r.add(J(e))}function ne(e){return r.has(J(e))}function ae(e){r.delete(e);try{r.delete(T.realpathSync(e))}catch{r.delete(D.resolve(e))}}function oe(){let e=new Set(r);if(l)for(let t of l.getClientComponentPaths())e.add(t);return e}function ce(e){let t={hasUseServer:!1,hasUseClient:!1},n=e.replace(x,`/`);if(!_.test(n)||!n.includes(`/src/`))return t;try{let n=c.get(e);t.hasUseServer=n.directives.hasUseServer,t.hasUseClient=n.directives.hasUseClient}catch{}return t}let S=null,ue=null;function de(){if(l)return l.getHtmlOnlyImports();let t=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd(),n=D.join(t,`index.html`);try{let e=T.statSync(n).mtimeMs;if(S!==null&&e===ue)return S;ue=e}catch{return S??=new Set,S}return S=yn(t),S}function C(e){if(e.includes(`node_modules`)||Si(e))return!1;let t=J(e);try{return cr(t,c.get(e),de(),t)}catch{return!1}}function w(e,t){try{let n=new Set(gt(e));return(t?.hasDefaultExport??vt(e))&&n.add(`default`),[...n]}catch{return[]}}function me(t,n,r){let i=tt(n,e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd()),a=zn(t,i),o=a?.code??t;if(!r.topLevelUseServer)return a==null?t:(o+=`
114
+ `);this.error(e===``?`React Compiler transform failed.`:e)}for(let e of p)this.warn(e);return{code:f.code,map:f.map}}}}function Pr(e){return a(e)}function Fr(e){return a(e)}async function Ir(e){let t=await import(e);return Pr(t)?t:{}}function Lr(e,t){e&&(e.notFound&&(t.notFound=!0),e.redirect!=null&&(t.redirect=typeof e.redirect==`string`?e.redirect:e.redirect.destination),e.revalidate!==void 0&&(t.revalidate=e.revalidate),e.props&&(t.props={...t.props,...e.props}))}async function Rr(e,t,n,r){typeof e.getData==`function`&&Lr(await e.getData({params:t,searchParams:n}),r)}async function zr(e,t,n,r){typeof e.getServerSideProps==`function`&&Lr(await e.getServerSideProps({params:t,searchParams:n}),r)}async function Br(e,t,n){typeof e.getStaticProps==`function`&&Lr(await e.getStaticProps({params:t}),n)}async function Vr(e,t,n){try{let r=await Ir(e),i={props:{}};return await Rr(r,t,n,i),await zr(r,t,n,i),await Br(r,t,i),i}catch(t){return console.error(`[rari] Router: Failed to extract server props from ${e}:`,t),{props:{}}}}async function Hr(e,t,n){try{let r=await Ir(e);if(typeof r.generateMetadata==`function`){let e=await r.generateMetadata({params:t,searchParams:n});if(Fr(e))return e}return Fr(r.metadata)?r.metadata:{}}catch(t){return console.error(`[rari] Router: Failed to extract metadata from ${e}:`,t),{}}}async function Ur(e){try{let t=await Se(e);return t==null?[]:r(t)?t:(c(e),[])}catch(t){return console.error(`[rari] Router: Failed to extract static params from ${e}:`,t),[]}}async function Wr(e){try{let t=await Ir(e);return!!(t.getData??t.getServerSideProps??t.getStaticProps??t.generateMetadata??t.generateStaticParams)}catch{return!1}}const Gr=new Map;async function Kr(e,t,n,r=6e4){let i=`${e}:${JSON.stringify(t)}:${JSON.stringify(n)}`,a=Gr.get(i);if(a&&Date.now()-a.timestamp<r)return a.result;let o=await Vr(e,t,n);return Gr.set(i,{result:o,timestamp:Date.now()}),o}function qr(){Gr.clear()}function Jr(e){for(let t of Gr.keys())t.startsWith(e)&&Gr.delete(t)}const Yr="[rari] Runtime dist not built. Run `pnpm build` in the rari package first.",Xr=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Zr=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Qr=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,$r=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ei=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ti=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,ni=/import\s+["']\.\.?\/([^"']+)["'];?/g,ri=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,ii=/^['"]use client['"];?\s*$/gm,ai=/import\s+["']([^"']+)["']/g,oi=/^[./@~#]/;function si(e,t){for(let n of Object.keys(t))if(e===n||e.startsWith(`${n}/`))return!0;return!1}function ci(e){let t=o(e);return t===`ENOENT`||t===`ERR_PACKAGE_PATH_NOT_EXPORTED`||t===`ERR_MODULE_NOT_FOUND`}function li(e){return e===`react`||e instanceof RegExp&&e.source===`^react$`&&e.flags===``}const ui=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,di=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,fi=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,pi=/import\s+["']([^"']+)["']/g,mi=/from(\s*)(['"])(?:\.\/vendor\/react-flight-client\/index|rari\/runtime\/vendor\/react-flight-client\/index)\.mjs\2/g,hi=/\bJSX\b/,gi=/\{([^}]*)\}/,_i=/^['"]use client['"];?\s*\n/,vi={remotePatterns:[],localPatterns:[],deviceSizes:f,imageSizes:d,formats:u,qualityAllowlist:l,minimumCacheTTL:60},yi=new Map;async function bi(e){let t=yi.get(e);if(t!=null&&t!==``)return t;let n=import.meta.url,r=O(n),i=E.dirname(r),a=[E.join(i,`runtime`,e),E.join(i,`../runtime`,e)];for(let t of a)try{let n=await w.promises.readFile(t,`utf-8`);return t.endsWith(`.ts`)&&(n=n.replace(Xr,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(Zr,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace(Qr,(e,t,n)=>`import type ${t} from "rari/${n}";`),n=n.replace($r,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(ei,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(ti,(e,t,n)=>`import ${t} from "rari/${n}";`),n=n.replace(ni,(e,t)=>`import "rari/${t}";`)),yi.set(e,n),n}catch(e){let n=o(e);n!==`ENOENT`&&n!==`EISDIR`&&console.warn(`[rari] Unexpected error reading ${t}:`,e)}throw Error(`Could not find ${e}. Tried: ${a.join(`, `)}`)}const xi=E.dirname(O(import.meta.url)),Si=E.dirname(xi);function $(e){let t=[E.join(xi,`runtime`,e),E.join(xi,`../runtime`,e)];for(let e of t)if(w.existsSync(e))return e;return null}function Ci(e){return e.startsWith(Si)}async function wi(){return bi(`rsc-client-runtime.mjs`)}async function Ti(e,t){return(await bi(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function Ei(){return bi(`rsc-references.mjs`)}async function Di(e,t){let r=E.join(e,`src`),{getBinaryPath:i}=await import(`./platform.mjs`),a=i(),o=he(a,[`scan-images`,`--src`,r],{encoding:`utf8`,cwd:e,shell:!1,timeout:6e4});if(o.error)throw Error(`Failed to scan for image usage: ${o.error.message}`);if(o.signal)throw Error(`Failed to scan for image usage: process terminated by signal ${o.signal}`);if(o.status!==0)throw Error(`Failed to scan for image usage: ${o.stderr||o.stdout||`exit code ${o.status}`}`);let s;try{s={images:n(o.stdout,`images`)??[]}}catch(e){let t=e instanceof SyntaxError||e instanceof Error?e.message:String(e),n=(o.stdout||o.stderr||`(empty)`).slice(0,500);throw Error(`Failed to parse image scanner output as JSON: ${t}. Scanner output: ${n}`,{cause:e})}let c={...vi,...t.images,preoptimizeManifest:s.images},l=E.join(e,`dist`),u=E.join(l,`server`);w.existsSync(u)||w.mkdirSync(u,{recursive:!0});let d=E.join(u,`image.json`);w.writeFileSync(d,JSON.stringify(c))}function Oi(e){return e}function ki(e={}){if(e.jsPoolSize!=null){let t=e.jsPoolSize;if(!Number.isInteger(t)||t<1||!Number.isFinite(t))throw Error(`jsPoolSize must be a finite positive integer; received ${String(t)}`)}let n=new Map,r=new Set,c=new Wt,l=null,u=null,d=null,f={},p=null;function m(){p=null}function h(){return p!=null&&p!==``||(p=on(an({projectRoot:e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd(),mdxOptions:e.mdx,alias:f,cache:c}))),p}function v(e){return n.get(q(e))}function y(e,t){n.set(q(e),t)}function b(e){Ht(n,e)}function te(e){r.add(q(e))}function ne(e){return r.has(q(e))}function ae(e){r.delete(e);try{r.delete(w.realpathSync(e))}catch{r.delete(E.resolve(e))}}function oe(){let e=new Set(r);if(l)for(let t of l.getClientComponentPaths())e.add(t);return e}function ce(e){let t={hasUseServer:!1,hasUseClient:!1},n=e.replace(x,`/`);if(!_.test(n)||!n.includes(`/src/`))return t;try{let n=c.get(e);t.hasUseServer=n.directives.hasUseServer,t.hasUseClient=n.directives.hasUseClient}catch{}return t}let S=null,ue=null;function de(){if(l)return l.getHtmlOnlyImports();let t=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd(),n=E.join(t,`index.html`);try{let e=w.statSync(n).mtimeMs;if(S!==null&&e===ue)return S;ue=e}catch{return S??=new Set,S}return S=bn(t),S}function C(e){if(e.includes(`node_modules`)||Ci(e))return!1;let t=q(e);try{return lr(t,c.get(e),de(),t)}catch{return!1}}function fe(e,t){try{let n=new Set(gt(e));return(t?.hasDefaultExport??vt(e))&&n.add(`default`),[...n]}catch{return[]}}function he(t,n,r){let i=tt(n,e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd()),a=Bn(t,i),o=a?.code??t;if(!r.topLevelUseServer)return a==null?t:(o+=`
115
115
 
116
116
  if (import.meta.hot) {
117
117
  import.meta.hot.accept(() => {
118
118
  });
119
- }`,o);let s=w(o,r);if(s.length===0&&a==null)return t;let c=JSON.stringify(i);xn(o)?o+=`
119
+ }`,o);let s=fe(o,r);if(s.length===0&&a==null)return t;let c=JSON.stringify(i);Sn(o)?o+=`
120
120
  `:o+=`
121
121
 
122
122
  import {registerServerReference} from "react-server-dom-rari/server";
123
- `;for(let e of s)if(e==="default"){let t=ti.exec(o);if(t){let n=t[1];o+=`
123
+ `;for(let e of s)if(e==="default"){let t=ri.exec(o);if(t){let n=t[1];o+=`
124
124
  // Register server reference for default export
125
125
  `,o+=`registerServerReference(${n}, ${c}, ${JSON.stringify(e)});\n`}else{let t=`__default_export__`,n=Mt(o,t);n!=null&&(o=n,o+=`
126
126
  // Register server reference for default export
@@ -131,10 +131,10 @@ import {registerServerReference} from "react-server-dom-rari/server";
131
131
  if (import.meta.hot) {
132
132
  import.meta.hot.accept(() => {
133
133
  });
134
- }`,o}function E(t,n,r){let i=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd(),a=C(n);if(r.topLevelUseServer){let e=w(t,r);if(e.length===0)return``;let a=tt(n,i),o=`import { createServerReference } from "virtual:react-flight-client";
134
+ }`,o}function T(t,n,r){let i=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd(),a=C(n);if(r.topLevelUseServer){let e=fe(t,r);if(e.length===0)return``;let a=tt(n,i),o=`import { createServerReference } from "virtual:react-flight-client";
135
135
  `;o+=`import { callServer } from "rari/runtime/call-server";
136
- `;for(let t of e){let e=`${a}#${t}`,n=JSON.stringify(e);o+=t==="default"?`export default createServerReference(${n}, callServer);\n`:`export const ${t} = createServerReference(${n}, callServer);\n`}return o}if(a)return console.warn(`[rari] Server component ${n} should not be imported in client bundle`),``;if(!r.topLevelUseClient)return t;let o=w(t,r);if(o.length===0)return``;let s=JSON.stringify(n),c=`import {registerClientReference} from "react-server-dom-rari/server";
137
- `;for(let e of o){if(e==="default"){let e=`Attempted to call the default export of ${n} from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export default `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(e)});`}else{let t=`Attempted to call ${e}() from the server but ${e} is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export const ${e} = `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(t)});`}c+=`},`,c+=`${s},`,c+=`${JSON.stringify(e)});\n`}return c}function A(e,t,n){return!n.topLevelUseClient||w(e,n).length===0?e:e.replace(ni,``)}let j=!1;async function he(){let e=`http://localhost:${M()}`;try{let t=(await fetch(`${e}/_rari/health`,{signal:AbortSignal.timeout(1e3)})).ok;return j=t,t}catch{return j=!1,!1}}let _e=null;async function ye(e){return await he()?!0:(_e??=(async()=>{try{let t=Date.now()+e,n=50;for(;Date.now()<t;){if(await new Promise(e=>{setTimeout(e,Math.min(n,t-Date.now()))}),await he())return!0;n=Math.min(n*2,500)}return!1}finally{_e=null}})(),_e)}let be={name:`rari`,config(t,{command:n}){if(t.define??={},n===`serve`||O.env.RARI_SERVER_URL!=null&&O.env.RARI_SERVER_URL!==``||O.env.RARI_HOST!=null&&O.env.RARI_HOST!==``){let e=M(),n;if(O.env.RARI_SERVER_URL!=null&&O.env.RARI_SERVER_URL!==``)n=O.env.RARI_SERVER_URL;else if(O.env.RARI_HOST!=null&&O.env.RARI_HOST!==``){let t=O.env.RARI_HOST.startsWith(`http`)?O.env.RARI_HOST:`http://${O.env.RARI_HOST}`;n=t.replace(ie,``).includes(`:`)?t:`${t}:${e}`}else n=`http://localhost:${e}`;t.define[`import.meta.env.RARI_SERVER_URL`]=JSON.stringify(n)}let r=typeof t.css?.modules==`object`?t.css.modules:{};if(t.css={...t.css,transformer:t.css?.transformer??`lightningcss`,modules:{...r,pattern:Jn}},n===`build`){let n=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd(),r=D.join(n,`index.html`);if(T.existsSync(r))try{let e=T.readFileSync(r,`utf-8`),n=[];for(let t of e.matchAll(ri)){let e=t[1];if(e.startsWith(`/src/`)&&_.test(e)){let t=e.slice(1),r=D.basename(t,D.extname(t));n.push({path:t,name:r})}}if(n.length>0){t.build??={},t.build.rolldownOptions??={};let e=t.build.rolldownOptions.input??{main:`./index.html`},r;r=typeof e==`string`?{main:e}:Array.isArray(e)?{main:e[0]??`./index.html`}:{...e},n.forEach(({path:e,name:t})=>{r[t]=`./${e}`}),t.build.rolldownOptions.input=r}}catch(e){console.warn(`[rari] Error parsing index.html for build inputs:`,e)}}t.resolve??={};let o=t.resolve,c=Array.isArray(o.dedupe)?o.dedupe:[],l=[`react`,`react-dom`];o.dedupe=[...new Set([...c,...l])];let u=[];i(o.alias)?u=o.alias:a(o.alias)&&(u=s(o.alias)),u=u.map(e=>e.find===`react`?{find:/^react$/,replacement:e.replacement}:e);let d=new Set(u.map(e=>String(e.find))),f=u.some(e=>si(e.find));try{let e=k(import.meta.resolve(`react`)),t=k(import.meta.resolve(`react-dom/client`)),n=k(import.meta.resolve(`react/jsx-runtime`)),r=[];d.has(`react/jsx-runtime`)||r.push({find:`react/jsx-runtime`,replacement:n});try{let e=k(import.meta.resolve(`react/jsx-dev-runtime`));d.has(`react/jsx-dev-runtime`)||r.push({find:`react/jsx-dev-runtime`,replacement:e})}catch(e){oi(e)||console.warn(`[rari] Unexpected error resolving react/jsx-dev-runtime:`,e)}try{let e=k(import.meta.resolve(`react/compiler-runtime`));d.has(`react/compiler-runtime`)||r.push({find:`react/compiler-runtime`,replacement:e})}catch(e){oi(e)||console.warn(`[rari] Unexpected error resolving react/compiler-runtime:`,e)}f||r.push({find:/^react$/,replacement:e}),d.has(`react-dom/client`)||r.push({find:`react-dom/client`,replacement:t}),o.alias=[...u,...r]}catch(e){oi(e)||console.warn(`[rari] Unexpected error configuring React aliases:`,e)}t.environments??={},t.environments.rsc={resolve:{conditions:[`react-server`,`node`,`import`]},...t.environments.rsc},t.environments.ssr={resolve:{conditions:[`node`,`import`]},...t.environments.ssr},t.environments.client={resolve:{conditions:[`browser`,`import`]},...t.environments.client},t.optimizeDeps??={},t.optimizeDeps.include??=[];for(let e of[`react`,`react-dom`,`react-dom/client`,`react-dom/server`,`react/jsx-runtime`,`react/jsx-dev-runtime`])t.optimizeDeps.include.includes(e)||t.optimizeDeps.include.push(e);if(t.optimizeDeps.exclude??=[],t.optimizeDeps.exclude.includes(`rari`)||t.optimizeDeps.exclude.push(`rari`),n===`build`)for(let e of[`rsc`,`ssr`,`client`]){let n=t.environments[e];n.build!=null&&(n.build.rolldownOptions??={})}t.server??={},t.server.proxy??={};let p=M();if(t.server.proxy[`/api`]={target:`http://localhost:${p}`,changeOrigin:!0,secure:!1,ws:!0},t.server.proxy[`/_rari`]={target:`http://localhost:${p}`,changeOrigin:!0,secure:!1,ws:!0},n===`build`){t.build??={},t.build.rolldownOptions??={},t.build.rolldownOptions.input??={main:`./index.html`},t.build.rolldownOptions.output??={};let e=Array.isArray(t.build.rolldownOptions.output)?t.build.rolldownOptions.output:[t.build.rolldownOptions.output];for(let t of e){if(t.codeSplitting!==!1&&typeof t.codeSplitting!=`object`&&(t.codeSplitting={}),typeof t.codeSplitting==`object`){t.codeSplitting.groups??=[];let e=t.codeSplitting.groups;t.codeSplitting.groups.push({name(t){if(t.includes(`node_modules`)){for(let n of e)if(n.test!=null){let e=!1;if(typeof n.test==`function`?e=!!n.test(t):n.test instanceof RegExp?e=n.test.test(t):typeof n.test==`string`&&(e=t.includes(n.test)),e)return null}return t.includes(`node_modules/react-dom`)?`react-dom`:t.includes(`node_modules/react`)?`react`:`vendor`}return null}})}t.chunkFileNames??=e=>e.moduleIds.some(e=>ce(e).hasUseServer)?`client/actions/[name]-[hash].js`:e.moduleIds.some(e=>ce(e).hasUseClient)?`client/components/[name]-[hash].js`:`assets/[name]-[hash].js`}}t.environments.client.build??={},t.environments.client.build.rolldownOptions??={},t.environments.client.build.rolldownOptions.input??={},t.environments.client.build.rolldownOptions.external??=[];let m=t.environments.client.build.rolldownOptions.external;if(Array.isArray(m)){let e=m.indexOf(`react-server-dom-webpack/client`);e!==-1&&m.splice(e,1)}return t},configResolved(e){let t=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react/compiler-runtime`,`react-dom/client`]),n=e.resolve.alias;Array.isArray(n)?n.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!t.has(e.find)&&(f[e.find]=e.replacement)}):typeof n==`object`&&Object.entries(n).forEach(([e,n])=>{typeof n==`string`&&!t.has(e)&&(f[e]=n)})},async transform(t,n){if(n.endsWith(`.mdx`)&&m(),/\.(?:tsx?|jsx?|mts|mjs)$/.test(n)&&t.includes(`defineMdxComponents`)){let r=Cr({code:t,id:n,projectRoot:e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd(),resolvedAlias:f});if(r!=null&&r!==``)return{code:r,map:null}}if(!_.test(n))return null;let r=t,i=!1;if(e.experimental?.useCache||e.experimental?.useCacheRemote){let e=await Vn();if(e){let r=e(t,n);r!=null&&r!==``&&(t=r,i=!0)}}let a=this.environment,o=c.get(n,r);if(o.topLevelUseClient){y(n,`client`),te(n);for(let e of o.importSources){if(!ii.test(e)&&!ai(e,f))continue;let t=le(e,n,f);T.existsSync(t)&&(y(t,`client`),te(t))}return A(t,n,o)}if(v(n)===`client`||ne(n))return A(t,n,o);if(C(n)){if(y(n,`server`),a.name===`rsc`||a.name===`ssr`)return me(t,n,o);{let e=E(t,n,o);return e=`// HMR acceptance for server component
136
+ `;for(let t of e){let e=`${a}#${t}`,n=JSON.stringify(e);o+=t==="default"?`export default createServerReference(${n}, callServer);\n`:`export const ${t} = createServerReference(${n}, callServer);\n`}return o}if(a)return console.warn(`[rari] Server component ${n} should not be imported in client bundle`),``;if(!r.topLevelUseClient)return t;let o=fe(t,r);if(o.length===0)return``;let s=JSON.stringify(n),c=`import {registerClientReference} from "react-server-dom-rari/server";
137
+ `;for(let e of o){if(e==="default"){let e=`Attempted to call the default export of ${n} from the server but it's on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export default `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(e)});`}else{let t=`Attempted to call ${e}() from the server but ${e} is on the client. It's not possible to invoke a client function from the server, it can only be rendered as a Component or passed to props of a Client Component.`;c+=`export const ${e} = `,c+=`registerClientReference(function() {`,c+=`throw new Error(${JSON.stringify(t)});`}c+=`},`,c+=`${s},`,c+=`${JSON.stringify(e)});\n`}return c}function k(e,t,n){return!n.topLevelUseClient||fe(e,n).length===0?e:e.replace(ii,``)}let A=!1;async function j(){let e=`http://localhost:${M()}`;try{let t=(await fetch(`${e}/_rari/health`,{signal:AbortSignal.timeout(1e3)})).ok;return A=t,t}catch{return A=!1,!1}}let _e=null;async function ye(e){return await j()?!0:(_e??=(async()=>{try{let t=Date.now()+e,n=50;for(;Date.now()<t;){if(await new Promise(e=>{setTimeout(e,Math.min(n,t-Date.now()))}),await j())return!0;n=Math.min(n*2,500)}return!1}finally{_e=null}})(),_e)}let be={name:`rari`,config(t,{command:n}){if(t.define??={},n===`serve`||D.env.RARI_SERVER_URL!=null&&D.env.RARI_SERVER_URL!==``||D.env.RARI_HOST!=null&&D.env.RARI_HOST!==``){let e=M(),n;if(D.env.RARI_SERVER_URL!=null&&D.env.RARI_SERVER_URL!==``)n=D.env.RARI_SERVER_URL;else if(D.env.RARI_HOST!=null&&D.env.RARI_HOST!==``){let t=D.env.RARI_HOST.startsWith(`http`)?D.env.RARI_HOST:`http://${D.env.RARI_HOST}`;n=t.replace(ie,``).includes(`:`)?t:`${t}:${e}`}else n=`http://localhost:${e}`;t.define[`import.meta.env.RARI_SERVER_URL`]=JSON.stringify(n)}let r=typeof t.css?.modules==`object`?t.css.modules:{};if(t.css={...t.css,transformer:t.css?.transformer??`lightningcss`,modules:{...r,pattern:Yn}},n===`build`){let n=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd(),r=E.join(n,`index.html`);if(w.existsSync(r))try{let e=w.readFileSync(r,`utf-8`),n=[];for(let t of e.matchAll(ai)){let e=t[1];if(e.startsWith(`/src/`)&&_.test(e)){let t=e.slice(1),r=E.basename(t,E.extname(t));n.push({path:t,name:r})}}if(n.length>0){t.build??={},t.build.rolldownOptions??={};let e=t.build.rolldownOptions.input??{main:`./index.html`},r;r=typeof e==`string`?{main:e}:Array.isArray(e)?{main:e[0]??`./index.html`}:{...e},n.forEach(({path:e,name:t})=>{r[t]=`./${e}`}),t.build.rolldownOptions.input=r}}catch(e){console.warn(`[rari] Error parsing index.html for build inputs:`,e)}}t.resolve??={};let o=t.resolve,c=Array.isArray(o.dedupe)?o.dedupe:[],l=[`react`,`react-dom`];o.dedupe=[...new Set([...c,...l])];let u=[];i(o.alias)?u=o.alias:a(o.alias)&&(u=s(o.alias)),u=u.map(e=>e.find===`react`?{find:/^react$/,replacement:e.replacement}:e);let d=new Set(u.map(e=>String(e.find))),f=u.some(e=>li(e.find));try{let e=O(import.meta.resolve(`react`)),t=O(import.meta.resolve(`react-dom/client`)),n=O(import.meta.resolve(`react/jsx-runtime`)),r=[];d.has(`react/jsx-runtime`)||r.push({find:`react/jsx-runtime`,replacement:n});try{let e=O(import.meta.resolve(`react/jsx-dev-runtime`));d.has(`react/jsx-dev-runtime`)||r.push({find:`react/jsx-dev-runtime`,replacement:e})}catch(e){ci(e)||console.warn(`[rari] Unexpected error resolving react/jsx-dev-runtime:`,e)}try{let e=O(import.meta.resolve(`react/compiler-runtime`));d.has(`react/compiler-runtime`)||r.push({find:`react/compiler-runtime`,replacement:e})}catch(e){ci(e)||console.warn(`[rari] Unexpected error resolving react/compiler-runtime:`,e)}f||r.push({find:/^react$/,replacement:e}),d.has(`react-dom/client`)||r.push({find:`react-dom/client`,replacement:t}),o.alias=[...u,...r]}catch(e){ci(e)||console.warn(`[rari] Unexpected error configuring React aliases:`,e)}t.environments??={},t.environments.rsc={resolve:{conditions:[`react-server`,`node`,`import`]},...t.environments.rsc},t.environments.ssr={resolve:{conditions:[`node`,`import`]},...t.environments.ssr},t.environments.client={resolve:{conditions:[`browser`,`import`]},...t.environments.client},t.optimizeDeps??={},t.optimizeDeps.include??=[];for(let e of[`react`,`react-dom`,`react-dom/client`,`react-dom/server`,`react/jsx-runtime`,`react/jsx-dev-runtime`])t.optimizeDeps.include.includes(e)||t.optimizeDeps.include.push(e);if(t.optimizeDeps.exclude??=[],t.optimizeDeps.exclude.includes(`rari`)||t.optimizeDeps.exclude.push(`rari`),n===`build`)for(let e of[`rsc`,`ssr`,`client`]){let n=t.environments[e];n.build!=null&&(n.build.rolldownOptions??={})}t.server??={},t.server.proxy??={};let p=M();if(t.server.proxy[`/api`]={target:`http://localhost:${p}`,changeOrigin:!0,secure:!1,ws:!0},t.server.proxy[`/_rari`]={target:`http://localhost:${p}`,changeOrigin:!0,secure:!1,ws:!0},n===`build`){t.build??={},t.build.rolldownOptions??={},t.build.rolldownOptions.input??={main:`./index.html`},t.build.rolldownOptions.output??={};let e=Array.isArray(t.build.rolldownOptions.output)?t.build.rolldownOptions.output:[t.build.rolldownOptions.output];for(let t of e){if(t.codeSplitting!==!1&&typeof t.codeSplitting!=`object`&&(t.codeSplitting={}),typeof t.codeSplitting==`object`){t.codeSplitting.groups??=[];let e=t.codeSplitting.groups;t.codeSplitting.groups.push({name(t){if(t.includes(`node_modules`)){for(let n of e)if(n.test!=null){let e=!1;if(typeof n.test==`function`?e=!!n.test(t):n.test instanceof RegExp?e=n.test.test(t):typeof n.test==`string`&&(e=t.includes(n.test)),e)return null}return t.includes(`node_modules/react-dom`)?`react-dom`:t.includes(`node_modules/react`)?`react`:`vendor`}return null}})}t.chunkFileNames??=e=>e.moduleIds.some(e=>ce(e).hasUseServer)?`client/actions/[name]-[hash].js`:e.moduleIds.some(e=>ce(e).hasUseClient)?`client/components/[name]-[hash].js`:`assets/[name]-[hash].js`}}t.environments.client.build??={},t.environments.client.build.rolldownOptions??={},t.environments.client.build.rolldownOptions.input??={},t.environments.client.build.rolldownOptions.external??=[];let m=t.environments.client.build.rolldownOptions.external;if(Array.isArray(m)){let e=m.indexOf(`react-server-dom-webpack/client`);e!==-1&&m.splice(e,1)}return t},configResolved(e){let t=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react/compiler-runtime`,`react-dom/client`]),n=e.resolve.alias;Array.isArray(n)?n.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!t.has(e.find)&&(f[e.find]=e.replacement)}):typeof n==`object`&&Object.entries(n).forEach(([e,n])=>{typeof n==`string`&&!t.has(e)&&(f[e]=n)})},async transform(t,n){if(n.endsWith(`.mdx`)&&m(),/\.(?:tsx?|jsx?|mts|mjs)$/.test(n)&&t.includes(`defineMdxComponents`)){let r=wr({code:t,id:n,projectRoot:e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd(),resolvedAlias:f});if(r!=null&&r!==``)return{code:r,map:null}}if(!_.test(n))return null;let r=t,i=!1;if(e.experimental?.useCache||e.experimental?.useCacheRemote){let e=await Hn();if(e){let r=e(t,n);r!=null&&r!==``&&(t=r,i=!0)}}let a=this.environment,o=c.get(n,r);if(o.topLevelUseClient){y(n,`client`),te(n);for(let e of o.importSources){if(!oi.test(e)&&!si(e,f))continue;let t=le(e,n,f);w.existsSync(t)&&(y(t,`client`),te(t))}return k(t,n,o)}if(v(n)===`client`||ne(n))return k(t,n,o);if(C(n)){if(y(n,`server`),a.name===`rsc`||a.name===`ssr`)return he(t,n,o);{let e=T(t,n,o);return e=`// HMR acceptance for server component
138
138
  if (import.meta.hot) {
139
139
  import.meta.hot.accept();
140
140
  if (typeof globalThis !== 'undefined') {
@@ -144,8 +144,8 @@ if (import.meta.hot) {
144
144
  }
145
145
  }
146
146
 
147
- ${e}`,e}}if(o.topLevelUseServer)return y(n,`server`),a.name===`rsc`||a.name===`ssr`?me(t,n,o):E(t,n,o);let s=v(n);if(s===`server`)return a.name===`rsc`||a.name===`ssr`?me(t,n,o):E(t,n,o);if(s===`client`)return A(t,n,o);y(n,`unknown`);let l=t,u=!1,d=!1,p=n.includes(`entry-client`),h=[],g=new Set;for(let e of ht(t)){if(e.typeOnly||e.sideEffectOnly||!ii.test(e.source)&&!ai(e.source,f))continue;let t=le(e.source,n,f),r=v(t)===`client`||T.existsSync(t)&&c.get(t).topLevelUseClient;if(r&&(y(t,`client`),te(t)),!r||p||a.name!==`rsc`&&a.name!==`ssr`)continue;let i=dn(e,t);if(i.code!==``){for(let e of i.helpers)g.add(e);h.push({start:e.start,end:e.end,replacement:i.code}),u=!0,d=!0}}for(let{start:e,end:t,replacement:n}of[...h].sort((e,t)=>t.start-e.start))l=l.slice(0,e)+n+l.slice(t);if(g.size>0&&(l=cn(l,`react-server-dom-rari/server`,[...g])),u){let e=l.includes(`import React`)||ci.test(l)||li.test(l),t=``;if(d&&!e&&(t+=`import React from 'react';
148
- `),t&&(l=t+l),!l.includes(`Suspense`)){let e=ui.exec(l);e&&(e[1]&&!e[2].includes(`Suspense`)?l=l.replace(e[0],e[0].replace(mi,`{ Suspense, $1 }`)):e[1]||(l=l.replace(e[0],`import React, { Suspense } from 'react';`)))}let r=O.env.NODE_ENV!==`production`;return(l.includes(`</`)||l.includes(`/>`)||pi.test(l))&&r&&(l=`'use client';\n\n${l}`,y(n,`client`)),l}return i?t:null},async configureServer(n){let r=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd(),i=D.join(r,`src`);await Ei(r,e);let a=async()=>{try{let t=new lr(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:f,csp:e.csp,cacheControl:e.cacheControl,cache:e.cache,action:e.action,jsPoolSize:e.jsPoolSize,origin:e.origin,htmlLimitedBots:e.htmlLimitedBots,experimental:e.experimental,moduleAnalysisCache:c});if(l=t,d??=new Zt(t,M()),T.existsSync(i)){let e=pr(i,t,Object.values(f));e.serverComponentPaths.length>0&&n.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:e.serverComponentPaths}})}let a=await t.getTransformedComponentsForDevelopment(),o=`http://localhost:${M()}`;await Promise.all(a.map(async e=>{try{if(e.id.startsWith(`app/`)||e.isAction)return;let t=await fetch(`${o}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Runtime: Failed to register component ${e.id}:`,t instanceof Error?t.message:String(t))}}))}catch(e){console.error(`[rari] Runtime: Component discovery failed:`,e instanceof Error?e.message:String(e))}},o=async()=>{try{let e=`http://localhost:${M()}`,t=oe();await Promise.all([...t].map(async t=>{let n=D.relative(O.cwd(),t),r=D.basename(t).replace(re,``);try{await fetch(`${e}/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:r,file_path:n,export_name:`default`})})}catch(e){console.error(`[rari] Runtime: Failed to pre-register client component ${r}:`,e)}}))}catch(e){console.error(`[rari] Runtime: Failed to pre-register client components:`,e)}},s=async()=>{if(u)return;let{getBinaryPath:t,getInstallationInstructions:r}=await import(`./platform.mjs`),i;try{i=t()}catch(e){console.error(`rari binary not found`),console.error(` ${e instanceof Error?e.message:String(e)}`),console.error(r());return}let s=M(),c=O.env.NODE_ENV===`production`?`production`:`development`,l=n.config.server.port,d=e.origin?.trim().replace(/\/+$/,``),f=O.env.RARI_ORIGIN?.trim().replace(/\/+$/,``),p=[`--mode`,c,`--port`,s.toString(),`--host`,`127.0.0.1`];u=pe(i,p,{stdio:[`ignore`,`pipe`,`pipe`],cwd:O.cwd(),env:{...O.env,RUST_LOG:O.env.RUST_LOG!=null&&O.env.RUST_LOG!==``?O.env.RUST_LOG:`error`,RARI_VITE_PORT:l.toString(),...e.jsPoolSize!=null&&(O.env.RARI_JS_POOL_SIZE==null||O.env.RARI_JS_POOL_SIZE===``)?{RARI_JS_POOL_SIZE:String(e.jsPoolSize)}:{},...d!=null&&d!==``&&(f==null||f===``)?{RARI_ORIGIN:d}:{},...e.htmlLimitedBots!=null&&(O.env.RARI_HTML_LIMITED_BOTS==null||O.env.RARI_HTML_LIMITED_BOTS===``)?{RARI_HTML_LIMITED_BOTS:e.htmlLimitedBots}:{}}}),u.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(t)}),u.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(t)}),u.on(`error`,e=>{j=!1,console.error(`Failed to start rari server:`,e.message),e.message.includes(`ENOENT`)&&console.error(` Binary not found. Please ensure rari is properly installed.`)}),u.on(`exit`,(e,t)=>{u=null,j=!1,t?console.error(`rari server stopped by signal ${t}`):e===0?console.error(`rari server stopped successfully`):e&&console.error(`rari server exited with code ${e}`)}),await ye(1e4)?(await a(),await o()):console.error(`Server failed to become ready for component registration`)},p=async e=>{try{if(!C(e))return;l??await a();let t=l;if(t==null)return;let n=c.getSource(e);t.addServerComponent(e,n);let r=qt(t.getImportGraph(),[e]);r.add(e);let i=await t.getTransformedComponentsForDevelopment(e=>r.has(e));if(i.length===0)return;let o=`http://localhost:${M()}`;await Promise.all(i.map(async e=>{try{let t=await fetch(`${o}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Failed to register component`,`${e.id}:`,t instanceof Error?t.message:String(t))}}))}catch(t){console.error(`[rari] Targeted HMR failed for`,`${e}:`,t instanceof Error?t.message:String(t))}};s().catch(e=>{console.error(`[rari] Failed to start Rust server:`,e)}),n.middlewares.use((e,t,n)=>{(async()=>{let r=e.headers.accept;if(r!=null&&r!==``&&r.includes(`text/x-component`)&&e.url!=null&&e.url!==``&&!e.url.startsWith(`/api`)&&!e.url.startsWith(`/rsc`)&&!e.url.includes(`.`)){if(!j&&!await ye(1e4)){console.error(`[rari] Rust server not ready, cannot proxy RSC request`),t.headersSent||(t.statusCode=503,t.end(`Server not ready`));return}let n=M(),r=`http://localhost:${n}${e.url}`;try{let i={};for(let[t,n]of Object.entries(e.headers))typeof n==`string`?i[t]=n:Array.isArray(n)&&(i[t]=n.join(`,`));i.host=`localhost:${n}`,i[`accept-encoding`]=`identity`;let a=await fetch(r,{method:e.method,headers:i});if(t.statusCode=a.status,a.headers.forEach((e,n)=>{n.toLowerCase()!==`content-encoding`&&t.setHeader(n,e)}),a.body){let e=a.body.getReader();try{let n=!1;for(;!n;){let{done:r,value:i}=await e.read();n=r,!n&&i!=null&&t.write(fe.from(i))}t.end()}catch(e){console.error(`[rari] Stream error:`,e),t.headersSent||(t.statusCode=500),t.end()}}else t.end();return}catch(e){console.error(`[rari] Failed to proxy RSC request:`,e),t.headersSent||(t.statusCode=500,t.end(`Internal Server Error`));return}}n()})()}),n.watcher.on(`change`,e=>{(async()=>{_.test(e)&&(b(e),ae(e),c.invalidate(e)),_.test(e)&&e.includes(i)&&C(e)&&(n.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:e}}),await p(e))})()}),n.middlewares.use(`/api/vite/hmr-transform`,(e,n)=>{if(e.method!==`POST`){n.statusCode=405,n.end(`Method Not Allowed`);return}let r=``;e.on(`data`,e=>{r+=e.toString()}),e.on(`end`,()=>{(async()=>{try{let e=t(r),i=e&&typeof e.filePath==`string`?e.filePath:void 0;if(i==null||i===``){n.statusCode=400,n.end(JSON.stringify({error:`filePath is required`}));return}await p(i),n.statusCode=200,n.setHeader(`Content-Type`,`application/json`),n.end(JSON.stringify({success:!0,filePath:i,message:`Component transformation completed`}))}catch(e){n.statusCode=500,n.setHeader(`Content-Type`,`application/json`),n.end(JSON.stringify({success:!1,error:e instanceof Error?e.message:String(e)}))}})()})}),n.httpServer?.on(`close`,()=>{if(d&&=(d.dispose(),null),u){let e=u;u=null,j=!1;let t=!1,n=setTimeout(()=>{t||e.kill(`SIGKILL`)},5e3);n.unref(),e.once(`exit`,()=>{t=!0,clearTimeout(n)}),e.kill(`SIGTERM`);return}j=!1})},resolveId(e,t){if(e===`virtual:rsc-integration`||e===`virtual:rsc-integration.ts`)return`virtual:rsc-integration.ts`;if(e===`virtual:rari-entry-client`||e===`virtual:rari-entry-client.ts`)return`virtual:rari-entry-client.ts`;if(e===`virtual:react-flight-client`||e===`virtual:react-flight-client.ts`)return`virtual:react-flight-client.ts`;if(e===`virtual:app-router-provider`||e===`virtual:app-router-provider.tsx`)return`virtual:app-router-provider.tsx`;if(e===`virtual:error-boundary-wrapper`||e===`virtual:error-boundary-wrapper.tsx`)return`virtual:error-boundary-wrapper.tsx`;if(Qt(e)||e===`virtual:rari-mdx-components`||e===`virtual:rari-mdx-components.ts`)return`virtual:rari-mdx-components.ts`;if(e===`react-server-dom-webpack/client`||e===`react-server-dom-webpack/client.browser`)return`virtual:react-flight-client.ts`;if(e===`./LoadingErrorBoundary`||e===`./LoadingErrorBoundary.tsx`)return`virtual:loading-error-boundary.tsx`;if(e===`react-server-dom-rari/server`)return e;if(t!=null&&t!==``&&t.startsWith(`virtual:`)&&e.startsWith(`./`)){let t=xi(D.basename(e));if(t!=null&&t!==``)return t}if(t!=null&&t!==``&&t.startsWith(`virtual:`)&&e.startsWith(`../`)){let n=import.meta.url,r=k(n),i=D.dirname(r),a=null,o=[D.join(i,`runtime`),D.join(i,`../runtime`)];for(let e of o)if(T.existsSync(e)){a=e;break}if(a!=null&&a!==``){let t=D.join(a,e);if(T.existsSync(t))return t;let n=D.join(a,`../dist`,D.basename(e));if(T.existsSync(n))return n}else console.warn(`[rari] Runtime directory not found, attempting fallback resolution for virtual import.\n Importer: ${t}\n ID: ${e}\n Current Dir: ${i}\n Hint: Runtime lookup failed, trying currentDir as fallback`);let s=D.join(i,e);if(T.existsSync(s))return s;let c=D.join(i,`../dist`,D.basename(e));if(T.existsSync(c))return c}if(O.env.NODE_ENV===`production`)try{let t=D.resolve(e);if(T.existsSync(t)&&C(t))return{id:e,external:!0}}catch(t){o(t)!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving server component:`,e,t)}return null},async load(t){if(_.test(t)&&this.environment.name===`client`)try{let e=c.get(t);if(e.topLevelUseServer)return E(c.getSource(t),t,e)}catch{}if(t===`virtual:rari-mdx-components.ts`)return h();if(t===`virtual:rari-entry-client.ts`){let t=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd(),n=Ht(It(D.join(t,`src`),Object.values(f)),c),r=new Set([...oe(),...n]),i=[{path:`rari/image`,exports:[`Image`]},{path:`virtual:error-boundary-wrapper.tsx`,exports:[`ErrorBoundaryWrapper`]}],a=[...r].filter(e=>{try{return c.get(e).topLevelUseClient}catch{return!1}}).map(e=>{let t=D.relative(O.cwd(),e).replace(x,`/`),n=t.replace(_,``),r=t.startsWith(`..`)?e.replace(x,`/`):t,i=!1,a=``;try{if(!c.get(e).hasDefaultExport){let t=c.getSource(e).match(ee);t&&(i=!0,a=t[1])}}catch(t){o(t)!==`ENOENT`&&console.warn(`[rari] Unexpected error reading component for export detection:`,e,t)}let s=i?a:`default`,l=i?a:D.basename(e,D.extname(e)),u=r.replace(x,`/`),d=u.startsWith(`/`)||g.test(u)?u:`/${u}`;return` "${r}": {
147
+ ${e}`,e}}if(o.topLevelUseServer)return y(n,`server`),a.name===`rsc`||a.name===`ssr`?he(t,n,o):T(t,n,o);let s=v(n);if(s===`server`)return a.name===`rsc`||a.name===`ssr`?he(t,n,o):T(t,n,o);if(s===`client`)return k(t,n,o);y(n,`unknown`);let l=t,u=!1,d=!1,p=n.includes(`entry-client`),h=[],g=new Set;for(let e of ht(t)){if(e.typeOnly||e.sideEffectOnly||!oi.test(e.source)&&!si(e.source,f))continue;let t=le(e.source,n,f),r=v(t)===`client`||w.existsSync(t)&&c.get(t).topLevelUseClient;if(r&&(y(t,`client`),te(t)),!r||p||a.name!==`rsc`&&a.name!==`ssr`)continue;let i=fn(e,t);if(i.code!==``){for(let e of i.helpers)g.add(e);h.push({start:e.start,end:e.end,replacement:i.code}),u=!0,d=!0}}for(let{start:e,end:t,replacement:n}of[...h].sort((e,t)=>t.start-e.start))l=l.slice(0,e)+n+l.slice(t);if(g.size>0&&(l=ln(l,`react-server-dom-rari/server`,[...g])),u){let e=l.includes(`import React`)||ui.test(l)||di.test(l),t=``;if(d&&!e&&(t+=`import React from 'react';
148
+ `),t&&(l=t+l),!l.includes(`Suspense`)){let e=fi.exec(l);e&&(e[1]&&!e[2].includes(`Suspense`)?l=l.replace(e[0],e[0].replace(gi,`{ Suspense, $1 }`)):e[1]||(l=l.replace(e[0],`import React, { Suspense } from 'react';`)))}let r=D.env.NODE_ENV!==`production`;return(l.includes(`</`)||l.includes(`/>`)||hi.test(l))&&r&&(l=`'use client';\n\n${l}`,y(n,`client`)),l}return i?t:null},async configureServer(n){let r=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd(),i=E.join(r,`src`);await Di(r,e);let a=async()=>{try{let t=new ur(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:f,csp:e.csp,cacheControl:e.cacheControl,cache:e.cache,action:e.action,jsPoolSize:e.jsPoolSize,origin:e.origin,htmlLimitedBots:e.htmlLimitedBots,experimental:e.experimental,moduleAnalysisCache:c});if(l=t,d??=new Qt(t,M()),w.existsSync(i)){let e=mr(i,t,Object.values(f));e.serverComponentPaths.length>0&&n.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:e.serverComponentPaths}})}let a=await t.getTransformedComponentsForDevelopment(),o=`http://localhost:${M()}`;await Promise.all(a.map(async e=>{try{if(e.id.startsWith(`app/`)||e.isAction)return;let t=await fetch(`${o}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Runtime: Failed to register component ${e.id}:`,t instanceof Error?t.message:String(t))}}))}catch(e){console.error(`[rari] Runtime: Component discovery failed:`,e instanceof Error?e.message:String(e))}},o=async()=>{try{let e=`http://localhost:${M()}`,t=oe();await Promise.all([...t].map(async t=>{let n=E.relative(D.cwd(),t),r=E.basename(t).replace(re,``);try{await fetch(`${e}/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:r,file_path:n,export_name:`default`})})}catch(e){console.error(`[rari] Runtime: Failed to pre-register client component ${r}:`,e)}}))}catch(e){console.error(`[rari] Runtime: Failed to pre-register client components:`,e)}},s=async()=>{if(u)return;let{getBinaryPath:t,getInstallationInstructions:r}=await import(`./platform.mjs`),i;try{i=t()}catch(e){console.error(`rari binary not found`),console.error(` ${e instanceof Error?e.message:String(e)}`),console.error(r());return}let s=M(),c=D.env.NODE_ENV===`production`?`production`:`development`,l=n.config.server.port,d=e.origin?.trim().replace(/\/+$/,``),f=D.env.RARI_ORIGIN?.trim().replace(/\/+$/,``),p=[`--mode`,c,`--port`,s.toString(),`--host`,`127.0.0.1`];u=me(i,p,{stdio:[`ignore`,`pipe`,`pipe`],cwd:D.cwd(),env:{...D.env,RUST_LOG:D.env.RUST_LOG!=null&&D.env.RUST_LOG!==``?D.env.RUST_LOG:`error`,RARI_VITE_PORT:l.toString(),...e.jsPoolSize!=null&&(D.env.RARI_JS_POOL_SIZE==null||D.env.RARI_JS_POOL_SIZE===``)?{RARI_JS_POOL_SIZE:String(e.jsPoolSize)}:{},...d!=null&&d!==``&&(f==null||f===``)?{RARI_ORIGIN:d}:{},...e.htmlLimitedBots!=null&&(D.env.RARI_HTML_LIMITED_BOTS==null||D.env.RARI_HTML_LIMITED_BOTS===``)?{RARI_HTML_LIMITED_BOTS:e.htmlLimitedBots}:{}}}),u.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(t)}),u.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(t)}),u.on(`error`,e=>{A=!1,console.error(`Failed to start rari server:`,e.message),e.message.includes(`ENOENT`)&&console.error(` Binary not found. Please ensure rari is properly installed.`)}),u.on(`exit`,(e,t)=>{u=null,A=!1,t?console.error(`rari server stopped by signal ${t}`):e===0?console.error(`rari server stopped successfully`):e&&console.error(`rari server exited with code ${e}`)}),await ye(1e4)?(await a(),await o()):console.error(`Server failed to become ready for component registration`)},p=async e=>{try{if(!C(e))return;l??await a();let t=l;if(t==null)return;let n=c.getSource(e);t.addServerComponent(e,n);let r=Jt(t.getImportGraph(),[e]);r.add(e);let i=await t.getTransformedComponentsForDevelopment(e=>r.has(e));if(i.length===0)return;let o=`http://localhost:${M()}`;await Promise.all(i.map(async e=>{try{let t=await fetch(`${o}/_rari/register`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:e.id,component_code:e.code})});if(!t.ok){let e=await t.text();throw Error(`HTTP ${t.status}: ${e}`)}}catch(t){console.error(`[rari] Failed to register component`,`${e.id}:`,t instanceof Error?t.message:String(t))}}))}catch(t){console.error(`[rari] Targeted HMR failed for`,`${e}:`,t instanceof Error?t.message:String(t))}};s().catch(e=>{console.error(`[rari] Failed to start Rust server:`,e)}),n.middlewares.use((e,t,n)=>{(async()=>{let r=e.headers.accept;if(r!=null&&r!==``&&r.includes(`text/x-component`)&&e.url!=null&&e.url!==``&&!e.url.startsWith(`/api`)&&!e.url.startsWith(`/rsc`)&&!e.url.includes(`.`)){if(!A&&!await ye(1e4)){console.error(`[rari] Rust server not ready, cannot proxy RSC request`),t.headersSent||(t.statusCode=503,t.end(`Server not ready`));return}let n=M(),r=`http://localhost:${n}${e.url}`;try{let i={};for(let[t,n]of Object.entries(e.headers))typeof n==`string`?i[t]=n:Array.isArray(n)&&(i[t]=n.join(`,`));i.host=`localhost:${n}`,i[`accept-encoding`]=`identity`;let a=await fetch(r,{method:e.method,headers:i});if(t.statusCode=a.status,a.headers.forEach((e,n)=>{n.toLowerCase()!==`content-encoding`&&t.setHeader(n,e)}),a.body){let e=a.body.getReader();try{let n=!1;for(;!n;){let{done:r,value:i}=await e.read();n=r,!n&&i!=null&&t.write(pe.from(i))}t.end()}catch(e){console.error(`[rari] Stream error:`,e),t.headersSent||(t.statusCode=500),t.end()}}else t.end();return}catch(e){console.error(`[rari] Failed to proxy RSC request:`,e),t.headersSent||(t.statusCode=500,t.end(`Internal Server Error`));return}}n()})()}),n.watcher.on(`change`,e=>{(async()=>{_.test(e)&&(b(e),ae(e),c.invalidate(e)),_.test(e)&&e.includes(i)&&C(e)&&(n.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:e}}),await p(e))})()}),n.middlewares.use(`/api/vite/hmr-transform`,(e,n)=>{if(e.method!==`POST`){n.statusCode=405,n.end(`Method Not Allowed`);return}let r=``;e.on(`data`,e=>{r+=e.toString()}),e.on(`end`,()=>{(async()=>{try{let e=t(r),i=e&&typeof e.filePath==`string`?e.filePath:void 0;if(i==null||i===``){n.statusCode=400,n.end(JSON.stringify({error:`filePath is required`}));return}await p(i),n.statusCode=200,n.setHeader(`Content-Type`,`application/json`),n.end(JSON.stringify({success:!0,filePath:i,message:`Component transformation completed`}))}catch(e){n.statusCode=500,n.setHeader(`Content-Type`,`application/json`),n.end(JSON.stringify({success:!1,error:e instanceof Error?e.message:String(e)}))}})()})}),n.httpServer?.on(`close`,()=>{if(d&&=(d.dispose(),null),u){let e=u;u=null,A=!1;let t=!1,n=setTimeout(()=>{t||e.kill(`SIGKILL`)},5e3);n.unref(),e.once(`exit`,()=>{t=!0,clearTimeout(n)}),e.kill(`SIGTERM`);return}A=!1})},resolveId(e,t){if(e===`virtual:rsc-integration`||e===`virtual:rsc-integration.ts`)return`virtual:rsc-integration.ts`;if(e===`virtual:rari-entry-client`||e===`virtual:rari-entry-client.ts`)return`virtual:rari-entry-client.ts`;if(e===`virtual:react-flight-client`||e===`virtual:react-flight-client.ts`)return`virtual:react-flight-client.ts`;if(e===`virtual:app-router-provider`||e===`virtual:app-router-provider.tsx`)return`virtual:app-router-provider.tsx`;if(e===`virtual:client-router`||e===`virtual:client-router.tsx`)return`virtual:client-router.tsx`;if(e===`virtual:error-boundary-wrapper`||e===`virtual:error-boundary-wrapper.tsx`)return`virtual:error-boundary-wrapper.tsx`;if($t(e)||e===`virtual:rari-mdx-components`||e===`virtual:rari-mdx-components.ts`)return`virtual:rari-mdx-components.ts`;if(e===`react-server-dom-webpack/client`||e===`react-server-dom-webpack/client.browser`)return`virtual:react-flight-client.ts`;if(e===`./LoadingErrorBoundary`||e===`./LoadingErrorBoundary.tsx`)return`virtual:loading-error-boundary.tsx`;if(e===`react-server-dom-rari/server`)return e;if(t!=null&&t!==``&&t.startsWith(`virtual:`)&&e.startsWith(`./`)){let t=$(E.basename(e));if(t!=null&&t!==``)return t}if(t!=null&&t!==``&&t.startsWith(`virtual:`)&&e.startsWith(`../`)){let n=import.meta.url,r=O(n),i=E.dirname(r),a=null,o=[E.join(i,`runtime`),E.join(i,`../runtime`)];for(let e of o)if(w.existsSync(e)){a=e;break}if(a!=null&&a!==``){let t=E.join(a,e);if(w.existsSync(t))return t;let n=E.join(a,`../dist`,E.basename(e));if(w.existsSync(n))return n}else console.warn(`[rari] Runtime directory not found, attempting fallback resolution for virtual import.\n Importer: ${t}\n ID: ${e}\n Current Dir: ${i}\n Hint: Runtime lookup failed, trying currentDir as fallback`);let s=E.join(i,e);if(w.existsSync(s))return s;let c=E.join(i,`../dist`,E.basename(e));if(w.existsSync(c))return c}if(D.env.NODE_ENV===`production`)try{let t=E.resolve(e);if(w.existsSync(t)&&C(t))return{id:e,external:!0}}catch(t){o(t)!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving server component:`,e,t)}return null},async load(t){if(_.test(t)&&this.environment.name===`client`)try{let e=c.get(t);if(e.topLevelUseServer)return T(c.getSource(t),t,e)}catch{}if(t===`virtual:rari-mdx-components.ts`)return h();if(t===`virtual:rari-entry-client.ts`){let t=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd(),n=Ut(It(E.join(t,`src`),Object.values(f)),c),r=new Set([...oe(),...n]),i=[{path:`rari/image`,exports:[`Image`]},{path:`virtual:error-boundary-wrapper.tsx`,exports:[`ErrorBoundaryWrapper`]}],a=[...r].filter(e=>{try{return c.get(e).topLevelUseClient}catch{return!1}}).map(e=>{let t=E.relative(D.cwd(),e).replace(x,`/`),n=t.replace(_,``),r=t.startsWith(`..`)?e.replace(x,`/`):t,i=!1,a=``;try{if(!c.get(e).hasDefaultExport){let t=c.getSource(e).match(ee);t&&(i=!0,a=t[1])}}catch(t){o(t)!==`ENOENT`&&console.warn(`[rari] Unexpected error reading component for export detection:`,e,t)}let s=i?a:`default`,l=i?a:E.basename(e,E.extname(e)),u=r.replace(x,`/`),d=u.startsWith(`/`)||g.test(u)?u:`/${u}`;return` "${r}": {
149
149
  id: "${n}",
150
150
  path: "${r}",
151
151
  exportName: "${s}",
@@ -170,7 +170,7 @@ globalThis['~clientComponents']["${e.path}"] = globalThis['~clientComponents']["
170
170
  globalThis['~clientComponents']["${e.path}"].component = ExternalModule${t};
171
171
  globalThis['~clientComponentPaths'] = globalThis['~clientComponentPaths'] || {};
172
172
  globalThis['~clientComponentPaths']["${e.path}"] = "${n}";`)).join(`
173
- `);return wi(s,[`
173
+ `);return Ti(s,[`
174
174
  const lazyComponentRegistry = {
175
175
  ${a}
176
176
  };
@@ -183,9 +183,9 @@ for (const [path, config] of Object.entries(lazyComponentRegistry)) {
183
183
  globalThis['~clientComponentPaths'][path] = config.id;
184
184
  }
185
185
  `,l].filter(Boolean).join(`
186
- `))}if(t===`react-server-dom-rari/server`)return Ti();if(t===`virtual:app-router-provider.tsx`){let e=xi(`AppRouterProvider.mjs`);if(e!=null&&e!==``)return T.readFileSync(e,`utf-8`);throw Error(qr)}if(t===`virtual:loading-error-boundary.tsx`){let e=xi(`LoadingErrorBoundary.mjs`);if(e!=null&&e!==``)return T.readFileSync(e,`utf-8`);throw Error(qr)}if(t===`virtual:error-boundary-wrapper.tsx`){let e=xi(`ErrorBoundaryWrapper.mjs`);if(e!=null&&e!==``){let t=T.readFileSync(e,`utf-8`);if(!t.includes(`import React`)&&!t.includes(`from "react"`)&&!t.includes(`from 'react'`)){let e=hi.exec(t);if(e){let n=e[0];return`
186
+ `))}if(t===`react-server-dom-rari/server`)return Ei();if(t===`virtual:app-router-provider.tsx`){let e=$(`AppRouterProvider.mjs`);if(e!=null&&e!==``)return w.readFileSync(e,`utf-8`);throw Error(Yr)}if(t===`virtual:client-router.tsx`){let e=$(`ClientRouter.mjs`);if(e!=null&&e!==``)return w.readFileSync(e,`utf-8`);throw Error(Yr)}if(t===`virtual:loading-error-boundary.tsx`){let e=$(`LoadingErrorBoundary.mjs`);if(e!=null&&e!==``)return w.readFileSync(e,`utf-8`);throw Error(Yr)}if(t===`virtual:error-boundary-wrapper.tsx`){let e=$(`ErrorBoundaryWrapper.mjs`);if(e!=null&&e!==``){let t=w.readFileSync(e,`utf-8`);if(!t.includes(`import React`)&&!t.includes(`from "react"`)&&!t.includes(`from 'react'`)){let e=_i.exec(t);if(e){let n=e[0];return`
187
187
  ${n}import * as React from 'react';\n${t.slice(n.length)}`}return`
188
- import * as React from 'react';\n${t}`}return t}throw Error(qr)}if(t===`virtual:rsc-integration.ts`)return(await Ci()).replace(fi,(e,t,n)=>`from${t}${n}virtual:react-flight-client.ts${n}`);if(t===`virtual:react-flight-client.ts`){let e,t;try{let n=D.dirname(k(import.meta.resolve(`react-server-dom-webpack/package.json`)));e=D.join(n,`cjs/react-server-dom-webpack-client.browser.production.js`),t=D.join(n,`cjs/react-server-dom-webpack-client.edge.production.js`)}catch{let n=D.dirname(k(import.meta.url)),r=D.resolve(n,`../../node_modules`);e=D.join(r,`react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.production.js`),t=D.join(r,`react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.production.js`)}return{code:`
188
+ import * as React from 'react';\n${t}`}return t}throw Error(Yr)}if(t===`virtual:rsc-integration.ts`)return(await wi()).replace(mi,(e,t,n)=>`from${t}${n}virtual:react-flight-client.ts${n}`);if(t===`virtual:react-flight-client.ts`){let e,t;try{let n=E.dirname(O(import.meta.resolve(`react-server-dom-webpack/package.json`)));e=E.join(n,`cjs/react-server-dom-webpack-client.browser.production.js`),t=E.join(n,`cjs/react-server-dom-webpack-client.edge.production.js`)}catch{let n=E.dirname(O(import.meta.url)),r=E.resolve(n,`../../node_modules`);e=E.join(r,`react-server-dom-webpack/cjs/react-server-dom-webpack-client.browser.production.js`),t=E.join(r,`react-server-dom-webpack/cjs/react-server-dom-webpack-client.edge.production.js`)}return{code:`
189
189
  import * as React from 'react';
190
190
  import * as ReactDOM from 'react-dom';
191
191
  import { callServer as rariCallServer } from 'rari/runtime/call-server';
@@ -193,7 +193,7 @@ import { callServer as rariCallServer } from 'rari/runtime/call-server';
193
193
  const module = { exports: {} };
194
194
  const exports = module.exports;
195
195
  (function(module, exports, require) {
196
- ${Qe(T.readFileSync(e,`utf-8`),T.readFileSync(t,`utf-8`))}
196
+ ${Qe(w.readFileSync(e,`utf-8`),w.readFileSync(t,`utf-8`))}
197
197
  })(module, module.exports, function require(id) {
198
198
  if (id === 'react') return React;
199
199
  if (id === 'react-dom') return ReactDOM;
@@ -209,4 +209,4 @@ export function createFromReadableStream(stream, options) {
209
209
  export const createServerReference = module.exports.createServerReference;
210
210
  export const encodeReply = module.exports.encodeReply;
211
211
  export const createTemporaryReferenceSet = module.exports.createTemporaryReferenceSet;
212
- `}}if(t.endsWith(`.mjs`)&&T.existsSync(t))try{let n=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd(),r=T.realpathSync(t),i=D.relative(n,r),a=!i.startsWith(`..`)&&!D.isAbsolute(i),o=r.includes(`${D.sep}node_modules${D.sep}`),s=r.includes(`${D.sep}packages${D.sep}rari${D.sep}`)||r.includes(`${D.sep}node_modules${D.sep}rari${D.sep}`);return a||o||s?T.readFileSync(t,`utf-8`):(console.warn(`[rari] Refusing to load .mjs file outside project root and node_modules: ${t}`),null)}catch(e){return console.warn(`[rari] Error validating .mjs file path: ${t}`,e),null}},async handleHotUpdate({file:e,server:t}){if(se(),e.endsWith(`.mdx`)&&m(),!_.test(e))return;if(b(e),ae(e),c.invalidate(e),m(),e.includes(`/dist/`)||e.includes(`\\dist\\`))return[];let n=d?.detectComponentType(e)??`unknown`,r=e.includes(`/app/`)||e.includes(`\\app\\`),i=(e,t)=>e.endsWith(`${t}.tsx`)||e.endsWith(`${t}.jsx`)||e.endsWith(`${t}.ts`)||e.endsWith(`${t}.js`),a=[`page`,`layout`,`template`,`loading`,`error`,`not-found`].some(t=>i(e,t));if(!(r&&a)&&n!==`client`&&n===`server`)return d&&await d.handleServerComponentUpdate(e,t),[]},transformIndexHtml:{order:`pre`,handler(e){let t=[];for(let n of e.matchAll(di)){let e=n[1];e.startsWith(`/src/`)&&t.push(e)}let n=[];n.push({tag:`script`,attrs:{type:`module`},children:`import 'virtual:rari-entry-client';`,injectTo:`head-prepend`}),t.length>0&&n.push(...t.map(e=>({tag:`script`,attrs:{type:`module`,src:e},injectTo:`head-prepend`})));let r=e;r=r.replace(/^\s*import\s+["']\/src\/[^"']+["'];?\s*$/gm,``),r=r.replace(/^\s*import\s+["']virtual:rari-entry-client["'];?\s*$/gm,``);let i;do i=r,r=r.replace(/<script\s+type=["']module["'][^>]*>\s*<\/script>/gi,``);while(r!==i);return{html:r,tags:n}}},async writeBundle(){await Ei(e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:O.cwd(),e)}},xe=mr({...e.serverBuild,csp:e.csp,cacheControl:e.cacheControl,cache:e.cache,action:e.action,jsPoolSize:e.jsPoolSize,origin:e.origin,htmlLimitedBots:e.htmlLimitedBots,experimental:e.experimental,moduleAnalysisCache:c,mdx:e.mdx}),Se={name:`rari:patch-react-server-dom-webpack`,transform(e){if(!e.includes(`__webpack_require__`)&&!e.includes(`__webpack_chunk_load__`))return null;let t=e;return t.includes(`__webpack_chunk_load__`)&&(t=t.replaceAll(`__webpack_chunk_load__`,`__rari_chunk_load__`)),t.includes(`__webpack_require__.u`)&&(t=t.replaceAll(`__webpack_require__.u`,`({}).u`)),t.includes(`__webpack_require__`)&&(t=t.replaceAll(`__webpack_require__`,`__rari_rsc_require__`)),t===e?null:{code:t,map:null}}},N=[];return e.compiler!=null&&e.compiler!==!1&&N.push(jr(e.compiler)),N.push(be,Se,xe),e.proxy!==!1&&N.push(ve(e.proxy??{})),e.router!==!1&&N.push(Xe(e.router??{})),ge(N)}function ki(e){return{...e,plugins:[Oi(),...e.plugins??[]]}}export{e as ApiResponse,Gr as clearPropsCache,Kr as clearPropsCacheForComponent,ki as defineRariConfig,Di as defineRariOptions,Br as extractMetadata,zr as extractServerProps,Wr as extractServerPropsWithCache,Vr as extractStaticParams,Fe as generateAppRouteManifest,Hr as hasServerSideDataFetching,Oi as rari,ve as rariProxy,Xe as rariRouter};
212
+ `}}if(t.endsWith(`.mjs`)&&w.existsSync(t))try{let n=e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd(),r=w.realpathSync(t),i=E.relative(n,r),a=!i.startsWith(`..`)&&!E.isAbsolute(i),o=r.includes(`${E.sep}node_modules${E.sep}`),s=r.includes(`${E.sep}packages${E.sep}rari${E.sep}`)||r.includes(`${E.sep}node_modules${E.sep}rari${E.sep}`);return a||o||s?w.readFileSync(t,`utf-8`):(console.warn(`[rari] Refusing to load .mjs file outside project root and node_modules: ${t}`),null)}catch(e){return console.warn(`[rari] Error validating .mjs file path: ${t}`,e),null}},async handleHotUpdate({file:e,server:t}){if(se(),e.endsWith(`.mdx`)&&m(),!_.test(e))return;if(b(e),ae(e),c.invalidate(e),m(),e.includes(`/dist/`)||e.includes(`\\dist\\`))return[];let n=d?.detectComponentType(e)??`unknown`,r=e.includes(`/app/`)||e.includes(`\\app\\`),i=(e,t)=>e.endsWith(`${t}.tsx`)||e.endsWith(`${t}.jsx`)||e.endsWith(`${t}.ts`)||e.endsWith(`${t}.js`),a=[`page`,`layout`,`template`,`loading`,`error`,`not-found`].some(t=>i(e,t));if(!(r&&a)&&n!==`client`&&n===`server`)return d&&await d.handleServerComponentUpdate(e,t),[]},transformIndexHtml:{order:`pre`,handler(e){let t=[];for(let n of e.matchAll(pi)){let e=n[1];e.startsWith(`/src/`)&&t.push(e)}let n=[];n.push({tag:`script`,attrs:{type:`module`},children:`import 'virtual:rari-entry-client';`,injectTo:`head-prepend`}),t.length>0&&n.push(...t.map(e=>({tag:`script`,attrs:{type:`module`,src:e},injectTo:`head-prepend`})));let r=e;r=r.replace(/^\s*import\s+["']\/src\/[^"']+["'];?\s*$/gm,``),r=r.replace(/^\s*import\s+["']virtual:rari-entry-client["'];?\s*$/gm,``);let i;do i=r,r=r.replace(/<script\s+type=["']module["'][^>]*>\s*<\/script>/gi,``);while(r!==i);return{html:r,tags:n}}},async writeBundle(){await Di(e.projectRoot!=null&&e.projectRoot!==``?e.projectRoot:D.cwd(),e)}},xe=hr({...e.serverBuild,csp:e.csp,cacheControl:e.cacheControl,cache:e.cache,action:e.action,jsPoolSize:e.jsPoolSize,origin:e.origin,htmlLimitedBots:e.htmlLimitedBots,experimental:e.experimental,moduleAnalysisCache:c,mdx:e.mdx}),Se={name:`rari:patch-react-server-dom-webpack`,transform(e){if(!e.includes(`__webpack_require__`)&&!e.includes(`__webpack_chunk_load__`))return null;let t=e;return t.includes(`__webpack_chunk_load__`)&&(t=t.replaceAll(`__webpack_chunk_load__`,`__rari_chunk_load__`)),t.includes(`__webpack_require__.u`)&&(t=t.replaceAll(`__webpack_require__.u`,`({}).u`)),t.includes(`__webpack_require__`)&&(t=t.replaceAll(`__webpack_require__`,`__rari_rsc_require__`)),t===e?null:{code:t,map:null}}},N=[];return e.compiler!=null&&e.compiler!==!1&&N.push(Nr(e.compiler)),N.push(be,Se,xe),e.proxy!==!1&&N.push(ve(e.proxy??{})),e.router!==!1&&N.push(Xe(e.router??{})),ge(N)}function Ai(e){return{...e,plugins:[ki(),...e.plugins??[]]}}export{e as ApiResponse,qr as clearPropsCache,Jr as clearPropsCacheForComponent,Ai as defineRariConfig,Oi as defineRariOptions,Hr as extractMetadata,Vr as extractServerProps,Kr as extractServerPropsWithCache,Ur as extractStaticParams,Fe as generateAppRouteManifest,Wr as hasServerSideDataFetching,ki as rari,ve as rariProxy,Xe as rariRouter};
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "rari",
3
3
  "type": "module",
4
- "version": "0.15.15",
4
+ "version": "0.15.17",
5
5
  "description": "Runtime Accelerated Rendering Infrastructure (rari)",
6
6
  "author": "Ryan Skinner",
7
7
  "license": "MIT",
@@ -111,6 +111,10 @@
111
111
  "types": "./dist/runtime/ErrorBoundaryWrapper.d.mts",
112
112
  "default": "./dist/runtime/ErrorBoundaryWrapper.mjs"
113
113
  },
114
+ "./runtime/ClientRouter": {
115
+ "types": "./dist/runtime/ClientRouter.d.mts",
116
+ "default": "./dist/runtime/ClientRouter.mjs"
117
+ },
114
118
  "./vite": {
115
119
  "types": "./dist/vite.d.mts",
116
120
  "default": "./dist/vite.mjs"
@@ -146,28 +150,28 @@
146
150
  "dependencies": {
147
151
  "lightningcss": "^1.33.0",
148
152
  "react-server-dom-webpack": "^19.2.8",
149
- "rolldown": "^1.2.5"
153
+ "rolldown": "^1.2.6"
150
154
  },
151
155
  "optionalDependencies": {
152
- "@rari/use-cache": "0.15.14",
153
- "rari-darwin-arm64": "0.15.14",
154
- "rari-darwin-x64": "0.15.14",
155
- "rari-linux-arm64": "0.15.14",
156
- "rari-linux-x64": "0.15.14",
157
- "rari-win32-arm64": "0.15.14",
158
- "rari-win32-x64": "0.15.14"
156
+ "@rari/use-cache": "0.15.17",
157
+ "rari-darwin-arm64": "0.15.17",
158
+ "rari-darwin-x64": "0.15.17",
159
+ "rari-linux-arm64": "0.15.17",
160
+ "rari-linux-x64": "0.15.17",
161
+ "rari-win32-arm64": "0.15.17",
162
+ "rari-win32-x64": "0.15.17"
159
163
  },
160
164
  "devDependencies": {
161
165
  "@mdx-js/mdx": "^3.1.1",
162
166
  "@rari/deploy": "0.0.0",
163
167
  "@rari/logger": "0.0.0",
164
- "@types/node": "^26.2.0",
168
+ "@types/node": "^26.4.0",
165
169
  "@types/react": "^19.2.18",
166
- "@types/react-dom": "^19.2.4",
170
+ "@types/react-dom": "^19.2.5",
167
171
  "oxc-transform-react": "^0.147.0",
168
172
  "typescript": "npm:@typescript/typescript6@^6.0.2",
169
173
  "typescript-7": "npm:typescript@^7.0.2",
170
- "vite-plus": "^0.2.9"
174
+ "vite-plus": "^0.3.0"
171
175
  },
172
176
  "scripts": {
173
177
  "build": "pnpm typecheck && vp pack",
@@ -1 +0,0 @@
1
- import{n as e,p as t}from"./type-guards-CTkEL8zw.mjs";import{createContext as n,use as r,useEffect as i,useMemo as a,useRef as o,useState as s}from"react";import{jsx as c}from"react/jsx-runtime";let l=null;function u(){return l}function d(e){if(typeof window>`u`){console.warn(`[rari] Router cannot register navigate in non-browser environment`);return}l&&typeof process<`u`&&process.env.NODE_ENV!==`production`&&console.warn(`[rari] Router: registerNavigate called multiple times, overwriting existing navigate function`,{previous:l,new:e}),l=e,window.dispatchEvent(new CustomEvent(`rari:register-navigate`,{detail:{navigate:e}}))}function f(){if(typeof window>`u`){console.warn(`[rari] Router cannot deregister navigate in non-browser environment`);return}l=null,window.dispatchEvent(new CustomEvent(`rari:deregister-navigate`))}async function p(e,t){if(typeof window>`u`){console.warn(`[rari] Router cannot navigate in non-browser environment`);return}if(!l){console.warn(`[rari] Router not initialized, falling back to window.location`),t?.replace?window.location.replace(e):window.location.href=e;return}return l(e,t)}function m(e){return t(e)&&typeof e.to==`string`}function h(e){return t(e)&&typeof e.navigate==`function`}const g=n(null);function _({children:t,initialPathname:n}){let[r,l]=s(n),[d,f]=s(()=>typeof window<`u`?new URLSearchParams(window.location.search):new URLSearchParams),p=o(null);i(()=>{let t=t=>{let n=e(t,m);n&&(l(n.to),f(new URLSearchParams(window.location.search)))};return window.addEventListener(`rari:navigate`,t),()=>{window.removeEventListener(`rari:navigate`,t)}},[]),i(()=>{let t=u();t&&(p.current=t);let n=t=>{let n=e(t,h);n&&(p.current=n.navigate)},r=()=>{p.current=null};return window.addEventListener(`rari:register-navigate`,n),window.addEventListener(`rari:deregister-navigate`,r),()=>{window.removeEventListener(`rari:register-navigate`,n),window.removeEventListener(`rari:deregister-navigate`,r)}},[]);let _=a(()=>({pathname:r,params:{},searchParams:d,push:async(e,t)=>{p.current?await p.current(e,t):(console.warn(`[rari] Router not ready, falling back to window.location`),window.location.href=e)},replace:async(e,t)=>{p.current?await p.current(e,{...t,replace:!0}):(console.warn(`[rari] Router not ready, falling back to window.location`),window.location.replace(e))},back:()=>{window.history.back()},forward:()=>{window.history.forward()},refresh:()=>{window.dispatchEvent(new CustomEvent(`rari:app-router-rerender`))},prefetch:async e=>{try{let t=new URL(e,window.location.origin);await fetch(t.pathname+t.search,{headers:{Accept:`text/x-component`},priority:`low`})}catch(e){console.warn(`[rari] Prefetch failed:`,e)}}}),[r,d]);return c(g,{value:_,children:t})}function v(){let e=r(g);if(!e)throw Error(`useRouter must be used within a RouterProvider`);return e}function y(){return v().pathname}function b(){return v().params}function x(){return v().searchParams}export{x as a,d as c,v as i,b as n,f as o,y as r,p as s,_ as t};