First working version
This commit is contained in:
+3
-2
@@ -1,4 +1,5 @@
|
||||
#!/usr/bin/env bun
|
||||
import type { BuildConfig } from "bun";
|
||||
import plugin from "bun-plugin-tailwind";
|
||||
import { existsSync } from "fs";
|
||||
import { rm } from "fs/promises";
|
||||
@@ -48,8 +49,8 @@ const parseValue = (value: string): any => {
|
||||
return value;
|
||||
};
|
||||
|
||||
function parseArgs(): Partial<Bun.BuildConfig> {
|
||||
const config: Partial<Bun.BuildConfig> = {};
|
||||
function parseArgs(): Partial<BuildConfig> {
|
||||
const config: any = {};
|
||||
const args = process.argv.slice(2);
|
||||
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
|
||||
@@ -1,101 +1,326 @@
|
||||
import plugin from "bun-plugin-tailwind";
|
||||
import { readdirSync, statSync, unlinkSync } from "fs";
|
||||
import { existsSync, writeFileSync } from "fs";
|
||||
import path from "path";
|
||||
import * as esbuild from "esbuild";
|
||||
import postcss from "postcss";
|
||||
import tailwindcss from "@tailwindcss/postcss";
|
||||
import { readFile } from "fs/promises";
|
||||
import grabAllPages from "../../utils/grab-all-pages";
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import grabPageName from "../../utils/grab-page-name";
|
||||
import writeWebPageHydrationScript from "../server/web-pages/write-web-page-hydration-script";
|
||||
import path from "path";
|
||||
import bundle from "../../utils/bundle";
|
||||
import AppNames from "../../utils/grab-app-names";
|
||||
import type { PageFiles } from "../../types";
|
||||
import isDevelopment from "../../utils/is-development";
|
||||
import type { BundlerCTXMap } from "../../types";
|
||||
import { execSync } from "child_process";
|
||||
import grabConstants from "../../utils/grab-constants";
|
||||
|
||||
const { BUNX_HYDRATION_SRC_DIR, HYDRATION_DST_DIR } = grabDirNames();
|
||||
const { HYDRATION_DST_DIR, PAGES_DIR } = grabDirNames();
|
||||
|
||||
export default async function allPagesBundler() {
|
||||
console.time("build");
|
||||
const tailwindPlugin: esbuild.Plugin = {
|
||||
name: "tailwindcss",
|
||||
setup(build) {
|
||||
build.onLoad({ filter: /\.css$/ }, async (args) => {
|
||||
const source = await readFile(args.path, "utf-8");
|
||||
const result = await postcss([tailwindcss()]).process(source, {
|
||||
from: args.path,
|
||||
});
|
||||
|
||||
return {
|
||||
contents: result.css,
|
||||
loader: "css",
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
type Params = {
|
||||
watch?: boolean;
|
||||
exit_after_first_build?: boolean;
|
||||
post_build_fn?: (params: { artifacts: BundlerCTXMap[] }) => Promise<void>;
|
||||
};
|
||||
|
||||
export default async function allPagesBundler(params?: Params) {
|
||||
const pages = grabAllPages({ exclude_api: true });
|
||||
const { ClientRootElementIDName, ClientRootComponentWindowName } =
|
||||
await grabConstants();
|
||||
|
||||
for (let i = 0; i < pages.length; i++) {
|
||||
const page = pages[i];
|
||||
const virtualEntries: Record<string, string> = {};
|
||||
const dev = isDevelopment();
|
||||
|
||||
if (!isPageValid(page)) {
|
||||
continue;
|
||||
const root_component_path = path.join(
|
||||
PAGES_DIR,
|
||||
`${AppNames["RootPagesComponentName"]}.tsx`,
|
||||
);
|
||||
|
||||
const does_root_exist = existsSync(root_component_path);
|
||||
|
||||
for (const page of pages) {
|
||||
const key = page.local_path;
|
||||
|
||||
let txt = ``;
|
||||
txt += `import { hydrateRoot } from "react-dom/client";\n`;
|
||||
if (does_root_exist) {
|
||||
txt += `import Root from "${root_component_path}";\n`;
|
||||
}
|
||||
txt += `import Page from "${page.local_path}";\n\n`;
|
||||
txt += `const pageProps = window.__PAGE_PROPS__ || {};\n`;
|
||||
|
||||
const pageName = grabPageName({ path: page.local_path });
|
||||
if (does_root_exist) {
|
||||
txt += `const component = <Root {...pageProps}><Page {...pageProps} /></Root>\n`;
|
||||
} else {
|
||||
txt += `const component = <Page {...pageProps} />\n`;
|
||||
}
|
||||
txt += `const root = hydrateRoot(document.getElementById("${ClientRootElementIDName}"), component);\n\n`;
|
||||
txt += `window.${ClientRootComponentWindowName} = root;\n`;
|
||||
|
||||
writeWebPageHydrationScript({
|
||||
pageName,
|
||||
page_file: page.local_path,
|
||||
});
|
||||
virtualEntries[key] = txt;
|
||||
}
|
||||
|
||||
const hydration_files = readdirSync(BUNX_HYDRATION_SRC_DIR);
|
||||
const virtualPlugin: esbuild.Plugin = {
|
||||
name: "virtual-entrypoints",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^virtual:/ }, (args) => ({
|
||||
path: args.path.replace("virtual:", ""),
|
||||
namespace: "virtual",
|
||||
}));
|
||||
|
||||
for (let i = 0; i < hydration_files.length; i++) {
|
||||
const hydration_file = hydration_files[i];
|
||||
build.onLoad({ filter: /.*/, namespace: "virtual" }, (args) => ({
|
||||
contents: virtualEntries[args.path],
|
||||
loader: "tsx",
|
||||
resolveDir: process.cwd(),
|
||||
}));
|
||||
},
|
||||
};
|
||||
|
||||
const valid_file = pages.find((p) => {
|
||||
if (!isPageValid(p)) {
|
||||
return false;
|
||||
}
|
||||
const artifactTracker: esbuild.Plugin = {
|
||||
name: "artifact-tracker",
|
||||
setup(build) {
|
||||
build.onStart(() => {
|
||||
console.time("build");
|
||||
});
|
||||
|
||||
const pageName = grabPageName({ path: p.local_path });
|
||||
build.onEnd((result) => {
|
||||
if (result.errors.length > 0) return;
|
||||
|
||||
const file_tsx_name = `${pageName}.tsx`;
|
||||
if (file_tsx_name == hydration_file) {
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
});
|
||||
const artifacts: (BundlerCTXMap | undefined)[] = Object.entries(
|
||||
result.metafile!.outputs,
|
||||
)
|
||||
.filter(([, meta]) => meta.entryPoint)
|
||||
.map(([outputPath, meta]) => {
|
||||
const target_page = pages.find((p) => {
|
||||
return (
|
||||
meta.entryPoint === `virtual:${p.local_path}`
|
||||
);
|
||||
});
|
||||
|
||||
if (!valid_file) {
|
||||
unlinkSync(path.join(BUNX_HYDRATION_SRC_DIR, hydration_file));
|
||||
}
|
||||
}
|
||||
if (!target_page || !meta.entryPoint) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const entrypoints = readdirSync(BUNX_HYDRATION_SRC_DIR)
|
||||
.filter((f) => f.endsWith(".tsx"))
|
||||
.map((f) => path.join(BUNX_HYDRATION_SRC_DIR, f))
|
||||
.filter((f) => statSync(f).isFile());
|
||||
const { file_name, local_path, url_path } = target_page;
|
||||
|
||||
bundle({
|
||||
src: entrypoints.join(" "),
|
||||
out_dir: HYDRATION_DST_DIR,
|
||||
exec_options: { stdio: "ignore" },
|
||||
const cssPath = meta.cssBundle || undefined;
|
||||
|
||||
return {
|
||||
path: outputPath,
|
||||
hash: path.basename(
|
||||
outputPath,
|
||||
path.extname(outputPath),
|
||||
),
|
||||
type: outputPath.endsWith(".css")
|
||||
? "text/css"
|
||||
: "text/javascript",
|
||||
entrypoint: meta.entryPoint,
|
||||
css_path: cssPath,
|
||||
file_name,
|
||||
local_path,
|
||||
url_path,
|
||||
};
|
||||
});
|
||||
|
||||
if (artifacts.length > 0) {
|
||||
const final_artifacts = artifacts.filter((a) =>
|
||||
Boolean(a?.entrypoint),
|
||||
) as BundlerCTXMap[];
|
||||
// writeFileSync(
|
||||
// HYDRATION_DST_DIR_MAP_JSON_FILE,
|
||||
// JSON.stringify(final_artifacts),
|
||||
// );
|
||||
|
||||
global.BUNDLER_CTX_MAP = final_artifacts;
|
||||
params?.post_build_fn?.({ artifacts: final_artifacts });
|
||||
}
|
||||
|
||||
console.timeEnd("build");
|
||||
|
||||
if (params?.exit_after_first_build) {
|
||||
console.log(
|
||||
"global.BUNDLER_CTX_MAP",
|
||||
global.BUNDLER_CTX_MAP,
|
||||
);
|
||||
process.exit();
|
||||
}
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
execSync(`rm -rf ${HYDRATION_DST_DIR}`);
|
||||
|
||||
const ctx = await esbuild.context({
|
||||
entryPoints: Object.keys(virtualEntries).map((k) => `virtual:${k}`),
|
||||
outdir: HYDRATION_DST_DIR,
|
||||
bundle: true,
|
||||
minify: !dev,
|
||||
format: "esm",
|
||||
target: "es2020",
|
||||
platform: "browser",
|
||||
define: {
|
||||
"process.env.NODE_ENV": JSON.stringify(
|
||||
dev ? "development" : "production",
|
||||
),
|
||||
},
|
||||
entryNames: "[dir]/[name]/[hash]",
|
||||
// entryNames: "[name]/[hash]",
|
||||
metafile: true,
|
||||
plugins: [tailwindPlugin, virtualPlugin, artifactTracker],
|
||||
jsx: "automatic",
|
||||
});
|
||||
|
||||
// console.log(`Bundling ...`);
|
||||
await ctx.rebuild();
|
||||
|
||||
// const result = await Bun.build({
|
||||
// entrypoints,
|
||||
// outdir: HYDRATION_DST_DIR,
|
||||
// plugins: [plugin],
|
||||
// minify: true,
|
||||
// target: "browser",
|
||||
// // sourcemap: "linked",
|
||||
// define: {
|
||||
// "process.env.NODE_ENV": JSON.stringify(
|
||||
// isDevelopment() ? "development" : "production",
|
||||
// ),
|
||||
// },
|
||||
// });
|
||||
|
||||
// console.log("result", result);
|
||||
|
||||
console.timeEnd("build");
|
||||
if (params?.watch) {
|
||||
global.BUNDLER_CTX = ctx;
|
||||
global.BUNDLER_CTX.watch();
|
||||
}
|
||||
}
|
||||
|
||||
function isPageValid(page: PageFiles): boolean {
|
||||
if (page.file_name == AppNames["RootPagesComponentName"]) {
|
||||
return false;
|
||||
}
|
||||
// import plugin from "bun-plugin-tailwind";
|
||||
// import { readdirSync, statSync, unlinkSync, writeFileSync } from "fs";
|
||||
// import grabAllPages from "../../utils/grab-all-pages";
|
||||
// import grabDirNames from "../../utils/grab-dir-names";
|
||||
// import grabPageName from "../../utils/grab-page-name";
|
||||
// import writeWebPageHydrationScript from "../server/web-pages/write-web-page-hydration-script";
|
||||
// import path from "path";
|
||||
// import bundle from "../../utils/bundle";
|
||||
// import AppNames from "../../utils/grab-app-names";
|
||||
// import type { PageFiles } from "../../types";
|
||||
// import isDevelopment from "../../utils/is-development";
|
||||
// import { execSync } from "child_process";
|
||||
|
||||
if (page.url_path.match(/\(|\)|--/)) {
|
||||
return false;
|
||||
}
|
||||
// const {
|
||||
// BUNX_HYDRATION_SRC_DIR,
|
||||
// HYDRATION_DST_DIR,
|
||||
// HYDRATION_DST_DIR_MAP_JSON_FILE,
|
||||
// } = grabDirNames();
|
||||
|
||||
return true;
|
||||
}
|
||||
// export default async function allPagesBundler() {
|
||||
// console.time("build");
|
||||
|
||||
// const pages = grabAllPages({ exclude_api: true });
|
||||
|
||||
// for (let i = 0; i < pages.length; i++) {
|
||||
// const page = pages[i];
|
||||
|
||||
// if (!isPageValid(page)) {
|
||||
// continue;
|
||||
// }
|
||||
|
||||
// const pageName = grabPageName({ path: page.local_path });
|
||||
|
||||
// writeWebPageHydrationScript({
|
||||
// pageName,
|
||||
// page_file: page.local_path,
|
||||
// });
|
||||
// }
|
||||
|
||||
// // const hydration_files = readdirSync(BUNX_HYDRATION_SRC_DIR);
|
||||
|
||||
// // for (let i = 0; i < hydration_files.length; i++) {
|
||||
// // const hydration_file = hydration_files[i];
|
||||
|
||||
// // const valid_file = pages.find((p) => {
|
||||
// // if (!isPageValid(p)) {
|
||||
// // return false;
|
||||
// // }
|
||||
|
||||
// // const pageName = grabPageName({ path: p.local_path });
|
||||
|
||||
// // const file_tsx_name = `${pageName}.tsx`;
|
||||
// // if (file_tsx_name == hydration_file) {
|
||||
// // return true;
|
||||
// // }
|
||||
// // return false;
|
||||
// // });
|
||||
|
||||
// // if (!valid_file) {
|
||||
// // unlinkSync(path.join(BUNX_HYDRATION_SRC_DIR, hydration_file));
|
||||
// // }
|
||||
// // }
|
||||
|
||||
// // const entrypoints = readdirSync(BUNX_HYDRATION_SRC_DIR)
|
||||
// // .filter((f) => f.endsWith(".tsx"))
|
||||
// // .map((f) => path.join(BUNX_HYDRATION_SRC_DIR, f))
|
||||
// // .filter((f) => statSync(f).isFile());
|
||||
|
||||
// const entrypoints = pages.map((p) => p.local_path);
|
||||
|
||||
// // execSync(`rm -rf ${HYDRATION_DST_DIR}`);
|
||||
|
||||
// // bundle({
|
||||
// // src: entrypoints.join(" "),
|
||||
// // out_dir: HYDRATION_DST_DIR,
|
||||
// // exec_options: { stdio: "ignore" },
|
||||
// // entry_naming: `[dir]/[name]/[hash].js`,
|
||||
// // minify: true,
|
||||
// // target: "browser",
|
||||
// // });
|
||||
|
||||
// // console.log(`Bundling ...`);
|
||||
|
||||
// const result = await Bun.build({
|
||||
// entrypoints,
|
||||
// outdir: HYDRATION_DST_DIR,
|
||||
// plugins: [plugin],
|
||||
// minify: true,
|
||||
// target: "browser",
|
||||
// // sourcemap: "linked",
|
||||
// define: {
|
||||
// "process.env.NODE_ENV": JSON.stringify(
|
||||
// isDevelopment() ? "development" : "production",
|
||||
// ),
|
||||
// },
|
||||
// naming: "[dir]/[name]/[hash].js",
|
||||
// });
|
||||
|
||||
// const artifacts = result.outputs.map(({ path, hash, type }) => {
|
||||
// const target_page = pages.find((p) =>
|
||||
// p.local_path.replace(/src\/pages/, "public/pages"),
|
||||
// );
|
||||
|
||||
// return {
|
||||
// path,
|
||||
// hash,
|
||||
// type,
|
||||
// ...target_page,
|
||||
// };
|
||||
// });
|
||||
|
||||
// if (artifacts?.[0]) {
|
||||
// writeFileSync(
|
||||
// HYDRATION_DST_DIR_MAP_JSON_FILE,
|
||||
// JSON.stringify(artifacts),
|
||||
// );
|
||||
// }
|
||||
|
||||
// console.timeEnd("build");
|
||||
// }
|
||||
|
||||
// function isPageValid(page: PageFiles): boolean {
|
||||
// if (page.file_name == AppNames["RootPagesComponentName"]) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// if (page.url_path.match(/\(|\)|--/)) {
|
||||
// return false;
|
||||
// }
|
||||
|
||||
// return true;
|
||||
// }
|
||||
|
||||
@@ -1,40 +0,0 @@
|
||||
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 {} = 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,
|
||||
};
|
||||
}
|
||||
@@ -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,
|
||||
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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");
|
||||
}
|
||||
+19
-2
@@ -128,7 +128,7 @@ export type LivePageDistGenParams = {
|
||||
head?: ReactNode;
|
||||
pageProps?: any;
|
||||
module?: BunextPageModule;
|
||||
pageName: string;
|
||||
bundledMap: BundlerCTXMap;
|
||||
};
|
||||
|
||||
export type BunextPageModule = {
|
||||
@@ -155,7 +155,7 @@ export type GrabPageComponentRes = {
|
||||
component: JSX.Element;
|
||||
serverRes?: BunextPageModuleServerReturn;
|
||||
routeParams?: BunxRouteParams;
|
||||
pageName: string;
|
||||
bundledMap: BundlerCTXMap;
|
||||
module: BunextPageModule;
|
||||
};
|
||||
|
||||
@@ -164,3 +164,20 @@ export type PageFiles = {
|
||||
url_path: string;
|
||||
file_name: string;
|
||||
};
|
||||
|
||||
export type BundlerCTXMap = {
|
||||
path: string;
|
||||
hash: string;
|
||||
type: string;
|
||||
entrypoint: string;
|
||||
local_path: string;
|
||||
url_path: string;
|
||||
file_name: string;
|
||||
css_path?: string;
|
||||
};
|
||||
|
||||
export type GlobalHMRControllerObject = {
|
||||
controller: ReadableStreamDefaultController<string>;
|
||||
page_url: string;
|
||||
target_map: BundlerCTXMap;
|
||||
};
|
||||
|
||||
+49
-2
@@ -1,12 +1,28 @@
|
||||
import plugin from "bun-plugin-tailwind";
|
||||
import { execSync, type ExecSyncOptions } from "child_process";
|
||||
|
||||
const BuildKeys = [
|
||||
{ key: "production" },
|
||||
{ key: "bytecode" },
|
||||
{ key: "conditions" },
|
||||
{ key: "format" },
|
||||
{ key: "root" },
|
||||
{ key: "splitting" },
|
||||
{ key: "cdd-chunking" },
|
||||
] as const;
|
||||
|
||||
type Params = {
|
||||
src: string;
|
||||
out_dir: string;
|
||||
entry_naming?: string;
|
||||
minify?: boolean;
|
||||
exec_options?: ExecSyncOptions;
|
||||
debug?: boolean;
|
||||
sourcemap?: boolean;
|
||||
target?: "browser" | "node" | "bun";
|
||||
build_options?: {
|
||||
[k in (typeof BuildKeys)[number]["key"]]: string | boolean;
|
||||
};
|
||||
};
|
||||
|
||||
export default function bundle({
|
||||
@@ -15,15 +31,46 @@ export default function bundle({
|
||||
minify = true,
|
||||
exec_options,
|
||||
debug,
|
||||
entry_naming,
|
||||
sourcemap,
|
||||
target,
|
||||
build_options,
|
||||
}: Params) {
|
||||
let cmd = `bun build`;
|
||||
|
||||
cmd += ` ${src} --outdir ${out_dir}`;
|
||||
|
||||
if (minify) {
|
||||
cmd += ` --minify`;
|
||||
}
|
||||
|
||||
if (entry_naming) {
|
||||
cmd += ` --entry-naming "${entry_naming}"`;
|
||||
}
|
||||
|
||||
if (sourcemap) {
|
||||
cmd += ` --sourcemap`;
|
||||
}
|
||||
|
||||
if (target) {
|
||||
cmd += ` --target ${target}`;
|
||||
}
|
||||
|
||||
if (build_options) {
|
||||
const keys = Object.keys(build_options);
|
||||
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i] as (typeof BuildKeys)[number]["key"];
|
||||
const value = build_options[key];
|
||||
|
||||
if (typeof value == "boolean" && value) {
|
||||
cmd += ` --${key}`;
|
||||
} else if (key && value) {
|
||||
cmd += ` --${key} ${value}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
cmd += ` ${src} --outdir ${out_dir}`;
|
||||
|
||||
if (debug) {
|
||||
console.log("cmd =>", cmd);
|
||||
}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { existsSync, readdirSync, statSync } from "fs";
|
||||
import grabDirNames from "./grab-dir-names";
|
||||
import path from "path";
|
||||
import type { PageFiles } from "../types";
|
||||
import AppNames from "./grab-app-names";
|
||||
|
||||
type Params = {
|
||||
exclude_api?: boolean;
|
||||
@@ -37,11 +38,11 @@ function grabPageDirRecursively({ page_dir }: { page_dir: string }) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (page.match(/__root\.(tx|js)x?/)) {
|
||||
if (page.match(new RegExp(`${AppNames["RootPagesComponentName"]}`))) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (page.match(/\(|\)/)) {
|
||||
if (page.match(/\(|\)|--/)) {
|
||||
continue;
|
||||
}
|
||||
|
||||
|
||||
@@ -7,6 +7,7 @@ export default async function grabConstants() {
|
||||
|
||||
const ClientWindowPagePropsName = "__PAGE_PROPS__";
|
||||
const ClientRootElementIDName = "__bunext";
|
||||
const ClientRootComponentWindowName = "BUNEXT_ROOT";
|
||||
|
||||
const ServerDefaultRequestBodyLimitBytes = MB_IN_BYTES * 10;
|
||||
|
||||
@@ -15,5 +16,6 @@ export default async function grabConstants() {
|
||||
ClientWindowPagePropsName,
|
||||
MBInBytes: MB_IN_BYTES,
|
||||
ServerDefaultRequestBodyLimitBytes,
|
||||
};
|
||||
ClientRootComponentWindowName,
|
||||
} as const;
|
||||
}
|
||||
|
||||
@@ -7,6 +7,10 @@ export default function grabDirNames() {
|
||||
const API_DIR = path.join(PAGES_DIR, "api");
|
||||
const PUBLIC_DIR = path.join(ROOT_DIR, "public");
|
||||
const HYDRATION_DST_DIR = path.join(PUBLIC_DIR, "pages");
|
||||
const HYDRATION_DST_DIR_MAP_JSON_FILE = path.join(
|
||||
HYDRATION_DST_DIR,
|
||||
"map.json",
|
||||
);
|
||||
const CONFIG_FILE = path.join(ROOT_DIR, "bunext.config.ts");
|
||||
|
||||
const BUNX_CWD_DIR = path.resolve(ROOT_DIR, ".bunext");
|
||||
@@ -41,5 +45,6 @@ export default function grabDirNames() {
|
||||
BUNX_ROOT_PRESETS_DIR,
|
||||
BUNX_ROOT_500_PRESET_COMPONENT,
|
||||
BUNX_ROOT_500_FILE_NAME,
|
||||
HYDRATION_DST_DIR_MAP_JSON_FILE,
|
||||
};
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user