Bugfix: Refactor SSR bundler. Fix stale cache SSR modules.

This commit is contained in:
2026-04-09 23:50:58 +01:00
parent 40fc7778a8
commit 7fb1784b95
28 changed files with 434 additions and 85 deletions
@@ -5,6 +5,7 @@ type Params = {
entryToPage: Map<string, PageFiles & {
tsx: string;
}>;
virtual_match?: string;
};
export default function grabArtifactsFromBundledResults({ result, entryToPage, }: Params): BundlerCTXMap[] | undefined;
export default function grabArtifactsFromBundledResults({ result, entryToPage, virtual_match, }: Params): BundlerCTXMap[] | undefined;
export {};
@@ -3,19 +3,18 @@ import * as esbuild from "esbuild";
import grabDirNames from "../../utils/grab-dir-names";
import { log } from "../../utils/log";
const { ROOT_DIR } = grabDirNames();
export default function grabArtifactsFromBundledResults({ result, entryToPage, }) {
export default function grabArtifactsFromBundledResults({ result, entryToPage, virtual_match = "hydration-virtual", }) {
if (result.errors.length > 0)
return;
const virtual_regex = new RegExp(`^${virtual_match}:`);
const artifacts = Object.entries(result.metafile.outputs)
.filter(([, meta]) => meta.entryPoint)
.map(([outputPath, meta]) => {
const entrypoint = meta.entryPoint?.match(/^hydration-virtual:/)
? meta.entryPoint?.replace(/^hydration-virtual:/, "")
const entrypoint = meta.entryPoint?.match(virtual_regex)
? meta.entryPoint?.replace(virtual_regex, "")
: meta.entryPoint
? path.join(ROOT_DIR, meta.entryPoint)
: "";
// const entrypoint = path.join(ROOT_DIR, meta.entryPoint || "");
// console.log("entrypoint", entrypoint);
const target_page = entryToPage.get(entrypoint);
if (!target_page || !meta.entryPoint) {
return undefined;
+7
View File
@@ -0,0 +1,7 @@
type Params = {
post_build_fn?: (params: {
artifacts: any[];
}) => Promise<void> | void;
};
export default function pagesSSRContextBundler(params?: Params): Promise<void>;
export {};
+63
View File
@@ -0,0 +1,63 @@
import * as esbuild from "esbuild";
import grabAllPages from "../../utils/grab-all-pages";
import grabDirNames from "../../utils/grab-dir-names";
import isDevelopment from "../../utils/is-development";
import tailwindEsbuildPlugin from "../server/web-pages/tailwind-esbuild-plugin";
import grabPageReactComponentString from "../server/web-pages/grab-page-react-component-string";
import grabRootFilePath from "../server/web-pages/grab-root-file-path";
import ssrVirtualFilesPlugin from "./plugins/ssr-virtual-files-plugin";
import ssrCTXArtifactTracker from "./plugins/ssr-ctx-artifact-tracker";
const { BUNX_CWD_MODULE_CACHE_DIR } = grabDirNames();
export default async function pagesSSRContextBundler(params) {
const pages = grabAllPages({ exclude_api: true });
const dev = isDevelopment();
if (global.SSR_BUNDLER_CTX) {
await global.SSR_BUNDLER_CTX.dispose();
global.SSR_BUNDLER_CTX = undefined;
}
const entryToPage = new Map();
const { root_file_path } = grabRootFilePath();
for (const page of pages) {
const tsx = grabPageReactComponentString({
file_path: page.local_path,
root_file_path,
});
if (!tsx)
continue;
entryToPage.set(page.local_path, { ...page, tsx });
}
const entryPoints = [...entryToPage.keys()].map((e) => `ssr-virtual:${e}`);
global.SSR_BUNDLER_CTX = await esbuild.context({
entryPoints,
outdir: BUNX_CWD_MODULE_CACHE_DIR,
bundle: true,
minify: !dev,
format: "esm",
target: "es2020",
platform: "node",
define: {
"process.env.NODE_ENV": JSON.stringify(dev ? "development" : "production"),
},
entryNames: "[dir]/[hash]",
metafile: true,
plugins: [
tailwindEsbuildPlugin,
ssrVirtualFilesPlugin({
entryToPage,
}),
ssrCTXArtifactTracker({
entryToPage,
post_build_fn: params?.post_build_fn,
}),
],
jsx: "automatic",
external: [
"react",
"react-dom",
"react/jsx-runtime",
"react/jsx-dev-runtime",
],
logLevel: "silent",
});
await global.SSR_BUNDLER_CTX.rebuild();
}
@@ -1,6 +1,7 @@
import {} from "esbuild";
import { log } from "../../../utils/log";
import grabArtifactsFromBundledResults from "../grab-artifacts-from-bundled-result";
import pagesSSRContextBundler from "../pages-ssr-context-bundler";
let buildStart = 0;
let build_starts = 0;
const MAX_BUILD_STARTS = 2;
@@ -17,6 +18,8 @@ export default function esbuildCTXArtifactTracker({ entryToPage, post_build_fn,
global.BUNDLER_CTX_DISPOSED = true;
global.RECOMPILING = false;
global.IS_SERVER_COMPONENT = false;
await global.SSR_BUNDLER_CTX?.dispose();
global.SSR_BUNDLER_CTX = undefined;
await global.BUNDLER_CTX?.dispose();
global.BUNDLER_CTX = undefined;
}
@@ -60,16 +63,18 @@ export default function esbuildCTXArtifactTracker({ entryToPage, post_build_fn,
}
}
post_build_fn?.({ artifacts });
// writeFileSync(
// HYDRATION_DST_DIR_MAP_JSON_FILE,
// JSON.stringify(artifacts, null, 4),
// );
}
const elapsed = (performance.now() - buildStart).toFixed(0);
log.success(`[Built] in ${elapsed}ms`);
global.RECOMPILING = false;
global.IS_SERVER_COMPONENT = false;
build_starts = 0;
if (global.SSR_BUNDLER_CTX) {
global.SSR_BUNDLER_CTX.rebuild();
}
else {
pagesSSRContextBundler();
}
});
},
};
@@ -0,0 +1,12 @@
import { type Plugin } from "esbuild";
import type { PageFiles } from "../../../types";
type Params = {
entryToPage: Map<string, PageFiles & {
tsx: string;
}>;
post_build_fn?: (params: {
artifacts: any[];
}) => Promise<void> | void;
};
export default function ssrCTXArtifactTracker({ entryToPage, post_build_fn, }: Params): Plugin;
export {};
@@ -0,0 +1,43 @@
import {} from "esbuild";
import { log } from "../../../utils/log";
import grabArtifactsFromBundledResults from "../grab-artifacts-from-bundled-result";
let buildStart = 0;
let build_starts = 0;
const MAX_BUILD_STARTS = 2;
export default function ssrCTXArtifactTracker({ entryToPage, post_build_fn, }) {
const artifactTracker = {
name: "ssr-artifact-tracker",
setup(build) {
build.onStart(async () => {
build_starts++;
buildStart = performance.now();
if (build_starts == MAX_BUILD_STARTS) {
// const error_msg = `SSR Build Failed. Please check all your components and imports.`;
// log.error(error_msg);
}
});
build.onEnd((result) => {
if (result.errors.length > 0) {
return;
}
const artifacts = grabArtifactsFromBundledResults({
result,
entryToPage,
virtual_match: `ssr-virtual`,
});
if (artifacts?.[0] && artifacts.length > 0) {
for (let i = 0; i < artifacts.length; i++) {
const artifact = artifacts[i];
if (artifact?.local_path &&
global.SSR_BUNDLER_CTX_MAP) {
global.SSR_BUNDLER_CTX_MAP[artifact.local_path] =
artifact;
}
}
post_build_fn?.({ artifacts });
}
});
},
};
return artifactTracker;
}
@@ -0,0 +1,9 @@
import type { Plugin } from "esbuild";
import type { PageFiles } from "../../../types";
type Params = {
entryToPage: Map<string, PageFiles & {
tsx: string;
}>;
};
export default function ssrVirtualFilesPlugin({ entryToPage }: Params): Plugin;
export {};
@@ -0,0 +1,28 @@
import path from "path";
import { log } from "../../../utils/log";
export default function ssrVirtualFilesPlugin({ entryToPage }) {
const virtualPlugin = {
name: "ssr-virtual-hydration",
setup(build) {
build.onResolve({ filter: /^ssr-virtual:/ }, (args) => {
const final_path = args.path.replace(/ssr-virtual:/, "");
return {
path: final_path,
namespace: "ssr-virtual",
};
});
build.onLoad({ filter: /.*/, namespace: "ssr-virtual" }, (args) => {
const target = entryToPage.get(args.path);
if (!target?.tsx)
return null;
const contents = target.tsx;
return {
contents: contents || "",
loader: "tsx",
resolveDir: path.dirname(target.local_path),
};
});
},
};
return virtualPlugin;
}