Add dist
This commit is contained in:
+138
@@ -0,0 +1,138 @@
|
||||
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 AppNames from "../../utils/grab-app-names";
|
||||
import isDevelopment from "../../utils/is-development";
|
||||
import { execSync } from "child_process";
|
||||
import grabConstants from "../../utils/grab-constants";
|
||||
const { HYDRATION_DST_DIR, PAGES_DIR, HYDRATION_DST_DIR_MAP_JSON_FILE } = grabDirNames();
|
||||
const tailwindPlugin = {
|
||||
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",
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
export default async function allPagesBundler(params) {
|
||||
const pages = grabAllPages({ exclude_api: true });
|
||||
const { ClientRootElementIDName, ClientRootComponentWindowName } = grabConstants();
|
||||
const virtualEntries = {};
|
||||
const dev = isDevelopment();
|
||||
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`;
|
||||
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`;
|
||||
virtualEntries[key] = txt;
|
||||
}
|
||||
const virtualPlugin = {
|
||||
name: "virtual-entrypoints",
|
||||
setup(build) {
|
||||
build.onResolve({ filter: /^virtual:/ }, (args) => ({
|
||||
path: args.path.replace("virtual:", ""),
|
||||
namespace: "virtual",
|
||||
}));
|
||||
build.onLoad({ filter: /.*/, namespace: "virtual" }, (args) => ({
|
||||
contents: virtualEntries[args.path],
|
||||
loader: "tsx",
|
||||
resolveDir: process.cwd(),
|
||||
}));
|
||||
},
|
||||
};
|
||||
const artifactTracker = {
|
||||
name: "artifact-tracker",
|
||||
setup(build) {
|
||||
build.onStart(() => {
|
||||
console.time("build");
|
||||
});
|
||||
build.onEnd((result) => {
|
||||
if (result.errors.length > 0)
|
||||
return;
|
||||
const artifacts = 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 (!target_page || !meta.entryPoint) {
|
||||
return undefined;
|
||||
}
|
||||
const { file_name, local_path, url_path } = target_page;
|
||||
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));
|
||||
global.BUNDLER_CTX_MAP = final_artifacts;
|
||||
params?.post_build_fn?.({ artifacts: final_artifacts });
|
||||
writeFileSync(HYDRATION_DST_DIR_MAP_JSON_FILE, JSON.stringify(artifacts));
|
||||
}
|
||||
console.timeEnd("build");
|
||||
if (params?.exit_after_first_build) {
|
||||
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: true,
|
||||
format: "esm",
|
||||
target: "es2020",
|
||||
platform: "browser",
|
||||
define: {
|
||||
"process.env.NODE_ENV": JSON.stringify(dev ? "development" : "production"),
|
||||
},
|
||||
entryNames: "[dir]/[name]/[hash]",
|
||||
metafile: true,
|
||||
plugins: [tailwindPlugin, virtualPlugin, artifactTracker],
|
||||
jsx: "automatic",
|
||||
splitting: true,
|
||||
});
|
||||
await ctx.rebuild();
|
||||
if (params?.watch) {
|
||||
global.BUNDLER_CTX = ctx;
|
||||
global.BUNDLER_CTX.watch();
|
||||
}
|
||||
}
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
import { readFileSync } from "fs";
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import grabCacheNames from "./grab-cache-names";
|
||||
import path from "path";
|
||||
export default function getCache({ key, paradigm }) {
|
||||
try {
|
||||
const { BUNEXT_CACHE_DIR } = grabDirNames();
|
||||
const { cache_name } = grabCacheNames({ key, paradigm });
|
||||
const content = readFileSync(path.join(BUNEXT_CACHE_DIR, cache_name), "utf-8");
|
||||
return content;
|
||||
}
|
||||
catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
+6
@@ -0,0 +1,6 @@
|
||||
export default function grabCacheNames({ key, paradigm = "html" }) {
|
||||
const parsed_key = encodeURIComponent(key);
|
||||
const cache_name = `${parsed_key}.res.${paradigm}`;
|
||||
const cache_meta_name = `${parsed_key}.meta.json`;
|
||||
return { cache_name, cache_meta_name };
|
||||
}
|
||||
+21
@@ -0,0 +1,21 @@
|
||||
import { readdirSync } from "fs";
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import trimCacheKey from "./trim-cache-key";
|
||||
export default async function trimAllCache() {
|
||||
try {
|
||||
const { BUNEXT_CACHE_DIR } = grabDirNames();
|
||||
const cached_items = readdirSync(BUNEXT_CACHE_DIR);
|
||||
for (let i = 0; i < cached_items.length; i++) {
|
||||
const cached_item = cached_items[i];
|
||||
if (!cached_item.endsWith(`.meta.json`))
|
||||
continue;
|
||||
const cache_key = decodeURIComponent(cached_item.replace(/\.meta\.json/, ""));
|
||||
const trim_key = await trimCacheKey({
|
||||
key: cache_key,
|
||||
});
|
||||
}
|
||||
}
|
||||
catch (error) {
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
+40
@@ -0,0 +1,40 @@
|
||||
import { readFileSync, unlinkSync } from "fs";
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import grabCacheNames from "./grab-cache-names";
|
||||
import path from "path";
|
||||
import { AppData } from "../../data/app-data";
|
||||
export default async function trimCacheKey({ key, }) {
|
||||
try {
|
||||
const { BUNEXT_CACHE_DIR } = grabDirNames();
|
||||
const { cache_name, cache_meta_name } = grabCacheNames({
|
||||
key,
|
||||
});
|
||||
const config = global.CONFIG;
|
||||
const default_expiry_time_seconds = config.defaultCacheExpiry ||
|
||||
AppData["DefaultCacheExpiryTimeSeconds"];
|
||||
const default_expiry_time_milliseconds = default_expiry_time_seconds * 1000;
|
||||
const cache_content_path = path.join(BUNEXT_CACHE_DIR, cache_name);
|
||||
const cache_meta_path = path.join(BUNEXT_CACHE_DIR, cache_meta_name);
|
||||
const cache_meta = JSON.parse(readFileSync(cache_meta_path, "utf-8"));
|
||||
const expiry_milliseconds = cache_meta.expiry_seconds
|
||||
? cache_meta.expiry_seconds * 1000
|
||||
: default_expiry_time_milliseconds;
|
||||
if (Date.now() - cache_meta.date_created < expiry_milliseconds) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Cache has not expired yet`,
|
||||
};
|
||||
}
|
||||
unlinkSync(cache_content_path);
|
||||
unlinkSync(cache_meta_path);
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Trim cache key ERROR: ${error.message}`,
|
||||
};
|
||||
}
|
||||
}
|
||||
Vendored
+38
@@ -0,0 +1,38 @@
|
||||
import { existsSync, writeFileSync } from "fs";
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import grabCacheNames from "./grab-cache-names";
|
||||
import path from "path";
|
||||
export default async function writeCache({ key, value, paradigm = "html", expiry_seconds, }) {
|
||||
try {
|
||||
const { BUNEXT_CACHE_DIR } = grabDirNames();
|
||||
const { cache_meta_name, cache_name } = grabCacheNames({
|
||||
key,
|
||||
paradigm,
|
||||
});
|
||||
const target_path = path.join(BUNEXT_CACHE_DIR, cache_name);
|
||||
if (existsSync(target_path)) {
|
||||
return {
|
||||
success: false,
|
||||
msg: `Cache entry already exists`,
|
||||
};
|
||||
}
|
||||
writeFileSync(path.join(target_path), value);
|
||||
const cache_file_meta = {
|
||||
date_created: Date.now(),
|
||||
paradigm,
|
||||
};
|
||||
if (expiry_seconds) {
|
||||
cache_file_meta.expiry_seconds = expiry_seconds;
|
||||
}
|
||||
writeFileSync(path.join(BUNEXT_CACHE_DIR, cache_meta_name), JSON.stringify(cache_file_meta));
|
||||
return {
|
||||
success: true,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
success: false,
|
||||
msg: error.message,
|
||||
};
|
||||
}
|
||||
}
|
||||
Vendored
+19
@@ -0,0 +1,19 @@
|
||||
import { existsSync } from "fs";
|
||||
import grabDirNames from "../utils/grab-dir-names";
|
||||
import exitWithError from "../utils/exit-with-error";
|
||||
export default async function grabConfig() {
|
||||
try {
|
||||
const { CONFIG_FILE } = grabDirNames();
|
||||
if (!existsSync(CONFIG_FILE)) {
|
||||
exitWithError(`Config file \`${CONFIG_FILE}\` doesn't exist!`);
|
||||
}
|
||||
const config = (await import(CONFIG_FILE)).default;
|
||||
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;
|
||||
}
|
||||
}
|
||||
Vendored
+22
@@ -0,0 +1,22 @@
|
||||
import { existsSync, mkdirSync, statSync, writeFileSync } from "fs";
|
||||
import grabDirNames from "../utils/grab-dir-names";
|
||||
import { execSync } from "child_process";
|
||||
export default async function () {
|
||||
const dirNames = grabDirNames();
|
||||
execSync(`rm -rf ${dirNames.BUNEXT_CACHE_DIR}`);
|
||||
const keys = Object.keys(dirNames);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const key = keys[i];
|
||||
const dir = dirNames[key];
|
||||
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);
|
||||
}
|
||||
}
|
||||
}
|
||||
Vendored
+8
@@ -0,0 +1,8 @@
|
||||
import { AppData } from "../../data/app-data";
|
||||
import trimAllCache from "../cache/trim-all-cache";
|
||||
export default async function cron() {
|
||||
while (true) {
|
||||
await trimAllCache();
|
||||
await Bun.sleep(AppData["DefaultCronInterval"]);
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
import grabRouteParams from "../../utils/grab-route-params";
|
||||
import grabConstants from "../../utils/grab-constants";
|
||||
import grabRouter from "../../utils/grab-router";
|
||||
export default async function ({ req, server }) {
|
||||
const url = new URL(req.url);
|
||||
const { MBInBytes, ServerDefaultRequestBodyLimitBytes } = grabConstants();
|
||||
const router = grabRouter();
|
||||
const match = router.match(url.pathname);
|
||||
if (!match?.filePath) {
|
||||
const errMsg = `Route ${url.pathname} not found`;
|
||||
return Response.json({
|
||||
success: false,
|
||||
msg: errMsg,
|
||||
}, {
|
||||
status: 401,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
const routeParams = await grabRouteParams({ req });
|
||||
const module = await import(match.filePath);
|
||||
const config = module.config;
|
||||
const contentLength = req.headers.get("content-length");
|
||||
if (contentLength) {
|
||||
const size = parseInt(contentLength, 10);
|
||||
if ((config?.maxRequestBodyMB &&
|
||||
size > config.maxRequestBodyMB * MBInBytes) ||
|
||||
size > ServerDefaultRequestBodyLimitBytes) {
|
||||
return Response.json({
|
||||
success: false,
|
||||
msg: "Request Body Too Large!",
|
||||
}, {
|
||||
status: 413,
|
||||
headers: {
|
||||
"Content-Type": "application/json",
|
||||
},
|
||||
});
|
||||
}
|
||||
}
|
||||
const res = await module["default"]({
|
||||
...routeParams,
|
||||
server,
|
||||
});
|
||||
return res;
|
||||
}
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
import allPagesBundler from "../bundler/all-pages-bundler";
|
||||
import serverPostBuildFn from "./server-post-build-fn";
|
||||
export default async function rebuildBundler() {
|
||||
try {
|
||||
global.ROUTER.reload();
|
||||
await global.BUNDLER_CTX?.dispose();
|
||||
global.BUNDLER_CTX = undefined;
|
||||
await allPagesBundler({
|
||||
watch: true,
|
||||
post_build_fn: serverPostBuildFn,
|
||||
});
|
||||
}
|
||||
catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
}
|
||||
+91
@@ -0,0 +1,91 @@
|
||||
import path from "path";
|
||||
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 grabConstants from "../../utils/grab-constants";
|
||||
import { AppData } from "../../data/app-data";
|
||||
export default async function (params) {
|
||||
const port = grabAppPort();
|
||||
const { PUBLIC_DIR } = grabDirNames();
|
||||
const is_dev = isDevelopment();
|
||||
return {
|
||||
async fetch(req, server) {
|
||||
try {
|
||||
const url = new URL(req.url);
|
||||
const { config } = grabConstants();
|
||||
if (config?.middleware) {
|
||||
const middleware_res = await config.middleware({
|
||||
req,
|
||||
url,
|
||||
server,
|
||||
});
|
||||
if (typeof middleware_res == "object") {
|
||||
return middleware_res;
|
||||
}
|
||||
}
|
||||
if (url.pathname === "/__hmr" && is_dev) {
|
||||
const referer_url = new URL(req.headers.get("referer") || "");
|
||||
const match = global.ROUTER.match(referer_url.pathname);
|
||||
const target_map = match?.filePath
|
||||
? global.BUNDLER_CTX_MAP?.find((m) => m.local_path == match.filePath)
|
||||
: undefined;
|
||||
let controller;
|
||||
const stream = new ReadableStream({
|
||||
start(c) {
|
||||
controller = c;
|
||||
global.HMR_CONTROLLERS.push({
|
||||
controller: c,
|
||||
page_url: referer_url.href,
|
||||
target_map,
|
||||
});
|
||||
},
|
||||
cancel() {
|
||||
const targetControllerIndex = global.HMR_CONTROLLERS.findIndex((c) => c.controller == controller);
|
||||
if (typeof targetControllerIndex == "number" &&
|
||||
targetControllerIndex >= 0) {
|
||||
global.HMR_CONTROLLERS.splice(targetControllerIndex, 1);
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(stream, {
|
||||
headers: {
|
||||
"Content-Type": "text/event-stream",
|
||||
"Cache-Control": "no-cache",
|
||||
Connection: "keep-alive",
|
||||
},
|
||||
});
|
||||
}
|
||||
if (url.pathname.startsWith("/api/")) {
|
||||
return await handleRoutes({ req, server });
|
||||
}
|
||||
if (url.pathname.startsWith("/public/")) {
|
||||
const file = Bun.file(path.join(PUBLIC_DIR, url.pathname.replace(/^\/public/, "")));
|
||||
let res_opts = {};
|
||||
if (!is_dev && url.pathname.match(/__bunext/)) {
|
||||
res_opts.headers = {
|
||||
"Cache-Control": `public, max-age=${AppData["BunextStaticFilesCacheExpiry"]}, must-revalidate`,
|
||||
};
|
||||
}
|
||||
return new Response(file, res_opts);
|
||||
}
|
||||
if (url.pathname.startsWith("/favicon.")) {
|
||||
const file = Bun.file(path.join(PUBLIC_DIR, url.pathname));
|
||||
return new Response(file);
|
||||
}
|
||||
return await handleWebPages({ req });
|
||||
}
|
||||
catch (error) {
|
||||
return new Response(`Server Error: ${error.message}`, {
|
||||
status: 500,
|
||||
});
|
||||
}
|
||||
},
|
||||
port,
|
||||
idleTimeout: 0,
|
||||
development: {
|
||||
hmr: true,
|
||||
},
|
||||
};
|
||||
}
|
||||
+26
@@ -0,0 +1,26 @@
|
||||
import _ from "lodash";
|
||||
export default async function serverPostBuildFn({ artifacts }) {
|
||||
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);
|
||||
const final_artifact = {
|
||||
..._.omit(controller, ["controller"]),
|
||||
target_map: target_artifact,
|
||||
};
|
||||
if (!target_artifact) {
|
||||
delete final_artifact.target_map;
|
||||
}
|
||||
try {
|
||||
controller.controller.enqueue(`event: update\ndata: ${JSON.stringify(final_artifact)}\n\n`);
|
||||
}
|
||||
catch {
|
||||
global.HMR_CONTROLLERS.splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
+46
@@ -0,0 +1,46 @@
|
||||
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";
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import EJSON from "../../utils/ejson";
|
||||
import { readFileSync } from "fs";
|
||||
import cron from "./cron";
|
||||
const { HYDRATION_DST_DIR_MAP_JSON_FILE } = grabDirNames();
|
||||
export default async function startServer(params) {
|
||||
const { name } = AppNames;
|
||||
const serverParams = await serverParamsGen();
|
||||
if (params?.dev) {
|
||||
await allPagesBundler({
|
||||
watch: true,
|
||||
post_build_fn: serverPostBuildFn,
|
||||
});
|
||||
watcher();
|
||||
}
|
||||
else {
|
||||
const artifacts = EJSON.parse(readFileSync(HYDRATION_DST_DIR_MAP_JSON_FILE, "utf-8"));
|
||||
if (!artifacts?.[0]) {
|
||||
console.error(`Please build first.`);
|
||||
process.exit(1);
|
||||
}
|
||||
global.BUNDLER_CTX_MAP = artifacts;
|
||||
global.IS_FIRST_BUNDLE_READY = true;
|
||||
cron();
|
||||
}
|
||||
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;
|
||||
console.log(`${name} Server Running on http://localhost:${server.port} ...`);
|
||||
return server;
|
||||
}
|
||||
Vendored
+31
@@ -0,0 +1,31 @@
|
||||
import { watch, existsSync } from "fs";
|
||||
import path from "path";
|
||||
import grabDirNames from "../../utils/grab-dir-names";
|
||||
import rebuildBundler from "./rebuild-bundler";
|
||||
const { SRC_DIR } = grabDirNames();
|
||||
export default function watcher() {
|
||||
watch(SRC_DIR, {
|
||||
recursive: true,
|
||||
persistent: true,
|
||||
}, async (event, filename) => {
|
||||
if (!filename)
|
||||
return;
|
||||
if (event !== "rename")
|
||||
return;
|
||||
if (global.RECOMPILING)
|
||||
return;
|
||||
const fullPath = path.join(SRC_DIR, filename);
|
||||
const action = existsSync(fullPath) ? "created" : "deleted";
|
||||
try {
|
||||
global.RECOMPILING = true;
|
||||
console.log(`Page ${action}: ${filename}. Rebuilding ...`);
|
||||
await rebuildBundler();
|
||||
}
|
||||
catch (error) {
|
||||
console.error(error);
|
||||
}
|
||||
finally {
|
||||
global.RECOMPILING = false;
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import path from "path";
|
||||
import grabContants from "../../../utils/grab-constants";
|
||||
import EJSON from "../../../utils/ejson";
|
||||
import isDevelopment from "../../../utils/is-development";
|
||||
import grabWebPageHydrationScript from "./grab-web-page-hydration-script";
|
||||
import grabWebMetaHTML from "./grab-web-meta-html";
|
||||
export default async function genWebHTML({ component, pageProps, bundledMap, head: Head, module, meta, routeParams, }) {
|
||||
const { ClientRootElementIDName, ClientWindowPagePropsName } = grabContants();
|
||||
const { renderToString } = await import(path.join(process.cwd(), "node_modules", "react-dom", "server"));
|
||||
const componentHTML = renderToString(component);
|
||||
const headHTML = Head
|
||||
? renderToString(_jsx(Head, { serverRes: pageProps, ctx: routeParams }))
|
||||
: "";
|
||||
let html = `<!DOCTYPE html>\n`;
|
||||
html += `<html>\n`;
|
||||
html += ` <head>\n`;
|
||||
html += ` <meta charset="utf-8" />\n`;
|
||||
html += ` <meta name="viewport" content="width=device-width, initial-scale=1.0">\n`;
|
||||
if (meta) {
|
||||
html += ` ${grabWebMetaHTML({ meta })}\n`;
|
||||
}
|
||||
if (bundledMap?.css_path) {
|
||||
html += ` <link rel="stylesheet" href="/${bundledMap.css_path}" />\n`;
|
||||
}
|
||||
html += ` <script>window.${ClientWindowPagePropsName} = ${EJSON.stringify(pageProps || {}) || "{}"}</script>\n`;
|
||||
if (bundledMap?.path) {
|
||||
html += ` <script src="/${bundledMap.path}" type="module" async></script>\n`;
|
||||
}
|
||||
if (isDevelopment()) {
|
||||
html += `<script defer>\n${await grabWebPageHydrationScript({ bundledMap })}\n</script>\n`;
|
||||
}
|
||||
if (headHTML) {
|
||||
html += ` ${headHTML}\n`;
|
||||
}
|
||||
html += ` </head>\n`;
|
||||
html += ` <body>\n`;
|
||||
html += ` <div id="${ClientRootElementIDName}">${componentHTML}</div>\n`;
|
||||
html += ` </body>\n`;
|
||||
html += `</html>\n`;
|
||||
return html;
|
||||
}
|
||||
@@ -0,0 +1,109 @@
|
||||
import { jsx as _jsx } from "react/jsx-runtime";
|
||||
import grabDirNames from "../../../utils/grab-dir-names";
|
||||
import grabRouteParams from "../../../utils/grab-route-params";
|
||||
import path from "path";
|
||||
import AppNames from "../../../utils/grab-app-names";
|
||||
import { existsSync } from "fs";
|
||||
import grabPageErrorComponent from "./grab-page-error-component";
|
||||
class NotFoundError extends Error {
|
||||
}
|
||||
export default async function grabPageComponent({ req, file_path: passed_file_path, }) {
|
||||
const url = req?.url ? new URL(req.url) : undefined;
|
||||
const router = global.ROUTER;
|
||||
const { PAGES_DIR } = grabDirNames();
|
||||
let routeParams = undefined;
|
||||
try {
|
||||
routeParams = req ? await grabRouteParams({ req }) : undefined;
|
||||
let url_path = url ? url.pathname : undefined;
|
||||
if (url_path && url?.search) {
|
||||
url_path += url.search;
|
||||
}
|
||||
const match = url_path ? router.match(url_path) : undefined;
|
||||
if (!match?.filePath && url?.pathname) {
|
||||
throw new NotFoundError(`Page ${url.pathname} not found`);
|
||||
}
|
||||
const file_path = match?.filePath || passed_file_path;
|
||||
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 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`;
|
||||
const root_pages_component_js_file = `${path.join(PAGES_DIR, AppNames["RootPagesComponentName"])}.js`;
|
||||
const root_pages_component_jsx_file = `${path.join(PAGES_DIR, AppNames["RootPagesComponentName"])}.jsx`;
|
||||
const root_file = existsSync(root_pages_component_tsx_file)
|
||||
? root_pages_component_tsx_file
|
||||
: existsSync(root_pages_component_ts_file)
|
||||
? root_pages_component_ts_file
|
||||
: existsSync(root_pages_component_jsx_file)
|
||||
? root_pages_component_jsx_file
|
||||
: existsSync(root_pages_component_js_file)
|
||||
? root_pages_component_js_file
|
||||
: undefined;
|
||||
const now = Date.now();
|
||||
const root_module = root_file
|
||||
? await import(`${root_file}?t=${now}`)
|
||||
: undefined;
|
||||
const RootComponent = root_module?.default;
|
||||
// const component_file_path = root_module
|
||||
// ? `${file_path}`
|
||||
// : `${file_path}?t=${global.LAST_BUILD_TIME ?? 0}`;
|
||||
const module = await import(`${file_path}?t=${now}`);
|
||||
const serverRes = await (async () => {
|
||||
try {
|
||||
if (routeParams) {
|
||||
const serverData = await module["server"]?.(routeParams);
|
||||
return {
|
||||
...serverData,
|
||||
query: match?.query,
|
||||
};
|
||||
}
|
||||
return {
|
||||
query: match?.query,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
return {
|
||||
query: match?.query,
|
||||
};
|
||||
}
|
||||
})();
|
||||
const meta = module.meta
|
||||
? typeof module.meta == "function" && routeParams
|
||||
? await module.meta({
|
||||
ctx: routeParams,
|
||||
serverRes,
|
||||
})
|
||||
: typeof module.meta == "object"
|
||||
? module.meta
|
||||
: undefined
|
||||
: undefined;
|
||||
const Component = module.default;
|
||||
const Head = module.Head;
|
||||
const component = RootComponent ? (_jsx(RootComponent, { ...serverRes, children: _jsx(Component, { ...serverRes }) })) : (_jsx(Component, { ...serverRes }));
|
||||
return {
|
||||
component,
|
||||
serverRes,
|
||||
routeParams,
|
||||
module,
|
||||
bundledMap,
|
||||
meta,
|
||||
head: Head,
|
||||
};
|
||||
}
|
||||
catch (error) {
|
||||
return await grabPageErrorComponent({
|
||||
error,
|
||||
routeParams,
|
||||
is404: error instanceof NotFoundError,
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
||||
import grabDirNames from "../../../utils/grab-dir-names";
|
||||
export default async function grabPageErrorComponent({ error, routeParams, is404, }) {
|
||||
const router = global.ROUTER;
|
||||
const { BUNX_ROOT_500_PRESET_COMPONENT, BUNX_ROOT_404_PRESET_COMPONENT } = grabDirNames();
|
||||
const errorRoute = is404 ? "/404" : "/500";
|
||||
const presetComponent = is404
|
||||
? BUNX_ROOT_404_PRESET_COMPONENT
|
||||
: BUNX_ROOT_500_PRESET_COMPONENT;
|
||||
try {
|
||||
const match = router.match(errorRoute);
|
||||
const filePath = match?.filePath || presetComponent;
|
||||
const bundledMap = match?.filePath
|
||||
? (global.BUNDLER_CTX_MAP?.find((m) => m.local_path === match.filePath) ?? {})
|
||||
: {};
|
||||
const module = await import(filePath);
|
||||
const Component = module.default;
|
||||
const component = _jsx(Component, { children: _jsx("span", { children: error.message }) });
|
||||
return {
|
||||
component,
|
||||
routeParams,
|
||||
module,
|
||||
bundledMap,
|
||||
};
|
||||
}
|
||||
catch {
|
||||
const DefaultNotFound = () => (_jsxs("div", { style: {
|
||||
width: "100vw",
|
||||
height: "100vh",
|
||||
display: "flex",
|
||||
alignItems: "center",
|
||||
justifyContent: "center",
|
||||
flexDirection: "column",
|
||||
}, children: [_jsx("h1", { children: is404 ? "404 Not Found" : "500 Internal Server Error" }), _jsx("span", { children: error.message })] }));
|
||||
return {
|
||||
component: _jsx(DefaultNotFound, {}),
|
||||
routeParams,
|
||||
module: { default: DefaultNotFound },
|
||||
bundledMap: {},
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
export default function grabWebMetaHTML({ meta }) {
|
||||
let html = ``;
|
||||
if (meta.title) {
|
||||
html += ` <title>${meta.title}</title>\n`;
|
||||
}
|
||||
if (meta.description) {
|
||||
html += ` <meta name="description" content="${meta.description}" />\n`;
|
||||
}
|
||||
if (meta.keywords) {
|
||||
const keywords = Array.isArray(meta.keywords)
|
||||
? meta.keywords.join(", ")
|
||||
: meta.keywords;
|
||||
html += ` <meta name="keywords" content="${keywords}" />\n`;
|
||||
}
|
||||
if (meta.author) {
|
||||
html += ` <meta name="author" content="${meta.author}" />\n`;
|
||||
}
|
||||
if (meta.robots) {
|
||||
html += ` <meta name="robots" content="${meta.robots}" />\n`;
|
||||
}
|
||||
if (meta.canonical) {
|
||||
html += ` <link rel="canonical" href="${meta.canonical}" />\n`;
|
||||
}
|
||||
if (meta.themeColor) {
|
||||
html += ` <meta name="theme-color" content="${meta.themeColor}" />\n`;
|
||||
}
|
||||
if (meta.og) {
|
||||
const { og } = meta;
|
||||
if (og.title)
|
||||
html += ` <meta property="og:title" content="${og.title}" />\n`;
|
||||
if (og.description)
|
||||
html += ` <meta property="og:description" content="${og.description}" />\n`;
|
||||
if (og.image)
|
||||
html += ` <meta property="og:image" content="${og.image}" />\n`;
|
||||
if (og.url)
|
||||
html += ` <meta property="og:url" content="${og.url}" />\n`;
|
||||
if (og.type)
|
||||
html += ` <meta property="og:type" content="${og.type}" />\n`;
|
||||
if (og.siteName)
|
||||
html += ` <meta property="og:site_name" content="${og.siteName}" />\n`;
|
||||
if (og.locale)
|
||||
html += ` <meta property="og:locale" content="${og.locale}" />\n`;
|
||||
}
|
||||
if (meta.twitter) {
|
||||
const { twitter } = meta;
|
||||
if (twitter.card)
|
||||
html += ` <meta name="twitter:card" content="${twitter.card}" />\n`;
|
||||
if (twitter.title)
|
||||
html += ` <meta name="twitter:title" content="${twitter.title}" />\n`;
|
||||
if (twitter.description)
|
||||
html += ` <meta name="twitter:description" content="${twitter.description}" />\n`;
|
||||
if (twitter.image)
|
||||
html += ` <meta name="twitter:image" content="${twitter.image}" />\n`;
|
||||
if (twitter.site)
|
||||
html += ` <meta name="twitter:site" content="${twitter.site}" />\n`;
|
||||
if (twitter.creator)
|
||||
html += ` <meta name="twitter:creator" content="${twitter.creator}" />\n`;
|
||||
}
|
||||
return html;
|
||||
}
|
||||
@@ -0,0 +1,55 @@
|
||||
import grabDirNames from "../../../utils/grab-dir-names";
|
||||
const { BUNX_HYDRATION_SRC_DIR } = grabDirNames();
|
||||
export default async function ({ bundledMap }) {
|
||||
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;
|
||||
}
|
||||
@@ -0,0 +1,77 @@
|
||||
import isDevelopment from "../../../utils/is-development";
|
||||
import getCache from "../../cache/get-cache";
|
||||
import writeCache from "../../cache/write-cache";
|
||||
import genWebHTML from "./generate-web-html";
|
||||
import grabPageComponent from "./grab-page-component";
|
||||
import grabPageErrorComponent from "./grab-page-error-component";
|
||||
export default async function handleWebPages({ req, }) {
|
||||
try {
|
||||
if (!isDevelopment()) {
|
||||
const url = new URL(req.url);
|
||||
const key = url.pathname + (url.search || "");
|
||||
const existing_cache = getCache({ key, paradigm: "html" });
|
||||
if (existing_cache) {
|
||||
const res_opts = {
|
||||
headers: {
|
||||
"Content-Type": "text/html",
|
||||
"X-Bunext-Cache": "HIT",
|
||||
},
|
||||
};
|
||||
return new Response(existing_cache, res_opts);
|
||||
}
|
||||
}
|
||||
const componentRes = await grabPageComponent({ req });
|
||||
return await generateRes(componentRes);
|
||||
}
|
||||
catch (error) {
|
||||
const componentRes = await grabPageErrorComponent({ error });
|
||||
return await generateRes(componentRes);
|
||||
}
|
||||
}
|
||||
async function generateRes({ component, module, bundledMap, head, meta, routeParams, serverRes, }) {
|
||||
const html = await genWebHTML({
|
||||
component,
|
||||
pageProps: serverRes,
|
||||
bundledMap,
|
||||
module,
|
||||
meta,
|
||||
head,
|
||||
routeParams,
|
||||
});
|
||||
if (serverRes?.redirect?.destination) {
|
||||
return Response.redirect(serverRes.redirect.destination, serverRes.redirect.permanent
|
||||
? 301
|
||||
: serverRes.redirect.status_code || 302);
|
||||
}
|
||||
const res_opts = {
|
||||
...serverRes?.responseOptions,
|
||||
headers: {
|
||||
"Content-Type": "text/html",
|
||||
...serverRes?.responseOptions?.headers,
|
||||
},
|
||||
};
|
||||
if (isDevelopment()) {
|
||||
res_opts.headers = {
|
||||
...res_opts.headers,
|
||||
"Cache-Control": "no-cache, no-store, must-revalidate",
|
||||
Pragma: "no-cache",
|
||||
Expires: "0",
|
||||
};
|
||||
}
|
||||
const cache_page = module.config?.cachePage || serverRes?.cachePage || false;
|
||||
const expiry_seconds = module.config?.cacheExpiry || serverRes?.cacheExpiry;
|
||||
if (cache_page && routeParams?.url) {
|
||||
const key = routeParams.url.pathname + (routeParams.url.search || "");
|
||||
writeCache({
|
||||
key,
|
||||
value: html,
|
||||
paradigm: "html",
|
||||
expiry_seconds,
|
||||
});
|
||||
}
|
||||
const res = new Response(html, res_opts);
|
||||
if (routeParams?.resTransform) {
|
||||
return await routeParams.resTransform(res);
|
||||
}
|
||||
return res;
|
||||
}
|
||||
Reference in New Issue
Block a user