This commit is contained in:
2026-04-09 07:47:38 +01:00
parent ab6fc3be26
commit eb0721f94b
47 changed files with 826 additions and 136 deletions
+1 -1
View File
@@ -1,2 +1,2 @@
import type { LivePageDistGenParams } from "../../../types";
export default function genWebHTML({ component, pageProps, bundledMap, module, routeParams, debug, root_module, }: LivePageDistGenParams): Promise<string>;
export default function genWebHTML({ component: Main, pageProps, bundledMap, module, routeParams, debug, root_module, }: LivePageDistGenParams): Promise<string>;
+6 -3
View File
@@ -9,12 +9,15 @@ import { AppData } from "../../../data/app-data";
import _ from "lodash";
import grabDirNames from "../../../utils/grab-dir-names";
const { ROOT_DIR } = grabDirNames();
export default async function genWebHTML({ component, pageProps, bundledMap, module, routeParams, debug, root_module, }) {
export default async function genWebHTML({ component: Main, pageProps, bundledMap, module, routeParams, debug, root_module, }) {
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", component);
log.info("component", Main);
}
if (!Main) {
throw new Error(`Main Component not found!`);
}
const serializedProps = (EJSON.stringify(pageProps || {}) || "{}").replace(/<\//g, "<\\/");
const page_hydration_script = await grabWebPageHydrationScript();
@@ -46,7 +49,7 @@ export default async function genWebHTML({ component, pageProps, bundledMap, mod
__html: JSON.stringify(global.REACT_IMPORTS_MAP),
}, defer: true, "data-bunext-head": true }), _jsx("script", { src: `/${bundledMap.path}`, type: "module", id: AppData["BunextClientHydrationScriptID"], defer: true, "data-bunext-head": true })] })) : null, is_dev ? (_jsx("script", { defer: true, dangerouslySetInnerHTML: {
__html: page_hydration_script,
}, "data-bunext-head": true })) : null] }), _jsx("body", { children: _jsx("div", { id: ClientRootElementIDName, suppressHydrationWarning: !dev, children: component }) })] }));
}, "data-bunext-head": true })) : null] }), _jsx("body", { children: _jsx("div", { id: ClientRootElementIDName, suppressHydrationWarning: !dev, children: _jsx(Main, { ...pageProps }) }) })] }));
let html = `<!DOCTYPE html>\n`;
// const stream = await renderToReadableStream(final_component, {
// onError(error: any) {
@@ -1,8 +1,7 @@
import type { GrabPageReactBundledComponentRes } from "../../../types";
type Params = {
file_path: string;
root_file_path?: string;
server_res?: any;
return_tsx_only?: boolean;
};
export default function grabPageBundledReactComponent({ file_path, root_file_path, server_res, }: Params): Promise<GrabPageReactBundledComponentRes | undefined>;
export default function grabPageBundledReactComponent({ file_path, return_tsx_only, }: Params): Promise<GrabPageReactBundledComponentRes | undefined>;
export {};
@@ -1,23 +1,27 @@
import { jsx as _jsx } from "react/jsx-runtime";
import grabPageReactComponentString from "./grab-page-react-component-string";
import grabTsxStringModule from "./grab-tsx-string-module";
import { log } from "../../../utils/log";
export default async function grabPageBundledReactComponent({ file_path, root_file_path, server_res, }) {
import grabRootFilePath from "./grab-root-file-path";
export default async function grabPageBundledReactComponent({ file_path, return_tsx_only, }) {
try {
const { root_file_path } = grabRootFilePath();
let tsx = grabPageReactComponentString({
file_path,
root_file_path,
server_res,
});
if (!tsx) {
return undefined;
}
const mod = await grabTsxStringModule({ tsx });
if (return_tsx_only) {
return { tsx };
}
const mod = await grabTsxStringModule({
tsx,
page_file_path: file_path,
});
const Main = mod.default;
const component = _jsx(Main, {});
return {
component,
server_res,
component: Main,
tsx,
};
}
+2 -1
View File
@@ -4,6 +4,7 @@ type Params = {
file_path?: string;
debug?: boolean;
return_server_res_only?: boolean;
skip_server_res?: boolean;
};
export default function grabPageComponent({ req, file_path: passed_file_path, debug, return_server_res_only, }: Params): Promise<GrabPageComponentRes>;
export default function grabPageComponent({ req, file_path: passed_file_path, debug, return_server_res_only, skip_server_res, }: Params): Promise<GrabPageComponentRes>;
export {};
+3 -1
View File
@@ -11,7 +11,7 @@ class NotFoundError extends Error {
this.name = "NotFoundError";
}
}
export default async function grabPageComponent({ req, file_path: passed_file_path, debug, return_server_res_only, }) {
export default async function grabPageComponent({ req, file_path: passed_file_path, debug, return_server_res_only, skip_server_res, }) {
const url = req?.url ? new URL(req.url) : undefined;
const router = global.ROUTER;
let routeParams = undefined;
@@ -63,6 +63,7 @@ export default async function grabPageComponent({ req, file_path: passed_file_pa
query: match?.query,
routeParams,
url,
skip_server_res,
});
return {
component,
@@ -79,6 +80,7 @@ export default async function grabPageComponent({ req, file_path: passed_file_pa
error?.status === 404;
if (!is404) {
log.error(`Error Grabbing Page Component: ${error.message}`);
log.error(`Page: ${passed_file_path || url?.pathname}`);
}
return await grabPageErrorComponent({
error,
@@ -19,7 +19,9 @@ export default async function grabPageErrorComponent({ error, routeParams, is404
if (!match?.filePath) {
const default_module = await import(presetComponent);
const Component = default_module.default;
const default_jsx = (_jsx(Component, { children: _jsx("span", { children: error.message }) }));
const default_jsx = () => {
return _jsx(Component, { children: _jsx("span", { children: error.message }) });
};
return {
component: default_jsx,
module: default_module,
@@ -54,7 +56,7 @@ export default async function grabPageErrorComponent({ error, routeParams, is404
flexDirection: "column",
}, children: [_jsx("h1", { children: is404 ? "404 Not Found" : "500 Internal Server Error" }), _jsx("span", { children: error.message })] }));
return {
component: _jsx(DefaultNotFound, {}),
component: DefaultNotFound,
routeParams,
module: { default: DefaultNotFound },
serverRes: default_server_res,
+4 -3
View File
@@ -5,10 +5,11 @@ type Params = {
url?: URL;
query?: any;
routeParams?: BunxRouteParams;
skip_server_res?: boolean;
};
export default function grabPageModules({ file_path, debug, url, query, routeParams, }: Params): Promise<{
component: import("react").JSX.Element;
serverRes: import("../../../types").BunextPageModuleServerReturn;
export default function grabPageModules({ file_path, debug, url, query, routeParams, skip_server_res, }: Params): Promise<{
component: import("react").FC;
serverRes: import("../../../types").BunextPageModuleServerReturn | undefined;
module: BunextPageModule;
root_module: BunextPageModule | undefined;
}>;
+10 -10
View File
@@ -3,7 +3,7 @@ import _ from "lodash";
import { log } from "../../../utils/log";
import grabRootFilePath from "./grab-root-file-path";
import grabPageCombinedServerRes from "./grab-page-combined-server-res";
export default async function grabPageModules({ file_path, debug, url, query, routeParams, }) {
export default async function grabPageModules({ file_path, debug, url, query, routeParams, skip_server_res, }) {
const now = Date.now();
const { root_file_path } = grabRootFilePath();
const root_module = root_file_path
@@ -13,17 +13,17 @@ export default async function grabPageModules({ file_path, debug, url, query, ro
if (debug) {
log.info(`module:`, module);
}
const { serverRes } = await grabPageCombinedServerRes({
file_path,
debug,
query,
routeParams,
url,
});
const { serverRes } = skip_server_res
? {}
: await grabPageCombinedServerRes({
file_path,
debug,
query,
routeParams,
url,
});
const { component } = (await grabPageBundledReactComponent({
file_path,
root_file_path,
server_res: serverRes,
})) || {};
if (!component) {
throw new Error(`Couldn't grab page component`);
@@ -1,7 +1,6 @@
type Params = {
file_path: string;
root_file_path?: string;
server_res?: any;
};
export default function grabPageReactComponentString({ file_path, root_file_path, server_res, }: Params): string | undefined;
export default function grabPageReactComponentString({ file_path, root_file_path, }: Params): string | undefined;
export {};
@@ -1,15 +1,19 @@
import EJSON from "../../../utils/ejson";
import { log } from "../../../utils/log";
export default function grabPageReactComponentString({ file_path, root_file_path, server_res, }) {
export default function grabPageReactComponentString({ file_path, root_file_path,
// server_res,
}) {
try {
let tsx = ``;
const server_res_json = JSON.stringify(EJSON.stringify(server_res || {}) ?? "{}");
// const server_res_json = JSON.stringify(
// EJSON.stringify(server_res || {}) ?? "{}",
// );
if (root_file_path) {
tsx += `import Root from "${root_file_path}"\n`;
}
tsx += `import Page from "${file_path}"\n`;
tsx += `export default function Main() {\n\n`;
tsx += `const props = JSON.parse(${server_res_json})\n\n`;
tsx += `export default function Main({...props}) {\n\n`;
// tsx += `const props = JSON.parse(${server_res_json})\n\n`;
tsx += ` return (\n`;
if (root_file_path) {
tsx += ` <Root {...props}><Page {...props} /></Root>\n`;
@@ -0,0 +1,5 @@
type Params = {
tsx: string;
};
export default function grabTsxStringModule<T>({ tsx, }: Params): Promise<T>;
export {};
@@ -0,0 +1,73 @@
import isDevelopment from "../../../utils/is-development";
import * as esbuild from "esbuild";
export default async function grabTsxStringModule({ tsx, }) {
const dev = isDevelopment();
const now = Date.now();
const final_tsx = dev ? tsx + `\n// v_${now}` : tsx;
const result = await esbuild.transform(final_tsx, {
loader: "tsx",
format: "esm",
jsx: "automatic",
minify: !dev,
});
const blob = new Blob([result.code], { type: "text/javascript" });
const url = URL.createObjectURL(blob);
const mod = await import(url);
URL.revokeObjectURL(url);
return mod;
}
// export default async function grabTsxStringModule<T extends any = any>({
// tsx,
// }: Params): Promise<T> {
// const dev = isDevelopment();
// const now = Date.now();
// const { BUNX_CWD_MODULE_CACHE_DIR } = grabDirNames();
// const target_cache_file_path = path.join(
// BUNX_CWD_MODULE_CACHE_DIR,
// `server-render-${now}.js`,
// );
// await esbuild.build({
// stdin: {
// contents: dev ? tsx + `\n// v_${now}` : tsx,
// resolveDir: process.cwd(),
// loader: "tsx",
// },
// bundle: true,
// format: "esm",
// target: "es2020",
// platform: "node",
// external: [
// "react",
// "react-dom",
// "react/jsx-runtime",
// "react/jsx-dev-runtime",
// ],
// minify: !dev,
// define: {
// "process.env.NODE_ENV": JSON.stringify(
// dev ? "development" : "production",
// ),
// },
// jsx: "automatic",
// outfile: target_cache_file_path,
// plugins: [tailwindEsbuildPlugin],
// });
// Loader.registry.delete(target_cache_file_path);
// const mod = await import(`${target_cache_file_path}?t=${now}`);
// return mod as T;
// }
// if (!dev) {
// const now = Date.now();
// const final_tsx = dev ? tsx + `\n// v_${now}` : tsx;
// const result = await esbuild.transform(final_tsx, {
// loader: "tsx",
// format: "esm",
// jsx: "automatic",
// minify: !dev,
// });
// const blob = new Blob([result.code], { type: "text/javascript" });
// const url = URL.createObjectURL(blob);
// const mod = await import(url);
// URL.revokeObjectURL(url);
// return mod as T;
// }
@@ -1,5 +1,4 @@
type Params = {
tsx: string;
};
export default function grabTsxStringModule<T extends any = any>({ tsx, }: Params): Promise<T>;
import type { GrabTSXModuleBatchParams, GrabTSXModuleSingleParams } from "../../../types";
type Params = GrabTSXModuleSingleParams | GrabTSXModuleBatchParams;
export default function grabTsxStringModule<T>(params: Params): Promise<T | T[]>;
export {};
+130 -13
View File
@@ -3,17 +3,60 @@ import * as esbuild from "esbuild";
import grabDirNames from "../../../utils/grab-dir-names";
import path from "path";
import tailwindEsbuildPlugin from "./tailwind-esbuild-plugin";
export default async function grabTsxStringModule({ tsx, }) {
import { existsSync, unlinkSync } from "fs";
import { log } from "../../../utils/log";
const { PAGES_DIR, BUNX_CWD_MODULE_CACHE_DIR } = grabDirNames();
function toModPath(page_file_path) {
return path.join(BUNX_CWD_MODULE_CACHE_DIR, page_file_path.replace(PAGES_DIR, "").replace(/\.(t|j)sx?$/, ".js"));
}
function isBatch(params) {
return "tsx_map" in params;
}
async function buildEntries({ entries, clean_cache }) {
const dev = isDevelopment();
const now = Date.now();
const { BUNX_CWD_MODULE_CACHE_DIR } = grabDirNames();
const target_cache_file_path = path.join(BUNX_CWD_MODULE_CACHE_DIR, `server-render-${now}.js`);
await esbuild.build({
stdin: {
contents: dev ? tsx + `\n// v_${now}` : tsx,
resolveDir: process.cwd(),
loader: "tsx",
const toBuild = [];
for (const entry of entries) {
const mod_file_path = toModPath(entry.page_file_path);
if (!global.REACT_DOM_MODULE_CACHE.has(entry.page_file_path) &&
!(await Bun.file(mod_file_path).exists())) {
toBuild.push({
tsx: entry.tsx,
mod_file_path,
});
}
else {
try {
if (clean_cache && existsSync(mod_file_path)) {
unlinkSync(mod_file_path);
}
}
catch (error) { }
}
}
if (toBuild.length === 0)
return;
const virtualEntries = {};
for (const { tsx, mod_file_path } of toBuild) {
virtualEntries[mod_file_path] = tsx;
}
const virtualPlugin = {
name: "virtual-tsx-entries",
setup(build) {
const entryPaths = new Set(Object.keys(virtualEntries));
build.onResolve({ filter: /.*/ }, (args) => {
if (entryPaths.has(args.path)) {
return { path: args.path, namespace: "virtual" };
}
});
build.onLoad({ filter: /.*/, namespace: "virtual" }, (args) => ({
contents: virtualEntries[args.path],
resolveDir: process.cwd(),
loader: "tsx",
}));
},
};
await esbuild.build({
entryPoints: Object.keys(virtualEntries),
bundle: true,
format: "esm",
target: "es2020",
@@ -29,10 +72,84 @@ export default async function grabTsxStringModule({ tsx, }) {
"process.env.NODE_ENV": JSON.stringify(dev ? "development" : "production"),
},
jsx: "automatic",
outfile: target_cache_file_path,
plugins: [tailwindEsbuildPlugin],
outdir: BUNX_CWD_MODULE_CACHE_DIR,
plugins: [virtualPlugin, tailwindEsbuildPlugin],
});
}
async function loadEntry(page_file_path) {
const now = Date.now();
const mod_file_path = toModPath(page_file_path);
const mod_css_path = mod_file_path.replace(/\.js$/, ".css");
if (global.REACT_DOM_MODULE_CACHE.has(page_file_path)) {
return global.REACT_DOM_MODULE_CACHE.get(page_file_path)?.main;
}
const mod = await import(`${mod_file_path}?t=${now}`);
global.REACT_DOM_MODULE_CACHE.set(page_file_path, {
main: mod,
css: mod_css_path,
});
Loader.registry.delete(target_cache_file_path);
const mod = await import(`${target_cache_file_path}?t=${now}`);
return mod;
}
export default async function grabTsxStringModule(params) {
if (isBatch(params)) {
await buildEntries({ entries: params.tsx_map });
return Promise.all(params.tsx_map.map((entry) => loadEntry(entry.page_file_path)));
}
await buildEntries({ entries: [params], clean_cache: true });
return loadEntry(params.page_file_path);
}
// export default async function grabTsxStringModule<T extends any = any>({
// tsx,
// }: Params): Promise<T> {
// const dev = isDevelopment();
// const now = Date.now();
// const { BUNX_CWD_MODULE_CACHE_DIR } = grabDirNames();
// const target_cache_file_path = path.join(
// BUNX_CWD_MODULE_CACHE_DIR,
// `server-render-${now}.js`,
// );
// await esbuild.build({
// stdin: {
// contents: dev ? tsx + `\n// v_${now}` : tsx,
// resolveDir: process.cwd(),
// loader: "tsx",
// },
// bundle: true,
// format: "esm",
// target: "es2020",
// platform: "node",
// external: [
// "react",
// "react-dom",
// "react/jsx-runtime",
// "react/jsx-dev-runtime",
// ],
// minify: !dev,
// define: {
// "process.env.NODE_ENV": JSON.stringify(
// dev ? "development" : "production",
// ),
// },
// jsx: "automatic",
// outfile: target_cache_file_path,
// plugins: [tailwindEsbuildPlugin],
// });
// Loader.registry.delete(target_cache_file_path);
// const mod = await import(`${target_cache_file_path}?t=${now}`);
// return mod as T;
// }
// if (!dev) {
// const now = Date.now();
// const final_tsx = dev ? tsx + `\n// v_${now}` : tsx;
// const result = await esbuild.transform(final_tsx, {
// loader: "tsx",
// format: "esm",
// jsx: "automatic",
// minify: !dev,
// });
// const blob = new Blob([result.code], { type: "text/javascript" });
// const url = URL.createObjectURL(blob);
// const mod = await import(url);
// URL.revokeObjectURL(url);
// return mod as T;
// }