Files
bunext/dist/functions/server/web-pages/grab-page-component.js
T
tbenandClaude Opus 5.5 96e392f556 1.4.0: not_found, server-only response options, compression
- 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]>
2026-11-09 04:14:56 +01:00

169 lines
6.7 KiB
JavaScript

import grabRouteParams from "../../../utils/grab-route-params";
import grabPageErrorComponent from "./grab-page-error-component";
import _ from "lodash";
import { log } from "../../../utils/log";
import grabPageModules from "./grab-page-modules";
import grabPageCombinedServerRes from "./grab-page-combined-server-res";
import fullRebuild from "../full-rebuild";
import serverPostBuildFn from "../server-post-build-fn";
import isDevelopment from "../../../utils/is-development";
import { existsSync } from "fs";
import grabDirNames from "../../../utils/grab-dir-names";
import grabRelativePath from "../../../utils/grab-relative-path";
import { logBuildErrorsOnce } from "../../../utils/build-error-log";
import { RequestBodyTooLargeError } from "../../../utils/read-request-body";
import NotFoundError from "../../../utils/not-found-error";
import isRoutablePage from "../../../utils/is-routable-page";
const { ROOT_DIR } = grabDirNames();
export default async function grabPageComponent(params) {
const { BUNX_BUNDLER_ERROR_EXIT_FILE } = grabDirNames();
const { req, file_path: passed_file_path, debug, return_server_res_only, skip_server_res, is_hydration, no_retry, } = params;
const url = req?.url ? new URL(req.url) : undefined;
const router = global.BUNEXT_ROUTER;
const is_dev = isDevelopment();
const forwarded_proto = global.BUNEXT_CONFIG?.trust_proxy
? req?.headers.get("x-forwarded-proto")?.split(",")[0]?.trim()
: undefined;
if (url && (forwarded_proto == "http" || forwarded_proto == "https")) {
url.protocol = forwarded_proto;
}
let routeParams = undefined;
const does_error_file_exist = existsSync(BUNX_BUNDLER_ERROR_EXIT_FILE);
try {
routeParams = req ? await grabRouteParams({ req }) : undefined;
let url_path = url ? url.pathname : undefined;
if (url_path && url?.search) {
url_path += url.search;
}
if (debug) {
log.info(`url_path:`, url_path);
}
const match = url_path ? router.match(url_path) : undefined;
if (!match?.filePath && url?.pathname) {
throw new NotFoundError(`Page ${url.pathname} not found`);
}
// The router also matches files that are never bundled (.server.ts
// companions, __root, excluded paths). Without this they would sit
// in the dev rebuild/retry loop and never respond.
if (match?.filePath && !isRoutablePage(match.filePath)) {
throw new NotFoundError(`Page ${url?.pathname} not found`);
}
const file_path = match?.filePath || passed_file_path;
if (debug) {
log.info(`file_path:`, file_path);
}
if (!file_path) {
const errMsg = `No File Path (\`file_path\`) or Request Object (\`req\`) provided not found`;
// log.error(errMsg);
throw new Error(errMsg);
}
const relative_file_path = grabRelativePath(file_path);
let bundledMap = global.BUNEXT_BUNDLER_CTX_MAP[relative_file_path];
if (!bundledMap?.path) {
if (does_error_file_exist) {
throw new Error(`Application Error. Please Check your components. ${match?.filePath} likely exists but has no exported module.`);
}
let retries = 0;
const MAX_RETRIES = 2;
// Only retry transient failures: if the last rebuild failed
// (BUNEXT_BUILD_FAILED), the file is broken and more rebuilds
// will just repeat the same error.
while (retries < MAX_RETRIES && !global.BUNEXT_BUILD_FAILED) {
await fullRebuild({
msg: `Retrying Bundle map for file \`${relative_file_path}\``,
});
await Bun.sleep(1000);
bundledMap = global.BUNEXT_BUNDLER_CTX_MAP[relative_file_path];
if (bundledMap?.path)
break;
retries++;
}
if (!bundledMap?.path) {
const errMsg = `No Bundled File Path for this request path!`;
throw new Error(errMsg);
}
}
if (debug) {
log.info(`bundledMap:`, bundledMap);
}
if (return_server_res_only) {
const { serverRes } = await grabPageCombinedServerRes({
file_path,
debug,
query: match?.query,
routeParams,
url,
});
return { serverRes };
}
const page_modules = await grabPageModules({
file_path,
debug,
query: match?.query,
routeParams,
url,
skip_server_res,
});
if (page_modules instanceof Response) {
return page_modules;
}
const { component, module, serverRes, root_module } = page_modules;
return {
component,
serverRes,
routeParams,
module,
bundledMap,
root_module,
success: true,
};
}
catch (error) {
if (error instanceof RequestBodyTooLargeError) {
return new Response("Request Body Too Large", { status: 413 });
}
const is404 = error instanceof NotFoundError ||
error?.name === "NotFoundError" ||
error?.status === 404;
if (!params.retry && !params.no_retry && is_dev && !is404) {
while (!global.BUNEXT_BUILD_FAILED &&
global.BUNEXT_REBUILD_RETRIES < 2) {
global.BUNEXT_REBUILD_RETRIES =
global.BUNEXT_REBUILD_RETRIES + 1;
await fullRebuild();
await Bun.sleep(200);
const component_retried = await grabPageComponent({
...params,
retry: true,
});
if (component_retried instanceof Response ||
component_retried.success) {
global.BUNEXT_REBUILD_RETRIES = 0;
await serverPostBuildFn();
return component_retried;
}
}
global.BUNEXT_REBUILD_RETRIES = 0;
}
if (is404) {
global.BUNEXT_IS_404_PAGE = true;
}
else {
logBuildErrorsOnce([
{
text: `Error Grabbing Page Component: ${error.message}; Page: ${passed_file_path || url?.pathname}`,
},
], (line) => log.error(line));
if (is_dev && !params.no_retry && !global.BUNEXT_BUILD_FAILED) {
fullRebuild();
}
}
return await grabPageErrorComponent({
error,
routeParams,
is404,
url,
});
}
}