First working version

This commit is contained in:
2026-03-16 20:44:15 +01:00
parent ca9d6a75ff
commit 19d0ceb7db
24 changed files with 873 additions and 276 deletions
+1 -2
View File
@@ -28,8 +28,7 @@ export default async function ({
if (!match?.filePath) {
const errMsg = `Route ${url.pathname} not found`;
console.error(errMsg);
// console.error(errMsg);
return {
success: false,
+98 -8
View File
@@ -1,33 +1,114 @@
import path from "path";
import type { ServeOptions } from "bun";
import type { RouterTypes, ServeOptions } from "bun";
import grabAppPort from "../../utils/grab-app-port";
import grabDirNames from "../../utils/grab-dir-names";
import handleWebPages from "./web-pages/handle-web-pages";
import handleRoutes from "./handle-routes";
import isDevelopment from "../../utils/is-development";
import type { Server } from "http";
type Params = {
dev?: boolean;
};
// type ServerOptions = Omit<ServeOptions, "fetch"> & {
// routes: { [K: string]: RouterTypes.RouteValue<string> };
// fetch?: (
// this: Server,
// request: Request,
// server: Server,
// ) => Response | Promise<Response>;
// };
export default async function (params?: Params): Promise<ServeOptions> {
const port = grabAppPort();
const { PUBLIC_DIR } = grabDirNames();
// const opts: ServerOptions = {
// routes: {
// "/__hmr": {
// async GET(req) {
// if (!isDevelopment()) {
// return new Response(`Production Environment`);
// }
// let controller: ReadableStreamDefaultController<string>;
// const stream = new ReadableStream<string>({
// start(c) {
// controller = c;
// global.HMR_CONTROLLERS.add(c);
// },
// cancel() {
// global.HMR_CONTROLLERS.delete(controller);
// },
// });
// return new Response(stream, {
// headers: {
// "Content-Type": "text/event-stream",
// "Cache-Control": "no-cache",
// Connection: "keep-alive",
// },
// });
// },
// },
// "/api/*": {},
// "/*": {
// async GET(req) {
// return await handleWebPages({ req });
// },
// },
// },
// };
return {
async fetch(req, server) {
try {
const url = new URL(req.url);
if (url.pathname === "/__hmr" && isDevelopment()) {
const referer_url = new URL(
req.headers.get("referer") || "",
);
const match = global.ROUTER.match(referer_url.pathname);
if (!match?.filePath) {
return new Response(`Unhandled Path.`);
}
const target_map = global.BUNDLER_CTX_MAP?.find(
(m) => m.local_path == match.filePath,
);
if (!target_map?.entrypoint) {
return new Response(`Target Path has no map`);
}
let controller: ReadableStreamDefaultController<string>;
const stream = new ReadableStream<string>({
start(c) {
controller = c;
global.HMR_CONTROLLERS.add(c);
global.HMR_CONTROLLERS.push({
controller: c,
page_url: referer_url.href,
target_map,
});
},
cancel() {
global.HMR_CONTROLLERS.delete(controller);
const targetControllerIndex =
global.HMR_CONTROLLERS.findIndex(
(c) => c.controller == controller,
);
if (
typeof targetControllerIndex == "number" &&
targetControllerIndex >= 0
) {
global.HMR_CONTROLLERS.splice(
targetControllerIndex,
1,
);
}
},
});
@@ -38,7 +119,9 @@ export default async function (params?: Params): Promise<ServeOptions> {
Connection: "keep-alive",
},
});
} else if (url.pathname.startsWith("/api/")) {
}
if (url.pathname.startsWith("/api/")) {
const res = await handleRoutes({ req, server });
return new Response(JSON.stringify(res), {
@@ -47,7 +130,9 @@ export default async function (params?: Params): Promise<ServeOptions> {
"Content-Type": "application/json",
},
});
} else if (url.pathname.startsWith("/public/")) {
}
if (url.pathname.startsWith("/public/")) {
const file = Bun.file(
path.join(
PUBLIC_DIR,
@@ -56,13 +141,15 @@ export default async function (params?: Params): Promise<ServeOptions> {
);
return new Response(file);
} else if (url.pathname.startsWith("/favicon.")) {
}
if (url.pathname.startsWith("/favicon.")) {
const file = Bun.file(path.join(PUBLIC_DIR, url.pathname));
return new Response(file);
} else {
return await handleWebPages({ req });
}
return await handleWebPages({ req });
} catch (error: any) {
return new Response(`Server Error: ${error.message}`, {
status: 500,
@@ -71,5 +158,8 @@ export default async function (params?: Params): Promise<ServeOptions> {
},
port,
idleTimeout: 0,
development: {
hmr: true,
},
} as ServeOptions;
}
@@ -0,0 +1,38 @@
import _ from "lodash";
import type { BundlerCTXMap, GlobalHMRControllerObject } from "../../types";
type Params = {
artifacts: BundlerCTXMap[];
};
export default async function serverPostBuildFn({ artifacts }: Params) {
if (!global.IS_FIRST_BUNDLE_READY) {
global.IS_FIRST_BUNDLE_READY = true;
}
if (!global.HMR_CONTROLLERS?.[0]) {
return;
}
for (let i = 0; i < global.HMR_CONTROLLERS.length; i++) {
const controller = global.HMR_CONTROLLERS[i];
const target_artifact = artifacts.find(
(a) => controller.target_map.local_path == a.local_path,
);
if (!target_artifact?.local_path) continue;
const final_artifact: Omit<GlobalHMRControllerObject, "controller"> = {
..._.omit(controller, ["controller"]),
target_map: target_artifact,
};
try {
controller.controller.enqueue(
`event: update\ndata: ${JSON.stringify(final_artifact)}\n\n`,
);
} catch {
global.HMR_CONTROLLERS.splice(i, 1);
}
}
}
+24 -6
View File
@@ -1,7 +1,9 @@
import _ from "lodash";
import AppNames from "../../utils/grab-app-names";
import allPagesBundler from "../bundler/all-pages-bundler";
import serverParamsGen from "./server-params-gen";
import watcher from "./watcher";
import serverPostBuildFn from "./server-post-build-fn";
type Params = {
dev?: boolean;
@@ -12,19 +14,35 @@ export default async function startServer(params?: Params) {
const serverParams = await serverParamsGen();
if (params?.dev) {
await allPagesBundler({
watch: true,
post_build_fn: serverPostBuildFn,
});
watcher();
} else {
global.IS_FIRST_BUNDLE_READY = true;
}
let bundle_ready_retries = 0;
const MAX_BUNDLE_READY_RETRIES = 10;
while (!global.IS_FIRST_BUNDLE_READY) {
if (bundle_ready_retries > MAX_BUNDLE_READY_RETRIES) {
console.error(`Couldn't grab first bundle for dev environment`);
process.exit(1);
}
bundle_ready_retries++;
await Bun.sleep(500);
}
const server = Bun.serve(serverParams);
global.SERVER = server;
await allPagesBundler();
console.log(
`${name} Server Running on http://localhost:${server.port} ...`,
);
if (params?.dev) {
watcher();
}
return server;
}
+16 -15
View File
@@ -1,14 +1,13 @@
import { watch } from "fs";
import grabDirNames from "../../utils/grab-dir-names";
import serverParamsGen from "./server-params-gen";
import allPagesBundler from "../bundler/all-pages-bundler";
// import allPagesBundler from "../bundler/all-pages-bundler";
const { ROOT_DIR, BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR, PAGES_DIR } =
grabDirNames();
const { PAGES_DIR } = grabDirNames();
export default function watcher() {
watch(
ROOT_DIR,
PAGES_DIR,
{
recursive: true,
persistent: true,
@@ -20,6 +19,8 @@ export default function watcher() {
// if (filename.match(/\.bunext|\/?public\//)) return;
// if (!filename.match(/\.(tsx|ts|css|js|jsx)$/)) return;
console.log("event", event);
if (global.RECOMPILING) return;
clearTimeout(global.WATCHER_TIMEOUT);
@@ -29,19 +30,19 @@ export default function watcher() {
console.log(`File Changed. Rebuilding ...`);
await allPagesBundler();
// await allPagesBundler();
global.LAST_BUILD_TIME = Date.now();
// global.LAST_BUILD_TIME = Date.now();
for (const controller of global.HMR_CONTROLLERS) {
try {
controller.enqueue(
`event: update\ndata: ${global.LAST_BUILD_TIME}\n\n`,
);
} catch {
global.HMR_CONTROLLERS.delete(controller);
}
}
// for (const controller of global.HMR_CONTROLLERS) {
// try {
// controller.enqueue(
// `event: update\ndata: ${global.LAST_BUILD_TIME}\n\n`,
// );
// } catch {
// global.HMR_CONTROLLERS.delete(controller);
// }
// }
} catch (error: any) {
console.log(error);
} finally {
@@ -4,12 +4,12 @@ import grabDirNames from "../../../utils/grab-dir-names";
import EJSON from "../../../utils/ejson";
import type { LivePageDistGenParams } from "../../../types";
import isDevelopment from "../../../utils/is-development";
import grabWebPageHydrationScript from "./grab-web-page-hydration-script";
export default async function genWebHTML({
component,
pageProps,
pageName,
module,
bundledMap,
}: LivePageDistGenParams) {
const { ClientRootElementIDName, ClientWindowPagePropsName } =
await grabContants();
@@ -20,38 +20,31 @@ export default async function genWebHTML({
const componentHTML = renderToString(component);
const SCRIPT_SRC = path.join("/public/pages", pageName + ".js");
const CSS_SRC = path.join("/public/pages", pageName + ".css");
const { HYDRATION_DST_DIR } = grabDirNames();
const cssExists = await Bun.file(
path.join(HYDRATION_DST_DIR, pageName + ".css"),
).exists();
// const SCRIPT_SRC = path.join("/public/pages", bundledMap.path);
// const CSS_SRC = bundledMap.css_path
// ? path.join("/public/pages", bundledMap.css_path)
// : undefined;
// const { HYDRATION_DST_DIR } = grabDirNames();
let html = `<!DOCTYPE html>\n`;
html += `<html>\n`;
html += ` <head>\n`;
html += ` <meta charset="utf-8" />\n`;
if (cssExists) {
html += ` <link rel="stylesheet" href="${CSS_SRC}" />\n`;
if (bundledMap.css_path) {
html += ` <link rel="stylesheet" href="/${bundledMap.css_path}" />\n`;
}
// if (isDevelopment()) {
// html += `<script>
// const hmr = new EventSource("/__hmr");
// hmr.addEventListener("update", (event) => {
// if (event.data === "reload") {
// window.location.reload();
// }
// });
// </script>\n`;
// }
html += ` </head>\n`;
html += ` <body>\n`;
html += ` <div id="${ClientRootElementIDName}">${componentHTML}</div>\n`;
html += ` <script>window.${ClientWindowPagePropsName} = ${
EJSON.stringify(pageProps || {}) || "{}"
}</script>\n`;
html += ` <script src="${SCRIPT_SRC}" type="module"></script>\n`;
html += ` <script src="/${bundledMap.path}" type="module" defer></script>\n`;
if (isDevelopment()) {
html += `<script defer>\n${await grabWebPageHydrationScript({ bundledMap })}\n</script>\n`;
}
html += ` </head>\n`;
html += ` <body>\n`;
html += ` <div id="${ClientRootElementIDName}">${componentHTML}</div>\n`;
html += ` </body>\n`;
html += `</html>\n`;
@@ -1,6 +1,5 @@
import type { FC } from "react";
import grabDirNames from "../../../utils/grab-dir-names";
import grabPageName from "../../../utils/grab-page-name";
import grabRouteParams from "../../../utils/grab-route-params";
import grabRouter from "../../../utils/grab-router";
import type { BunextPageModule, GrabPageComponentRes } from "../../../types";
@@ -20,12 +19,7 @@ export default async function grabPageComponent({
const url = req?.url ? new URL(req.url) : undefined;
const router = grabRouter();
const {
BUNX_ROOT_500_PRESET_COMPONENT,
HYDRATION_DST_DIR,
BUNX_ROOT_500_FILE_NAME,
PAGES_DIR,
} = grabDirNames();
const { BUNX_ROOT_500_PRESET_COMPONENT, PAGES_DIR } = grabDirNames();
const routeParams = req ? await grabRouteParams({ req }) : undefined;
@@ -34,7 +28,7 @@ export default async function grabPageComponent({
if (!match?.filePath && url?.pathname) {
const errMsg = `Page ${url.pathname} not found`;
console.error(errMsg);
// console.error(errMsg);
throw new Error(errMsg);
}
@@ -42,11 +36,21 @@ export default async function grabPageComponent({
if (!file_path) {
const errMsg = `No File Path (\`file_path\`) or Request Object (\`req\`) provided not found`;
// console.error(errMsg);
throw new Error(errMsg);
}
const bundledMap = global.BUNDLER_CTX_MAP?.find(
(m) => m.local_path == file_path,
);
if (!bundledMap?.path) {
const errMsg = `No Bundled File Path for this request path!`;
console.error(errMsg);
throw new Error(errMsg);
}
const pageName = grabPageName({ path: file_path });
// const pageName = grabPageName({ path: file_path });
const root_pages_component_ts_file = `${path.join(PAGES_DIR, AppNames["RootPagesComponentName"])}.ts`;
const root_pages_component_tsx_file = `${path.join(PAGES_DIR, AppNames["RootPagesComponentName"])}.tsx`;
@@ -63,17 +67,19 @@ export default async function grabPageComponent({
? root_pages_component_js_file
: undefined;
const now = Date.now();
const root_module = root_file
? await import(`${root_file}?t=${global.LAST_BUILD_TIME ?? 0}`)
? await import(`${root_file}?t=${now}`)
: undefined;
const RootComponent = root_module?.default as FC<any> | undefined;
const component_file_path = root_module
? `${file_path}`
: `${file_path}?t=${global.LAST_BUILD_TIME ?? 0}`;
// const component_file_path = root_module
// ? `${file_path}`
// : `${file_path}?t=${global.LAST_BUILD_TIME ?? 0}`;
const module: BunextPageModule = await import(component_file_path);
const module: BunextPageModule = await import(`${file_path}?t=${now}`);
const serverRes = await (async () => {
try {
@@ -87,6 +93,7 @@ export default async function grabPageComponent({
})();
const Component = module.default as FC<any>;
const component = RootComponent ? (
<RootComponent {...serverRes}>
<Component {...serverRes} />
@@ -95,34 +102,30 @@ export default async function grabPageComponent({
<Component {...serverRes} />
);
return { component, serverRes, routeParams, pageName, module };
return {
component,
serverRes,
routeParams,
module,
bundledMap,
};
} catch (error: any) {
// console.log(`Grab page component ERROR =>`, error.message);
const match = router.match("/500");
const filePath = match?.filePath || BUNX_ROOT_500_PRESET_COMPONENT;
// if (!match?.filePath) {
// bundle({
// out_dir: HYDRATION_DST_DIR,
// src: `${BUNX_ROOT_500_PRESET_COMPONENT}`,
// debug: true,
// });
// }
const module: BunextPageModule = await import(filePath);
// const module: BunextPageModule = await import(
// `${filePath}?t=${global.LAST_BUILD_TIME ?? 0}`
// );
const Component = module.default as FC<any>;
const component = <Component />;
return {
component,
pageName: BUNX_ROOT_500_FILE_NAME,
routeParams,
module,
bundledMap: {},
};
}
}
@@ -0,0 +1,75 @@
import grabDirNames from "../../../utils/grab-dir-names";
import type { BundlerCTXMap, PageDistGenParams } from "../../../types";
import grabConstants from "../../../utils/grab-constants";
const { BUNX_HYDRATION_SRC_DIR } = grabDirNames();
type Params = {
bundledMap: BundlerCTXMap;
};
export default async function ({ bundledMap }: Params) {
const { ClientRootElementIDName, ClientRootComponentWindowName } =
await grabConstants();
let script = "";
// script += `import React from "react";\n`;
// script += `import { hydrateRoot } from "react-dom/client";\n`;
// script += `import App from "${page_file}";\n`;
// script += `declare global {\n`;
// script += ` interface Window {\n`;
// script += ` ${ClientWindowPagePropsName}: any;\n`;
// script += ` }\n`;
// script += `}\n`;
// script += `let root: any = null;\n\n`;
// script += `const component = <App {...window.${ClientWindowPagePropsName}} />;\n\n`;
// script += `const container = document.getElementById("${ClientRootElementIDName}");\n\n`;
// script += `if (container) {\n`;
// script += ` root = hydrateRoot(container, component);\n`;
// script += `}\n\n`;
script += `console.log(\`Development Environment\`);\n`;
// script += `console.log(import.meta);\n`;
// script += `if (import.meta.hot) {\n`;
// script += ` console.log(\`HMR active\`);\n`;
// script += ` import.meta.hot.dispose(() => {\n`;
// script += ` console.log("dispose");\n`;
// script += ` });\n`;
// script += `}\n`;
script += `const hmr = new EventSource("/__hmr");\n`;
script += `hmr.addEventListener("update", async (event) => {\n`;
// script += ` console.log(\`HMR even received:\`, event);\n`;
script += ` if (event.data) {\n`;
script += ` console.log(\`HMR Changes Detected. Reloading ...\`);\n`;
// script += ` console.log("event", event);\n`;
// script += ` console.log("window.${ClientRootComponentWindowName}", window.${ClientRootComponentWindowName});\n\n`;
// script += ` const event_data = JSON.parse(event.data);\n\n`;
// script += ` const new_js_path = \`/\${event_data.target_map.path}\`;\n\n`;
// script += ` console.log("event_data", event_data);\n\n`;
// script += ` console.log("new_js_path", new_js_path);\n\n`;
// script += ` if (window.${ClientRootComponentWindowName}) {\n`;
// script += ` const new_component = await import(new_js_path);\n`;
// script += ` window.${ClientRootComponentWindowName}.render(new_component);\n`;
// script += ` }\n`;
// script += ` import("${page_file}?t=" + event.data.update).then((module) => {\n`;
// script += ` root.render(module.default);\n`;
// script += ` })\n`;
// script += ` console.log("root", root);\n`;
// script += ` root.unmount();\n`;
// script += ` const container = document.getElementById("${ClientRootElementIDName}");\n\n`;
// script += ` root = hydrateRoot(container!, component);\n`;
// script += ` window.history.pushState({ page: 1 }, "New Page Title", \`\${window.location.pathname}?v=\${Date.now()}\`);\n`;
// script += ` root.render(component);\n`;
script += ` window.location.reload();\n`;
script += ` }\n`;
script += ` });\n`;
return script;
}
@@ -8,23 +8,16 @@ type Params = {
export default async function ({ req }: Params): Promise<Response> {
try {
const { component, pageName, module, serverRes } =
const { component, bundledMap, module, serverRes } =
await grabPageComponent({ req });
const html = await genWebHTML({
component,
pageProps: serverRes,
pageName,
bundledMap,
module,
});
// writeWebPageHydrationScript({
// component,
// pageName,
// module,
// pageProps: serverRes,
// });
const res_opts: ResponseInit = {
headers: {
"Content-Type": "text/html",
@@ -44,6 +37,8 @@ export default async function ({ req }: Params): Promise<Response> {
return res;
} catch (error: any) {
console.log(`Handle web pages Error =>`, error.message);
return new Response(error.message || `Page Not Found`, {
status: 404,
});
@@ -1,56 +0,0 @@
import { writeFileSync } from "fs";
import path from "path";
import grabDirNames from "../../../utils/grab-dir-names";
import grabContants from "../../../utils/grab-constants";
import type { PageDistGenParams } from "../../../types";
import isDevelopment from "../../../utils/is-development";
const { BUNX_HYDRATION_SRC_DIR } = grabDirNames();
export default async function (params: PageDistGenParams) {
const { pageName, page_file } = params;
const { ClientRootElementIDName, ClientWindowPagePropsName } =
await grabContants();
const pageSrcTsFileName = `${pageName}.tsx`;
let script = "";
script += `import React from "react";\n`;
script += `import { hydrateRoot } from "react-dom/client";\n`;
script += `import App from "${page_file}";\n`;
script += `declare global {\n`;
script += ` interface Window {\n`;
script += ` ${ClientWindowPagePropsName}: any;\n`;
script += ` }\n`;
script += `}\n`;
script += `let root: any = null;\n\n`;
script += `const component = <App {...window.${ClientWindowPagePropsName}} />;\n\n`;
script += `const container = document.getElementById("${ClientRootElementIDName}");\n\n`;
script += `if (container) {\n`;
script += ` root = hydrateRoot(container, component);\n`;
script += `}\n\n`;
if (isDevelopment()) {
script += `const hmr = new EventSource("/__hmr");\n`;
script += `hmr.addEventListener("update", (event) => {\n`;
// script += ` console.log(\`HMR even received:\`, event);\n`;
script += ` if (event.data && root) {\n`;
script += ` console.log(\`HMR Changes Detected. Reloading ...\`);\n`;
// script += ` import("${page_file}?t=" + event.data.update).then((module) => {\n`;
// script += ` root.render(module.default);\n`;
// script += ` })\n`;
// script += ` console.log("root", root);\n`;
// script += ` root.unmount();\n`;
// script += ` const container = document.getElementById("${ClientRootElementIDName}");\n\n`;
// script += ` root = hydrateRoot(container!, component);\n`;
// script += ` root.render(component);\n`;
script += ` window.location.reload();\n`;
script += ` }\n`;
script += ` });\n`;
}
const SRC_WRITE_FILE = path.join(BUNX_HYDRATION_SRC_DIR, pageSrcTsFileName);
writeFileSync(SRC_WRITE_FILE, script, "utf-8");
}