- Server functions can return not_found: true to render the 404 page with status 404. - Page components and window.__PAGE_PROPS__ (and HMR updates) only get props, query, url and error. response_options, redirect, cache settings and res_transform stay on the server, so cookies and private headers no longer end up in the HTML. BunextPageProps is narrowed to match (breaking for code that read server-only fields from component props). - response_options headers go through a Headers object, so repeated headers such as several Set-Cookie survive. - Redirects: status_code wins over permanent; response_options headers and res_transform apply to redirects too. - Gzip for compressible text responses; compress: false to turn it off. - Files the router matches but never bundles (.server.ts, __root, excluded paths and directories) return 404 instead of looping through dev rebuild retries. - Missing public files return 404 rather than 403, so dotted page paths like /users/john.doe fall through to pages again. - importFresh detects rewrites within the filesystem's mtime granularity. - README: self-hosted React (not esm.sh), snake_case option names, static file serving, cache headers, the new options. Co-Authored-By: Claude Opus 5.5 <[email protected]>
282 lines
8.7 KiB
TypeScript
282 lines
8.7 KiB
TypeScript
import grabContants from "../../../utils/grab-constants";
|
|
import serializeForScript from "../../../utils/serialize-for-script";
|
|
import type { LivePageDistGenParams } from "../../../types";
|
|
import isDevelopment from "../../../utils/is-development";
|
|
import grabWebPageHydrationScript from "./grab-web-page-hydration-script";
|
|
import grabWebMetaHTML from "./grab-web-meta-html";
|
|
import { log } from "../../../utils/log";
|
|
import { AppData } from "../../../data/app-data";
|
|
import _ from "lodash";
|
|
import grabDirNames from "../../../utils/grab-dir-names";
|
|
import { NoSEORobotsValue } from "../../../utils/disable-seo";
|
|
import grabClientPageProps from "../../../utils/grab-client-page-props";
|
|
|
|
const { ROOT_DIR } = grabDirNames();
|
|
|
|
export default async function genWebHTML({
|
|
component: Main,
|
|
pageProps,
|
|
bundledMap,
|
|
module,
|
|
routeParams,
|
|
debug,
|
|
root_module,
|
|
}: LivePageDistGenParams) {
|
|
const { ClientRootElementIDName, ClientWindowPagePropsName } =
|
|
grabContants();
|
|
|
|
const { renderToReadableStream } = await import(
|
|
`${ROOT_DIR}/node_modules/react-dom/server.js`
|
|
);
|
|
|
|
const is_dev = isDevelopment();
|
|
|
|
if (debug) {
|
|
log.info("component", Main);
|
|
}
|
|
|
|
if (!Main) {
|
|
throw new Error(`Main Component not found!`);
|
|
}
|
|
|
|
// Only the client-safe part reaches the components and the HTML;
|
|
// response_options (headers, cookies) etc. stay on the server. Head and
|
|
// meta still get the full server result: they only render here.
|
|
const client_props = grabClientPageProps(pageProps);
|
|
|
|
let serializedProps = "{}";
|
|
|
|
try {
|
|
serializedProps = serializeForScript(client_props);
|
|
} catch (error) {}
|
|
|
|
const page_hydration_script = await grabWebPageHydrationScript();
|
|
const root_meta = root_module?.meta
|
|
? typeof root_module.meta == "function" && routeParams
|
|
? await root_module.meta({ ctx: routeParams, serverRes: pageProps })
|
|
: typeof root_module.meta == "function"
|
|
? undefined
|
|
: root_module.meta
|
|
: undefined;
|
|
const page_meta = module?.meta
|
|
? typeof module.meta == "function" && routeParams
|
|
? await module.meta({ ctx: routeParams, serverRes: pageProps })
|
|
: typeof module.meta == "function"
|
|
? undefined
|
|
: module.meta
|
|
: undefined;
|
|
|
|
const html_props = {
|
|
...module?.html_props,
|
|
...root_module?.html_props,
|
|
};
|
|
|
|
const Head = module?.Head;
|
|
const RootHead = root_module?.Head;
|
|
|
|
const dev = isDevelopment();
|
|
|
|
const final_meta = global.BUNEXT_CONFIG.disable_seo
|
|
? { ..._.merge(root_meta, page_meta), robots: NoSEORobotsValue }
|
|
: _.merge(root_meta, page_meta);
|
|
|
|
const public_envs = Object.fromEntries(
|
|
Object.entries(process.env).filter(([k]) =>
|
|
k.startsWith("BUNEXT_PUBLIC_"),
|
|
),
|
|
);
|
|
|
|
const client_process = {
|
|
env: {
|
|
NODE_ENV: dev ? "development" : "production",
|
|
...public_envs,
|
|
...global.BUNEXT_CONFIG.public_envs,
|
|
},
|
|
};
|
|
|
|
let final_component = (
|
|
<html {...html_props}>
|
|
<head>
|
|
<meta charSet="utf-8" data-bunext-head />
|
|
<meta
|
|
name="viewport"
|
|
content="width=device-width, initial-scale=1.0"
|
|
data-bunext-head
|
|
/>
|
|
|
|
{final_meta ? grabWebMetaHTML({ meta: final_meta }) : null}
|
|
|
|
{bundledMap?.css_path ? (
|
|
<link
|
|
rel="stylesheet"
|
|
href={`/${bundledMap.css_path}`}
|
|
data-bunext-head
|
|
/>
|
|
) : null}
|
|
|
|
<script
|
|
dangerouslySetInnerHTML={{
|
|
__html: `window.${ClientWindowPagePropsName} = ${serializedProps};\nwindow.process = ${serializeForScript(client_process)}`,
|
|
}}
|
|
data-bunext-head
|
|
/>
|
|
|
|
{RootHead ? (
|
|
<RootHead serverRes={pageProps} ctx={routeParams} />
|
|
) : null}
|
|
{Head ? <Head serverRes={pageProps} ctx={routeParams} /> : null}
|
|
|
|
{bundledMap?.path ? (
|
|
<>
|
|
<script
|
|
type="importmap"
|
|
dangerouslySetInnerHTML={{
|
|
__html: serializeForScript(
|
|
global.BUNEXT_REACT_IMPORTS_MAP,
|
|
),
|
|
}}
|
|
defer
|
|
data-bunext-head
|
|
/>
|
|
<script
|
|
src={`/${bundledMap.path}`}
|
|
type="module"
|
|
id={AppData["BunextClientHydrationScriptID"]}
|
|
defer
|
|
data-bunext-head
|
|
/>
|
|
</>
|
|
) : null}
|
|
|
|
{is_dev ? (
|
|
<script
|
|
defer
|
|
dangerouslySetInnerHTML={{
|
|
__html: page_hydration_script,
|
|
}}
|
|
data-bunext-head
|
|
/>
|
|
) : null}
|
|
</head>
|
|
<body>
|
|
<div
|
|
id={ClientRootElementIDName}
|
|
suppressHydrationWarning={!dev}
|
|
>
|
|
<Main {...client_props} />
|
|
</div>
|
|
</body>
|
|
</html>
|
|
);
|
|
|
|
let html = `<!DOCTYPE html>\n`;
|
|
|
|
// const stream = await renderToReadableStream(final_component, {
|
|
// onError(error: any) {
|
|
// if (error.message.includes('unique "key" prop')) return;
|
|
// console.error(error);
|
|
// },
|
|
// });
|
|
|
|
// const htmlBody = await new Response(stream).text();
|
|
|
|
silenceConsole();
|
|
|
|
let htmlBody: string;
|
|
let render_error: any;
|
|
let has_render_error = false;
|
|
|
|
const render_timeout_ms =
|
|
global.BUNEXT_CONFIG.ssr_render_timeout_ms ||
|
|
AppData["DefaultSSRRenderTimeoutMs"];
|
|
|
|
// Without a deadline, a Suspense boundary that never settles keeps the
|
|
// request (and its whole render tree) alive forever. The timer is
|
|
// cleared once the render ends so finished requests don't linger.
|
|
const render_abort = new AbortController();
|
|
const render_timeout = setTimeout(
|
|
() =>
|
|
render_abort.abort(
|
|
new RenderTimeoutError(
|
|
`Page render timed out after ${render_timeout_ms}ms`,
|
|
),
|
|
),
|
|
render_timeout_ms,
|
|
);
|
|
|
|
try {
|
|
const stream = await renderToReadableStream(final_component, {
|
|
signal: render_abort.signal,
|
|
onError(error: any) {
|
|
if (error?.message?.includes('unique "key" prop')) return;
|
|
|
|
if (!has_render_error) {
|
|
has_render_error = true;
|
|
render_error = error;
|
|
}
|
|
|
|
// A timeout has no useful stack; it's logged upstream.
|
|
if (!(error instanceof RenderTimeoutError)) {
|
|
original_console.error(error);
|
|
}
|
|
},
|
|
});
|
|
|
|
htmlBody = await new Response(stream).text();
|
|
} finally {
|
|
clearTimeout(render_timeout);
|
|
restoreConsole();
|
|
}
|
|
|
|
// A component crash during SSR must surface as a proper error (handled
|
|
// upstream as a 500 page). React only reports these to `onError`; without
|
|
// rethrowing, the user gets a 200 with broken/blank markup.
|
|
if (has_render_error) {
|
|
throw render_error;
|
|
}
|
|
|
|
html += htmlBody;
|
|
|
|
return html;
|
|
}
|
|
|
|
class RenderTimeoutError extends Error {}
|
|
|
|
let original_console: Pick<
|
|
Console,
|
|
"log" | "warn" | "error" | "info" | "debug"
|
|
> = console;
|
|
|
|
let silenced_renders = 0;
|
|
|
|
/**
|
|
* Renders can overlap (each one awaits the stream), so the console is
|
|
* swapped only by the first active render and restored by the last one.
|
|
* Otherwise a render could save another render's no-ops as the "original"
|
|
* console and silence the server for good.
|
|
*/
|
|
function silenceConsole() {
|
|
if (silenced_renders++ > 0) return;
|
|
|
|
original_console = {
|
|
log: console.log,
|
|
warn: console.warn,
|
|
error: console.error,
|
|
info: console.info,
|
|
debug: console.debug,
|
|
};
|
|
|
|
console.log = () => {};
|
|
console.warn = () => {};
|
|
console.error = () => {};
|
|
console.info = () => {};
|
|
console.debug = () => {};
|
|
}
|
|
|
|
function restoreConsole() {
|
|
if (--silenced_renders > 0) return;
|
|
|
|
silenced_renders = 0;
|
|
Object.assign(console, original_console);
|
|
}
|