rari 0.10.21 → 0.10.23
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/client.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
import{i as e,t}from"./navigate-hfIqe3MK.mjs";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _}from"./runtime-client-yoJmu7vX.mjs";import{Component as v,useEffect as y,useLayoutEffect as ee,useRef as b,useState as x}from"react";import{Fragment as S,jsx as C,jsxs as w}from"react/jsx-runtime";function T(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;return 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))return h(e);let n=e-i,o=e-a,s=t-n,c=u===void 0?1/0:u-o,l=Math.min(s,c);r=setTimeout(p,l)}function m(e){return a=e,r=setTimeout(p,t),c?d(e):void 0}function h(e){if(r=null,l&&o)return d(e);o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){return r===null?void 0: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)return m(i);if(u!==void 0)return r=setTimeout(p,t),d(i)}r===null&&(r=setTimeout(p,t))}return y.cancel=g,y.flush=_,y.pending=v,y}const E=/fetch|networkerror|load failed/i;function D(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function O(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function k(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 A(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function j(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 M(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 N(e,t){if(e instanceof Error&&e.name===`AbortError`)return D(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return O(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?k(e,n,t):M(e,t)}return e instanceof TypeError&&E.test(e.message)?A(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?j(e,t):M(e,t)}var P=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=N(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()}};const F=/(^\/+)|(\/+$)/g;function I(e){let t=e.replace(F,``);return t?t.split(`/`):[]}function L(e){try{return decodeURIComponent(e)}catch{return null}}function R(e,t){let n=L(e),r=L(t);return n===null||r===null?!1:n===r}function z(e,t,n){if(!t)return!1;let r=L(e);return r===null?!1:(n[t]=r,!0)}function B(e,t,n,r){if(!n)return{success:!1,newIndex:t};let i=[];for(let n of e.slice(t)){let e=L(n);if(e===null)return{success:!1,newIndex:t};i.push(e)}return r[n]=i,{success:!0,newIndex:e.length}}function V(e,t,n,r){e>=t&&n&&(r[n]=[])}function H(e,t,n,r){if(n>=t.length)return e.type===`optional-catch-all`&&e.param?(V(n,t.length,e.param,r),{success:!0,newIndex:n}):{success:!1,newIndex:n};switch(e.type){case`static`:return R(t[n],e.value)?{success:!0,newIndex:n+1}:{success:!1,newIndex:n};case`dynamic`:return z(t[n],e.param,r)?{success:!0,newIndex:n+1}:{success:!1,newIndex:n};case`catch-all`:case`optional-catch-all`:return B(t,n,e.param,r);default:return{success:!1,newIndex:n}}}function U(e,t,n){let r=I(n),i={},a=0;for(let e of t){let t=H(e,r,a,i);if(!t.success)return null;a=t.newIndex}return a===r.length?i:null}function W(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 G(e,t){try{return new URL(e,t||window.location.origin).origin!==(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}}function K({error:e,onRetry:t,onReload:n,onDismiss:r,retryCount:i=0,maxRetries:a=3}){let o=e.retryable&&i<a;return C(`div`,{style:{position:`fixed`,top:0,left:0,right:0,bottom:0,background:`rgba(0, 0, 0, 0.5)`,display:`flex`,alignItems:`center`,justifyContent:`center`,zIndex:1e4,padding:`20px`},onClick:e=>{e.target===e.currentTarget&&r&&r()},children:w(`div`,{style:{background:`white`,borderRadius:`8px`,padding:`24px`,maxWidth:`500px`,width:`100%`,boxShadow:`0 4px 12px rgba(0, 0, 0, 0.15)`},onClick:e=>e.stopPropagation(),children:[w(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,marginBottom:`16px`},children:[C(`span`,{style:{fontSize:`32px`},children:(()=>{switch(e.type){case`timeout`:return`⏱️`;case`network-error`:return`📡`;case`not-found`:return`🔍`;case`server-error`:return`⚠️`;case`parse-error`:return`📄`;case`abort`:return`🚫`;default:return`❌`}})()}),C(`h2`,{style:{margin:0,fontSize:`20px`,fontWeight:`600`,color:`#1f2937`},children:`Navigation Error`})]}),C(`p`,{style:{margin:`0 0 16px 0`,fontSize:`15px`,lineHeight:`1.5`,color:`#4b5563`},children:(()=>{switch(e.type){case`timeout`:return`The page took too long to load. Please try again.`;case`network-error`:return`Unable to connect to the server. Please check your internet connection.`;case`not-found`:return`The page you're looking for doesn't exist.`;case`server-error`:return`The server encountered an error. Please try again in a moment.`;case`parse-error`:return`Unable to load the page content. Please try reloading.`;case`abort`:return`Navigation was cancelled.`;default:return e.message||`An unexpected error occurred.`}})()}),e.url&&w(`details`,{style:{marginBottom:`16px`,fontSize:`13px`,color:`#6b7280`},children:[C(`summary`,{style:{cursor:`pointer`,userSelect:`none`,marginBottom:`8px`},children:`Technical details`}),w(`div`,{style:{padding:`12px`,background:`#f9fafb`,borderRadius:`4px`,fontFamily:`monospace`,fontSize:`12px`,wordBreak:`break-all`},children:[w(`div`,{style:{marginBottom:`4px`},children:[C(`strong`,{children:`URL:`}),` `,e.url]}),e.statusCode&&w(`div`,{style:{marginBottom:`4px`},children:[C(`strong`,{children:`Status:`}),` `,e.statusCode]}),w(`div`,{style:{marginBottom:`4px`},children:[C(`strong`,{children:`Type:`}),` `,e.type]}),e.originalError&&w(`div`,{children:[C(`strong`,{children:`Error:`}),` `,e.originalError.message]})]})]}),o&&i>0&&w(`div`,{style:{marginBottom:`16px`,padding:`8px 12px`,background:`#fef3c7`,border:`1px solid #fbbf24`,borderRadius:`4px`,fontSize:`13px`,color:`#92400e`},children:[`Retry attempt`,` `,i,` `,`of`,` `,a]}),w(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[o&&t&&C(`button`,{onClick:t,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#3b82f6`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#2563eb`},onMouseLeave:e=>{e.currentTarget.style.background=`#3b82f6`},children:`Try Again`}),n&&C(`button`,{onClick:n,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#6b7280`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.background=`#6b7280`},children:`Reload Page`}),r&&C(`button`,{onClick:r,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`transparent`,color:`#6b7280`,border:`1px solid #d1d5db`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`all 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#f9fafb`,e.currentTarget.style.borderColor=`#9ca3af`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.borderColor=`#d1d5db`},children:`Dismiss`})]}),C(`p`,{style:{marginTop:`16px`,marginBottom:0,fontSize:`12px`,color:`#9ca3af`,textAlign:`center`},children:`Your current page is still available below this message`})]})})}const q=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)}}async fetchRouteInfo(e){let t={path:e},n=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=null;try{e=await n.json()}catch{}throw e?.error?Error(e.error):Error(`Failed to fetch route info: ${n.status} ${n.statusText}`)}let r=n.clone();try{return await n.json()}catch(t){try{let e=await r.text();return JSON.parse(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=window[`~rari`]||{};window[`~rari`]||(window[`~rari`]=e),e.routeInfoCache=q}var J=class{stateHistory;routeAccessOrder;maxHistorySize;scrollableSelector;constructor(e={}){this.stateHistory=new Map,this.routeAccessOrder=[],this.maxHistorySize=e.maxHistorySize||50,this.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&&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&&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)||document.querySelector(`form[name="${n}"]`)||document.querySelectorAll(`form`)[Number.parseInt(n.replace(`form-`,``),10)];r instanceof HTMLFormElement?e.forEach((e,n)=>{try{let t=r.elements.namedItem(n);t instanceof RadioNodeList?t.forEach(t=>{t instanceof HTMLInputElement&&(t.type===`radio`||t.type===`checkbox`?t.checked=t.value===e: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: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 Y(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 X(e){let t=document.querySelector(e);t&&t.remove()}function Z(e){e.title&&(document.title=e.title),e.description?Y(`meta[name="description"]`,{name:`description`,content:e.description}):X(`meta[name="description"]`),e.keywords&&e.keywords.length>0?Y(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):X(`meta[name="keywords"]`),e.viewport&&Y(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function Q(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 $(e){if(e===void 0){X(`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?Y(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):X(`meta[name="robots"]`)}function ne(e){if(e===void 0){X(`meta[property="og:title"]`),X(`meta[property="og:description"]`),X(`meta[property="og:url"]`),X(`meta[property="og:site_name"]`),X(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());return}if(e.title?Y(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):X(`meta[property="og:title"]`),e.description?Y(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):X(`meta[property="og:description"]`),e.url?Y(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):X(`meta[property="og:url"]`),e.siteName?Y(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):X(`meta[property="og:site_name"]`),e.type?Y(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):X(`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 re(e){if(e===void 0){X(`meta[name="twitter:card"]`),X(`meta[name="twitter:site"]`),X(`meta[name="twitter:creator"]`),X(`meta[name="twitter:title"]`),X(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());return}if(e.card?Y(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):X(`meta[name="twitter:card"]`),e.site?Y(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):X(`meta[name="twitter:site"]`),e.creator?Y(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):X(`meta[name="twitter:creator"]`),e.title?Y(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):X(`meta[name="twitter:title"]`),e.description?Y(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):X(`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 ie(e){Z(e),Q(e.canonical),$(e.robots),ne(e.openGraph),re(e.twitter)}function ae({children:n,initialRoute:r,staleWindowMs:i=3e4}){let[a,o]=x(()=>({currentRoute:W(r),navigationId:0,error:null})),s=b(null),c=b(!0),l=b(W(r)),u=b(new P({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),d=b(new Map),f=b([]),p=b(new J({maxHistorySize:50})),m=b(null),h=b(i),g=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,_=()=>{s.current&&=(s.current.abort(),null)},v=()=>{for(let[,e]of d.current.entries())e.abortController.abort();d.current.clear()},E=(e,t)=>{d.current.delete(e),c.current&&a.navigationId===t&&o(e=>({...e}))},D=async e=>q.get(e),O=b(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){let e=decodeURIComponent(t);ie(JSON.parse(e))}}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}},j=async(e,t,n,r,i,a,o,s,c)=>{if(!e.body)return;let l=e.body.getReader(),u=new TextDecoder,d=``;try{for(;;){let{done:e,value:r}=await l.read();if(e)break;if(t.signal.aborted){await l.cancel(),E(n,i);return}d+=u.decode(r,{stream:!0});let a=d.split(`
|
|
1
|
+
import{i as e,t}from"./navigate-hfIqe3MK.mjs";import{_ as n,a as r,c as i,d as a,f as o,g as s,h as c,i as l,l as u,m as d,n as f,o as p,p as m,r as h,s as g,t as _}from"./runtime-client-yoJmu7vX.mjs";import{Component as v,useEffect as y,useLayoutEffect as ee,useRef as b,useState as x}from"react";import{Fragment as S,jsx as C,jsxs as w}from"react/jsx-runtime";function T(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;return 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))return h(e);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){return a=e,r=setTimeout(p,t),c?d(e):void 0}function h(e){if(r=null,l&&o)return d(e);o=null,s=null}function g(){r!==null&&clearTimeout(r),a=0,o=null,i=0,s=null,r=null}function _(){return r===null?void 0: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)return m(i);if(u!==void 0)return r=setTimeout(p,t),d(i)}r===null&&(r=setTimeout(p,t))}return y.cancel=g,y.flush=_,y.pending=v,y}const E=/fetch|networkerror|load failed/i;function D(e,t){return{type:`abort`,message:`Navigation was cancelled`,originalError:e,url:t,timestamp:Date.now(),retryable:!1}}function O(e,t){return{type:`timeout`,message:`Navigation request timed out`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function k(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 A(e,t){return{type:`network-error`,message:`Network error - check your connection`,originalError:e,url:t,timestamp:Date.now(),retryable:!0}}function j(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 M(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 N(e,t){if(e instanceof Error&&e.name===`AbortError`)return D(e,t);if(e instanceof Error&&(e.name===`TimeoutError`||e.message.includes(`timeout`)))return O(e,t);if(e instanceof Error&&`status`in e){let n=e.status;return typeof n==`number`?k(e,n,t):M(e,t)}return e instanceof TypeError&&E.test(e.message)?A(e,t):e instanceof SyntaxError||e instanceof Error&&e.message.includes(`parse`)?j(e,t):M(e,t)}var P=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=N(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()}};const F=/(^\/+)|(\/+$)/g;function I(e){let t=e.replace(F,``);return t?t.split(`/`):[]}function L(e){try{return decodeURIComponent(e)}catch{return null}}function R(e,t){let n=L(e),r=L(t);return n===null||r===null?!1:n===r}function z(e,t,n){if(!t)return!1;let r=L(e);return r===null?!1:(n[t]=r,!0)}function B(e,t,n,r){if(!n)return{success:!1,newIndex:t};let i=[];for(let n of e.slice(t)){let e=L(n);if(e===null)return{success:!1,newIndex:t};i.push(e)}return r[n]=i,{success:!0,newIndex:e.length}}function V(e,t,n,r){e>=t&&n&&(r[n]=[])}function H(e,t,n,r){if(n>=t.length)return e.type===`optional-catch-all`&&e.param?(V(n,t.length,e.param,r),{success:!0,newIndex:n}):{success:!1,newIndex:n};switch(e.type){case`static`:return R(t[n],e.value)?{success:!0,newIndex:n+1}:{success:!1,newIndex:n};case`dynamic`:return z(t[n],e.param,r)?{success:!0,newIndex:n+1}:{success:!1,newIndex:n};case`catch-all`:case`optional-catch-all`:return B(t,n,e.param,r);default:return{success:!1,newIndex:n}}}function U(e,t,n){let r=I(n),i={},a=0;for(let e of t){let t=H(e,r,a,i);if(!t.success)return null;a=t.newIndex}return a===r.length?i:null}function W(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 G(e,t){try{return new URL(e,t||window.location.origin).origin!==(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}}function K({error:e,onRetry:t,onReload:n,onDismiss:r,retryCount:i=0,maxRetries:a=3}){let o=e.retryable&&i<a;return C(`div`,{style:{position:`fixed`,top:0,left:0,right:0,bottom:0,background:`rgba(0, 0, 0, 0.5)`,display:`flex`,alignItems:`center`,justifyContent:`center`,zIndex:1e4,padding:`20px`},onClick:e=>{e.target===e.currentTarget&&r&&r()},children:w(`div`,{style:{background:`white`,borderRadius:`8px`,padding:`24px`,maxWidth:`500px`,width:`100%`,boxShadow:`0 4px 12px rgba(0, 0, 0, 0.15)`},onClick:e=>e.stopPropagation(),children:[w(`div`,{style:{display:`flex`,alignItems:`center`,gap:`12px`,marginBottom:`16px`},children:[C(`span`,{style:{fontSize:`32px`},children:(()=>{switch(e.type){case`timeout`:return`⏱️`;case`network-error`:return`📡`;case`not-found`:return`🔍`;case`server-error`:return`⚠️`;case`parse-error`:return`📄`;case`abort`:return`🚫`;default:return`❌`}})()}),C(`h2`,{style:{margin:0,fontSize:`20px`,fontWeight:`600`,color:`#1f2937`},children:`Navigation Error`})]}),C(`p`,{style:{margin:`0 0 16px 0`,fontSize:`15px`,lineHeight:`1.5`,color:`#4b5563`},children:(()=>{switch(e.type){case`timeout`:return`The page took too long to load. Please try again.`;case`network-error`:return`Unable to connect to the server. Please check your internet connection.`;case`not-found`:return`The page you're looking for doesn't exist.`;case`server-error`:return`The server encountered an error. Please try again in a moment.`;case`parse-error`:return`Unable to load the page content. Please try reloading.`;case`abort`:return`Navigation was cancelled.`;default:return e.message||`An unexpected error occurred.`}})()}),e.url&&w(`details`,{style:{marginBottom:`16px`,fontSize:`13px`,color:`#6b7280`},children:[C(`summary`,{style:{cursor:`pointer`,userSelect:`none`,marginBottom:`8px`},children:`Technical details`}),w(`div`,{style:{padding:`12px`,background:`#f9fafb`,borderRadius:`4px`,fontFamily:`monospace`,fontSize:`12px`,wordBreak:`break-all`},children:[w(`div`,{style:{marginBottom:`4px`},children:[C(`strong`,{children:`URL:`}),` `,e.url]}),e.statusCode&&w(`div`,{style:{marginBottom:`4px`},children:[C(`strong`,{children:`Status:`}),` `,e.statusCode]}),w(`div`,{style:{marginBottom:`4px`},children:[C(`strong`,{children:`Type:`}),` `,e.type]}),e.originalError&&w(`div`,{children:[C(`strong`,{children:`Error:`}),` `,e.originalError.message]})]})]}),o&&i>0&&w(`div`,{style:{marginBottom:`16px`,padding:`8px 12px`,background:`#fef3c7`,border:`1px solid #fbbf24`,borderRadius:`4px`,fontSize:`13px`,color:`#92400e`},children:[`Retry attempt`,` `,i,` `,`of`,` `,a]}),w(`div`,{style:{display:`flex`,gap:`8px`,flexWrap:`wrap`},children:[o&&t&&C(`button`,{onClick:t,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#3b82f6`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#2563eb`},onMouseLeave:e=>{e.currentTarget.style.background=`#3b82f6`},children:`Try Again`}),n&&C(`button`,{onClick:n,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`#6b7280`,color:`white`,border:`none`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`background 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#4b5563`},onMouseLeave:e=>{e.currentTarget.style.background=`#6b7280`},children:`Reload Page`}),r&&C(`button`,{onClick:r,type:`button`,style:{flex:1,minWidth:`120px`,padding:`10px 16px`,background:`transparent`,color:`#6b7280`,border:`1px solid #d1d5db`,borderRadius:`6px`,fontSize:`14px`,fontWeight:`500`,cursor:`pointer`,transition:`all 0.2s`},onMouseEnter:e=>{e.currentTarget.style.background=`#f9fafb`,e.currentTarget.style.borderColor=`#9ca3af`},onMouseLeave:e=>{e.currentTarget.style.background=`transparent`,e.currentTarget.style.borderColor=`#d1d5db`},children:`Dismiss`})]}),C(`p`,{style:{marginTop:`16px`,marginBottom:0,fontSize:`12px`,color:`#9ca3af`,textAlign:`center`},children:`Your current page is still available below this message`})]})})}const q=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)}}async fetchRouteInfo(e){let t={path:e},n=await fetch(`/_rari/route-info`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify(t)});if(!n.ok){let e=null;try{e=await n.json()}catch{}throw e?.error?Error(e.error):Error(`Failed to fetch route info: ${n.status} ${n.statusText}`)}let r=n.clone();try{return await n.json()}catch(t){try{let e=await r.text();return JSON.parse(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=window[`~rari`]||{};window[`~rari`]||(window[`~rari`]=e),e.routeInfoCache=q}var J=class{stateHistory;routeAccessOrder;maxHistorySize;scrollableSelector;constructor(e={}){this.stateHistory=new Map,this.routeAccessOrder=[],this.maxHistorySize=e.maxHistorySize||50,this.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&&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&&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)||document.querySelector(`form[name="${n}"]`)||document.querySelectorAll(`form`)[Number.parseInt(n.replace(`form-`,``),10)];r instanceof HTMLFormElement?e.forEach((e,n)=>{try{let t=r.elements.namedItem(n);t instanceof RadioNodeList?t.forEach(t=>{t instanceof HTMLInputElement&&(t.type===`radio`||t.type===`checkbox`?t.checked=t.value===e: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: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 Y(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 X(e){let t=document.querySelector(e);t&&t.remove()}function Z(e){e.title&&(document.title=e.title),e.description?Y(`meta[name="description"]`,{name:`description`,content:e.description}):X(`meta[name="description"]`),e.keywords&&e.keywords.length>0?Y(`meta[name="keywords"]`,{name:`keywords`,content:e.keywords.join(`, `)}):X(`meta[name="keywords"]`),e.viewport&&Y(`meta[name="viewport"]`,{name:`viewport`,content:e.viewport})}function Q(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 $(e){if(e===void 0){X(`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?Y(`meta[name="robots"]`,{name:`robots`,content:t.join(`, `)}):X(`meta[name="robots"]`)}function ne(e){if(e===void 0){X(`meta[property="og:title"]`),X(`meta[property="og:description"]`),X(`meta[property="og:url"]`),X(`meta[property="og:site_name"]`),X(`meta[property="og:type"]`),document.querySelectorAll(`meta[property="og:image"]`).forEach(e=>e.remove());return}if(e.title?Y(`meta[property="og:title"]`,{property:`og:title`,content:e.title}):X(`meta[property="og:title"]`),e.description?Y(`meta[property="og:description"]`,{property:`og:description`,content:e.description}):X(`meta[property="og:description"]`),e.url?Y(`meta[property="og:url"]`,{property:`og:url`,content:e.url}):X(`meta[property="og:url"]`),e.siteName?Y(`meta[property="og:site_name"]`,{property:`og:site_name`,content:e.siteName}):X(`meta[property="og:site_name"]`),e.type?Y(`meta[property="og:type"]`,{property:`og:type`,content:e.type}):X(`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 re(e){if(e===void 0){X(`meta[name="twitter:card"]`),X(`meta[name="twitter:site"]`),X(`meta[name="twitter:creator"]`),X(`meta[name="twitter:title"]`),X(`meta[name="twitter:description"]`),document.querySelectorAll(`meta[name="twitter:image"]`).forEach(e=>e.remove());return}if(e.card?Y(`meta[name="twitter:card"]`,{name:`twitter:card`,content:e.card}):X(`meta[name="twitter:card"]`),e.site?Y(`meta[name="twitter:site"]`,{name:`twitter:site`,content:e.site}):X(`meta[name="twitter:site"]`),e.creator?Y(`meta[name="twitter:creator"]`,{name:`twitter:creator`,content:e.creator}):X(`meta[name="twitter:creator"]`),e.title?Y(`meta[name="twitter:title"]`,{name:`twitter:title`,content:e.title}):X(`meta[name="twitter:title"]`),e.description?Y(`meta[name="twitter:description"]`,{name:`twitter:description`,content:e.description}):X(`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 ie(e){Z(e),Q(e.canonical),$(e.robots),ne(e.openGraph),re(e.twitter)}function ae({children:n,initialRoute:r,staleWindowMs:i=3e4}){let[a,o]=x(()=>({currentRoute:W(r),navigationId:0,error:null})),s=b(null),c=b(!0),l=b(W(r)),u=b(new P({timeout:1e4,maxRetries:3,onError:e=>{console.error(`[rari] Router: Navigation error:`,e)},onRetry:()=>{}})),d=b(new Map),f=b([]),p=b(new J({maxHistorySize:50})),m=b(null),h=b(i),g=()=>`${Date.now()}-${Math.random().toString(36).substring(2,9)}`,_=()=>{s.current&&=(s.current.abort(),null)},v=()=>{for(let[,e]of d.current.entries())e.abortController.abort();d.current.clear()},E=(e,t)=>{d.current.delete(e),c.current&&a.navigationId===t&&o(e=>({...e}))},D=async e=>q.get(e),O=b(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`);t&&ie(JSON.parse(decodeURIComponent(t)))}catch(e){console.warn(`[rari] Router: Failed to parse x-rari-metadata header:`,e)}},j=async(e,t,n,r,i,a,o,s,c)=>{if(!e.body)return;let l=e.body.getReader(),u=new TextDecoder,d=``;try{for(;;){let{done:e,value:r}=await l.read();if(e)break;if(t.signal.aborted){await l.cancel(),E(n,i);return}d+=u.decode(r,{stream:!0});let a=d.split(`
|
|
2
2
|
`);d=a.pop()||``;for(let e of a)e.trim()&&window.dispatchEvent(new CustomEvent(`rari:rsc-row`,{detail:{rscRow:e}}))}d+=u.decode(),d.trim()&&window.dispatchEvent(new CustomEvent(`rari:rsc-row`,{detail:{rscRow:d}})),window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:a,to:r,navigationId:i,options:o,routeInfo:{...s,extractedParams:c},abortSignal:t.signal,isStreaming:!0}}))}catch(e){throw console.error(`[rari] Router: Streaming error:`,e),e}},M=async(e,t,n,r,i,a,o,s)=>{let c=await e.text();window.dispatchEvent(new CustomEvent(`rari:navigate`,{detail:{from:t,to:n,navigationId:r,options:i,routeInfo:{...a,extractedParams:o},abortSignal:s.signal,rscWireFormat:c}}))},N=(e,t,n)=>{n.historyKey?requestAnimationFrame(()=>{p.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()})},F=(e,t,n,r)=>{c.current&&(l.current=e,o(t=>({...t,currentRoute:e,navigationId:r,error:null})),u.current.resetRetry(e),N(e,t,n))},I=(e,t,n,r)=>{if(e instanceof Error&&e.name===`AbortError`){E(t,n);return}let i=u.current.handleError(e,t);c.current&&o(e=>({...e,error:i})),d.current.delete(t),window.dispatchEvent(new CustomEvent(`rari:navigate-error`,{detail:{from:r,to:t,error:i,navigationId:n}})),O.current?.()},L=async(e,t={})=>{if(!e||typeof e!=`string`){console.error(`[rari] Router: Invalid navigation target:`,e);return}let[n,r]=e.includes(`#`)?e.split(`#`):[e,``],i=W(n);if(i===l.current&&!t.replace){k(i,r);return}let o=d.current.get(i);if(o)return o.promise;let c=await D(i);v(),_();let u=new AbortController;s.current=u;let f=a.navigationId+1,m=(async()=>{let e=l.current;try{t.historyKey||p.current.captureState(e);let n=t.historyKey||g(),a=window.location.origin+i,o=await fetch(a,{headers:{Accept:`text/x-component`},signal:u.signal});if(!o.ok&&o.status!==404)throw Error(`Failed to fetch: ${o.status}`);let s=new URL(o.url).pathname;if(u.signal.aborted){E(i,f);return}let l=r?`${s}#${r}`:s,m={route:s,navigationId:f,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:n};t.replace?window.history.replaceState(m,``,l):window.history.pushState(m,``,l),A(o);let h=o.headers.get(`x-render-mode`)===`streaming`,_=c?.segments&&U(``,c.segments,s)||{};if(h&&o.body?await j(o,u,i,s,f,e,t,c,_):await M(o,e,s,f,t,c,_,u),u.signal.aborted){E(i,f);return}F(s,r,t,f),d.current.delete(i),O.current?.()}catch(t){I(t,i,f,e)}})();return d.current.set(i,{targetPath:i,navigationId:f,promise:m,abortController:u}),m},R=async()=>{if(f.current.length===0)return;let e=f.current.at(-1);e&&(f.current=[],await L(e.path,e.options))},z=b(L);ee(()=>(O.current=R,z.current=L,()=>{O.current=null,z.current=null}));let B=b(null);B.current||=T((e,t)=>{z.current?.(e,t)},50,{leading:!1,trailing:!0,maxWait:200});let V=e=>{if(e.button!==0||e.ctrlKey||e.shiftKey||e.altKey||e.metaKey)return;let t=e.target;for(;t&&t.tagName!==`A`;)t=t.parentElement;if(!t||t.tagName!==`A`)return;let n=t;if(n.target&&n.target!==`_self`||n.hasAttribute(`download`))return;let r=n.getAttribute(`href`);if(!r||G(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);B.current&&B.current(i,{replace:!1})},H=e=>{let t=window.location.pathname,n=e.state;z.current&&z.current(t,{replace:!0,scroll:!1,historyKey:n?.key})},Y=()=>{if(a.error&&a.error.url){let e=a.error.url;u.current.incrementRetry(e),L(e,{replace:!1})}},X=()=>{window.location.reload()},Z=()=>{o(e=>({...e,error:null}))};y(()=>{let e=window.history.state;if(!e||!e.key){let e={route:W(r),navigationId:0,scrollPosition:{x:window.scrollX,y:window.scrollY},timestamp:Date.now(),key:g()};window.history.replaceState(e,``,window.location.pathname+window.location.search+window.location.hash)}},[r]);let Q=e=>{if(e.persisted){let e=window.location.pathname;p.current.captureState(e)}},$=e=>{if(e.persisted){let e=window.location.pathname,t=window.history.state;requestAnimationFrame(()=>{p.current.restoreState(e),t?.scrollPosition&&window.scrollTo(t.scrollPosition.x,t.scrollPosition.y)})}};return y(()=>(document.addEventListener(`click`,V),window.addEventListener(`popstate`,H),window.addEventListener(`pagehide`,Q),window.addEventListener(`pageshow`,$),()=>{document.removeEventListener(`click`,V),window.removeEventListener(`popstate`,H),window.removeEventListener(`pagehide`,Q),window.removeEventListener(`pageshow`,$)}),[]),y(()=>{h.current=i;let e=()=>{document.hidden?m.current=Date.now():m.current!==null&&Date.now()-m.current>h.current&&q.clear()};return document.addEventListener(`visibilitychange`,e),()=>{document.removeEventListener(`visibilitychange`,e)}},[i]),y(()=>(c.current=!0,e((e,t)=>z.current?.(e,t)??Promise.resolve()),()=>{c.current=!1,t(),_(),v(),B.current?.cancel&&B.current.cancel()}),[]),w(S,{children:[n,a.error&&C(K,{error:a.error,onRetry:Y,onReload:X,onDismiss:Z,retryCount:u.current.getRetryCount(a.error.url||``),maxRetries:3})]})}var oe=class extends v{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,t){console.error(`[rari] Layout: Error in layout "${this.props.layoutPath}":`,e,t),this.props.onError&&this.props.onError(e,t),typeof window<`u`&&window.dispatchEvent(new CustomEvent(`rari:layout-error`,{detail:{layoutPath:this.props.layoutPath,error:e,errorInfo:t,timestamp:Date.now()}}))}reset=()=>{this.setState({hasError:!1,error:null})};render(){return this.state.hasError&&this.state.error?this.props.fallback?this.props.fallback(this.state.error,this.reset):w(`div`,{style:{padding:`16px`,margin:`16px 0`,background:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`},children:[C(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`},children:`Layout Error`}),w(`p`,{style:{margin:`0 0 8px 0`,fontSize:`14px`},children:[`An error occurred in layout:`,` `,C(`code`,{children:this.props.layoutPath})]}),w(`details`,{style:{fontSize:`12px`,marginBottom:`8px`},children:[C(`summary`,{style:{cursor:`pointer`},children:`Error details`}),w(`pre`,{style:{marginTop:`8px`,padding:`8px`,background:`#fff`,border:`1px solid #ddd`,borderRadius:`2px`,overflow:`auto`},children:[this.state.error.message,`
|
|
3
3
|
`,this.state.error.stack]})]}),C(`button`,{onClick:this.reset,type:`button`,style:{padding:`6px 12px`,background:`#c00`,color:`white`,border:`none`,borderRadius:`4px`,cursor:`pointer`,fontSize:`14px`},children:`Try Again`})]}):this.props.children}};export{ae as ClientRouter,_ as DefaultError,f as DefaultLoading,h as ErrorBoundary,l as HttpRuntimeClient,oe as LayoutErrorBoundary,r as LoadingSpinner,P as NavigationErrorHandler,K as NavigationErrorOverlay,p as NotFound,J as StatePreserver,a as clearPropsCache,o as clearPropsCacheForComponent,g as createErrorBoundary,i as createHttpRuntimeClient,u as createLoadingBoundary,m as extractMetadata,d as extractServerProps,c as extractServerPropsWithCache,s as extractStaticParams,n as hasServerSideDataFetching};
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DR3Ue2cl.mjs";import{t,x as n}from"./regex-constants-DOQkuGm5.mjs";import{promises as r}from"node:fs";import i from"node:path";var a=e({generateAppRouteManifest:()=>f});const o={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`},s={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},c=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,l=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,u=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var d=class{appDir;extensions;verbose;constructor(e){this.appDir=i.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=[];return await this.scanDirectory(``,e,t,n,r,i,a,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} API routes`),console.warn(`[rari] Router: Found ${o.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,apiRoutes:this.sortApiRoutes(a),ogImages:o,generated:new Date().toISOString()}}async scanDirectory(e,t,n,a,o,s,c,l){let u=i.join(this.appDir,e),d;try{d=await r.readdir(u)}catch{return}let f=[],p=[];for(let e of d){let t=i.join(u,e),n=await r.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&p.push(e):n.isFile()&&f.push(e)}await this.processSpecialFiles(e,f,t,n,a,o,s,c,l);for(let r of p){let u=e?i.join(e,r):r;await this.scanDirectory(u,t,n,a,o,s,c,l)}}async processSpecialFiles(e,n,a,s,u,d,f,p,m){let h=this.pathToRoute(e),g=this.findFile(n,o.PAGE);if(g){let n=this.parseRouteSegments(e),r=this.extractParams(n);a.push({path:h,filePath:i.join(e,g).replace(t,`/`),segments:n,params:r,isDynamic:r.length>0})}let _=this.findFile(n,o.LAYOUT);if(_){let n=this.getParentPath(e);s.push({path:h,filePath:i.join(e,_).replace(t,`/`),parentPath:n?this.pathToRoute(n):void 0})}let v=this.findFile(n,o.LOADING);if(v){let n=this.generateComponentId(h,`loading`);u.push({path:h,filePath:i.join(e,v).replace(t,`/`),componentId:n})}let y=this.findFile(n,o.ERROR);y&&d.push({path:h,filePath:i.join(e,y).replace(t,`/`)});let b=this.findFile(n,o.NOT_FOUND);b&&f.push({path:h,filePath:i.join(e,b).replace(t,`/`)});let x=this.findFile(n,o.OG_IMAGE);if(x){let n=i.join(e,x).replace(t,`/`),a=i.join(this.appDir,n),o,s,u;try{let e=await r.readFile(a,`utf-8`),t=e.match(c);t&&(o=Number.parseInt(t[1],10),s=Number.parseInt(t[2],10));let n=e.match(l);n&&(u=n[1])}catch{}m.push({path:h,filePath:n,width:o,height:s,contentType:u})}let S=this.findFile(n,o.ROUTE);if(S){let t=await this.processApiRouteFile(e,S);p.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(t,`/`).split(`/`).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?`[[...${e.match(s.OPTIONAL_CATCH_ALL)[1]}]]`:s.CATCH_ALL.test(e)?`[...${e.match(s.CATCH_ALL)[1]}]`:s.DYNAMIC.test(e)?`[${e.match(s.DYNAMIC)[1]}]`:e).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(n).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?{type:`optional-catch-all`,value:e,param:e.match(s.OPTIONAL_CATCH_ALL)[1]}:s.CATCH_ALL.test(e)?{type:`catch-all`,value:e,param:e.match(s.CATCH_ALL)[1]}:s.DYNAMIC.test(e)?{type:`dynamic`,value:e,param:e.match(s.DYNAMIC)[1]}:{type:`static`,value:e}):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(n).filter(Boolean);return t.length===0?null:t.slice(0,-1).join(`/`)}generateComponentId(e,t){return`${t}:${e}`}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!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)}async detectHttpMethods(e){let t=i.join(this.appDir,e),n=await r.readFile(t,`utf-8`),a=[];for(let e of u){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),r=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||r.test(n))&&a.push(e)}return a}async processApiRouteFile(e,n){let r=i.join(e,n).replace(t,`/`),a=this.pathToRoute(e),o=this.parseRouteSegments(e),s=this.extractParams(o),c=await this.detectHttpMethods(r);return{path:a,filePath:r,segments:o,params:s,isDynamic:s.length>0,methods:c}}};async function f(e,t={}){return new d({appDir:e,...t}).generateManifest()}export{a as n,f as t};
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import{_ as e,d as t,g as n,h as r,m as i,n as a,p as o,y as s}from"../regex-constants-DOQkuGm5.mjs";import{t as c}from"../get-client-component-YrjzU6RI.mjs";import
|
|
1
|
+
import{_ as e,d as t,g as n,h as r,m as i,n as a,p as o,y as s}from"../regex-constants-DOQkuGm5.mjs";import{t as c}from"../get-client-component-YrjzU6RI.mjs";import{createFromFetch as l,createFromReadableStream as u}from"./react-server-dom-rari-client.mjs";import*as d from"react";import{Suspense as f,cloneElement as p,createElement as m,isValidElement as h,use as g,useEffect as _,useState as v}from"react";import*as y from"react-dom/client";function b(){return import.meta.env?.RARI_SERVER_URL?import.meta.env.RARI_SERVER_URL:typeof window<`u`?window.location.origin:`http://localhost:3000`}if(globalThis[`~rari`]===void 0&&(globalThis[`~rari`]={}),globalThis[`~rari`].isDevelopment=process.env.NODE_ENV!==`production`,globalThis[`~clientComponents`]===void 0&&(globalThis[`~clientComponents`]={}),globalThis[`~clientComponentNames`]===void 0&&(globalThis[`~clientComponentNames`]={}),globalThis[`~clientComponentPaths`]===void 0&&(globalThis[`~clientComponentPaths`]={}),typeof window<`u`){window[`~rari`]||(window[`~rari`]=globalThis[`~rari`]),window[`~rari`].streaming||(window[`~rari`].streaming={bufferedRows:[],bufferedEvents:[]}),window[`~rari`].streaming.bufferedEvents||(window[`~rari`].streaming.bufferedEvents=[]),window[`~rari`].boundaryModules||(window[`~rari`].boundaryModules=new Map),window[`~rari`].pendingBoundaryHydrations||(window[`~rari`].pendingBoundaryHydrations=new Map),globalThis[`~rari`].processBoundaryUpdate=function(t,s,c){let l=document.querySelector(`[data-boundary-id="${t}"]`);if(l)try{let u=s.indexOf(`:`);if(u===-1){console.warn(`[rari] Invalid RSC row format (no colon):`,s);return}let d=s.substring(0,u),f=s.substring(u+1);if(f.startsWith(`I[`)){try{let e=JSON.parse(f.substring(1));if(Array.isArray(e)&&e.length>=3){let[t,n,r]=e,i=`$L${d}`;window[`~rari`].boundaryModules?.set(i,{id:t,chunks:Array.isArray(n)?n:[n],name:r||`default`})}}catch(e){console.error(`[rari] Failed to parse import row:`,f,e)}return}let p;try{p=JSON.parse(f)}catch(e){console.error(`[rari] Failed to parse RSC content:`,f,e);return}function m(e){if(!e)return!1;if(typeof e==`string`)return e.startsWith(`$L`);if(Array.isArray(e)){if(e.length>=4&&e[0]===`$`){let[,t]=e;if(typeof t==`string`&&t.startsWith(`$L`))return!0;let n=e[3];if(n&&n.children)return m(n.children)}return e.some(e=>m(e))}return!1}if(m(p)){if(window[`~rari`].pendingBoundaryHydrations?.set(t,{content:p,element:l,rowId:c}),globalThis[`~rari`].hydrateClientComponents){let e=globalThis[`~rari`].hydrateClientComponents;e(t,p,l)}return}function h(t){let s=t=>t.replace(o,`&`).replace(n,`<`).replace(r,`>`).replace(e,`"`).replace(i,`'`),c=new Set(`div.span.p.ul.ol.li.a.img.section.article.header.footer.nav.main.aside.strong.em.b.i.button.input.label.form.select.option.textarea.h1.h2.h3.h4.h5.h6.table.thead.tbody.tr.td.th.code.pre.blockquote.hr.br.small.mark.del.ins.sub.sup.abbr.time.figure.figcaption.details.summary.dialog.menu.menuitem.canvas.svg.path.circle.rect.line.polygon.polyline.ellipse.text.g.defs.use.symbol.clippath.mask.pattern.lineargradient.radialgradient.stop.image.video.audio.source.track.picture.dl.dt.dd.fieldset.legend`.split(`.`));if(!t)return``;if(typeof t==`string`||typeof t==`number`)return s(String(t));if(Array.isArray(t)){if(t.length>=4&&t[0]===`$`){let[,e,,n]=t,r=typeof e==`string`&&c.has(e.toLowerCase())?e.toLowerCase():`div`,i=null,o=``,l=``;if(n){for(let[e,t]of Object.entries(n))if(e===`dangerouslySetInnerHTML`&&t&&typeof t==`object`&&`__html`in t)i=t.__html;else if(e!==`children`&&e!==`~boundaryId`){let n=e===`className`?`class`:e;if(e===`style`&&typeof t==`object`&&t){let e=Object.entries(t).map(([e,t])=>`${e.replace(a,`$1-$2`).toLowerCase()}:${String(t)}`).join(`;`);l+=` style="${s(e)}"`}else typeof t==`string`||typeof t==`number`?l+=` ${n}="${s(String(t))}"`:typeof t==`boolean`&&t&&(l+=` ${n}`)}i===null&&n.children&&(o=h(n.children))}return`<${r}${l}>${i===null?o:i}</${r}>`}return t.map(h).join(``)}return``}let g=h(p);g&&requestAnimationFrame(()=>{let e=document.contains(l);e&&(l.innerHTML=g,l.classList.add(`rari-boundary-resolved`)),window.dispatchEvent(new CustomEvent(`rari:boundary-resolved`,{detail:{boundaryId:t,rscRow:s,rowId:c,element:l,wasAttached:e}}))})}catch(e){console.error(`[rari] Error processing boundary update:`,e)}};let t=window,s=globalThis;t[`~rari`].streaming?.bufferedEvents&&t[`~rari`].streaming.bufferedEvents.length>0&&(t[`~rari`].streaming.bufferedEvents.forEach(e=>{let{boundaryId:t,rscRow:n,rowId:r}=e;s[`~rari`].processBoundaryUpdate?.(t,n,r)}),t[`~rari`].streaming.bufferedEvents=[]),window.addEventListener(`rari:boundary-update`,e=>{let{boundaryId:t,rscRow:n,rowId:r}=e.detail;s[`~rari`].processBoundaryUpdate&&s[`~rari`].processBoundaryUpdate(t,n,r)})}function x(e,n,r){let i=r===`default`?e.name||n.split(`/`).pop()?.replace(t,``)||`DefaultComponent`:r,a=i,o={id:a,path:n,type:`client`,component:e,registered:!0};globalThis[`~clientComponents`][a]=o,globalThis[`~clientComponents`][n]=o,globalThis[`~clientComponentPaths`][n]=a,globalThis[`~clientComponentNames`][i]=a,e&&(e[`~isClientComponent`]=!0,e[`~clientComponentId`]=a),typeof window<`u`&&fetch(`/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:a,file_path:n,export_name:r})}).catch(e=>{console.error(`[rari] Failed to register client component with server:`,e)})}function S(e){return c(e)}function C(){let e={};for(let[t,n]of Object.entries(globalThis[`~clientComponents`]))e[t]={id:t,chunks:[n.path],name:t,async:!1,default:n.component};return e}let w=l,T=u,E=null;async function D(){return E||(E=(async()=>{try{return w=l,T=u,typeof T!=`function`&&(T=null),typeof w!=`function`&&(w=null),y}catch(e){return console.error(`Failed to load react-dom/client RSC functions:`,e),w=null,T=null,null}})(),E)}const O=new Map,k=new class{componentCache;moduleCache;inflightRequests;config;constructor(){this.componentCache=new Map,this.moduleCache=new Map,this.inflightRequests=new Map,this.config={maxRetries:5,retryDelay:500,timeout:1e4}}configure(e){this.config={...this.config,...e}}clearCache(){this.componentCache.clear(),this.moduleCache.clear(),O.clear()}async fetchServerComponent(e,t={}){let n=typeof window<`u`&&window[`~rari`]?.hmr?.refreshCounters?.[e]||0,r=`${e}:${JSON.stringify(t)}:hmr:${n}`;if(this.componentCache.has(r))return this.componentCache.get(r);if(this.inflightRequests.has(r))return this.inflightRequests.get(r);let i=this.fetchServerComponentStream(e,t);this.inflightRequests.set(r,i);try{let e=await i;return this.componentCache.set(r,e),e}finally{this.inflightRequests.delete(r)}}async fetchServerComponentStream(e,t={}){await D();let n=(()=>{let e=[`/_rari/stream`];try{if(typeof window<`u`&&(window.location.hostname===`localhost`||window.location.hostname===`127.0.0.1`)){let t=b();t&&e.push(`${t}/_rari/stream`)}}catch{}return e})(),r=null,i=null,a=async()=>{for(let r of n)try{let n=await this.fetchWithTimeout(r,{method:`POST`,headers:{"Content-Type":`application/json`,...this.buildRequestHeaders()},body:JSON.stringify({component_id:e,props:t})});if(n.ok)return n;i=Error(`HTTP ${n.status}: ${await n.text()}`)}catch(e){i=e}return null};if(r=await a(),r||=(await new Promise(e=>setTimeout(e,this.config.retryDelay)),await a()),!r)throw i||Error(`Failed to reach stream endpoint`);if(!r.ok){let e=await r.text();throw Error(`Server responded with ${r.status}: ${e}`)}let o=r.body;if(!o)throw Error(`No ReadableStream from stream response`);let s=o.getReader(),c=new TextDecoder,l=new Map,u=new Map,d=e=>{if(!m)return console.error(`React not available for RSC conversion`),null;if(!e)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e)){if(e.length>=3&&e[0]===`$`){let[,t,n,r]=e;if(t===`react.suspense`||t===`suspense`)return m(f,{fallback:d(r?.fallback)||null},r?.children?d(r.children):null);let i=r?{...r}:{};if(r?.children){let e=d(r.children);Array.isArray(e)?i.children=e.map((e,t)=>h(e)&&e.key==null?p(e,{key:t}):e):i.children=e}if(typeof t==`string`){if(t.startsWith(`$L`)){let e=l.get(t);if(e){let t=S(`${e.id}#${e.name||`default`}`);if(t)return m(t,n?{...i,key:n}:i)}return i&&i.children?i.children:null}if(t.includes(`.tsx#`)||t.includes(`.jsx#`)){let e=S(t);return e?m(e,n?{...i,key:n}:i):(console.error(`Failed to resolve client component:`,t),null)}else return i&&Object.hasOwn(i,`~boundaryId`)&&(i={...i},delete i[`~boundaryId`]),m(t,n?{...i,key:n}:i)}else console.error(`Unknown RSC element type:`,t)}return e.map(e=>d(e))}return typeof e==`object`?(console.error(`Unexpected object in RSC conversion:`,e),null):e},g=null,y=new Map,x=``,C=null,w=async()=>{try{for(;;){let{value:e,done:t}=await s.read();if(t)break;let n=c.decode(e,{stream:!0});x+=n;let r=x.split(`
|
|
2
2
|
`),i=r.slice(0,-1);x=r.at(-1)||``;for(let e of i)if(e.trim())try{let t=e.indexOf(`:`);if(t===-1)continue;let n=e.substring(0,t),r=e.substring(t+1);if(r.startsWith(`I[`))try{let e=JSON.parse(r.substring(1));if(Array.isArray(e)&&e.length>=3){let[t,r,i]=e;l.set(`$L${n}`,{id:t,chunks:Array.isArray(r)?r:[r],name:i||`default`})}}catch(e){console.error(`Failed to parse import row:`,r,e)}else if(r.startsWith(`E{`))try{let e=JSON.parse(r.substring(1));console.error(`RSC stream error:`,e)}catch(e){console.error(`Failed to parse error row:`,r,e)}else if(r.startsWith(`Symbol.for(`))continue;else if(r.startsWith(`[`)){let e=JSON.parse(r);if(Array.isArray(e)&&e.length>=4){let[t,r,i]=e,a=i?.[`~boundaryId`];if(t===`$`&&(r===`react.suspense`||r===`suspense`)&&i&&a&&u.set(`$L${n}`,a),t===`$`&&i&&Object.hasOwn(i,`children`)&&typeof r==`string`&&r.startsWith(`$L`)){let e=u.get(r)||null;if(e){let t=d(i.children);y.set(e,t),C&&C.updateBoundary(e,t);continue}}}if(!g){let t=!0;if(Array.isArray(e)&&e.length>=4&&e[0]===`$`){let n=e[1],r=e[3],i=r?.[`~boundaryId`];typeof n==`string`&&(n===`react.suspense`||n===`suspense`)&&r&&i&&(t=!1)}t&&(g=d(e),C&&typeof C.updateRoot==`function`&&C.updateRoot())}}}catch(t){console.error(`Failed to parse stream line:`,e,t)}}}catch(e){console.error(`Error processing stream:`,e)}},T=()=>{let[,e]=v(0);_(()=>(C={updateBoundary:(t,n)=>{y.set(t,n),e(e=>e+1)},updateRoot:()=>{e(e=>e+1)}},()=>{C=null}),[]);let t=e=>{if(!e)return null;if(h(e)){let n=e.props,r=n?.[`~boundaryId`];if(n&&r){let e=y.get(r);if(e)return e}if(n&&n.children){let r=t(n.children);if(r!==n.children){let t={...n};return e.key!==null&&e.key!==void 0&&(t.key=e.key),m(e.type,t,r)}}return e}return Array.isArray(e)?e.map(e=>t(e)):e};return t(g)};w();let E=Promise.resolve(m(T));return{"~isRscResponse":!0,"~rscPromise":E,readRoot(){return E}}}buildRequestHeaders(){return{Accept:`text/x-component`,"Cache-Control":`no-cache, no-transform`}}async fetchWithTimeout(e,t){let n=new AbortController,r=setTimeout(()=>n.abort(),this.config.timeout);try{let i=await fetch(e,{...t,signal:n.signal});return clearTimeout(r),i}catch(e){throw clearTimeout(r),e}}async processRscResponse(e){if(await D(),w)try{let t=w(Promise.resolve(e));return{"~isRscResponse":!0,"~rscPromise":t,readRoot(){return t}}}catch{throw Error(`React Server DOM client not available`)}else throw Error(`React Server DOM client not available`)}async processRscResponseManually(e){let t=await e.text();return this.parseRscResponse(t)}parseRscResponse(e){let t=e.trim().split(s),n=new Map,r=new Map,i=[];for(let e of t){let t=e.indexOf(`:`);if(t===-1)continue;let a=e.substring(0,t),o=e.substring(t+1);if(o)try{if(o.startsWith(`I[`)){let e=o.substring(1),t=JSON.parse(e);if(Array.isArray(t)&&t.length>=3){let[e,r,i]=t;n.set(`$L${a}`,{id:e,chunks:Array.isArray(r)?r:[r],name:i||`default`})}}else if(o.startsWith(`E{`)){let e=o.substring(1),t=JSON.parse(e);i.push(t),console.error(`RSC: Server error`,t)}else if(o.startsWith(`[`)){let e=JSON.parse(o);r.set(a,e)}else if(o.startsWith(`Symbol.for(`))continue;else console.error(`Unknown RSC row format:`,e)}catch(t){console.error(`Failed to parse RSC row:`,e,t)}}if(i.length>0)throw Error(`RSC Server Error: ${i.map(e=>e.message||e).join(`, `)}`);let a=null,o=r.keys().toSorted((e,t)=>Number.parseInt(e)-Number.parseInt(t));for(let e of o){let t=r.get(e);if(Array.isArray(t)&&t.length>=2&&t[0]===`$`){let[,e,,n]=t,r=n?.[`~boundaryId`];if(e===`react.suspense`&&n&&r)continue;a=t;break}}return a?this.reconstructElementFromRscData(a,n):(console.error(`No valid root element found in RSC payload`,{elements:r,modules:n}),null)}reconstructElementFromRscData(e,t){if(e==null)return null;if(typeof e==`string`||typeof e==`number`||typeof e==`boolean`)return e;if(Array.isArray(e))if(e.length>=4&&e[0]===`$`){let[,n,r,i]=e,a=n;if(typeof n==`string`&&n.includes(`#`))a=S(n)||(({children:e,...t})=>m(`div`,{...t,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},m(`small`,{style:{color:`#c00`}},`Missing Client Component: ${n}`),e));else if(typeof n==`string`&&n.startsWith(`$L`)&&t.has(n)){let e=t.get(n);e&&(a=S(`${e.id}#${e.name}`)||(({children:t,...r})=>m(`div`,{...r,"data-client-component":n,style:{border:`2px dashed #f00`,padding:`8px`,margin:`4px`,backgroundColor:`#fff0f0`}},m(`small`,{style:{color:`#c00`}},`Missing Client Component: ${e.name} (${e.id})`),t)))}let o=i?this.processPropsRecursively(i,t):{};return m(a,{key:r,...o})}else return e.map(e=>this.reconstructElementFromRscData(e,t));return typeof e==`object`?null:e}processPropsRecursively(e,t){if(!e||typeof e!=`object`)return e;let n={};for(let[r,i]of Object.entries(e))if(r===`children`)if(Array.isArray(i))if(i.length>=2&&i[0]===`$`)n[r]=this.reconstructElementFromRscData(i,t);else{let e=i.map(e=>this.reconstructElementFromRscData(e,t)).filter(e=>e!=null);e.length===0?n[r]=null:e.length===1?n[r]=e[0]:n[r]=e}else n[r]=this.reconstructElementFromRscData(i,t);else r===`dangerouslySetInnerHTML`?n[r]=i:n[r]=this.reconstructElementFromRscData(i,t);return n}};function A({error:e,details:t}){return m(`div`,{className:`rsc-error`,style:{padding:`16px`,backgroundColor:`#fee`,border:`1px solid #fcc`,borderRadius:`4px`,margin:`8px 0`,fontFamily:`monospace`}},m(`h3`,{style:{margin:`0 0 8px 0`,color:`#c00`}},`RSC Error`),m(`p`,{style:{margin:`0 0 8px 0`}},e),t&&m(`details`,{style:{marginTop:`8px`}},m(`summary`,{style:{cursor:`pointer`}},`Error Details`),m(`pre`,{style:{fontSize:`12px`,overflow:`auto`,backgroundColor:`#f5f5f5`,padding:`8px`}},JSON.stringify(t,null,2))))}function j({rootPromise:e}){return g(e)}function M({componentId:e,props:t,fallback:n}){let r=typeof window<`u`&&window[`~rari`]?.hmr?.refreshCounters?.[e]||0,i=`${e}:${JSON.stringify(t)}:hmr:${r}`;if(!O.has(i)){let n=k.fetchServerComponent(e,t).catch(e=>{throw O.delete(i),e});O.set(i,n)}let a=g(O.get(i));if(a?.[`~isRscResponse`]){let e=a.readRoot();return m(f,{fallback:n??null},m(j,{rootPromise:e}))}return a??null}var N=class extends d.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidUpdate(e){e.mountKey!==this.props.mountKey&&this.state.hasError&&this.setState({hasError:!1,error:null})}componentDidCatch(e,t){console.error(`[rari] ServerComponentErrorBoundary: Error in component ${this.props.componentId}:`,e,t)}render(){return this.state.hasError?m(A,{error:this.state.error?.message||`Unknown error`,details:{componentId:this.props.componentId}}):this.props.children}};function P(e){let t=0;if(typeof window<`u`){let n=window;n[`~rari`].hmr||(n[`~rari`].hmr={refreshCounters:{}}),n[`~rari`].hmr.refreshCounters[e]===void 0&&(n[`~rari`].hmr.refreshCounters[e]=0),t=n[`~rari`].hmr.refreshCounters[e]}let n=n=>{let[r,i]=v(t);return _(()=>{let t=t=>{let n=t.detail;if(n&&n.filePath&&I(n.filePath)&&(k.clearCache(),typeof window<`u`)){let t=window;t[`~rari`].hmr||(t[`~rari`].hmr={refreshCounters:{}}),t[`~rari`].hmr.refreshCounters[e]=(t[`~rari`].hmr.refreshCounters[e]||0)+1,i(t[`~rari`].hmr.refreshCounters[e])}};return typeof window<`u`&&window.addEventListener(`rari:rsc-invalidate`,t),()=>{typeof window<`u`&&window.removeEventListener(`rari:rsc-invalidate`,t)}},[]),m(f,{fallback:null},m(N,{componentId:e,mountKey:r},m(M,{key:`${e}-${r}`,componentId:e,props:n,fallback:null})))};return n.displayName=`ServerComponent(${e})`,function(e){return m(n,e)}}function F(e,t){return k.fetchServerComponent(e,t)}function I(e){if(!e)return!1;try{return typeof globalThis<`u`&&globalThis[`~rari`].serverComponents?globalThis[`~rari`].serverComponents.has(e):!1}catch(e){return console.error(`Error checking if file is server component:`,e),!1}}if(import.meta.hot){let e=!1,t=[],n=new Map;function r(r,i){n.set(r,i),import.meta.hot.on(r,async n=>{if(!e){t.push({event:r,data:n});return}try{await i(n)}catch(e){console.error(`[rari] HMR: Error in handler for '${r}':`,e)}})}r(`rari:register-server-component`,e=>{e?.filePath&&typeof globalThis<`u`&&(globalThis[`~rari`].serverComponents=globalThis[`~rari`].serverComponents||new Set,globalThis[`~rari`].serverComponents.add(e.filePath))}),r(`rari:server-components-registry`,e=>{e?.serverComponents&&Array.isArray(e.serverComponents)&&typeof globalThis<`u`&&(globalThis[`~rari`].serverComponents=globalThis[`~rari`].serverComponents||new Set,e.serverComponents.forEach(e=>{globalThis[`~rari`].serverComponents?.add(e)}))}),r(`vite:beforeFullReload`,async e=>{e?.path&&I(e.path)&&await u({filePath:e.path,forceReload:!0})}),r(`rari:server-component-updated`,async e=>{let t=e?.id||e?.componentId,n=e?.t||e?.timestamp;if(t){if(typeof window<`u`){let r=new CustomEvent(`rari:rsc-invalidate`,{detail:{componentId:t,filePath:e.filePath||e.file,type:`server-component`,timestamp:n}});window.dispatchEvent(r)}}else e?.path&&I(e.path)&&await u({filePath:e.path,forceReload:!1})}),r(`rari:app-router-updated`,async e=>{try{if(!e||!e.routePath&&(!e.affectedRoutes||e.affectedRoutes.length===0))return;await i(e)}catch(e){console.error(`[rari] HMR: App router update failed:`,e)}}),r(`rari:server-action-updated`,async e=>{if(e?.filePath&&(k.clearCache(),typeof window<`u`)){let t=new CustomEvent(`rari:rsc-invalidate`,{detail:{filePath:e.filePath,type:`server-action`}});window.dispatchEvent(t)}});async function i(e){let t=e.fileType,n=e.filePath,r=e.routePath,i=e.affectedRoutes,o=e.manifestUpdated,u=e.metadata;e.metadataChanged&&u&&a(u);try{let e=`${b()}/_rari/hmr`,t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`register`,file_path:n})});if(!t.ok){let e=await t.text(),n=`Component reload failed with status ${t.status}: ${e}`;throw console.error(`[rari] HMR:`,n),Error(n)}let r=await t.json();if(typeof r!=`object`||!r){let e=`Invalid reload response: null or non-object`;throw console.error(`[rari] HMR:`,e,r),Error(e)}if(r.success!==!0&&r.reloaded!==!0){let e=`Component reload unsuccessful: ${r.error||`unknown error`}`;throw console.error(`[rari] HMR:`,e,r),Error(e)}}catch(e){console.error(`[rari] HMR: Failed to reload component:`,e);return}let d=[r];switch(t){case`page`:d=[r];break;case`layout`:case`loading`:case`error`:case`not-found`:d=i;break;default:break}await s({routes:d,fileType:t,filePath:n,componentId:r}),o&&await l(),await c({routePath:r,affectedRoutes:i})}function a(e){if(!(typeof document>`u`)&&(e.title&&(document.title=e.title),e.description)){let t=document.querySelector(`meta[name="description"]`);t||(t=document.createElement(`meta`),t.setAttribute(`name`,`description`),document.head.appendChild(t)),t.setAttribute(`content`,e.description)}}function o(e){if(!e||e.length===0){k.clearCache();return}let t=[];for(let n of k.componentCache.keys())for(let r of e){if(n.includes(`route:${r}:`)||n.startsWith(`${r}:`)){t.push(n);break}if(r!==`/`&&n.includes(`route:${r}/`)){t.push(n);break}}for(let e of t)k.componentCache.delete(e),O.delete(e);let n=[];for(let t of O.keys())for(let r of e){if(t.includes(`route:${r}:`)||t.startsWith(`${r}:`)){n.push(t);break}if(r!==`/`&&t.includes(`route:${r}/`)){n.push(t);break}}for(let e of n)O.delete(e)}async function s(e){let t=e.routes||[],n=e.fileType,r=e.filePath,i=e.componentId;if(i||r)try{let e=`${b()}/_rari/hmr`,t=await fetch(e,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate`,componentId:i||r,filePath:r})}),n=await t.text();t.ok||console.error(`[rari] HMR: Server cache invalidation failed:`,t.status,n)}catch(e){console.error(`[rari] HMR: Failed to call server invalidation endpoint:`,e)}if(o(t),typeof window<`u`){let e=new CustomEvent(`rari:rsc-invalidate`,{detail:{routes:t,fileType:n}});window.dispatchEvent(e)}}async function c(e){let t=e.routePath,n=e.affectedRoutes||[t];if(!(typeof window>`u`))try{let e=window.location.pathname,r=new CustomEvent(`rari:app-router-rerender`,{detail:{routePath:t,affectedRoutes:n,currentPath:e,preserveParams:!0}});window.dispatchEvent(r)}catch(e){throw console.error(`[rari] HMR: Failed to trigger re-render:`,e),e}}async function l(){typeof window<`u`&&window[`~rari`]?.routeInfoCache&&window[`~rari`].routeInfoCache.clear()}async function u(e){let t=e?.filePath||e;if(k.clearCache(),typeof window<`u`){let e=new CustomEvent(`rari:rsc-invalidate`,{detail:{filePath:t}});window.dispatchEvent(e)}}t.length>0?(async()=>{try{for(;t.length>0;){let e=[...t];t.length=0;for(let{event:t,data:r}of e){let e=n.get(t);if(e)try{await e(r)}catch(e){console.error(`[rari] HMR: Error replaying buffered event '${t}':`,e)}}}}catch(e){console.error(`[rari] HMR: Error during event replay:`,e)}finally{e=!0}})():e=!0}var L=class{overlay;currentError;escapeKeyHandler;constructor(){this.overlay=null,this.currentError=null,this.escapeKeyHandler=null}show(e){this.currentError=e,this.overlay?this.updateOverlay(e):this.createOverlay(e)}hide(){this.overlay&&(this.overlay.remove(),this.overlay=null,this.currentError=null),this.escapeKeyHandler&&=(document.removeEventListener(`keydown`,this.escapeKeyHandler),null)}isVisible(){return this.overlay!==null}createOverlay(e){this.overlay=document.createElement(`div`),this.overlay.id=`rari-hmr-error-overlay`,this.updateOverlay(e),document.body.appendChild(this.overlay),this.escapeKeyHandler=e=>{e.key===`Escape`&&this.hide()},document.addEventListener(`keydown`,this.escapeKeyHandler)}updateOverlay(e){if(!this.overlay)return;this.overlay.replaceChildren();let t=document.createElement(`div`);t.style.cssText=`position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0, 0, 0, 0.85); z-index: 999999; display: flex; align-items: center; justify-content: center; padding: 2rem; backdrop-filter: blur(4px);`;let n=document.createElement(`div`);n.style.cssText=`background: #1e1e1e; color: #e0e0e0; border-radius: 0.5rem; padding: 2rem; max-width: 50rem; width: 100%; max-height: 90vh; overflow-y: auto; box-shadow: 0 20px 25px -5px rgba(0, 0, 0, 0.5), 0 10px 10px -5px rgba(0, 0, 0, 0.4); border: 1px solid #ef4444;`;let r=document.createElement(`div`);r.style.cssText=`display: flex; align-items: center; justify-content: space-between; margin-bottom: 1.5rem;`;let i=document.createElement(`div`);i.style.cssText=`display: flex; align-items: center; gap: 0.75rem;`;let a=document.createElementNS(`http://www.w3.org/2000/svg`,`svg`);a.style.cssText=`width: 2rem; height: 2rem; color: #ef4444;`,a.setAttribute(`fill`,`none`),a.setAttribute(`stroke`,`currentColor`),a.setAttribute(`viewBox`,`0 0 24 24`);let o=document.createElementNS(`http://www.w3.org/2000/svg`,`path`);o.setAttribute(`stroke-linecap`,`round`),o.setAttribute(`stroke-linejoin`,`round`),o.setAttribute(`stroke-width`,`2`),o.setAttribute(`d`,`M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z`),a.appendChild(o);let s=document.createElement(`h1`);s.style.cssText=`margin: 0; font-size: 1.5rem; font-weight: 700; color: #ef4444;`,s.textContent=`Build Error`,i.appendChild(a),i.appendChild(s);let c=document.createElement(`button`);if(c.style.cssText=`background: transparent; border: none; color: #9ca3af; cursor: pointer; padding: 0.5rem; border-radius: 0.25rem; transition: all 0.2s; font-size: 1.5rem; line-height: 1; width: 2rem; height: 2rem; display: flex; align-items: center; justify-content: center;`,c.textContent=`×`,c.setAttribute(`aria-label`,`Close overlay`),c.onclick=()=>this.hide(),c.onmouseover=()=>{c.style.background=`rgba(255,255,255,0.1)`,c.style.color=`#e0e0e0`},c.onmouseout=()=>{c.style.background=`transparent`,c.style.color=`#9ca3af`},c.onfocus=()=>{c.style.background=`rgba(255,255,255,0.1)`,c.style.color=`#e0e0e0`},c.onblur=()=>{c.style.background=`transparent`,c.style.color=`#9ca3af`},r.appendChild(i),r.appendChild(c),n.appendChild(r),e.filePath){let t=document.createElement(`div`);t.style.cssText=`margin-bottom: 1rem; padding: 0.75rem; background: rgba(0, 0, 0, 0.2); border-radius: 0.375rem; font-family: monospace; font-size: 0.875rem;`;let r=document.createElement(`strong`);r.textContent=`File: `,t.appendChild(r),t.appendChild(document.createTextNode(e.filePath)),n.appendChild(t)}let l=document.createElement(`div`);l.style.cssText=`margin-bottom: 1.5rem;`;let u=document.createElement(`h2`);u.style.cssText=`margin: 0 0 0.75rem 0; font-size: 1rem; font-weight: 600; color: #fca5a5;`,u.textContent=`Error Message:`;let d=document.createElement(`pre`);if(d.style.cssText=`margin: 0; padding: 1rem; background: rgba(239, 68, 68, 0.1); border-left: 4px solid #ef4444; border-radius: 0.375rem; overflow-x: auto; font-family: monospace; font-size: 0.875rem; line-height: 1.5; white-space: pre-wrap; word-break: break-word; color: #fca5a5;`,d.textContent=e.message??`An error occurred`,l.appendChild(u),l.appendChild(d),n.appendChild(l),e.stack){let t=document.createElement(`details`);t.style.cssText=`margin-top: 1rem; cursor: pointer;`;let r=document.createElement(`summary`);r.style.cssText=`font-weight: 600; margin-bottom: 0.5rem; user-select: none;`,r.textContent=`Stack Trace`;let i=document.createElement(`pre`);i.style.cssText=`margin: 0; padding: 0.75rem; background: rgba(0, 0, 0, 0.2); border-radius: 0.375rem; overflow-x: auto; font-size: 0.875rem; line-height: 1.5; white-space: pre-wrap; word-break: break-word;`,i.textContent=e.stack,t.appendChild(r),t.appendChild(i),n.appendChild(t)}let f=document.createElement(`div`);f.style.cssText=`margin-top: 1.5rem; padding-top: 1.5rem; border-top: 1px solid #374151; display: flex; gap: 0.75rem; align-items: center;`;let p=document.createElement(`button`);p.style.cssText=`padding: 0.625rem 1.25rem; background: #ef4444; color: white; border: none; border-radius: 0.375rem; cursor: pointer; font-weight: 600; font-size: 0.875rem; transition: all 0.2s;`,p.textContent=`Reload Page`,p.onclick=()=>window.location.reload(),p.onmouseover=()=>{p.style.background=`#dc2626`},p.onmouseout=()=>{p.style.background=`#ef4444`},p.onfocus=()=>{p.style.background=`#dc2626`},p.onblur=()=>{p.style.background=`#ef4444`};let m=document.createElement(`button`);m.style.cssText=`padding: 0.625rem 1.25rem; background: #374151; color: #e0e0e0; border: none; border-radius: 0.375rem; cursor: pointer; font-weight: 600; font-size: 0.875rem; transition: all 0.2s;`,m.textContent=`Dismiss`,m.onclick=()=>this.hide(),m.onmouseover=()=>{m.style.background=`#4b5563`},m.onmouseout=()=>{m.style.background=`#374151`},m.onfocus=()=>{m.style.background=`#4b5563`},m.onblur=()=>{m.style.background=`#374151`};let h=document.createElement(`span`);h.style.cssText=`margin-left: auto; font-size: 0.75rem; color: #9ca3af;`;let g=new Date(e.timestamp);h.textContent=Number.isNaN(g.valueOf())?``:g.toLocaleTimeString(),f.appendChild(p),f.appendChild(m),f.appendChild(h),n.appendChild(f),t.appendChild(n),this.overlay.appendChild(t)}};let R=null;function z(){return R||=new L,R}if(import.meta.hot){let e=z();import.meta.hot.on(`rari:hmr-error`,t=>{let n=t.msg||t.message,r=t.file||t.filePath,i=t.t||t.timestamp,a=t.count||t.errorCount,o=t.max||t.maxErrors;console.error(`[rari] HMR: Build error:`,n),r&&console.error(`[rari] HMR: File:`,r),t.stack&&console.error(`[rari] HMR: Stack:`,t.stack),e.show({message:n,stack:t.stack,filePath:r,timestamp:i}),a&&o&&(a>=o?console.error(`[rari] HMR: Maximum error count (${o}) reached. Consider restarting the dev server if issues persist.`):a>=o-2&&console.warn(`[rari] HMR: Error count: ${a}/${o}. Approaching maximum error threshold.`))}),import.meta.hot.on(`rari:hmr-error-cleared`,()=>{e.hide()}),import.meta.hot.on(`vite:error`,t=>{e.show({message:t.err?.message||`Unknown Vite error`,stack:t.err?.stack,filePath:t.err?.file,timestamp:Date.now()})})}export{A as RscErrorComponent,C as createClientModuleMap,P as createServerComponentWrapper,F as fetchServerComponent,S as getClientComponent,x as registerClientComponent,k as rscClient};
|
|
@@ -1,6 +1,6 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-DR3Ue2cl.mjs";import{T as t,a as n,f as r,i,l as a,o,r as s,s as c,w as l}from"./regex-constants-DOQkuGm5.mjs";import u from"node:fs";import d from"node:path";import f from"node:process";import{
|
|
2
|
-
`),n=!1,r=!1;for(let e of t){let t=e.trim();if(!(t.startsWith(`//`)||t.startsWith(`/*`)||!t)){if(t===`'use client'`||t===`"use client"`||t===`'use client';`||t===`"use client";`){n=!0;break}if(t===`'use server'`||t===`"use server"`||t===`'use server';`||t===`"use server";`){r=!0;break}if(t)break}}return!n&&!r}catch{return!1}}isClientComponent(e){try{if(!u.existsSync(e))return!1;let t=u.readFileSync(e,`utf-8`),n=[`'use client'`,`"use client"`,`/* @client */`,`// @client`],r=t.trim();return n.some(e=>r.startsWith(e)||t.includes(e))}catch{return!1}}buildImportGraph(e){this.fileImporters.clear();let n=e=>{if(!u.existsSync(e))return;let r=u.readdirSync(e,{withFileTypes:!0});for(let i of r){let r=d.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;n(r)}else if(i.isFile()&&t.test(i.name))try{let e=u.readFileSync(r,`utf-8`),t;for(
|
|
3
|
-
`);for(let e of t){let t=e.trim();if(!(t.startsWith(`//`)||t.startsWith(`/*`)||!t)){if(t===`'use server'`||t===`"use server"`||t===`'use server';`||t===`"use server";`)return!0;if(t)break}}return!1}extractDependencies(e){let t=[],n;for(
|
|
1
|
+
import{t as e}from"./rolldown-runtime-DR3Ue2cl.mjs";import{T as t,a as n,f as r,i,l as a,o,r as s,s as c,w as l}from"./regex-constants-DOQkuGm5.mjs";import u from"node:fs";import d from"node:path";import f from"node:process";import{pathToFileURL as p}from"node:url";import{build as m}from"rolldown";function h(e,t){let n=null;for(let r of t)if(e.endsWith(r)&&(n??=u.existsSync(e),n))return e;for(let n of t){let t=`${e}${n}`;if(u.existsSync(t))return t}return null}function g(e,t){if(u.existsSync(e)){if(!u.statSync(e).isDirectory())return null;for(let n of t){let t=d.join(e,`index${n}`);if(u.existsSync(t))return t}}return null}function _(e,t,n){if(typeof e!=`string`)throw TypeError(`Expected source to be a string, but received ${typeof e}`);if(t==null)throw TypeError(`Expected aliases to be an object, but received ${t}`);if(typeof t!=`object`||Array.isArray(t))throw TypeError(`Expected aliases to be a plain object, but received ${Array.isArray(t)?`array`:typeof t}`);if(Object.getPrototypeOf(t)!==Object.prototype&&Object.getPrototypeOf(t)!==null)throw TypeError(`Expected aliases to be a plain object, but received ${t.constructor?.name||`object with custom prototype`}`);if(typeof n!=`string`)throw TypeError(`Expected projectRoot to be a string, but received ${typeof n}`);let r=Object.entries(t).sort((e,t)=>t[0].length-e[0].length);for(let[t,i]of r)if(e.startsWith(`${t}/`)||e===t){let r=e.slice(t.length),a=d.join(i,r);return d.isAbsolute(a)?a:d.resolve(n,a)}return null}var v=e({ServerComponentBuilder:()=>F,createServerBuildPlugin:()=>L,scanDirectory:()=>I});const y=/import\s*\(\s*["']([^"']+)["']\s*\)|import\s+["']([^"']+)["']/g,b=/from\s+['"]([^'"]+)['"]|import\s*\(\s*['"]([^'"]+)['"]\s*\)|import\s+['"]([^'"]+)['"]/g,x=/import(?:\s+(?:\w+|\{[^}]*\}|\*\s+as\s+\w+)(?:\s*,\s*(?:\w+|\{[^}]*\}|\*\s+as\s+\w+))*\s+from\s+)?['"]([^'"]+)['"]/g,S=/import\s+(\w+)\s+from\s+['"]([^'"]+)['"]/g,C=/import\s+(?:(\w+)|\{([^}]+)\})\s+from\s+['"]([^'"]+)['"];?\s*$/gm,w=/^proxy\.(?:tsx?|jsx?|mts|mjs)$/,T=/\\/g,E=/\.(tsx?|jsx?)$/,D=/\/components\/(\w+)(?:\.tsx?|\.jsx?)?$/,O=/[/\\]components[/\\](\w+)(?:\.tsx?|\.jsx?)?$/,k=/^export\s*\{([^}]+)\};?\s*$/gm,A=/^export\s+(const|let|var)\s+(\w+)/gm,j=/^(?:robots|sitemap)\.(?:tsx?|jsx?)$/,M=/^node:/,N=/\\/g;function P(e){return p(e).href}var F=class{serverComponents=new Map;serverActions=new Map;options;projectRoot;buildCache=new Map;htmlOnlyImports=new Set;fileImporters=new Map;getComponentCount(){return this.serverComponents.size+this.serverActions.size}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)}constructor(e,t={}){this.projectRoot=e;let n=t.rscDir||`server`;this.options={outDir:t.outDir||d.join(e,`dist`),rscDir:n,manifestPath:t.manifestPath||d.join(n,`manifest.json`),serverConfigPath:t.serverConfigPath||d.join(n,`config.json`),minify:t.minify??f.env.NODE_ENV===`production`,alias:t.alias||{},define:t.define,csp:t.csp,rateLimit:t.rateLimit,spamBlocker:t.spamBlocker,cacheControl:t.cacheControl},this.parseHtmlImports()}parseHtmlImports(){let e=d.join(this.projectRoot,`index.html`);if(u.existsSync(e))try{let t=u.readFileSync(e,`utf-8`);for(let e of t.matchAll(y)){let t=e[1]||e[2];if(t.startsWith(`/src/`)){let e=d.join(this.projectRoot,t.slice(1));this.htmlOnlyImports.add(e)}}}catch(e){console.warn(`[server-build] Error parsing index.html:`,e)}}isHtmlOnlyImport(e){return this.htmlOnlyImports.has(e)}isServerComponent(e){if(e.includes(`node_modules`)||this.isHtmlOnlyImport(e))return!1;try{if(!u.existsSync(e))return!1;let t=u.readFileSync(e,`utf-8`).split(`
|
|
2
|
+
`),n=!1,r=!1;for(let e of t){let t=e.trim();if(!(t.startsWith(`//`)||t.startsWith(`/*`)||!t)){if(t===`'use client'`||t===`"use client"`||t===`'use client';`||t===`"use client";`){n=!0;break}if(t===`'use server'`||t===`"use server"`||t===`'use server';`||t===`"use server";`){r=!0;break}if(t)break}}return!n&&!r}catch{return!1}}isClientComponent(e){try{if(!u.existsSync(e))return!1;let t=u.readFileSync(e,`utf-8`),n=[`'use client'`,`"use client"`,`/* @client */`,`// @client`],r=t.trim();return n.some(e=>r.startsWith(e)||t.includes(e))}catch{return!1}}buildImportGraph(e){this.fileImporters.clear();let n=e=>{if(!u.existsSync(e))return;let r=u.readdirSync(e,{withFileTypes:!0});for(let i of r){let r=d.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;n(r)}else if(i.isFile()&&t.test(i.name))try{let e=u.readFileSync(r,`utf-8`),t;for(b.lastIndex=0,t=b.exec(e);t!==null;){let n=t[1]||t[2]||t[3],i=null;if(n.startsWith(`./`)||n.startsWith(`../`)){let e=d.dirname(r);i=d.resolve(e,n)}else if(n.startsWith(`@/`)){let e=n.slice(2);i=d.join(this.projectRoot,`src`,e)}if(i){let e=[``,`.ts`,`.tsx`,`.js`,`.jsx`],t=null;for(let n of e){let e=i+n;if(u.existsSync(e)&&u.statSync(e).isFile()){t=e;break}}t&&(this.fileImporters.has(t)||this.fileImporters.set(t,new Set),this.fileImporters.get(t).add(r))}t=b.exec(e)}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error building import graph:`,r,e)}}};n(e)}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){let t=u.readFileSync(e,`utf-8`);if(this.isServerAction(t)){let n=this.extractDependencies(t),r=this.hasNodeImports(t);this.serverActions.set(e,{filePath:e,originalCode:t,dependencies:n,hasNodeImports:r});return}if(!this.isServerComponent(e))return;let n=this.extractDependencies(t),r=this.hasNodeImports(t);this.serverComponents.set(e,{filePath:e,originalCode:t,dependencies:n,hasNodeImports:r})}isServerAction(e){let t=e.split(`
|
|
3
|
+
`);for(let e of t){let t=e.trim();if(!(t.startsWith(`//`)||t.startsWith(`/*`)||!t)){if(t===`'use server'`||t===`"use server"`||t===`'use server';`||t===`"use server";`)return!0;if(t)break}}return!1}extractDependencies(e){let t=[],n;for(x.lastIndex=0;n=x.exec(e),n!==null;){let e=n[1];!e.startsWith(`.`)&&!e.startsWith(`/`)&&!e.startsWith(`node:`)&&!this.isNodeBuiltin(e)&&t.push(e)}return[...new Set(t)]}isNodeBuiltin(e){return[`fs`,`path`,`os`,`crypto`,`util`,`stream`,`events`,`process`,`buffer`,`url`,`querystring`,`zlib`,`http`,`https`,`net`,`tls`,`child_process`,`cluster`,`worker_threads`].includes(e)}hasNodeImports(e){return e.includes(`from 'node:`)||e.includes(`from "node:`)||e.includes(`from 'fs'`)||e.includes(`from "fs"`)||e.includes(`from 'path'`)||e.includes(`from "path"`)||e.includes(`from 'os'`)||e.includes(`from "os"`)||e.includes(`from 'crypto'`)||e.includes(`from "crypto"`)||e.includes(`from 'util'`)||e.includes(`from "util"`)||e.includes(`from 'stream'`)||e.includes(`from "stream"`)||e.includes(`from 'events'`)||e.includes(`from "events"`)}async getTransformedComponentsForDevelopment(){let e=[];for(let[t]of this.serverComponents){let n=d.relative(this.projectRoot,t),r=this.getComponentId(n),i=await this.buildComponentCodeOnly(t);e.push({id:r,code:i})}for(let[t]of this.serverActions){let n=d.relative(this.projectRoot,t),r=this.getComponentId(n),i=await this.buildComponentCodeOnly(t);e.push({id:r,code:i})}return e}transformComponentImportsToGlobal(e){let t=[];for(let n of e.matchAll(S)){let[e,r,i]=n;if(!i.startsWith(`.`)&&!i.startsWith(`@`)&&!i.startsWith(`~`)&&!i.startsWith(`#`))continue;let a=null;if(i.startsWith(`.`)){if(i.includes(`/components/`)){let n=i.match(D);if(n){let i=n[1],a=[d.resolve(this.projectRoot,`src`,`components`,`${i}.tsx`),d.resolve(this.projectRoot,`src`,`components`,`${i}.ts`),d.resolve(this.projectRoot,`src`,`components`,`${i}.jsx`),d.resolve(this.projectRoot,`src`,`components`,`${i}.js`)],o=!1;for(let e of a)if(u.existsSync(e)&&this.isClientComponent(e)){o=!0;break}if(!o)continue;let s=`// Component reference: ${i}
|
|
4
4
|
const ${r} = (props) => {
|
|
5
5
|
let Component = globalThis['~clientComponents']?.['components/${i}']?.component
|
|
6
6
|
|| globalThis['components/${i}'];
|
|
@@ -18,7 +18,7 @@ const ${r} = (props) => {
|
|
|
18
18
|
}
|
|
19
19
|
|
|
20
20
|
return Component(props);
|
|
21
|
-
}`;t.push({original:e,replacement:s})}}continue}let o=this.options.alias||{};for(let[e,t]of Object.entries(o))if(i.startsWith(`${e}/`)||i===e){let n=i.slice(e.length);a=d.join(t,n);break}if(a){let n=a.match(
|
|
21
|
+
}`;t.push({original:e,replacement:s})}}continue}let o=this.options.alias||{};for(let[e,t]of Object.entries(o))if(i.startsWith(`${e}/`)||i===e){let n=i.slice(e.length);a=d.join(t,n);break}if(a){let n=a.match(O);if(n){let i=n[1],o=d.isAbsolute(a)?a:d.resolve(this.projectRoot,a),s=[o,`${o}.tsx`,`${o}.ts`,`${o}.jsx`,`${o}.js`],c=!1,l=o;for(let e of s)if(u.existsSync(e)){l=e,this.isClientComponent(e)&&(c=!0);break}if(!c)continue;let f=d.relative(this.projectRoot,l),p=this.getComponentId(f),m=`// Component reference: ${i}
|
|
22
22
|
const ${r} = (props) => {
|
|
23
23
|
let Component = globalThis['~clientComponents']?.['${p}']?.component
|
|
24
24
|
|| globalThis['${p}'];
|
|
@@ -36,7 +36,7 @@ const ${r} = (props) => {
|
|
|
36
36
|
}
|
|
37
37
|
|
|
38
38
|
return Component(props);
|
|
39
|
-
}`;t.push({original:e,replacement:m})}}}let n=e;for(let{original:e,replacement:r}of t)n=n.replace(e,r);return n}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}createBuildPlugins(e,t,n,i,a=!1){let o=d.dirname(i),s=
|
|
39
|
+
}`;t.push({original:e,replacement:m})}}}let n=e;for(let{original:e,replacement:r}of t)n=n.replace(e,r);return n}isPageComponent(e){return e.includes(`/app/`)||e.includes(`\\app\\`)}createBuildPlugins(e,t,n,i,a=!1){let o=d.dirname(i),s=w.test(d.basename(i)),c=this,l=new Map,f=new Map;return[{name:`virtual-module`,resolveId(t,n){if(t===e)return t;if(n===e&&(t.startsWith(`./`)||t.startsWith(`../`))){let e=d.resolve(o,t);for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`,``]){let n=e+t;if(u.existsSync(n)&&u.statSync(n).isFile())return n}for(let t of[`.ts`,`.tsx`,`.js`,`.jsx`]){let n=d.join(e,`index${t}`);if(u.existsSync(n))return n}return e}return null},load(r){return r===e?{code:t,moduleType:n}:null}},{name:`resolve-client-server-boundaries`,resolveId:(t,n)=>{if(!n||n.includes(`node_modules`)||n.includes(`/packages/rari/dist`)||t.startsWith(`node:`)||c.isNodeBuiltin(t)||t===`react`||t===`react-dom`||t===`react/jsx-runtime`||t===`react/jsx-dev-runtime`)return null;let r=null;if(r=_(t,c.options.alias||{},c.projectRoot),!r&&(t.startsWith(`./`)||t.startsWith(`../`))){let i=n===e?o:d.dirname(n);r=d.resolve(i,t)}if(r)for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=r+e;if(u.existsSync(t)&&u.statSync(t).isFile()){if(c.isClientComponent(t)){let e=d.relative(c.projectRoot,t),n=e.startsWith(`..`)?t:e;return l.set(t,n),{id:`\0client-ref:${t}`}}try{let e=u.readFileSync(t,`utf-8`).split(`
|
|
40
40
|
`);for(let n of e){let e=n.trim();if(!(e.startsWith(`//`)||e.startsWith(`/*`)||!e)){if(e===`'use server'`||e===`"use server"`||e===`'use server';`||e===`"use server";`){let e=d.relative(c.projectRoot,t),n=e.startsWith(`..`)?t:e;return f.set(t,n),{id:`\0server-action:${t}`}}if(e)break}}}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(c.projectRoot,t),r=l.get(t)||(n.startsWith(`..`)?t:n);return{code:`
|
|
41
41
|
function registerClientReference(clientReference, id, exportName) {
|
|
42
42
|
const key = id + '#' + exportName;
|
|
@@ -65,7 +65,7 @@ function registerClientReference(clientReference, id, exportName) {
|
|
|
65
65
|
}
|
|
66
66
|
|
|
67
67
|
export default registerClientReference(null, ${JSON.stringify(r)}, "default");
|
|
68
|
-
`,moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15);return{code:`export * from ${JSON.stringify(
|
|
68
|
+
`,moduleType:`js`}}if(e.startsWith(`\0server-action:`)){let t=e.slice(15),n=d.relative(c.projectRoot,t).replace(N,`/`),r=n.startsWith(`src/`)?n.slice(4):n,i=d.join(c.options.outDir,c.options.rscDir,r.replace(E,`.js`)),a=P(d.resolve(c.projectRoot,i));return{code:`export * from ${JSON.stringify(a)};`,moduleType:`js`}}return null}},{name:`use-transformed-server-components`,resolveId:(e,t)=>{if(!a)return null;if(e.startsWith(`file://`)){let t=e.replace(r,``);return u.existsSync(t)?{id:`\0transformed:${t}`}:null}let n=null;n=_(e,c.options.alias||{},c.projectRoot);let i=t?.startsWith(`\0`)?o:t?d.dirname(t):o;if(!n&&(e.startsWith(`./`)||e.startsWith(`../`))&&(n=d.resolve(i,e)),!n||i.includes(`node_modules`))return null;for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=n+e;if(u.existsSync(t)&&u.statSync(t).isFile()){if(c.isClientComponent(t))return null;let e=d.join(c.projectRoot,`src`);if(!t.startsWith(e))return null;let n=d.relative(e,t),r=d.join(c.options.outDir,c.options.rscDir,n.replace(E,`.js`));if(u.existsSync(r))return{id:`\0transformed:${r}`};break}}return null},load(e){if(e.startsWith(`\0transformed:`)){let t=e.slice(13);return{code:u.readFileSync(t,`utf-8`),moduleType:`js`}}return null}},{name:`resolve-aliases`,resolveId:e=>{if(e.startsWith(`\0`))return null;let t=c.options.alias||{};for(let[n,r]of Object.entries(t))if(e.startsWith(`${n}/`)||e===n){let t=e.slice(n.length),i=d.join(r,t),a=d.isAbsolute(i)?i:d.resolve(c.projectRoot,i);for(let e of[``,`.ts`,`.tsx`,`.js`,`.jsx`]){let t=a+e;if(u.existsSync(t)&&u.statSync(t).isFile())return t}for(let e of[`.ts`,`.tsx`,`.js`,`.jsx`]){let t=d.join(a,`index${e}`);if(u.existsSync(t))return t}return a}return null}},{name:`resolve-rari-proxy`,resolveId:e=>{if(s&&e===`rari`){let e=d.resolve(c.projectRoot,`node_modules/rari/dist/proxy/RariResponse.mjs`);if(u.existsSync(e))return e;let t=d.resolve(c.projectRoot,`node_modules/rari/src/proxy/RariResponse.ts`);if(u.existsSync(t))return t}return null}},{name:`externalize-deps`,resolveId:e=>e.startsWith(`\0`)?null:e.startsWith(`node:`)||c.isNodeBuiltin(e)||[`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`rari/image`].includes(e)?{id:e,external:!0}:e===`rari`||e===`rari/client`?null:!e.startsWith(`.`)&&!e.startsWith(`/`)?{id:e,external:!0}:null}]}async buildComponentCodeOnly(e){let t=await u.promises.readFile(e,`utf-8`),n=this.transformClientImports(t,e),r=this.isPageComponent(e),i=r?this.transformComponentImportsToGlobal(n):n,a=d.extname(e),o;o=a===`.tsx`?`tsx`:a===`.ts`?`ts`:a===`.jsx`?`jsx`:`js`;let s=`\0virtual:${e}`,c=await m({input:s,platform:`node`,write:!1,external:[M,`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`],output:{format:`esm`,minify:this.options.minify},moduleTypes:{[`.${o}`]:o},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(f.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(s,i,o,e,r)});if(!c.output||c.output.length===0)throw Error(`No output generated from Rolldown`);let l=c.output.find(e=>e.type===`chunk`&&e.isEntry);if(!l||l.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let p=l.code;return p=`// Built: ${new Date().toISOString()}\n${p}`,p}async buildServerComponents(){let e=d.join(this.options.outDir,this.options.rscDir);await u.promises.mkdir(e,{recursive:!0});let t={react:`npm:react@19`,"react-dom":`npm:react-dom@19`,"react/jsx-runtime":`npm:react@19/jsx-runtime`,"react/jsx-dev-runtime":`npm:react@19/jsx-dev-runtime`},n=this.options.alias||{};for(let[e,r]of Object.entries(n)){let n=d.isAbsolute(r)?r:d.resolve(this.projectRoot,r),i=d.join(this.projectRoot,`src`),a=d.relative(i,n);if(a.startsWith(`..`))continue;let o=d.join(this.options.outDir,this.options.rscDir,a),s=d.resolve(this.projectRoot,o);t[e]||(t[`${e}/`]=`${P(s)}/`)}let r={components:{},importMap:{imports:t},version:`1.0.0`,buildTime:new Date().toISOString()};for(let[e,t]of this.serverComponents){if(this.isPageComponent(e))continue;let n=d.relative(this.projectRoot,e),i=this.getComponentId(n),a=d.join(this.options.rscDir,`${i}.js`),o=d.join(this.options.outDir,a),s=d.dirname(o);await u.promises.mkdir(s,{recursive:!0}),await this.buildSingleComponent(e,o);let c=P(d.resolve(this.projectRoot,o));r.components[i]={id:i,filePath:e,relativePath:n,bundlePath:a,moduleSpecifier:c,dependencies:t.dependencies,hasNodeImports:t.hasNodeImports}}for(let[e,t]of this.serverComponents){if(!this.isPageComponent(e))continue;let n=d.relative(this.projectRoot,e),i=this.getComponentId(n),a=d.join(this.options.rscDir,`${i}.js`),o=d.join(this.options.outDir,a),s=d.dirname(o);await u.promises.mkdir(s,{recursive:!0}),await this.buildSingleComponent(e,o);let c=P(d.resolve(this.projectRoot,o));r.components[i]={id:i,filePath:e,relativePath:n,bundlePath:a,moduleSpecifier:c,dependencies:t.dependencies,hasNodeImports:t.hasNodeImports}}for(let[e,t]of this.serverActions){let n=d.relative(this.projectRoot,e),i=this.getComponentId(n),a=d.join(this.options.rscDir,`${i}.js`),o=d.join(this.options.outDir,a),s=d.dirname(o);await u.promises.mkdir(s,{recursive:!0}),await this.buildSingleComponent(e,o);let c=P(d.resolve(this.projectRoot,o));r.components[i]={id:i,filePath:e,relativePath:n,bundlePath:a,moduleSpecifier:c,dependencies:t.dependencies,hasNodeImports:t.hasNodeImports}}let i=d.join(this.options.outDir,this.options.manifestPath);await u.promises.writeFile(i,JSON.stringify(r,null,2),`utf-8`);let a={};this.options.csp&&(a.csp=this.options.csp),this.options.rateLimit&&(a.rateLimit=this.options.rateLimit),this.options.spamBlocker&&(a.spamBlocker=this.options.spamBlocker),this.options.cacheControl&&(a.cacheControl=this.options.cacheControl);let o=d.join(this.options.outDir,this.options.serverConfigPath);if(Object.keys(a).length===0)try{await u.promises.unlink(o)}catch(e){e.code!==`ENOENT`&&console.warn(`Failed to remove server config file:`,e)}else await u.promises.writeFile(o,JSON.stringify(a,null,2),`utf-8`);return r}async buildSingleComponent(e,t,n=!1){let r=await u.promises.readFile(e,`utf-8`),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}`,p=await m({input:l,platform:`node`,write:!1,external:[M,`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(f.env.NODE_ENV||`production`),...this.options.define}},plugins:this.createBuildPlugins(l,o,c,e,a)});if(!p.output||p.output.length===0)throw Error(`No output generated from Rolldown`);let h=p.output.find(e=>e.type===`chunk`&&e.isEntry);if(!h||h.type!==`chunk`)throw Error(`No entry chunk found in Rolldown output`);let g=h.code;g=`// Built: ${new Date().toISOString()}\n${g}`,await u.promises.writeFile(t,g,`utf-8`);let _=await u.promises.open(t,`r+`);if(await _.sync(),await _.close(),n)return g}createSelfRegisteringModule(e,t){if(e.includes(`Self-registering Production Component`))return e;let r=e,s=null,l=[];if(r=r.replace(o,(e,t)=>(s=t,`function ${t}`)),r=r.replace(i,(e,t)=>(s=t,`async function ${t}`)),r=r.replace(c,(e,t)=>(s=t,`// Default export: ${t}`)),r=r.replace(n,(e,t)=>(s=t,`// Default export: ${t}`)),r=r.replace(k,(e,n)=>{let i=n.split(`,`).map(e=>e.trim()),a=[];return i.forEach(e=>{if(e.includes(`as default`)){let t=e.replace(`as default`,``).trim();s=t,a.push(`${t} (default)`)}else if(e===`default`){let e=`${t}_default`;r.includes(`var ${e}`)&&(s=e),a.push(`default`)}else l.push(e),a.push(e)}),`// Exports: ${a.join(`, `)}`}),r=r.replace(a,(e,t)=>(l.push(t),e.replace(`export `,``))),r=r.replace(A,(e,t,n)=>(l.push(n),`${t} ${n}`)),!s){let e=`${t}_default`;r.includes(`var ${e}`)&&(s=e)}return`// Self-registering Production Component: ${t}
|
|
69
69
|
|
|
70
70
|
if (!globalThis["${t}"]) {
|
|
71
71
|
${r}
|
|
@@ -129,7 +129,7 @@ if (!globalThis["${t}"]) {
|
|
|
129
129
|
} catch (error) {
|
|
130
130
|
console.error('[rari] Build: Error in self-registration for ${t}:', error);
|
|
131
131
|
}
|
|
132
|
-
}`}transformClientImports(e,t){let n=e,r,i=[],a=!1,o=[`rari/image`];for(
|
|
132
|
+
}`}transformClientImports(e,t){let n=e,r,i=[],a=!1,o=[`rari/image`];for(C.lastIndex=0;r=C.exec(e),r!==null;){let[e,n,s,c]=r,l=!1,u=c;if(o.includes(c))l=!0;else{let e=this.resolveImportPath(c,t);this.isClientComponent(e)&&(l=!0,u=d.relative(this.projectRoot,e))}if(l){a=!0;let t=``;n?t=`const ${n} = registerClientReference(
|
|
133
133
|
null,
|
|
134
134
|
${JSON.stringify(u)},
|
|
135
135
|
"default"
|
|
@@ -171,5 +171,5 @@ function registerClientReference(clientReference, id, exportName) {
|
|
|
171
171
|
return clientProxy;
|
|
172
172
|
}
|
|
173
173
|
|
|
174
|
-
`+n);for(let{original:e,replacement:t}of i)n=n.replace(e,t);return n}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);n=d.join(i,r);break}d.isAbsolute(n)||(n=d.resolve(d.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`];return
|
|
175
|
-
`),t=!1;for(let n of e){let e=n.trim();if(!(e.startsWith(`//`)||e.startsWith(`/*`)||!e)){if(e===`'use server'`||e===`"use server"`||e===`'use server';`||e===`"use server";`){t=!0;break}if(e)break}}t&&n.addServerComponent(i)}}catch(e){console.warn(`[server-build] Error checking ${i}:`,e instanceof Error?e.message:e)}}}}function
|
|
174
|
+
`+n);for(let{original:e,replacement:t}of i)n=n.replace(e,t);return n}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);n=d.join(i,r);break}d.isAbsolute(n)||(n=d.resolve(d.dirname(t),n));let i=[`.tsx`,`.jsx`,`.ts`,`.js`];return h(n,i)||g(n,i)||`${n}.tsx`}getComponentId(e){return e.replace(T,`/`).replace(E,``).replace(s,`_`).replace(l,``)}async rebuildComponent(e){let t=this.getComponentId(d.relative(this.projectRoot,e)),n=await u.promises.readFile(e,`utf-8`),r=this.extractDependencies(n),i={filePath:e,originalCode:n,dependencies:r,hasNodeImports:this.hasNodeImports(n)};this.isServerAction(n)?this.serverActions.set(e,i):this.serverComponents.set(e,i);let a=d.join(this.options.rscDir,`${t}.js`),o=d.join(this.options.outDir,a),s=this.buildCache.get(e),c=(await u.promises.stat(e)).mtimeMs;if(s&&s.timestamp>=c&&JSON.stringify(s.dependencies)===JSON.stringify(r))return await u.promises.writeFile(o,s.code,`utf-8`),await this.updateManifestForComponent(t,e,a),{componentId:t,bundlePath:d.join(this.options.outDir,a),success:!0};let l=d.dirname(o);await u.promises.mkdir(l,{recursive:!0});let f=await this.buildSingleComponent(e,o,!0);return this.buildCache.set(e,{code:f,timestamp:Date.now(),dependencies:r}),await this.updateManifestForComponent(t,e,a),{componentId:t,bundlePath:d.join(this.options.outDir,a),success:!0}}manifestCache=null;async updateManifestForComponent(e,t,n){let r=d.join(this.options.outDir,this.options.manifestPath),i;if(this.manifestCache)i=this.manifestCache;else if(u.existsSync(r)){let e=await u.promises.readFile(r,`utf-8`);i=JSON.parse(e),this.manifestCache=i}else i={components:{},importMap:{imports:{react:`npm:react@19`,"react-dom":`npm:react-dom@19`,"react/jsx-runtime":`npm:react@19/jsx-runtime`,"react/jsx-dev-runtime":`npm:react@19/jsx-dev-runtime`}},version:`1.0.0`,buildTime:new Date().toISOString()},this.manifestCache=i;let a=this.serverComponents.get(t)||this.serverActions.get(t),o=d.join(this.options.outDir,n),s=P(d.resolve(this.projectRoot,o));if(a)i.components[e]={id:e,filePath:t,relativePath:d.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:s,dependencies:a.dependencies,hasNodeImports:a.hasNodeImports};else{let r=await u.promises.readFile(t,`utf-8`);i.components[e]={id:e,filePath:t,relativePath:d.relative(this.projectRoot,t),bundlePath:n,moduleSpecifier:s,dependencies:this.extractDependencies(r),hasNodeImports:this.hasNodeImports(r)}}i.importMap||={imports:{react:`npm:react@19`,"react-dom":`npm:react-dom@19`,"react/jsx-runtime":`npm:react@19/jsx-runtime`,"react/jsx-dev-runtime":`npm:react@19/jsx-dev-runtime`}},i.buildTime=new Date().toISOString(),await u.promises.writeFile(r,JSON.stringify(i,null,2),`utf-8`),this.manifestCache=i}clearCache(){this.buildCache.clear(),this.manifestCache=null}async getTransformedComponentCode(e){return await this.buildComponentCodeOnly(e)}};function I(e,n,r=!0){r&&n.buildImportGraph(e);let i=u.readdirSync(e,{withFileTypes:!0});for(let r of i){let i=d.join(e,r.name);if(r.isDirectory())I(i,n,!1);else if(r.isFile()&&t.test(r.name)){if(j.test(r.name)||r.name.endsWith(`.d.ts`)||n.isOnlyImportedByClientComponents(i))continue;try{if(n.isServerComponent(i))n.addServerComponent(i);else{let e=u.readFileSync(i,`utf-8`).split(`
|
|
175
|
+
`),t=!1;for(let n of e){let e=n.trim();if(!(e.startsWith(`//`)||e.startsWith(`/*`)||!e)){if(e===`'use server'`||e===`"use server"`||e===`'use server';`||e===`"use server";`){t=!0;break}if(e)break}}t&&n.addServerComponent(i)}}catch(e){console.warn(`[server-build] Error checking ${i}:`,e instanceof Error?e.message:e)}}}}function L(e={}){let n=null,r,i=!1;return{name:`rari-server-build`,configResolved(t){r=t.root,i=t.command===`serve`;let a={};if(t.resolve?.alias){let e=t.resolve.alias;Array.isArray(e)?e.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&(a[e.find]=e.replacement)}):typeof e==`object`&&Object.entries(e).forEach(([e,t])=>{typeof t==`string`&&(a[e]=t)})}n=new F(r,{...e,alias:a})},buildStart(){if(!n)return;let e=f.env.NODE_ENV===`production`,t=[d.join(r,`dist`,`cache`,`og`),d.join(r,`dist`,`cache`,`images`)];e&&t.push(`/tmp/rari-og-cache`,`/tmp/rari-image-cache`);for(let e of t)try{u.existsSync(e)&&u.rmSync(e,{recursive:!0,force:!0})}catch(t){console.warn(`[rari] Failed to clear cache ${e}:`,t)}let i=d.join(r,`src`);u.existsSync(i)&&I(i,n)},async closeBundle(){if(n){await n.buildServerComponents();try{let{generateRobotsFile:e}=await import(`./robots-generator-Bw9KFHn4.mjs`);await e({appDir:d.join(r,`src`,`app`),outDir:d.join(r,`dist`),extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]})}catch(e){console.warn(`[rari] Failed to generate robots.txt:`,e)}try{let{generateSitemapFiles:e}=await import(`./sitemap-generator-CzZZcCF6.mjs`);await e({appDir:d.join(r,`src`,`app`),outDir:d.join(r,`dist`),extensions:[`.ts`,`.tsx`,`.js`,`.jsx`]})}catch(e){console.warn(`[rari] Failed to generate sitemap:`,e)}}},async handleHotUpdate({file:e}){if(!n||!i)return;let a=d.relative(r,e).replace(T,`/`);if(!(!a.startsWith(`src/`)||!t.test(a)))try{if((await u.promises.readFile(e,`utf-8`)).includes(`use client`))return;await n.buildServerComponents()}catch(e){console.error(`[rari] Build: Error rebuilding ${a}:`,e)}}}}export{h as i,v as n,g as r,L as t};
|
package/dist/vite.mjs
CHANGED
|
@@ -1,10 +1,10 @@
|
|
|
1
|
-
import{RariRequest as e}from"./proxy/RariRequest.mjs";import{RariResponse as t}from"./proxy/RariResponse.mjs";import{_ as n,c as r,d as i,f as a,g as o,h as s,i as c,m as l,p as u,u as d}from"./runtime-client-yoJmu7vX.mjs";import{C as f,E as p,T as m,c as h,d as g,r as _,t as v,u as y,v as ee,w as b}from"./regex-constants-DOQkuGm5.mjs";import{t as x}from"./routes-mQPtaR9p.mjs";import{i as S,n as C,o as w,r as T,t as E}from"./constants-WBHkQ1Nm.mjs";import{i as te,r as ne,t as re}from"./server-build-BUnvC6Er.mjs";import{t as D}from"./timer-utils-BO5HIsHv.mjs";import O,{promises as k}from"node:fs";import A from"node:path";import j from"node:process";import{Buffer as M}from"node:buffer";import{spawn as ie}from"node:child_process";import{fileURLToPath as N}from"node:url";import P from"node:fs/promises";import{build as ae}from"rolldown";var oe=class extends Response{static json(e,t){let n=new Headers(t?.headers);return n.has(`content-type`)||n.set(`content-type`,`application/json`),new Response(JSON.stringify(e),{...t,headers:n})}static redirect(e,t=307){return new Response(null,{status:t,headers:{location:e}})}static noContent(e){return new Response(null,{...e,status:204})}};function F(e={}){let{root:t=j.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=A.join(t,n);try{return await k.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=A.join(t,n);try{await k.access(e);for(let t of i){let i=`${r}${t}`,a=A.join(e,i);try{return await k.access(a),s(`Found proxy file: ${A.join(n,i)}`),{filePath:a,exists:!0,relativePath:A.join(n,i)}}catch{}}}catch{}return null}return{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`}))}))},async handleHotUpdate({file:e,server:t}){if(o&&e===o.filePath)return s(`Hot reloading proxy...`),t.ws.send({type:`custom`,event:`rari:proxy-reload`,data:{file:o.relativePath}}),[]}}}const se=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,ce=/title\s*:\s*['"]([^'"]+)['"]/,le=/description\s*:\s*['"]([^'"]+)['"]/,ue=/keywords\s*:\s*\[([\s\S]*?)\]/,de={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function I(e){switch(A.basename(e).replace(m,``)){case`page`:return`page`;case`layout`:return`layout`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function fe(e,t){let n=A.relative(t,A.dirname(e));return!n||n===`.`?`/`:`/${n.replace(v,`/`).split(`/`).filter(Boolean).join(`/`)}`}function L(e,t,n){if(t===`page`)return[e];let r=n.filter(t=>t===e||t.startsWith(`${e}/`));return r.length>0?r:[e]}function R(e){try{let t=e.match(se);if(!t)return null;let n=t[1],r={},i=n.match(ce);i&&(r.title=i[1]);let a=n.match(le);a&&(r.description=a[1]);let o=n.match(ue);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(f,``)).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 z(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}async function B(e){try{let t=await fetch(`http://localhost:3000/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate-api-route`,filePath:e})});if(!t.ok){console.error(`[rari] Router: Failed to invalidate API route cache: ${t.statusText}`);return}let n=await t.json();n.success||console.error(`[rari] HMR: Failed to invalidate API route cache: ${n.error||`Unknown error`}`)}catch(e){console.error(`[rari] Router: Failed to notify API route invalidation:`,e)}}function V(e={}){let t={...de,...e},n=null,r=new Map,i=null,a=new Set,o=e=>[...e].toSorted().join(`|`),s=async e=>{let n=new Set,r=async e=>{try{let i=await k.readdir(e,{withFileTypes:!0});for(let a of i){let i=A.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&I(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=A.resolve(e,t.appDir);try{await k.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let{generateAppRouteManifest:d}=await import(`./routes-mQPtaR9p.mjs`).then(e=>e.n),f=await d(c,{extensions:t.extensions}),p=JSON.stringify(f,null,2),m=A.resolve(e,t.outDir);await k.mkdir(m,{recursive:!0});let h=A.join(m,`server`);return await k.mkdir(h,{recursive:!0}),await k.writeFile(A.join(h,`routes.json`),p,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),p}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=A.resolve(e.config.root,t.appDir);e.watcher.on(`all`,async(r,i)=>{if(i.startsWith(n)&&t.extensions.some(e=>i.endsWith(e)))try{let n=I(i)!==null,o=r===`add`||r===`unlink`,s=n&&!a.has(i);(o||s)&&(await c(e.config.root,!0),i.includes(t.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})},u;return{name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`runtime-client`)&&e.includes(`The above dynamic import cannot be analyzed`)||t(e,n)}},async writeBundle(){n=await c(u||j.cwd(),!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=A.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=I(i);if(e){let t=r.get(i);t&&clearTimeout(t);let l=setTimeout(async()=>{r.delete(i);let t=!a.has(i),l=n;n=await c(o.config.root,t);let u=l!==n,d=fe(i,s),f=[d];if(n)try{f=JSON.parse(n).routes.map(e=>e.path)}catch(e){console.error(`[rari] Router: Failed to parse manifest for affected routes:`,e)}let p=L(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=R(await k.readFile(i,`utf-8`));e&&(m=e,h=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{g=z(await k.readFile(i,`utf-8`)),await B(A.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:A.relative(o.config.root,i),routePath:d,affectedRoutes:p,manifestUpdated:u,timestamp:Date.now(),metadata:m,metadataChanged:h,methods:g};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:_})},200);return r.set(i,l),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear()}}}var pe=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=D(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=D(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()}},me=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=3e3){this.serverComponentBuilder=e,this.rustServerUrl=`http://localhost:${t}`,this.errorHandler=new pe({maxErrors:5,resetTimeout:3e4})}async handleClientComponentUpdate(e,t){let n=A.relative(j.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))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);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=await Promise.allSettled(e.map(async e=>{let t=A.relative(j.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw 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))}}})),r=[],i=[];if(n.forEach(e=>{e.status===`fulfilled`&&e.value.success?r.push(e.value):e.status===`fulfilled`&&!e.value.success?i.push(e.value):e.status===`rejected`&&i.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),r.length>0){let e=Date.now();r.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(i.length>0){let e=Date.now();i.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(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)}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 d(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(!i||typeof i!=`object`)throw Error(`Invalid server response (status ${n.status}): expected object, got ${typeof i}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`);let a=i;if(!a.success)throw Error(a.message||a.error||`Component reload failed`)}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}detectComponentType(e){try{let t=O.readFileSync(e,`utf-8`).split(`
|
|
2
|
-
`);for(let e of t){let t=e.trim();if(!(!
|
|
3
|
-
• `);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}`);break}}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()}};const
|
|
1
|
+
import{RariRequest as e}from"./proxy/RariRequest.mjs";import{RariResponse as t}from"./proxy/RariResponse.mjs";import{_ as n,c as r,d as i,f as a,g as o,h as s,i as c,m as l,p as u,u as d}from"./runtime-client-yoJmu7vX.mjs";import{C as f,E as p,T as m,c as h,d as g,r as _,t as v,u as y,v as ee,w as b}from"./regex-constants-DOQkuGm5.mjs";import{t as x}from"./routes-CHfPKKpf.mjs";import{i as S,n as C,o as w,r as T,t as E}from"./constants-WBHkQ1Nm.mjs";import{i as te,r as ne,t as re}from"./server-build-CZ1eXn5D.mjs";import{t as D}from"./timer-utils-BO5HIsHv.mjs";import O,{promises as k}from"node:fs";import A from"node:path";import j from"node:process";import{Buffer as M}from"node:buffer";import{spawn as ie}from"node:child_process";import{fileURLToPath as N}from"node:url";import P from"node:fs/promises";import{build as ae}from"rolldown";var oe=class extends Response{static json(e,t){let n=new Headers(t?.headers);return n.has(`content-type`)||n.set(`content-type`,`application/json`),new Response(JSON.stringify(e),{...t,headers:n})}static redirect(e,t=307){return new Response(null,{status:t,headers:{location:e}})}static noContent(e){return new Response(null,{...e,status:204})}};function F(e={}){let{root:t=j.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=A.join(t,n);try{return await k.access(i),s(`Found proxy file: ${n}`),{filePath:i,exists:!0,relativePath:n}}catch{}}let e=A.join(t,n);try{await k.access(e);for(let t of i){let i=`${r}${t}`,a=A.join(e,i);try{return await k.access(a),s(`Found proxy file: ${A.join(n,i)}`),{filePath:a,exists:!0,relativePath:A.join(n,i)}}catch{}}}catch{}return null}return{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`}))}))},async handleHotUpdate({file:e,server:t}){if(o&&e===o.filePath)return s(`Hot reloading proxy...`),t.ws.send({type:`custom`,event:`rari:proxy-reload`,data:{file:o.relativePath}}),[]}}}const se=/export\s+const\s+metadata\s*(?::\s*\w+\s*)?=\s*(\{[\s\S]*?\n\})/,ce=/title\s*:\s*['"]([^'"]+)['"]/,le=/description\s*:\s*['"]([^'"]+)['"]/,ue=/keywords\s*:\s*\[([\s\S]*?)\]/,de={appDir:`src/app`,extensions:[`.tsx`,`.jsx`,`.ts`,`.js`],outDir:`dist`};function I(e){switch(A.basename(e).replace(m,``)){case`page`:return`page`;case`layout`:return`layout`;case`loading`:return`loading`;case`error`:return`error`;case`not-found`:return`not-found`;case`route`:return`route`;default:return null}}function fe(e,t){let n=A.relative(t,A.dirname(e));return!n||n===`.`?`/`:`/${n.replace(v,`/`).split(`/`).filter(Boolean).join(`/`)}`}function L(e,t,n){if(t===`page`)return[e];let r=n.filter(t=>t===e||t.startsWith(`${e}/`));return r.length>0?r:[e]}function R(e){try{let t=e.match(se);if(!t)return null;let n=t[1],r={},i=n.match(ce);i&&(r.title=i[1]);let a=n.match(le);a&&(r.description=a[1]);let o=n.match(ue);o&&(r.keywords=o[1].split(`,`).map(e=>e.trim().replace(f,``)).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 z(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}async function B(e){try{let t=await fetch(`http://localhost:3000/_rari/hmr`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({action:`invalidate-api-route`,filePath:e})});if(!t.ok){console.error(`[rari] Router: Failed to invalidate API route cache: ${t.statusText}`);return}let n=await t.json();n.success||console.error(`[rari] HMR: Failed to invalidate API route cache: ${n.error||`Unknown error`}`)}catch(e){console.error(`[rari] Router: Failed to notify API route invalidation:`,e)}}function V(e={}){let t={...de,...e},n=null,r=new Map,i=null,a=new Set,o=e=>[...e].toSorted().join(`|`),s=async e=>{let n=new Set,r=async e=>{try{let i=await k.readdir(e,{withFileTypes:!0});for(let a of i){let i=A.join(e,a.name);a.isDirectory()?await r(i):a.isFile()&&t.extensions.some(e=>a.name.endsWith(e))&&I(i)&&n.add(i)}}catch{}};return await r(e),n},c=async(e,r=!1)=>{let c=A.resolve(e,t.appDir);try{await k.access(c)}catch{return null}try{let l=await s(c),u=o(l);if(!r&&i===u&&n)return n;let{generateAppRouteManifest:d}=await import(`./routes-CHfPKKpf.mjs`).then(e=>e.n),f=await d(c,{extensions:t.extensions}),p=JSON.stringify(f,null,2),m=A.resolve(e,t.outDir);await k.mkdir(m,{recursive:!0});let h=A.join(m,`server`);return await k.mkdir(h,{recursive:!0}),await k.writeFile(A.join(h,`routes.json`),p,`utf-8`),i=u,a.clear(),l.forEach(e=>a.add(e)),p}catch(e){return console.error(`[rari] Router: Failed to generate app routes:`,e),null}},l=e=>{let n=A.resolve(e.config.root,t.appDir);e.watcher.on(`all`,async(r,i)=>{if(i.startsWith(n)&&t.extensions.some(e=>i.endsWith(e)))try{let n=I(i)!==null,o=r===`add`||r===`unlink`,s=n&&!a.has(i);(o||s)&&(await c(e.config.root,!0),i.includes(t.appDir)&&e.ws.send({type:`full-reload`,path:`*`}))}catch(e){console.error(`[rari] Router: Failed to regenerate app routes:`,e)}})},u;return{name:`rari-router`,configResolved(e){u=e.root;let t=e.logger.warn;e.logger.warn=(e,n)=>{typeof e==`string`&&e.includes(`runtime-client`)&&e.includes(`The above dynamic import cannot be analyzed`)||t(e,n)}},async writeBundle(){n=await c(u||j.cwd(),!0)},configureServer(e){l(e)},async handleHotUpdate(e){let{file:i,server:o}=e,s=A.resolve(o.config.root,t.appDir);if(i.startsWith(s)&&t.extensions.some(e=>i.endsWith(e))){let e=I(i);if(e){let t=r.get(i);t&&clearTimeout(t);let l=setTimeout(async()=>{r.delete(i);let t=!a.has(i),l=n;n=await c(o.config.root,t);let u=l!==n,d=fe(i,s),f=[d];if(n)try{f=JSON.parse(n).routes.map(e=>e.path)}catch(e){console.error(`[rari] Router: Failed to parse manifest for affected routes:`,e)}let p=L(d,e,f),m,h=!1,g;if(e===`page`||e===`layout`)try{let e=R(await k.readFile(i,`utf-8`));e&&(m=e,h=!0)}catch(e){console.error(`[rari] Router: Failed to extract metadata:`,e)}if(e===`route`)try{g=z(await k.readFile(i,`utf-8`)),await B(A.relative(s,i))}catch(e){console.error(`[rari] Router: Failed to detect HTTP methods:`,e)}let _={fileType:e,filePath:A.relative(o.config.root,i),routePath:d,affectedRoutes:p,manifestUpdated:u,timestamp:Date.now(),metadata:m,metadataChanged:h,methods:g};o.ws.send({type:`custom`,event:`rari:app-router-updated`,data:_})},200);return r.set(i,l),[]}return n=await c(o.config.root),[]}},async closeBundle(){for(let e of r.values())clearTimeout(e);r.clear()}}}var pe=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=D(this.resetTimer),this.resetTimer=setTimeout(()=>{this.reset()},this.resetTimeout),this.errorCount>=this.maxErrors&&this.handleMaxErrorsReached()}reset(){this.errorCount=0,this.lastError=null,this.resetTimer=D(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()}};const me=/^(["'])use client\1\s*(?:;\s*)?(?:\/\/.*)?$/;var he=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=3e3){this.serverComponentBuilder=e,this.rustServerUrl=`http://localhost:${t}`,this.errorHandler=new pe({maxErrors:5,resetTimeout:3e4})}getErrorCount(){return this.errorHandler.getErrorCount()}async handleClientComponentUpdate(e,t){let n=A.relative(j.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))}}async handleServerComponentUpdate(e,t){this.pendingFiles.add(e);let n=this.pendingUpdates.get(e);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=await Promise.allSettled(e.map(async e=>{let t=A.relative(j.cwd(),e);try{let n=await this.serverComponentBuilder.rebuildComponent(e);if(!n.success)throw 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))}}})),r=[],i=[];if(n.forEach(e=>{e.status===`fulfilled`&&e.value.success?r.push(e.value):e.status===`fulfilled`&&!e.value.success?i.push(e.value):e.status===`rejected`&&i.push({filePath:``,relativePath:`unknown`,error:Error(String(e.reason))})}),r.length>0){let e=Date.now();r.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(i.length>0){let e=Date.now();i.forEach(({relativePath:n,error:r})=>{let i=r.message,a=(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)}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 d(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(!i||typeof i!=`object`)throw Error(`Invalid server response (status ${n.status}): expected object, got ${typeof i}. Response body: ${r.substring(0,200)}${r.length>200?`...`:``}`);let a=i;if(!a.success)throw Error(a.message||a.error||`Component reload failed`)}catch(e){throw console.error(`[rari] HMR: Failed to notify Rust server:`,e),e}}detectComponentType(e){try{let t=O.readFileSync(e,`utf-8`).split(`
|
|
2
|
+
`),n=!1;function r(e){return me.test(e.trim())}function i(e){let t=e;for(;t.includes(`/*`)&&t.includes(`*/`);){let e=t.indexOf(`/*`),n=t.indexOf(`*/`,e);if(n===-1)break;t=t.substring(0,e)+t.substring(n+2)}if(t.includes(`/*`)){let e=t.indexOf(`/*`);t=t.substring(0,e)}return t}for(let e of t){let t=e.trim();if(n){if(t.includes(`*/`)){n=!1;let e=t.substring(t.indexOf(`*/`)+2).trim();if(!e||e.startsWith(`//`))continue;let a=i(e).trim();if(!a||a.startsWith(`//`))continue;if(r(a))return`client`;break}continue}if(!(!t||t.startsWith(`//`))){if(t.includes(`/*`))if(t.includes(`*/`)){let e=i(t).trim();if(!e||e.startsWith(`//`))continue;if(r(e))return`client`;break}else{let e=t.substring(0,t.indexOf(`/*`)).trim();if(e){if(r(e))return`client`;break}n=!0;continue}if(r(t))return`client`;break}}return`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]=[]),e[t.type].push(t),e),{});for(let[t,n]of Object.entries(e))if(n.length===1){let e=n[0];this.outputLog(t,e.message)}else{let e=n.map(e=>e.message).join(`
|
|
3
|
+
• `);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}`);break}}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()}};const ge=/import\s+(\w+)\s+from\s+['"]rari\/image['"]/g,_e=/import\s+\{[^}]*\b(?:Image\s+as\s+(\w+)|Image)\b[^}]*\}\s+from\s+['"]rari\/image['"]/g,ve=/src:\s*["']([^"']+)["']/,H=/[.*+?^${}()|[\]\\]/g,U=/^[A-Z_$][\w$]*$/i,ye=/width:\s*(\d+)/,be=/quality:\s*(\d+)/,xe=/preload:\s*(true|!0)/,Se=/preload:\s*(false|!1)/,Ce=/src=\{?["']([^"']+)["']\}?|src=\{([^}]+)\}/,we=/width=\{?(\d+)\}?/,Te=/quality=\{?(\d+)\}?/,Ee=/preload(?:=\{?true\}?)?/,De=/preload=\{?false\}?/;async function Oe(e,t){try{await ze(await P.readFile(e,`utf8`),e,t)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to process ${e}:`,t)}}const ke=new class{permits;queue=[];constructor(e){this.permits=e}async acquire(){if(this.permits>0){this.permits--;return}return new Promise(e=>{this.queue.push(e)})}release(){this.permits++;let e=this.queue.shift();e&&(this.permits--,e())}async run(e){await this.acquire();try{return await e()}finally{this.release()}}}(50);async function W(e,t){try{await P.access(e)}catch{return}let n=await P.readdir(e,{withFileTypes:!0}),r=[];for(let i of n){let n=A.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`||i.name===`dist`)continue;r.push(W(n,t))}else i.isFile()&&m.test(i.name)&&r.push(ke.run(()=>Oe(n,t)))}await Promise.all(r)}async function Ae(e,t=[]){let n=new Map;try{await P.access(e),await W(e,n)}catch(t){throw t.code===`ENOENT`?Error(`Required source directory does not exist: ${e}`):t}for(let e of t)try{await P.access(e),await W(e,n)}catch(t){t.code!==`ENOENT`&&console.warn(`[rari] Image scanner: Failed to scan directory ${e}:`,t)}return{images:[...n.values()]}}function je(e){return e.endsWith(`.tsx`)?`tsx`:e.endsWith(`.jsx`)?`jsx`:e.endsWith(`.ts`)?`ts`:`js`}async function Me(e,t,n){let r=`\0virtual:${t}`,i=await ae({input:r,external:[`rari/image`],platform:`browser`,write:!1,output:{format:`esm`},moduleTypes:{[`.${n}`]:n},transform:{jsx:`react`},plugins:[{name:`virtual-module`,resolveId(e){return e===r?e:null},load(t){return t===r?{code:e,moduleType:n}:null}}]});if(!i.output||i.output.length===0)throw Error(`Transform produced no output`);return i.output[0].code}function G(e){let t=new Set;for(let n of e.matchAll(ge))t.add(n[1]);for(let n of e.matchAll(_e))n[1]?t.add(n[1]):t.add(`Image`);return t}function Ne(e){return G(e)}function Pe(e){let t=e.match(ve);if(!t)return null;let n=t[1];if(!n.startsWith(`/`)&&!n.startsWith(`http`))return null;let r=e.match(ye),i=r?Number.parseInt(r[1],10):void 0,a=e.match(be),o=a?Number.parseInt(a[1],10):void 0,s=e.match(xe),c=e.match(Se);return{src:n,width:i,quality:o,preload:!!s&&!c}}function Fe(e,t){let n=`${e.src}:${e.width??`auto`}:${e.quality??75}`;(!t.has(n)||e.preload)&&t.set(n,e)}function Ie(e,t){let n=0,r=!1,i=``,a=!1,o=0;for(let s=t;s<e.length;s++){let c=e[s];if(a){a=!1;continue}if(c===`\\`){a=!0;continue}if(!r&&(c===`"`||c===`'`||c==="`")){r=!0,i=c,c==="`"&&(o=1);continue}if(r&&c===i){i==="`"?(o--,o===0&&(r=!1,i=``)):(r=!1,i=``);continue}if(r&&i==="`"&&c===`$`&&s+1<e.length&&e[s+1]===`{`){n++,s++;continue}if(r&&i==="`"&&n>0&&c==="`"){o++;continue}if(r&&i==="`"&&c===`}`&&n>0){n--;continue}if(!r){if(c===`{`)n++;else if(c===`}`&&(n--,n===0))return e.substring(t+1,s)}}return null}function Le(e,t,n){for(let r of t){if(!U.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe identifier: ${r}`);continue}let t=r.replace(H,`\\$&`),i=RegExp(`React\\.createElement\\(\\s*${t}\\s*,\\s*\\{`,`g`);for(let t of e.matchAll(i)){let r=Ie(e,t.index+t[0].length-1);if(r){let e=Pe(r);e&&Fe(e,n)}}}}function Re(e){return G(e)}async function ze(e,t,n){let r=Re(e);if(r.size!==0)try{let r=await Me(e,t,je(t)),i=Ne(r);if(i.size===0)return;Le(r,i,n)}catch{Be(e,r,n)}}function Be(e,t,n){for(let r of t){if(!U.test(r)){console.warn(`[rari] Image scanner: Skipping unsafe alias: ${r}`);continue}let t=r.replace(H,`\\$&`),i=RegExp(`<${t}\\s([^/>]+)\\/>`,`g`),a=RegExp(`<${t}\\s([^>]+)>`,`g`);for(let t of e.matchAll(i))K(t[1],n);for(let t of e.matchAll(a))K(t[1],n)}}function K(e,t){let n=e.match(Ce);if(!n)return;let r=n[1]||n[2];if(!r||r.includes(`{`)||!r.startsWith(`/`)&&!r.startsWith(`http`))return;let i=e.match(we),a=i?Number.parseInt(i[1],10):void 0,o=e.match(Te),s=o?Number.parseInt(o[1],10):void 0,c=Ee.test(e)&&!De.test(e),l=`${r}:${a??`auto`}:${s??75}`;(!t.has(l)||c)&&t.set(l,{src:r,width:a,quality:s,preload:c})}const Ve=/import\s+type\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,He=/import\s+type\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Ue=/import\s+type\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,We=/import\s+(\{[^}]+\})\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Ge=/import\s+(\*\s+as\s+\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,Ke=/import\s+(\w+)\s+from\s+["']\.\.?\/([^"']+)["'];?/g,qe=/import\s+["']\.\.?\/([^"']+)["'];?/g,Je=/import\s*(?:\(\s*)?["']([^"']+)["']\)?/g,Ye=/export\s*\{([^}]+)\}/g,Xe=/\s+as\s+/,Ze=/export\s+default\s+(?:function|class)\s+\w+/,Qe=/export\s+default\s+(?:async\s+)?function\s+(\w+)/,q=/export\s+default\s+([^;]+)/,$e=/export\s+(?:async\s+)?(?:const|let|var|function|class)\s+(\w+)/g,et=/^['"]use client['"];?\s*$/gm,tt=/import\s+["']([^"']+)["']/g,J=/^\s*import\s+(?:(\w+)(?:\s*,\s*\{\s*(?:(\w+(?:\s*,\s*\w+)*)\s*)?\})?|\{\s*(\w+(?:\s*,\s*\w+)*)\s*\})\s+from\s+['"]([./@][^'"]+)['"].*$/,nt=/import\s+\{[^}]*\}\s+from\s+['"]react['"]/,rt=/import\s+[^,\s]+\s*,\s*\{[^}]*\}\s+from\s+['"]react['"]/,it=/import React(,\s*\{([^}]*)\})?\s+from\s+['"]react['"];?/,at=/import\s+["']([^"']+)["']/g,Y=/from(\s*)(['"])(?:\.\/|rari\/)react-server-dom-rari-client\.mjs\2/g,ot=/\bJSX\b/,st=/^components\//,ct=/\{([^}]*)\}/,lt=/^['"]use client['"];?\s*\n/,ut={remotePatterns:[],localPatterns:[],deviceSizes:E,imageSizes:T,formats:C,qualityAllowlist:w,minimumCacheTTL:60,maxCacheSize:S};async function X(e){let t=import.meta.url,n=N(t),r=A.dirname(n),i=[A.join(r,`runtime`,e),A.join(r,`../runtime`,e)];for(let e of i)try{let t=await O.promises.readFile(e,`utf-8`);return e.endsWith(`.ts`)&&(t=t.replace(Ve,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(He,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(Ue,(e,t,n)=>`import type ${t} from "rari/${n}";`),t=t.replace(We,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(Ge,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(Ke,(e,t,n)=>`import ${t} from "rari/${n}";`),t=t.replace(qe,(e,t)=>`import "rari/${t}";`)),t}catch(t){t.code!==`ENOENT`&&t.code!==`EISDIR`&&console.warn(`[rari] Unexpected error reading ${e}:`,t)}throw Error(`Could not find ${e}. Tried: ${i.join(`, `)}`)}async function dt(){return X(`rsc-client-runtime.mjs`)}async function ft(e,t){return(await X(`entry-client.mjs`)).replace(`/*! @preserve CLIENT_COMPONENT_IMPORTS_PLACEHOLDER */`,e).replace(`/*! @preserve CLIENT_COMPONENT_REGISTRATIONS_PLACEHOLDER */`,t)}async function pt(){return X(`react-server-dom-shim.mjs`)}async function Z(e,t){let n=await Ae(A.join(e,`src`)),r={...ut,...t.images,preoptimizeManifest:n.images},i=A.join(e,`dist`),a=A.join(i,`server`);O.existsSync(a)||O.mkdirSync(a,{recursive:!0});let o=A.join(a,`image.json`);O.writeFileSync(o,JSON.stringify(r,null,2))}function Q(e,t=[]){let n=new Set;function r(e){if(!O.existsSync(e))return;let t=O.readdirSync(e,{withFileTypes:!0});for(let i of t){let t=A.join(e,i.name);if(i.isDirectory()){if(i.name===`node_modules`)continue;r(t)}else if(i.isFile()&&m.test(i.name))try{let e=O.readFileSync(t,`utf8`);(e.includes(`'use client'`)||e.includes(`"use client"`))&&n.add(t)}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error during file scan:`,t,e)}}}r(e);for(let e of t)O.existsSync(e)&&r(e);return n}function mt(e){return e}function $(e={}){let t=new Map,n=new Set,r=new Map,i=null,a=null,o={};function s(e){if(r.has(e))return r.get(e);let t={hasUseServer:!1,hasUseClient:!1},n=e.replace(v,`/`);if(!m.test(n)||!n.includes(`/src/`))return r.set(e,t),t;try{let n=O.readFileSync(e,`utf-8`);t.hasUseServer=n.includes(`'use server'`)||n.includes(`"use server"`),t.hasUseClient=n.includes(`'use client'`)||n.includes(`"use client"`),r.set(e,t)}catch{r.set(e,t)}return t}function c(t){if(t.includes(`node_modules`)||t.includes(`/rari/dist/`)||t.includes(`\\rari\\dist\\`))return!1;let n=e.projectRoot||j.cwd(),r=A.join(n,`index.html`);if(O.existsSync(r))try{let e=O.readFileSync(r,`utf-8`);for(let r of e.matchAll(Je)){let e=r[1];if(e.startsWith(`/src/`)&&A.join(n,e.slice(1))===t)return!1}}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading index.html:`,e)}let i;try{i=O.realpathSync(t)}catch{return!1}try{if(!O.existsSync(i))return!1;let e=O.readFileSync(i,`utf-8`),t=u(e,`use client`);return u(e,`use server`)?!1:!t}catch{return!1}}function l(e){try{let t=[],n=e.matchAll(Ye);for(let e of n){let n=e[1].split(`,`);for(let e of n){let n=e.trim().split(Xe).at(-1)?.trim();n&&t.push(n)}}(Ze.test(e)||h.test(e))&&t.push(`default`);let r=e.matchAll($e);for(let e of r)e[1]&&t.push(e[1]);return[...new Set(t)]}catch{return[]}}function u(e,t){try{let n=e.split(`
|
|
4
4
|
`);for(let e of n){let n=e.trim();if(!(!n||n.startsWith(`//`)||n.startsWith(`/*`))){if(n===`'${t}'`||n===`"${t}"`||n===`'${t}';`||n===`"${t}";`)return!0;break}}return!1}catch{return!1}}function d(e,t){if(!u(e,`use server`))return e;let n=l(e);if(n.length===0)return e;let r=e;r+=`
|
|
5
5
|
|
|
6
6
|
import {registerServerReference} from "react-server-dom-rari/server";
|
|
7
|
-
`;for(let i of n)if(i===`default`){let n=e.match(
|
|
7
|
+
`;for(let i of n)if(i===`default`){let n=e.match(Qe);if(n){let e=n[1];r+=`
|
|
8
8
|
// Register server reference for default export
|
|
9
9
|
`,r+=`registerServerReference(${e}, ${JSON.stringify(t)}, ${JSON.stringify(i)});\n`}else{let n=e.match(q);if(n){let e=n[1].trim(),a=`__default_export__`;r=r.replace(q,`const ${a} = ${e};\nexport default ${a}`),r+=`
|
|
10
10
|
// Register server reference for default export
|
|
@@ -16,9 +16,9 @@ if (import.meta.hot) {
|
|
|
16
16
|
import.meta.hot.accept(() => {
|
|
17
17
|
});
|
|
18
18
|
}`,r}function f(e,t){let n=u(e,`use server`),r=c(t);if(n){let n=l(e);if(n.length===0)return``;let r=A.relative(j.cwd(),t).replace(v,`/`).replace(m,``).replace(_,`_`).replace(b,``),i=`import { createServerReference } from "rari/runtime/actions";
|
|
19
|
-
`;for(let e of n)e===`default`?i+=`export default createServerReference("default", ${JSON.stringify(r)}, "default");\n`:i+=`export const ${e} = createServerReference("${e}", ${JSON.stringify(r)}, "${e}");\n`;return i}if(r){let n=l(e);if(n.length===0)return``;let r=A.relative(j.cwd(),t).replace(v,`/`).replace(m,``).replace(_,`_`).replace(b,``).replace(
|
|
19
|
+
`;for(let e of n)e===`default`?i+=`export default createServerReference("default", ${JSON.stringify(r)}, "default");\n`:i+=`export const ${e} = createServerReference("${e}", ${JSON.stringify(r)}, "${e}");\n`;return i}if(r){let n=l(e);if(n.length===0)return``;let r=A.relative(j.cwd(),t).replace(v,`/`).replace(m,``).replace(_,`_`).replace(b,``).replace(st,``),i=`import { createServerComponentWrapper } from "virtual:rsc-integration.ts";
|
|
20
20
|
`;for(let e of n)e===`default`?i+=`export default createServerComponentWrapper("${r}", ${JSON.stringify(t)});\n`:i+=`export const ${e} = createServerComponentWrapper("${r}_${e}", ${JSON.stringify(t)});\n`;return i}if(!u(e,`use client`))return e;let i=l(e);if(i.length===0)return``;let a=`import {registerClientReference} from "react-server-dom-rari/server";
|
|
21
|
-
`;for(let e of i){if(e===`default`){let e=`Attempted to call the default export of ${t} 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.`;a+=`export default `,a+=`registerClientReference(function() {`,a+=`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.`;a+=`export const ${e} = `,a+=`registerClientReference(function() {`,a+=`throw new Error(${JSON.stringify(t)});`}a+=`},`,a+=`${JSON.stringify(t)},`,a+=`${JSON.stringify(e)});\n`}return a}function x(e,t){return!u(e,`use client`)||l(e).length===0?e:e.replace(
|
|
21
|
+
`;for(let e of i){if(e===`default`){let e=`Attempted to call the default export of ${t} 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.`;a+=`export default `,a+=`registerClientReference(function() {`,a+=`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.`;a+=`export const ${e} = `,a+=`registerClientReference(function() {`,a+=`throw new Error(${JSON.stringify(t)});`}a+=`},`,a+=`${JSON.stringify(t)},`,a+=`${JSON.stringify(e)});\n`}return a}function x(e,t){return!u(e,`use client`)||l(e).length===0?e:e.replace(et,``)}function S(e,t){let n=e;for(let[t,r]of Object.entries(o))if(e.startsWith(`${t}/`)){n=e.replace(t,r);break}else if(e===t){n=r;break}let r=A.resolve(A.dirname(t),n),i=[`.tsx`,`.jsx`,`.ts`,`.js`];return te(r,i)||ne(r,i)||`${r}.tsx`}function C(e){return(e.split(`/`).pop()||e).replace(g,``)}let w=!1;async function T(){let e=`http://localhost:${j.env.SERVER_PORT?Number(j.env.SERVER_PORT):Number(j.env.PORT||j.env.RSC_PORT||3e3)}`;try{let t=(await fetch(`${e}/_rari/health`,{signal:AbortSignal.timeout(1e3)})).ok;return w=t,t}catch{return w=!1,!1}}let E=[{name:`rari`,config(t,{command:n}){if(t.define=t.define||{},n===`serve`||j.env.RARI_SERVER_URL||j.env.RARI_HOST){let e=j.env.SERVER_PORT?Number(j.env.SERVER_PORT):Number(j.env.PORT||j.env.RSC_PORT||3e3),n;if(j.env.RARI_SERVER_URL)n=j.env.RARI_SERVER_URL;else if(j.env.RARI_HOST){let t=j.env.RARI_HOST.startsWith(`http`)?j.env.RARI_HOST:`http://${j.env.RARI_HOST}`;n=t.replace(ee,``).includes(`:`)?t:`${t}:${e}`}else n=`http://localhost:${e}`;t.define[`import.meta.env.RARI_SERVER_URL`]=JSON.stringify(n)}if(n===`build`){let n=e.projectRoot||j.cwd(),r=A.join(n,`index.html`);if(O.existsSync(r))try{let e=O.readFileSync(r,`utf-8`),n=[];for(let t of e.matchAll(tt)){let e=t[1];if(e.startsWith(`/src/`)&&m.test(e)){let t=e.slice(1),r=A.basename(t,A.extname(t));n.push({path:t,name:r})}}if(n.length>0){t.build=t.build||{},t.build.rolldownOptions=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=t.resolve||{};let r=Array.isArray(t.resolve.dedupe)?t.resolve.dedupe:[],i=[`react`,`react-dom`];t.resolve.dedupe=[...new Set([...r||[],...i])];let a=[];Array.isArray(t.resolve.alias)?a=t.resolve.alias:t.resolve.alias&&typeof t.resolve.alias==`object`&&(a=Object.entries(t.resolve.alias).map(([e,t])=>({find:e,replacement:t})));let o=new Set(a.map(e=>String(e.find)));try{let e=N(import.meta.resolve(`react`)),n=N(import.meta.resolve(`react-dom/client`)),r=N(import.meta.resolve(`react/jsx-runtime`)),i=[];o.has(`react/jsx-runtime`)||i.push({find:`react/jsx-runtime`,replacement:r});try{let e=N(import.meta.resolve(`react/jsx-dev-runtime`));o.has(`react/jsx-dev-runtime`)||i.push({find:`react/jsx-dev-runtime`,replacement:e})}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving react/jsx-dev-runtime:`,e)}o.has(`react`)||i.push({find:`react`,replacement:e}),o.has(`react-dom/client`)||i.push({find:`react-dom/client`,replacement:n}),i.length>0&&(t.resolve.alias=[...a,...i])}catch(e){e?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error configuring React aliases:`,e)}t.environments=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||{},t.optimizeDeps.include=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||[],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&&n.build&&(n.build.rolldownOptions=n.build.rolldownOptions||{})}t.server=t.server||{},t.server.proxy=t.server.proxy||{};let c=j.env.SERVER_PORT?Number(j.env.SERVER_PORT):Number(j.env.PORT||j.env.RSC_PORT||3e3);if(t.server.proxy[`/api`]={target:`http://localhost:${c}`,changeOrigin:!0,secure:!1,ws:!0},t.server.proxy[`/_rari`]={target:`http://localhost:${c}`,changeOrigin:!0,secure:!1,ws:!0},n===`build`){t.build=t.build||{},t.build.rolldownOptions=t.build.rolldownOptions||{},t.build.rolldownOptions.input||(t.build.rolldownOptions.input={main:`./index.html`}),t.build.rolldownOptions.output=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)t.codeSplitting!==!1&&typeof t.codeSplitting!=`object`&&(t.codeSplitting={}),typeof t.codeSplitting==`object`&&(t.codeSplitting.groups=t.codeSplitting.groups||[],t.codeSplitting.groups.push({name(e){return e.includes(`node_modules`)?e.includes(`node_modules/react-dom`)?`react-dom`:e.includes(`node_modules/react`)?`react`:`vendor`:null}})),t.chunkFileNames||=e=>e.moduleIds?.some(e=>s(e).hasUseServer)?`client/actions/[name]-[hash].js`:e.moduleIds?.some(e=>s(e).hasUseClient)?`client/components/[name]-[hash].js`:`assets/[name]-[hash].js`}return t.environments&&t.environments.client&&(t.environments.client.build||(t.environments.client.build={}),t.environments.client.build.rolldownOptions||(t.environments.client.build.rolldownOptions={}),t.environments.client.build.rolldownOptions.input||(t.environments.client.build.rolldownOptions.input={})),t},configResolved(e){let t=new Set([`react`,`react-dom`,`react/jsx-runtime`,`react/jsx-dev-runtime`,`react-dom/client`]);if(e.resolve?.alias){let n=e.resolve.alias;Array.isArray(n)?n.forEach(e=>{typeof e.find==`string`&&typeof e.replacement==`string`&&!t.has(e.find)&&(o[e.find]=e.replacement)}):typeof n==`object`&&Object.entries(n).forEach(([e,n])=>{typeof n==`string`&&!t.has(e)&&(o[e]=n)})}},transform(e,r){if(!m.test(r))return null;let i=this.environment;if(u(e,`use client`)){t.set(r,`client`),n.add(r);let i=e.split(`
|
|
22
22
|
`);for(let e of i){let i=e.match(J);if(!i)continue;let a=i[4];if(!a)continue;let o=S(a,r);O.existsSync(o)&&(t.set(o,`client`),n.add(o))}return x(e,r)}if(t.get(r)===`client`||n.has(r))return x(e,r);if(c(r)){if(t.set(r,`server`),i&&(i.name===`rsc`||i.name===`ssr`))return d(e,r);{let t=f(e,r);return t=`// HMR acceptance for server component
|
|
23
23
|
if (import.meta.hot) {
|
|
24
24
|
import.meta.hot.accept();
|
|
@@ -39,10 +39,10 @@ const ${t} = registerClientReference(
|
|
|
39
39
|
},
|
|
40
40
|
${JSON.stringify(_)},
|
|
41
41
|
${JSON.stringify(d||`default`)}
|
|
42
|
-
);`;s=s.replace(e,n),l=!0,p=!0}}else if(!v&&c(_)){l=!0,p=!0,h=!0;let e=a;d&&d!==`_`&&g.push(`const ${d} = createServerComponentWrapper('${m}', '${f}');`),s=s.replace(e,``)}}if(l){let e=s.includes(`import React`)||s.match(
|
|
42
|
+
);`;s=s.replace(e,n),l=!0,p=!0}}else if(!v&&c(_)){l=!0,p=!0,h=!0;let e=a;d&&d!==`_`&&g.push(`const ${d} = createServerComponentWrapper('${m}', '${f}');`),s=s.replace(e,``)}}if(l){let e=s.includes(`import React`)||s.match(nt)||s.match(rt),n=s.includes(`createServerComponentWrapper`),i=``;if(p&&!e&&(i+=`import React from 'react';
|
|
43
43
|
`),h&&!n&&(i+=`import { createServerComponentWrapper } from 'virtual:rsc-integration.ts';
|
|
44
44
|
`),g.length>0&&(i+=`${g.join(`
|
|
45
|
-
`)}\n`),i&&(s=i+s),!s.includes(`Suspense`)){let e=s.match(
|
|
45
|
+
`)}\n`),i&&(s=i+s),!s.includes(`Suspense`)){let e=s.match(it);e&&(e[1]&&!e[2].includes(`Suspense`)?s=s.replace(e[0],e[0].replace(ct,`{ Suspense, $1 }`)):e[1]||(s=s.replace(e[0],`import React, { Suspense } from 'react';`)))}let a=j.env.NODE_ENV!==`production`,o=s.includes(`</`)||s.includes(`/>`)||ot.test(s);return!s.includes(`'use client'`)&&!s.includes(`"use client"`)&&o&&a&&(s=`'use client';\n\n${s}`,t.set(r,`client`)),s}return null},async configureServer(n){let r=e.projectRoot||j.cwd(),s=A.join(r,`src`);await Z(r,e);let l=null,u=async()=>{try{let{ServerComponentBuilder:t,scanDirectory:i}=await import(`./server-build-CZ1eXn5D.mjs`).then(e=>e.n),s=new t(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:o,csp:e.csp,rateLimit:e.rateLimit,spamBlocker:e.spamBlocker,cacheControl:e.cacheControl});if(l=s,!a&&l){let e=j.env.SERVER_PORT?Number(j.env.SERVER_PORT):Number(j.env.PORT||j.env.RSC_PORT||3e3);a=new he(l,e)}let u=A.join(r,`src`),d=[];if(O.existsSync(u)){let e=t=>{let n=O.readdirSync(t,{withFileTypes:!0});for(let r of n){let n=A.join(t,r.name);if(r.isDirectory())e(n);else if(r.isFile()&&m.test(r.name))try{c(n)&&d.push(n)}catch(e){console.error(`[rari] Error checking ${n}:`,e)}}};e(u),i(u,s)}d.length>0&&n.ws.send({type:`custom`,event:`rari:server-components-registry`,data:{serverComponents:d}});let f=await s.getTransformedComponentsForDevelopment(),p=`http://localhost:${j.env.SERVER_PORT?Number(j.env.SERVER_PORT):Number(j.env.PORT||j.env.RSC_PORT||3e3)}`;for(let e of f)try{if(e.id.startsWith(`app/`)||e.code.includes(`"use server"`)||e.code.includes(`'use server'`))continue;let t=await fetch(`${p}/_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))}},d=async()=>{try{let e=`http://localhost:${j.env.SERVER_PORT?Number(j.env.SERVER_PORT):Number(j.env.PORT||j.env.RSC_PORT||3e3)}`,t=Q(s,Object.values(o));for(let n of t){let t=A.relative(j.cwd(),n),r=A.basename(n).replace(g,``);try{await fetch(`${e}/_rari/register-client`,{method:`POST`,headers:{"Content-Type":`application/json`},body:JSON.stringify({component_id:r,file_path:t,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)}},f=async()=>{if(i)return;let{getBinaryPath:e,getInstallationInstructions:t}=await import(`./platform.mjs`),r;try{r=e()}catch(e){console.error(`rari binary not found`),console.error(` ${e.message}`),console.error(t());return}let a=j.env.SERVER_PORT?Number(j.env.SERVER_PORT):Number(j.env.PORT||j.env.RSC_PORT||3e3),o=j.env.NODE_ENV===`production`?`production`:`development`,s=n.config.server.port||5173,c=[`--mode`,o,`--port`,a.toString(),`--host`,`127.0.0.1`];i=ie(r,c,{stdio:[`ignore`,`pipe`,`pipe`],cwd:j.cwd(),env:{...j.env,RUST_LOG:j.env.RUST_LOG||`error`,RARI_VITE_PORT:s.toString()}}),i.stdout?.on(`data`,e=>{let t=e.toString().trim();t&&console.error(`${t}`)}),i.stderr?.on(`data`,e=>{let t=e.toString().trim();t&&!t.includes(`warning`)&&console.error(`${t}`)}),i.on(`error`,e=>{w=!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.`)}),i.on(`exit`,(e,t)=>{i=null,w=!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}`)});let l=!1;for(let e=0;e<20&&(l=await T(),!l);e++)await new Promise(e=>setTimeout(e,500));l?(await d(),await u()):console.error(`Server failed to become ready for component registration`)},p=async t=>{try{if(!c(t))return;let{ServerComponentBuilder:n}=await import(`./server-build-CZ1eXn5D.mjs`).then(e=>e.n),i=new n(r,{outDir:`dist`,rscDir:`server`,manifestPath:`server/manifest.json`,serverConfigPath:`server/config.json`,alias:o,csp:e.csp,rateLimit:e.rateLimit,spamBlocker:e.spamBlocker,cacheControl:e.cacheControl});i.addServerComponent(t);let a=await i.getTransformedComponentsForDevelopment();if(a.length===0)return;let s=`http://localhost:${j.env.SERVER_PORT?Number(j.env.SERVER_PORT):Number(j.env.PORT||j.env.RSC_PORT||3e3)}`;for(let e of a)try{let t=await fetch(`${s}/_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(e){console.error(`[rari] Targeted HMR failed for`,`${t}:`,e instanceof Error?e.message:String(e)),setTimeout(u,1e3)}};f().catch(e=>{console.error(`[rari] Failed to start Rust server:`,e)}),n.middlewares.use(async(e,t,n)=>{let r=e.headers.accept;if(r&&r.includes(`text/x-component`)&&e.url&&!e.url.startsWith(`/api`)&&!e.url.startsWith(`/rsc`)&&!e.url.includes(`.`)){if(!w&&!await T()){let e=Date.now();for(;Date.now()-e<1e4&&!await T();)await new Promise(e=>setTimeout(e,100));if(!w){console.error(`[rari] Rust server not ready, cannot proxy RSC request`),t.headersSent||(t.statusCode=503,t.end(`Server not ready`));return}}let n=j.env.SERVER_PORT?Number(j.env.SERVER_PORT):Number(j.env.PORT||j.env.RSC_PORT||3e3),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{for(;;){let{done:n,value:r}=await e.read();if(n)break;t.write(M.from(r))}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`,async e=>{m.test(e)&&t.delete(e),m.test(e)&&e.includes(s)&&(c(e)?(n.ws.send({type:`custom`,event:`rari:register-server-component`,data:{filePath:e}}),await p(e)):setTimeout(u,1e3))}),n.middlewares.use(`/api/vite/hmr-transform`,async(e,t)=>{if(e.method!==`POST`){t.statusCode=405,t.end(`Method Not Allowed`);return}let n=``;e.on(`data`,e=>{n+=e.toString()}),e.on(`end`,async()=>{try{let{filePath:e}=JSON.parse(n);if(!e){t.statusCode=400,t.end(JSON.stringify({error:`filePath is required`}));return}await p(e),t.statusCode=200,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!0,filePath:e,message:`Component transformation completed`}))}catch(e){t.statusCode=500,t.setHeader(`Content-Type`,`application/json`),t.end(JSON.stringify({success:!1,error:e instanceof Error?e.message:String(e)}))}})}),n.httpServer?.on(`close`,()=>{a&&=(a.dispose(),null),i&&=(i.kill(`SIGTERM`),null),w=!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-server-dom-rari-client`||e===`virtual:react-server-dom-rari-client.ts`)return`virtual:react-server-dom-rari-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(e===`./DefaultLoadingIndicator`||e===`./DefaultLoadingIndicator.tsx`)return`virtual:default-loading-indicator.tsx`;if(e===`./LoadingErrorBoundary`||e===`./LoadingErrorBoundary.tsx`)return`virtual:loading-error-boundary.tsx`;if(e===`react-server-dom-rari/server`)return e;if(t&&t.startsWith(`virtual:`)&&e.startsWith(`../`)){let n=import.meta.url,r=N(n),i=A.dirname(r),a=null,o=[A.join(i,`runtime`),A.join(i,`../runtime`)];for(let e of o)if(O.existsSync(e)){a=e;break}if(a){let t=A.join(a,e);if(O.existsSync(t))return t;let n=A.join(a,`../dist`,A.basename(e));if(O.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=A.join(i,e);if(O.existsSync(s))return s;let c=A.join(i,`../dist`,A.basename(e));if(O.existsSync(c))return c}if(j.env.NODE_ENV===`production`)try{let t=A.resolve(e);if(O.existsSync(t)&&c(t))return{id:e,external:!0}}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error resolving server component:`,e,t)}return null},async load(t){if(m.test(t)){let e=this.environment;if(e&&e.name===`client`)try{let e=O.readFileSync(t,`utf-8`);if(u(e,`use server`))return f(e,t)}catch{}}if(t===`virtual:rari-entry-client.ts`){let e=Q(A.join(j.cwd(),`src`),Object.values(o)),t=new Set([...n,...e]),r=[{path:`rari/image`,exports:[`Image`]},{path:`virtual:error-boundary-wrapper.tsx`,exports:[`ErrorBoundaryWrapper`]}],i=[...t].filter(e=>{try{return u(O.readFileSync(e,`utf-8`),`use client`)}catch{return!1}}).map(e=>{let t=A.relative(j.cwd(),e).replace(v,`/`),n=t.replace(m,``),r=t.startsWith(`..`)?e.replace(v,`/`):t,i=!1,a=``;try{let t=O.readFileSync(e,`utf-8`),n=h.test(t),r=t.match(y);!n&&r&&(i=!0,a=r[1])}catch(t){t?.code!==`ENOENT`&&console.warn(`[rari] Unexpected error reading component for export detection:`,e,t)}let o=r.replace(v,`/`),s=o.startsWith(`/`)||p.test(o)?o:`/${o}`;return` "${r}": {
|
|
46
46
|
id: "${n}",
|
|
47
47
|
path: "${r}",
|
|
48
48
|
type: "client",
|
|
@@ -65,7 +65,7 @@ globalThis['~clientComponents']["${e.path}"] = globalThis['~clientComponents']["
|
|
|
65
65
|
globalThis['~clientComponents']["${e.path}"].component = ${r};
|
|
66
66
|
globalThis['~clientComponentPaths'] = globalThis['~clientComponentPaths'] || {};
|
|
67
67
|
globalThis['~clientComponentPaths']["${e.path}"] = "${n}";`})).join(`
|
|
68
|
-
`);return await
|
|
68
|
+
`);return await ft(a,[`
|
|
69
69
|
const lazyComponentRegistry = {
|
|
70
70
|
${i}
|
|
71
71
|
};
|
|
@@ -76,7 +76,7 @@ for (const [path, config] of Object.entries(lazyComponentRegistry)) {
|
|
|
76
76
|
globalThis['~clientComponentPaths'][path] = config.id;
|
|
77
77
|
}
|
|
78
78
|
`,s].filter(Boolean).join(`
|
|
79
|
-
`))}if(t===`react-server-dom-rari/server`)return await
|
|
79
|
+
`))}if(t===`react-server-dom-rari/server`)return await pt();if(t===`virtual:app-router-provider.tsx`){let e=[A.join(j.cwd(),`packages/rari/dist/runtime/AppRouterProvider.mjs`),A.join(j.cwd(),`node_modules/rari/dist/runtime/AppRouterProvider.mjs`)];for(let t of e)if(O.existsSync(t))return O.readFileSync(t,`utf-8`);return`export function AppRouterProvider({ children }) { return children; }`}if(t===`virtual:default-loading-indicator.tsx`){let e=[A.join(j.cwd(),`packages/rari/dist/runtime/DefaultLoadingIndicator.mjs`),A.join(j.cwd(),`node_modules/rari/dist/runtime/DefaultLoadingIndicator.mjs`)];for(let t of e)if(O.existsSync(t))return O.readFileSync(t,`utf-8`);return`export function DefaultLoadingIndicator() { return null; }`}if(t===`virtual:loading-error-boundary.tsx`){let e=[A.join(j.cwd(),`packages/rari/dist/runtime/LoadingErrorBoundary.mjs`),A.join(j.cwd(),`node_modules/rari/dist/runtime/LoadingErrorBoundary.mjs`)];for(let t of e)if(O.existsSync(t))return O.readFileSync(t,`utf-8`);return`export class LoadingErrorBoundary extends React.Component { render() { return this.props.children; } }`}if(t===`virtual:error-boundary-wrapper.tsx`){let e=[A.join(j.cwd(),`packages/rari/dist/runtime/ErrorBoundaryWrapper.mjs`),A.join(j.cwd(),`node_modules/rari/dist/runtime/ErrorBoundaryWrapper.mjs`),A.join(j.cwd(),`packages/rari/src/runtime/ErrorBoundaryWrapper.tsx`)];for(let t of e)if(O.existsSync(t)){let e=O.readFileSync(t,`utf-8`);if(!e.includes(`import React`)&&!e.includes(`from "react"`)&&!e.includes(`from 'react'`)){let t=e.match(lt);if(t){let n=t[0];return`
|
|
80
80
|
${n}import * as React from 'react';\n${e.slice(n.length)}`}return`
|
|
81
81
|
import * as React from 'react';\n${e}`}return e}return`'use client';
|
|
82
82
|
import * as React from 'react';
|
|
@@ -150,4 +150,4 @@ export class ErrorBoundaryWrapper extends React.Component {
|
|
|
150
150
|
}
|
|
151
151
|
return this.props.children;
|
|
152
152
|
}
|
|
153
|
-
}`}if(t===`virtual:rsc-integration.ts`)return(await
|
|
153
|
+
}`}if(t===`virtual:rsc-integration.ts`)return(await dt()).replace(Y,(e,t,n)=>`from${t}${n}virtual:react-server-dom-rari-client.ts${n}`);if(t===`virtual:react-server-dom-rari-client.ts`)return await X(`react-server-dom-rari-client.mjs`);if(t.endsWith(`.mjs`)&&O.existsSync(t))try{let n=e.projectRoot||j.cwd(),r=O.realpathSync(t),i=A.relative(n,r),a=!i.startsWith(`..`)&&!A.isAbsolute(i),o=r.includes(`${A.sep}node_modules${A.sep}`),s=r.includes(`${A.sep}packages${A.sep}rari${A.sep}`)||r.includes(`${A.sep}node_modules${A.sep}rari${A.sep}`);return a||o||s?O.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(!m.test(e))return;if(e.includes(`/dist/`)||e.includes(`\\dist\\`))return[];let n=a?.detectComponentType(e)||`unknown`,r=e.includes(`/app/`)||e.includes(`\\app\\`),i=e.endsWith(`page.tsx`)||e.endsWith(`page.jsx`),o=e.endsWith(`layout.tsx`)||e.endsWith(`layout.jsx`),s=e.endsWith(`loading.tsx`)||e.endsWith(`loading.jsx`),c=e.endsWith(`error.tsx`)||e.endsWith(`error.jsx`),l=e.endsWith(`not-found.tsx`)||e.endsWith(`not-found.jsx`);if(!(r&&(i||o||s||c||l))&&n!==`client`&&n===`server`)return a&&await a.handleServerComponentUpdate(e,t),[]},transformIndexHtml:{order:`pre`,handler(e){let t=[];for(let n of e.matchAll(at)){let e=n[1];e.startsWith(`/src/`)&&t.push(e)}return t.length>0?{html:e,tags:t.map(e=>({tag:`script`,attrs:{type:`module`,src:e},injectTo:`head-prepend`}))}:e}},async writeBundle(){await Z(e.projectRoot||j.cwd(),e)}},re({...e.serverBuild,csp:e.csp,rateLimit:e.rateLimit,spamBlocker:e.spamBlocker,cacheControl:e.cacheControl})];return e.proxy!==!1&&E.push(F(e.proxy||{})),e.router!==!1&&E.push(V(e.router||{})),E}function ht(e){return{plugins:[$(),...e.plugins||[]],...e}}export{oe as ApiResponse,c as HttpRuntimeClient,e as RariRequest,t as RariResponse,i as clearPropsCache,a as clearPropsCacheForComponent,r as createHttpRuntimeClient,ht as defineRariConfig,mt as defineRariOptions,u as extractMetadata,l as extractServerProps,s as extractServerPropsWithCache,o as extractStaticParams,x as generateAppRouteManifest,n as hasServerSideDataFetching,$ as rari,F as rariProxy,V as rariRouter};
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "rari",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "0.10.
|
|
4
|
+
"version": "0.10.23",
|
|
5
5
|
"description": "Runtime Accelerated Rendering Infrastructure (rari)",
|
|
6
6
|
"author": "Ryan Skinner",
|
|
7
7
|
"license": "MIT",
|
|
@@ -103,21 +103,21 @@
|
|
|
103
103
|
"react-dom": "^19.2.4"
|
|
104
104
|
},
|
|
105
105
|
"dependencies": {
|
|
106
|
-
"rolldown": "^1.0.0-rc.
|
|
106
|
+
"rolldown": "^1.0.0-rc.11"
|
|
107
107
|
},
|
|
108
108
|
"optionalDependencies": {
|
|
109
|
-
"rari-darwin-arm64": "0.10.
|
|
110
|
-
"rari-darwin-x64": "0.10.
|
|
111
|
-
"rari-linux-arm64": "0.10.
|
|
112
|
-
"rari-linux-x64": "0.10.
|
|
113
|
-
"rari-win32-x64": "0.10.
|
|
109
|
+
"rari-darwin-arm64": "0.10.23",
|
|
110
|
+
"rari-darwin-x64": "0.10.23",
|
|
111
|
+
"rari-linux-arm64": "0.10.23",
|
|
112
|
+
"rari-linux-x64": "0.10.23",
|
|
113
|
+
"rari-win32-x64": "0.10.23"
|
|
114
114
|
},
|
|
115
115
|
"devDependencies": {
|
|
116
116
|
"@types/node": "^25.5.0",
|
|
117
117
|
"@types/react": "^19.2.14",
|
|
118
118
|
"@types/react-dom": "^19.2.3",
|
|
119
|
-
"@typescript/native-preview": "^7.0.0-dev.
|
|
120
|
-
"vite-plus": "^0.1.
|
|
119
|
+
"@typescript/native-preview": "^7.0.0-dev.20260324.1",
|
|
120
|
+
"vite-plus": "^0.1.14",
|
|
121
121
|
"@rari/deploy": "0.1.0",
|
|
122
122
|
"@rari/logger": "0.1.0"
|
|
123
123
|
},
|
package/dist/routes-mQPtaR9p.mjs
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{t as e}from"./rolldown-runtime-DR3Ue2cl.mjs";import{t,x as n}from"./regex-constants-DOQkuGm5.mjs";import{promises as r}from"node:fs";import i from"node:path";var a=e({generateAppRouteManifest:()=>f});const o={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`},s={DYNAMIC:/^\[([^\]]+)\]$/,CATCH_ALL:/^\[\.\.\.([^\]]+)\]$/,OPTIONAL_CATCH_ALL:/^\[\[\.\.\.([^\]]+)\]\]$/},c=/export\s+const\s+size\s*=\s*\{\s*width\s*:\s*(\d+)\s*,\s*height\s*:\s*(\d+)\s*[,}]/,l=/export\s+const\s+contentType\s*=\s*['"]([^'"]+)['"]/,u=[`GET`,`POST`,`PUT`,`DELETE`,`PATCH`,`HEAD`,`OPTIONS`];var d=class{appDir;extensions;verbose;constructor(e){this.appDir=i.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=[];return await this.scanDirectory(``,e,t,n,r,i,a,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} API routes`),console.warn(`[rari] Router: Found ${o.length} OG images`)),{routes:this.sortRoutes(e),layouts:this.sortLayouts(t),loading:n,errors:r,notFound:i,apiRoutes:this.sortApiRoutes(a),ogImages:o,generated:new Date().toISOString()}}async scanDirectory(e,t,n,a,o,s,c,l){let u=i.join(this.appDir,e),d;try{d=await r.readdir(u)}catch{return}let f=[],p=[];for(let e of d){let t=i.join(u,e),n=await r.stat(t);n.isDirectory()?this.shouldScanDirectory(e)&&p.push(e):n.isFile()&&f.push(e)}await this.processSpecialFiles(e,f,t,n,a,o,s,c,l);for(let r of p){let u=e?i.join(e,r):r;await this.scanDirectory(u,t,n,a,o,s,c,l)}}async processSpecialFiles(e,t,n,a,s,u,d,f,p){let m=this.pathToRoute(e),h=this.findFile(t,o.PAGE);if(h){let t=this.parseRouteSegments(e),r=this.extractParams(t);n.push({path:m,filePath:i.join(e,h),segments:t,params:r,isDynamic:r.length>0})}let g=this.findFile(t,o.LAYOUT);if(g){let t=this.getParentPath(e);a.push({path:m,filePath:i.join(e,g),parentPath:t?this.pathToRoute(t):void 0})}let _=this.findFile(t,o.LOADING);if(_){let t=this.generateComponentId(m,`loading`);s.push({path:m,filePath:i.join(e,_),componentId:t})}let v=this.findFile(t,o.ERROR);v&&u.push({path:m,filePath:i.join(e,v)});let y=this.findFile(t,o.NOT_FOUND);y&&d.push({path:m,filePath:i.join(e,y)});let b=this.findFile(t,o.OG_IMAGE);if(b){let t=i.join(e,b),n=i.join(this.appDir,t),a,o,s;try{let e=await r.readFile(n,`utf-8`),t=e.match(c);t&&(a=Number.parseInt(t[1],10),o=Number.parseInt(t[2],10));let i=e.match(l);i&&(s=i[1])}catch{}p.push({path:m,filePath:t,width:a,height:o,contentType:s})}let x=this.findFile(t,o.ROUTE);if(x){let t=await this.processApiRouteFile(e,x);f.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(t,`/`).split(`/`).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?`[[...${e.match(s.OPTIONAL_CATCH_ALL)[1]}]]`:s.CATCH_ALL.test(e)?`[...${e.match(s.CATCH_ALL)[1]}]`:s.DYNAMIC.test(e)?`[${e.match(s.DYNAMIC)[1]}]`:e).join(`/`)}`:`/`}parseRouteSegments(e){return e?e.split(n).filter(Boolean).map(e=>s.OPTIONAL_CATCH_ALL.test(e)?{type:`optional-catch-all`,value:e,param:e.match(s.OPTIONAL_CATCH_ALL)[1]}:s.CATCH_ALL.test(e)?{type:`catch-all`,value:e,param:e.match(s.CATCH_ALL)[1]}:s.DYNAMIC.test(e)?{type:`dynamic`,value:e,param:e.match(s.DYNAMIC)[1]}:{type:`static`,value:e}):[]}extractParams(e){return e.filter(e=>e.param!==void 0).map(e=>e.param)}getParentPath(e){if(!e)return null;let t=e.split(n).filter(Boolean);return t.length===0?null:t.slice(0,-1).join(`/`)}generateComponentId(e,t){return`${t}:${e}`}shouldScanDirectory(e){return![`node_modules`,`.git`,`dist`,`build`,`__tests__`,`test`,`tests`,`coverage`].includes(e)&&!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)}async detectHttpMethods(e){let t=i.join(this.appDir,e),n=await r.readFile(t,`utf-8`),a=[];for(let e of u){let t=RegExp(`export\\s+(?:async\\s+)?function\\s+${e}\\s*\\(`),r=RegExp(`export\\s+(?:async\\s+)?(?:const|let|var)\\s+${e}\\s*=`);(t.test(n)||r.test(n))&&a.push(e)}return a}async processApiRouteFile(e,t){let n=i.join(e,t),r=this.pathToRoute(e),a=this.parseRouteSegments(e),o=this.extractParams(a),s=await this.detectHttpMethods(n);return{path:r,filePath:n,segments:a,params:o,isDynamic:o.length>0,methods:s}}};async function f(e,t={}){return new d({appDir:e,...t}).generateManifest()}export{a as n,f as t};
|