RSC Builder (generate-static-rsc.js)
Examine single-route React Server Component serialization, Flight stream buffering, and validation controls.
Key File Location: ./dinou/core/generate-static-rsc.js💡 Overview
To support Incremental Static Regeneration (ISR) and Dynamic Pre-rendering (ISG), Dinou needs to compile individual routes on demand. The generate-static-rsc.js utility handles this by serializing React Server Components (RSC) into Flight payloads (rsc.rsc) for a single path.
📊 RSC Serialization Flow
The flowchart below traces the steps executed during single-route RSC serialization:
⚡ Double-Buffered Compiling
To prevent serving broken payloads during an active compilation pass, the builder implements a double-buffering pattern:
- Temporary Writes: Outputs the serialized stream into a temporary file name containing a timestamp and random float hash.
- Safe Verification: Validates the response status code. If compilation fails (e.g. status
500), it deletes the temp file and exits without committing. - Decoupled Renames: The final rename commit is left to the calling engines (like
revalidatingorgenerating-isg), which use atomic OS rename calls to overwrite the active cache with zero downtime.
⚙️ Complete Code Walkthrough
Below is the full code of generate-static-rsc.js:
const fs = require("fs");
const path = require("path");
const { PassThrough } = require("stream");
const url = require("url");
const getJSX = require("./get-jsx.js");
const isWebpack = process.env.DINOU_BUILD_TOOL === "webpack";
const { renderToPipeableStream } = isWebpack
? require("react-server-dom-webpack/server")
: require("@roggc/react-server-dom-esm/server");
const { requestStorage } = require("./request-context.js");
const OUT_DIR = path.resolve("dist2");
async function generateStaticRSC(reqPath) {
const finalReqPath = reqPath.endsWith("/") ? reqPath : reqPath + "/";
const payloadPath = path.join(OUT_DIR, finalReqPath, "rsc.rsc");
// 1. Create temporary file path with timestamp & random token to prevent collision
const tempPayloadPath = path.join(OUT_DIR, finalReqPath, `rsc.rsc.${Date.now()}-${Math.random()}.tmp`);
// 2. Setup mock response with status tracking
const mockRes = {
_statusCode: 200,
_headers: {},
_redirectUrl: null,
_cookies: [],
cookie(name, value, options) {
this._cookies.push({ name, value, options });
},
clearCookie(name, options) {},
setHeader(name, value) {
this._headers[name.toLowerCase()] = value;
},
status(code) {
this._statusCode = code;
},
redirect(arg1, arg2) {
let status = 302;
let url = "";
if (typeof arg1 === "number") {
status = arg1;
url = arg2;
} else {
url = arg1;
}
this._statusCode = status;
this._redirectUrl = url;
console.warn(`⚠️ [ISR] Redirect detected during RSC generation of ${reqPath} -> ${url} (${status})`);
},
};
const mockContext = {
req: {
query: {},
cookies: {},
headers: {
"user-agent": "Dinou-ISR-Revalidator",
host: "localhost",
"x-forwarded-proto": "http",
},
path: finalReqPath,
method: "GET",
},
res: mockRes,
};
try {
// 3. Load React Client Manifest
const manifest = JSON.parse(
fs.readFileSync(
path.resolve(
isWebpack
? "dist3/react-client-manifest.json"
: "react_client_manifest/react-client-manifest.json"
),
"utf8"
)
);
fs.mkdirSync(path.dirname(payloadPath), { recursive: true });
const fileStream = fs.createWriteStream(tempPayloadPath);
const passThrough = new PassThrough();
// 4. Run components inside Context Store
await requestStorage.run(mockContext, async () => {
const jsx = await getJSX(finalReqPath, {}, null, false);
const { pipe } = isWebpack
? renderToPipeableStream(jsx, manifest)
: renderToPipeableStream(jsx, url.pathToFileURL(process.cwd()).href + "/");
pipe(passThrough);
passThrough.pipe(fileStream);
// Wait for the stream write to complete
await new Promise((resolve, reject) => {
fileStream.on("finish", resolve);
fileStream.on("error", reject);
passThrough.on("error", reject);
});
});
const success = mockRes._statusCode !== 500;
// 5. Return validation object - do NOT overwrite target file yet!
return {
success,
type: "rsc",
reqPath: finalReqPath,
tempPath: tempPayloadPath,
finalPath: payloadPath,
status: mockRes._statusCode,
};
} catch (error) {
console.error("❌ Error generating RSC payload:", error);
if (fs.existsSync(tempPayloadPath)) fs.unlinkSync(tempPayloadPath);
return { success: false, tempPath: tempPayloadPath };
}
}
module.exports = generateStaticRSC;