Updates
This commit is contained in:
@@ -0,0 +1,26 @@
|
||||
import { existsSync } from "fs";
|
||||
import type { BunextConfig } from "../types";
|
||||
import grabDirNames from "../utils/grab-dir-names";
|
||||
import exitWithError from "../utils/exit-with-error";
|
||||
|
||||
export default async function grabConfig(): Promise<BunextConfig | undefined> {
|
||||
try {
|
||||
const { CONFIG_FILE } = grabDirNames();
|
||||
|
||||
if (!existsSync(CONFIG_FILE)) {
|
||||
exitWithError(`Config file \`${CONFIG_FILE}\` doesn't exist!`);
|
||||
}
|
||||
|
||||
const config = (await import(CONFIG_FILE)).default as BunextConfig;
|
||||
|
||||
if (!config) {
|
||||
exitWithError(
|
||||
`Config file \`${CONFIG_FILE}\` is invalid! Please provide a valid default export in your config file.`
|
||||
);
|
||||
}
|
||||
|
||||
return config;
|
||||
} catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
import { existsSync, mkdirSync, statSync, writeFileSync } from "fs";
|
||||
import grabDirNames from "../utils/grab-dir-names";
|
||||
|
||||
export default async function () {
|
||||
const dirNames = grabDirNames();
|
||||
|
||||
const keys = Object.keys(dirNames) as (keyof ReturnType<
|
||||
typeof grabDirNames
|
||||
>)[];
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
const dir = dirNames[key];
|
||||
|
||||
// const stat = statSync(dir);
|
||||
|
||||
if (!existsSync(dir) && !dir.match(/\.\w+$/)) {
|
||||
mkdirSync(dir, { recursive: true });
|
||||
continue;
|
||||
}
|
||||
|
||||
if (key == "CONFIG_FILE" && !existsSync(dir)) {
|
||||
let basicConfig = ``;
|
||||
|
||||
basicConfig += `const config = {};\n`;
|
||||
basicConfig += `export default config;\n`;
|
||||
|
||||
writeFileSync(dir, basicConfig);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,40 @@
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import type { GetRouteReturn } from "../../types";
|
||||
import grabAssetsPrefix from "../../utils/grab-assets-prefix";
|
||||
import grabOrigin from "../../utils/grab-origin";
|
||||
import grabRouter from "../../utils/grab-router";
|
||||
|
||||
type Params = {
|
||||
route: string;
|
||||
};
|
||||
|
||||
export default async function getRoute({
|
||||
route,
|
||||
}: Params): Promise<GetRouteReturn | null> {
|
||||
const { ROUTES_DIR } = grabDirNames();
|
||||
|
||||
if (route.match(/\(/)) {
|
||||
return null;
|
||||
}
|
||||
|
||||
const router = grabRouter();
|
||||
|
||||
const match = router.match(route);
|
||||
|
||||
if (!match?.filePath) {
|
||||
console.error(`Route ${route} not found`);
|
||||
return null;
|
||||
}
|
||||
|
||||
const module = await import(match.filePath);
|
||||
|
||||
return {
|
||||
match,
|
||||
module,
|
||||
component: module.default,
|
||||
serverProps: module.serverProps,
|
||||
staticProps: module.staticProps,
|
||||
staticPaths: module.staticPaths,
|
||||
staticParams: module.staticParams,
|
||||
};
|
||||
}
|
||||
@@ -0,0 +1,69 @@
|
||||
import type { Server } from "bun";
|
||||
import type {
|
||||
APIResponseObject,
|
||||
BunextServerRouteConfig,
|
||||
BunxRouteParams,
|
||||
} from "../../types";
|
||||
import grabRouteParams from "../../utils/grab-route-params";
|
||||
import grabConstants from "../../utils/grab-constants";
|
||||
import grabRouter from "../../utils/grab-router";
|
||||
|
||||
type Params = {
|
||||
req: Request;
|
||||
server: Server;
|
||||
};
|
||||
|
||||
export default async function ({
|
||||
req,
|
||||
server,
|
||||
}: Params): Promise<APIResponseObject | undefined> {
|
||||
const url = new URL(req.url);
|
||||
|
||||
const { MBInBytes, ServerDefaultRequestBodyLimitBytes } =
|
||||
await grabConstants();
|
||||
|
||||
const router = grabRouter();
|
||||
|
||||
const match = router.match(url.pathname);
|
||||
|
||||
if (!match?.filePath) {
|
||||
const errMsg = `Route ${url.pathname} not found`;
|
||||
|
||||
console.error(errMsg);
|
||||
|
||||
return {
|
||||
success: false,
|
||||
status: 401,
|
||||
msg: errMsg,
|
||||
};
|
||||
}
|
||||
|
||||
const routeParams: BunxRouteParams = await grabRouteParams({ req, server });
|
||||
|
||||
const module = await import(match.filePath);
|
||||
const config = module.config as BunextServerRouteConfig | undefined;
|
||||
|
||||
const contentLength = req.headers.get("content-length");
|
||||
|
||||
if (contentLength) {
|
||||
const size = parseInt(contentLength, 10);
|
||||
|
||||
if (
|
||||
(config?.maxRequestBodyMB &&
|
||||
size > config.maxRequestBodyMB * MBInBytes) ||
|
||||
size > ServerDefaultRequestBodyLimitBytes
|
||||
) {
|
||||
return {
|
||||
success: false,
|
||||
status: 413,
|
||||
msg: "Request Body Too Large!",
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
const res: APIResponseObject = await module["default"](
|
||||
routeParams as BunxRouteParams
|
||||
);
|
||||
|
||||
return res;
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
import path from "path";
|
||||
import type { 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";
|
||||
|
||||
const port = grabAppPort();
|
||||
const { PUBLIC_DIR } = grabDirNames();
|
||||
|
||||
type Params = {
|
||||
dev?: boolean;
|
||||
};
|
||||
|
||||
export default async function (params?: Params): Promise<ServeOptions> {
|
||||
return {
|
||||
async fetch(req, server) {
|
||||
try {
|
||||
const url = new URL(req.url);
|
||||
|
||||
if (url.pathname === "/__hmr" && isDevelopment()) {
|
||||
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",
|
||||
},
|
||||
});
|
||||
} else if (url.pathname.startsWith("/api/")) {
|
||||
const res = await handleRoutes({ req, server });
|
||||
|
||||
return new Response(JSON.stringify(res), {
|
||||
status: res?.status,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
} else if (url.pathname.startsWith("/public/")) {
|
||||
const file = Bun.file(
|
||||
path.join(
|
||||
PUBLIC_DIR,
|
||||
url.pathname.replace(/^\/public/, ""),
|
||||
),
|
||||
);
|
||||
|
||||
return new Response(file);
|
||||
} else {
|
||||
return await handleWebPages({ req, server });
|
||||
}
|
||||
} catch (error: any) {
|
||||
return new Response(`Server Error: ${error.message}`, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
},
|
||||
port,
|
||||
development: isDevelopment() && {
|
||||
hmr: true,
|
||||
console: true,
|
||||
},
|
||||
} as ServeOptions;
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
import AppNames from "../../utils/grab-app-names";
|
||||
import serverParamsGen from "./server-params-gen";
|
||||
import watcher from "./watcher";
|
||||
|
||||
type Params = {
|
||||
dev?: boolean;
|
||||
};
|
||||
|
||||
export default async function startServer(params?: Params) {
|
||||
const { name } = AppNames;
|
||||
|
||||
const serverParams = await serverParamsGen();
|
||||
|
||||
const server = Bun.serve(serverParams);
|
||||
|
||||
global.SERVER = server;
|
||||
|
||||
console.log(
|
||||
`${name} Server Running on http://localhost:${server.port} ...`,
|
||||
);
|
||||
|
||||
if (params?.dev) {
|
||||
watcher();
|
||||
}
|
||||
|
||||
return server;
|
||||
}
|
||||
@@ -0,0 +1,127 @@
|
||||
import { watch } from "fs";
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import writeWebPageHydrationScript from "./web-pages/write-web-page-hydration-script";
|
||||
import grabPageName from "../../utils/grab-page-name";
|
||||
import path from "path";
|
||||
import { execSync } from "child_process";
|
||||
import serverParamsGen from "./server-params-gen";
|
||||
import grabRouter from "../../utils/grab-router";
|
||||
import type { FC } from "react";
|
||||
|
||||
const { ROOT_DIR, BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR, ROUTES_DIR } =
|
||||
grabDirNames();
|
||||
|
||||
export default function watcher() {
|
||||
watch(
|
||||
ROOT_DIR,
|
||||
{ recursive: true, persistent: true },
|
||||
async (event, filename) => {
|
||||
if (global.RECOMPILING) return;
|
||||
if (!filename) return;
|
||||
if (filename.match(/ /)) return;
|
||||
if (filename.match(/^node_modules\//)) return;
|
||||
if (filename.match(/\.bunext|\/public\//)) return;
|
||||
|
||||
if (filename.match(/\/routes\//)) {
|
||||
if (event == "change") {
|
||||
clearTimeout(global.WATCHER_TIMEOUT);
|
||||
|
||||
global.RECOMPILING = true;
|
||||
|
||||
const fullPath = path.join(ROOT_DIR, filename);
|
||||
|
||||
const pageName = grabPageName({ path: fullPath });
|
||||
|
||||
// const router = grabRouter();
|
||||
// const match = router.match(fullPath);
|
||||
|
||||
// if (match?.filePath) {
|
||||
// const module = await import(match.filePath);
|
||||
|
||||
// const serverRes = await (async () => {
|
||||
// try {
|
||||
// return await module["server"]();
|
||||
// } catch (error) {
|
||||
// return {};
|
||||
// }
|
||||
// })();
|
||||
|
||||
// const Component = module.default as FC<any>;
|
||||
// const component = <Component pageProps={serverRes} />;
|
||||
|
||||
// await writeWebPageHydrationScript({
|
||||
// pageName,
|
||||
// component,
|
||||
// });
|
||||
// }
|
||||
|
||||
let cmd = `bun build`;
|
||||
cmd += ` ${BUNX_HYDRATION_SRC_DIR}/${pageName}.tsx --outdir ${HYDRATION_DST_DIR}`;
|
||||
cmd += ` --minify`;
|
||||
|
||||
execSync(cmd, { stdio: "inherit" });
|
||||
|
||||
global.ROUTER = new Bun.FileSystemRouter({
|
||||
style: "nextjs",
|
||||
dir: ROUTES_DIR,
|
||||
});
|
||||
|
||||
const encoder = new TextEncoder();
|
||||
const msg = encoder.encode(`event: update\ndata: reload\n\n`);
|
||||
|
||||
for (const controller of global.HMR_CONTROLLERS) {
|
||||
controller.enqueue(msg);
|
||||
}
|
||||
global.RECOMPILING = false;
|
||||
} else if (event == "rename") {
|
||||
await reloadServer();
|
||||
}
|
||||
} else if (filename.match(/\.(js|ts|tsx|jsx)$/)) {
|
||||
clearTimeout(global.WATCHER_TIMEOUT);
|
||||
await reloadServer();
|
||||
}
|
||||
},
|
||||
);
|
||||
|
||||
// watch(BUNX_HYDRATION_SRC_DIR, async (event, filename) => {
|
||||
// if (!filename) return;
|
||||
|
||||
// const targetFile = path.join(BUNX_HYDRATION_SRC_DIR, filename);
|
||||
|
||||
// await Bun.build({
|
||||
// entrypoints: [targetFile],
|
||||
// outdir: HYDRATION_DST_DIR,
|
||||
// minify: true,
|
||||
// target: "browser",
|
||||
// format: "esm",
|
||||
// });
|
||||
|
||||
// global.SERVER?.publish("__bun_hmr", "update");
|
||||
|
||||
// setTimeout(() => {
|
||||
// global.RECOMPILING = false;
|
||||
// }, 200);
|
||||
// });
|
||||
|
||||
// watch(HYDRATION_DST_DIR, async (event, filename) => {
|
||||
// const encoder = new TextEncoder();
|
||||
// global.HMR_CONTROLLER?.enqueue(encoder.encode(`event: update\ndata: reload\n\n`));
|
||||
// global.RECOMPILING = false;
|
||||
// });
|
||||
|
||||
// let cmd = `bun build`;
|
||||
|
||||
// cmd += ` ${BUNX_HYDRATION_SRC_DIR}/*.tsx --outdir ${HYDRATION_DST_DIR}`;
|
||||
// cmd += ` --watch --minify`;
|
||||
|
||||
// execSync(cmd, { stdio: "inherit" });
|
||||
}
|
||||
|
||||
async function reloadServer() {
|
||||
const serverParams = await serverParamsGen();
|
||||
|
||||
console.log(`Reloading Server ...`);
|
||||
|
||||
global.SERVER?.stop();
|
||||
global.SERVER = Bun.serve(serverParams);
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
import path from "path";
|
||||
import { renderToString } from "react-dom/server";
|
||||
import grabContants from "../../../utils/grab-constants";
|
||||
import EJSON from "../../../utils/ejson";
|
||||
import type { PageDistGenParams } from "../../../types";
|
||||
import isDevelopment from "../../../utils/is-development";
|
||||
|
||||
export default async function genWebHTML({
|
||||
component,
|
||||
pageProps,
|
||||
pageName,
|
||||
module,
|
||||
}: PageDistGenParams) {
|
||||
const { ClientRootElementIDName, ClientWindowPagePropsName } =
|
||||
await grabContants();
|
||||
|
||||
const componentHTML = renderToString(component);
|
||||
|
||||
const SCRIPT_SRC = path.join("/public/routes", pageName + ".js");
|
||||
|
||||
let html = `<!DOCTYPE html>\n`;
|
||||
|
||||
if (isDevelopment()) {
|
||||
html += `<script>
|
||||
const hmr = new EventSource("/__hmr");
|
||||
hmr.addEventListener("update", (event) => {
|
||||
if (event.data === "reload") {
|
||||
window.location.reload();
|
||||
}
|
||||
});
|
||||
</script>\n`;
|
||||
}
|
||||
|
||||
html += `<html>\n`;
|
||||
html += ` <head>\n`;
|
||||
html += ` <meta charset="utf-8" />\n`;
|
||||
html += ` <title>React SSR with Bun</title>\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 += ` </body>\n`;
|
||||
html += `</html>\n`;
|
||||
|
||||
return html;
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import type { FC } from "react";
|
||||
import grabDirNames from "../../../utils/grab-dir-names";
|
||||
import type { Server } from "bun";
|
||||
import grabPageName from "../../../utils/grab-page-name";
|
||||
import grabRouteParams from "../../../utils/grab-route-params";
|
||||
import genWebHTML from "./generate-web-html";
|
||||
import grabRouter from "../../../utils/grab-router";
|
||||
import type { BunextPageModule } from "../../../types";
|
||||
|
||||
type Params = {
|
||||
req: Request;
|
||||
server: Server;
|
||||
};
|
||||
|
||||
export default async function ({ req, server }: Params): Promise<Response> {
|
||||
const url = new URL(req.url);
|
||||
|
||||
try {
|
||||
const router = grabRouter();
|
||||
const match = router.match(url.pathname);
|
||||
|
||||
if (!match?.filePath) {
|
||||
const errMsg = `Page ${url.pathname} not found`;
|
||||
console.error(errMsg);
|
||||
throw new Error(errMsg);
|
||||
}
|
||||
|
||||
const pageName = grabPageName({ path: match.filePath });
|
||||
|
||||
const module: BunextPageModule = await import(match.filePath);
|
||||
// const config = module.config as ServerRouteConfig | undefined;
|
||||
|
||||
const routeParams = await grabRouteParams({ req, server });
|
||||
|
||||
const serverRes = await (async () => {
|
||||
try {
|
||||
return await module["server"]?.(routeParams);
|
||||
} catch (error) {
|
||||
return {};
|
||||
}
|
||||
})();
|
||||
|
||||
const Component = module.default as FC<any>;
|
||||
const component = <Component pageProps={serverRes} />;
|
||||
|
||||
const html = await genWebHTML({
|
||||
component,
|
||||
pageProps: serverRes,
|
||||
pageName,
|
||||
module,
|
||||
});
|
||||
|
||||
return new Response(html, {
|
||||
headers: {
|
||||
"Content-Type": "text/html",
|
||||
},
|
||||
});
|
||||
} catch (error) {
|
||||
return new Response(`Page Not Found`, {
|
||||
status: 404,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,41 @@
|
||||
import { writeFileSync } from "fs";
|
||||
import path from "path";
|
||||
import grabDirNames from "../../../utils/grab-dir-names";
|
||||
import grabContants from "../../../utils/grab-constants";
|
||||
import genWebHTML from "./generate-web-html";
|
||||
import type { PageDistGenParams } from "../../../types";
|
||||
|
||||
const { BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR } = grabDirNames();
|
||||
|
||||
export default async function (params: PageDistGenParams) {
|
||||
const { ClientRootElementIDName, ClientWindowPagePropsName } =
|
||||
await grabContants();
|
||||
|
||||
const PAGE_DIST_DIR = path.join(HYDRATION_DST_DIR, params.pageName);
|
||||
|
||||
const pageSrcTs = `index.tsx`;
|
||||
|
||||
let script = "";
|
||||
|
||||
script += `import React from "react";\n`;
|
||||
script += `import { hydrateRoot } from "react-dom/client";\n`;
|
||||
script += `import App from "./";\n`;
|
||||
|
||||
script += `declare global {\n`;
|
||||
script += ` interface Window {\n`;
|
||||
script += ` ${ClientWindowPagePropsName}: any;\n`;
|
||||
script += ` }\n`;
|
||||
script += `}\n`;
|
||||
|
||||
script += `const container = document.getElementById("${ClientRootElementIDName}");\n`;
|
||||
script += `hydrateRoot(container, <App {...window.${ClientWindowPagePropsName}} />);\n`;
|
||||
|
||||
const SRC_WRITE_FILE = path.join(PAGE_DIST_DIR, pageSrcTs);
|
||||
writeFileSync(SRC_WRITE_FILE, script, "utf-8");
|
||||
|
||||
let html = await genWebHTML(params);
|
||||
const pageHtml = `index.html`;
|
||||
|
||||
const HTML_WRITE_FILE = path.join(PAGE_DIST_DIR, pageHtml);
|
||||
writeFileSync(HTML_WRITE_FILE, html, "utf-8");
|
||||
}
|
||||
Reference in New Issue
Block a user