Dinou Architecture & Runtime Engine
Comprehensive architectural specification of Dinou v7: the 0-Fork Ahead-of-Time (AOT) Dual-Bundle Pipeline, Horizontal & Vertical Layered Segmentation, Partial Prerendering (PPR), React 19 resilience primitives, and universal multi-runtime deployment across Node.js, Bun, Deno, and Edge Isolates.
1. Architectural Paradigm & High-Level Blueprint
Dinou v7 is engineered around a single foundational philosophy: Universal React 19 Portability without Platform Lock-in. While early React Server Components (RSC) implementations relied heavily on proprietary serverless hosting environments or heavy, dual-process Node.js architectures (spawning child_process.fork()), Dinou v7 introduces a universal, 0-fork in-memory Dual-Bundle engine based strictly on standard W3C Web primitives (Request, Response, and ReadableStream).
The exact same compiled application runs without modification across Node.js, Bun, Deno, Cloudflare Workers, Netlify Functions v2, self-contained single-binary executables, or 100% static hosting (GitHub Pages, AWS S3).
| Architectural Dimension | Legacy Meta-Frameworks (v6) | Dinou v7 Architecture |
|---|---|---|
| Process Architecture | 2 separate OS processes via child_process.fork() (Parent CJS + Child ESM) with pipe serialization. | 0-Fork AOT Dual-Bundle in the same OS process via W3C ReadableStream memory pipes. |
| Runtime Portability | Node.js only (due to child_process and Express API dependencies). | Universal (W3C Fetch): Node.js, Bun, Deno, Cloudflare Workers, Netlify Functions, Standalone Exe. |
| Layout Lifecycle | Monolithic route payload. Navigating between sibling routes re-mounted the layout and destroyed UI state. | Horizontal Segmentation: Layouts never re-render on sibling navigations. 100% state preserved. |
| Component Micro-Caching | Whole-page caching only. | Vertical Segmentation (<DinouCacheSlot>): Micro-ISR of individual Server Components + live client refresh. |
| Pre-Rendering Timing | Executed at server startup (dinou start), causing slow, blocked boot times in production. | Executed strictly during dinou build. Production server boots instantaneously. |
| Dev Server Storage | Continuously writes chunks and manifests to disk in .dinou/public/ (high disk I/O on Windows). | 100% In-Memory (__DINOU_MEM_FILES__) with <0.5ms asset response times. |
2. 0-Fork Dual-Bundle Compilation Pipeline
2.1. The React 19 Dual Condition Conflict
React 19 imposes a strict module-resolution constraint: Server Components must be imported under the "react-server" export condition (which disables client-only hooks such as useState and useEffect, as well as react-dom/server). Conversely, SSR rendering requires client conditions ("browser" or react-dom/server.edge).
Importing both engines within the same unisolated module graph throws a fatal runtime panic:
Earlier meta-frameworks circumvented this in Node.js by spawning an external child process via child_process.fork(). However, this introduced process serialization latency, doubled server memory consumption, and made deployment to Edge runtimes (Cloudflare Workers, Deno Deploy) impossible because Edge V8 isolates do not support spawning OS processes.
2.2. The 3-Pass Compilation Model (Pass A, Pass B, Pass C)
Dinou v7 resolves this conflict Ahead-of-Time (AOT) through an isolated, in-memory 3-pass compilation pipeline:
Bundled with ["react-server"] conditions. Replaces Client Components ("use client") with client reference descriptors via createClientModuleProxy. Binds Server Functions ("use server") and generates the RSC Flight stream.
Bundled with ["browser"] client conditions. Packages react-dom/server.edge (renderToReadableStream) and client manifests containing the physical component implementations needed to produce static HTML and client hydration.
Connects Pass A and Pass B in memory using standard W3C ReadableStream pipes. In Edge and Serverless runtimes, Pass C serves as the single unified fetch entry point, executing with zero OS-level serialization overhead.
2.3. In-Memory Dev Server & SWC Disk-Mirror
During development, Dinou v7 stores all generated chunks, manifests, sourcemaps, and CSS in a global in-memory buffer:
globalThis.__DINOU_MEM_FILES__Assets are served directly from RAM with response latencies under 0.5ms. This eliminates Windows antivirus real-time indexing contention and prevents drive wear. If you need physical files on disk for external proxies or inspection tools, start the server with DINOU_WRITE_TO_DISK=true npm run dev.
SWC Disk-Mirror Architecture for Massive Projects:
In large-scale codebases with hundreds of routes, running JavaScript-based transforms on every file over esbuild Go-to-Node IPC creates bottlenecks. Dinou mirrors modified files into .dinou/swc/ using Rust-based SWC in ~5ms. esbuild reads them with native Go loaders, preserving the in-memory AST cache and slashing incremental rebuild times by nearly 4x.
3. Horizontal Segmentation: Layout & Page Decoupling
In monolithic SSR architectures, every navigation request forces the server to evaluate and serialize both the layout and the target page together. Navigating between sibling routes inevitably forces the client to tear down and recreate the layout DOM tree.
Dinou v7 introduces Horizontal Segmentation, decomposing the route hierarchy into two independent execution planes:
3.1. 100% State Preservation & Zero Remounts
Horizontal segmentation guarantees that layout components never unmount or re-execute during client-side navigation between sibling routes:
- Active media playback: Audio and video players embedded in the layout continue playing seamlessly with 0 interruption.
- Form & filter states: Sidebar filters, search queries, and collapsible menus retain their exact state.
- Scroll position: Layout-level containers maintain their scroll coordinates across page transitions.
3.2. layout_functions for Independent Layout ISR
Layouts can declare their own independent caching, validation, and metadata lifecycle using layout_functions.ts (or named exports in layout.tsx):
// src/dashboard/layout_functions.ts
// ⚡ Cache the layout shell for 1 hour independently of child pages:
export const revalidate = 3600;
// Assign tags for granular invalidation:
export const tags = ["dashboard-shell", "user-nav"];
export async function validateParams(params) {
// Validate route parameters before evaluating layout
return true;
}This separation means that a child page with live SSR (revalidate = 0) can be rendered inside a layout shell that is cached statically or regenerated every hour.
4. Surgical Invalidation: revalidatePage vs revalidatePath
Because Dinou v7 decouples layouts from leaf pages, it introduces surgical invalidation control through two dedicated server APIs in "dinou/server":
revalidatePage(path) (New in v7)Surgically revalidates strictly the leaf page (page.rsc and index.html). Leaves the parent layout (layout.rsc) completely untouched in cache.
revalidatePath(path, options?)Revalidates both the page and the layout at the given route path. When { cascade: true } is provided, invalidation propagates downward across all nested child pages.
// Inside a Server Function ("use server") or CMS Webhook
import { revalidatePage, revalidatePath } from "dinou/server";
export async function publishArticle(slug: string) {
await db.articles.update({ where: { slug }, data: { status: "published" } });
// 1. Surgical: Invalidate ONLY the single article page (0 layout re-render)
await revalidatePage(`/blog/${slug}`);
// 2. Full Tree Cascade: Invalidate the blog listing and all nested children
// await revalidatePath("/blog", { cascade: true });
}5. Vertical Segmentation: <DinouCacheSlot>
While Horizontal Segmentation decouples pages from layouts, Vertical Segmentation brings micro-caching directly inside individual components within a single page using <DinouCacheSlot>.
5.1. Micro-ISR of Server Components & SWR
Wrap expensive Server Components in a cache slot. Stale content is served instantly while an asynchronous background task (via waitUntil) evaluates the component and updates the cache in the active StorageAdapter:
// src/analytics/page.tsx
import { DinouCacheSlot } from "dinou/server";
export default function AnalyticsPage() {
return (
<div className="dashboard-grid">
<h1>Live Analytics</h1>
{/* Caches this heavy Server Component for 60 seconds */}
<DinouCacheSlot id="metrics-widget" tag="metrics-tag" revalidate={60}>
<ExpensiveMetricsGraph />
</DinouCacheSlot>
</div>
);
}5.2. In-Place Client Live Refresh (refreshSlot)
Every <DinouCacheSlot> is automatically wrapped in a DinouCacheSlotBoundary. Client Components can programmatically re-render a single slot in place by calling refreshSlot(id) from "dinou" without triggering a full page reload:
"use client";
import { refreshSlot } from "dinou";
export function LiveRefreshButton() {
return (
<button
onClick={() => refreshSlot("metrics-widget")}
className="btn-refresh"
>
Refresh Metrics Only
</button>
);
}When refreshSlot("metrics-widget") fires, the client requests /____rsc_slot____/metrics-widget directly from the server and reconciles only that DOM subtree.
6. Partial Prerendering (PPR) Engine
Partial Prerendering (PPR) bridges the divide between static site generation (0ms TTFB) and dynamic server-side rendering in a single HTTP response.
6.1. Static Prelude (0ms TTFB) & Streaming Dynamic Holes
// src/dashboard/page.tsx
import { Suspense } from "react";
import { getContext } from "dinou";
async function UserFeed() {
const ctx = getContext();
const user = ctx?.req?.cookies?.user || "Guest";
const data = await fetchFeedForUser(user);
return <FeedList items={data} />;
}
export default function DashboardPage() {
return (
<div>
{/* 🚀 Static Shell: Sent at 0ms TTFB */}
<header><h1>Dashboard</h1></header>
{/* ⚡ Dynamic Hole: Streamed and replaced on the fly */}
<Suspense fallback={<div className="skeleton">Loading feed...</div>}>
<UserFeed />
</Suspense>
</div>
);
}6.2. Configuration Hierarchy (Global, Layout, Page)
1. Global (dinou.config.mjs)
defineConfig({ ppr: true })2. Layout Scope
export const ppr = true;3. Page Override (Max Priority)
export const ppr = false;7. React 19 Resilience, Isolation & Error Boundaries
During multi-browser E2E testing across Windows, Linux, and Edge runtimes, three critical resilience challenges were identified in React 19 streaming and engineered directly into Dinou's core engine:
7.1. Elimination of HTML Double-Wrapping in Error SSR
When a route crashed during Server-Side Rendering, earlier implementations checked whether the root JSX was an <html> element. When an application layout was applied, the root was the layout function, prompting the server to blindly inject an emergency <html><body> shell outside the layout. This produced nested <html> tags, triggering fatal hydration mismatches in React 19.
Dinou v7 tracks layoutApplied in getErrorJSX. When an application layout is present, error JSX is injected directly into the layout's active content area. The document structure remains valid HTML, and interactive navigation elements (sidebars, headers) remain fully operational.
7.2. Handling SuspenseException with use()
In React 19, reading pending promises inside component bodies with use(errorPromise) intentionally throws an internal suspension signal (SuspenseException). If executed inside an eager JavaScript try / catch block, the catch intercepted this signal as if it were a fatal runtime crash, preventing custom error.tsx components from ever rendering.
Dinou v7 decouples SlotErrorRenderer from eager try / catch blocks and wraps it in a native React <Suspense fallback={null}> boundary. Once the error chunk resolves, React smoothly renders your custom error.tsx component with its error and reset props.
7.3. Two-Level Error Boundaries with Clean Navigation Reset
Earlier frameworks reset error boundaries on navigation by mutating <ErrorBoundary key={pathname}>. However, mutating key indiscriminately destroys and remounts the DOM on every healthy navigation, wiping form inputs and scroll positions.
Dinou v7 implements a Two-Level Error Boundary Architecture in dinou/core/slot.js:
┌────────────────────────────────────────────────────────┐
│ SlotErrorBoundary (Level 1 - State-Preserving Reset) │
│ - Healthy navigation: Key unchanged, state intact. │
│ - On error: Listens to resetKey & resets state. │
│ ┌──────────────────────────────────────────────────┐ │
│ │ InnerErrorBoundary (Level 2 - Error Guard) │ │
│ │ - Guards against bugs inside custom error.tsx │ │
│ │ ┌────────────────────────────────────────────┐ │ │
│ │ │ <Suspense fallback={null}> │ │ │
│ │ │ <SlotErrorRenderer /> (use(errorPromise)│ │ │
│ │ └────────────────────────────────────────────┘ │ │
│ └──────────────────────────────────────────────────┘ │
└────────────────────────────────────────────────────────┘- Level 1 (
SlotErrorBoundary): Preserves DOM and state on healthy navigations. Only whenhasError === truedoescomponentDidUpdatecheck the compound navigation key (resetKey: ${route}::${navCount}) to reset the error state cleanly. - Level 2 (
InnerErrorBoundary): Fail-safe guard that catches bugs or unhandled exceptions inside the developer's customerror.tsxcomponent, safely displayingDefaultDevErrorand preventing a white screen of death.
8. StorageAdapter & Multi-Runtime Edge Portability
Dinou v7 decouples cache storage and runtime operations via the StorageAdapter interface:
Stores pre-rendered HTML and RSC payloads on disk under .dinou/dist2/ with atomic writes.
Integrates with Cloudflare KV (DINOU_CACHE) for low-latency worldwide edge ISR.
Backed by Deno.openKv() for distributed, zero-configuration key-value caching.
Pure in-memory LRU cache for unit test suites and ephemeral serverless containers.
9. Multi-Bundler Parity (esbuild, Rollup, Webpack)
Dinou v7 treats bundlers as interchangeable compilation backends. You are never locked into a single bundler:
- esbuild (Default): Ultra-fast day-to-day development server and production builds.
- Rollup: Advanced chunk optimization, tree-shaking, and enterprise ESM output via
rollup-plugin-swc.js. - Webpack: Maximum enterprise compatibility with legacy Webpack loaders and plugins.
All three bundlers share 100% feature parity: RSC Flight stream generation, client directive splitting, server functions RPCs, CSS Modules, and Fast Refresh.
10. Universal Request Pipeline (onRequest & W3C Standards)
With the elimination of Express in Dinou v7, the entire middleware and plugin execution pipeline operates on standard W3C Request and Response primitives:
// dinou.config.mjs
import { defineConfig } from "dinou/config";
export default defineConfig({
ppr: true,
plugins: [
{
name: "auth-guard",
async onRequest(request, context) {
const url = new URL(request.url);
if (url.pathname.startsWith("/admin")) {
const token = request.headers.get("Authorization");
if (!token) {
return Response.redirect(new URL("/login", request.url), 302);
}
}
},
},
],
});