refactor: centralize server into ServerContext (#26)
This commit centralizes all server related logic into a central ServerContext class.
This commit is contained in:
@@ -4,5 +4,8 @@ fmt:
|
|||||||
lint:
|
lint:
|
||||||
deno lint
|
deno lint
|
||||||
|
|
||||||
|
test:
|
||||||
|
deno test --no-check -A --config tsconfig.json
|
||||||
|
|
||||||
watch_example:
|
watch_example:
|
||||||
deployctl run --watch --no-check example/main.ts
|
deployctl run --watch --no-check example/main.ts
|
||||||
@@ -1,5 +1,5 @@
|
|||||||
import { denoPlugin, esbuild } from "./deps.ts";
|
import { denoPlugin, esbuild } from "./deps.ts";
|
||||||
import { Page } from "./routes.ts";
|
import { Page } from "./types.ts";
|
||||||
|
|
||||||
let esbuildInitalized: boolean | Promise<void> = false;
|
let esbuildInitalized: boolean | Promise<void> = false;
|
||||||
async function ensureEsbuildInialized() {
|
async function ensureEsbuildInialized() {
|
||||||
|
|||||||
@@ -0,0 +1,181 @@
|
|||||||
|
import { extname, mediaTypeLookup, router } from "./deps.ts";
|
||||||
|
import * as rt from "../runtime/deps.ts";
|
||||||
|
import { PageProps } from "../runtime/types.ts";
|
||||||
|
import { Routes } from "./mod.ts";
|
||||||
|
import { Bundler } from "./bundle.ts";
|
||||||
|
import { INTERNAL_PREFIX } from "./constants.ts";
|
||||||
|
import { JS_PREFIX } from "./constants.ts";
|
||||||
|
import { BUILD_ID } from "./constants.ts";
|
||||||
|
import { ApiRoute, Page } from "./types.ts";
|
||||||
|
import { render } from "./render.ts";
|
||||||
|
|
||||||
|
export class ServerContext {
|
||||||
|
#pages: Page[];
|
||||||
|
#apiRoutes: ApiRoute[];
|
||||||
|
#bundler: Bundler;
|
||||||
|
|
||||||
|
constructor(pages: Page[], apiRoutes: ApiRoute[]) {
|
||||||
|
this.#pages = pages;
|
||||||
|
this.#apiRoutes = apiRoutes;
|
||||||
|
this.#bundler = new Bundler(pages);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Process the routes into individual components and pages.
|
||||||
|
*/
|
||||||
|
static fromRoutes(routes: Routes): ServerContext {
|
||||||
|
// Get the routes' base URL.
|
||||||
|
const baseUrl = new URL("./", routes.baseUrl).href;
|
||||||
|
|
||||||
|
// Extract all pages, and prepare them into this `Page` structure.
|
||||||
|
const pages: Page[] = [];
|
||||||
|
const apiRoutes: ApiRoute[] = [];
|
||||||
|
for (const [self, module] of Object.entries(routes.pages)) {
|
||||||
|
const url = new URL(self, baseUrl).href;
|
||||||
|
if (!url.startsWith(baseUrl)) {
|
||||||
|
throw new TypeError("Page is not a child of the basepath.");
|
||||||
|
}
|
||||||
|
const path = url.substring(baseUrl.length).substring("pages".length);
|
||||||
|
const baseRoute = path.substring(1, path.length - extname(path).length);
|
||||||
|
const route = pathToRoute(baseRoute);
|
||||||
|
const name = baseRoute.replace("/", "-");
|
||||||
|
if (path.startsWith("/api/")) {
|
||||||
|
const apiRoute: ApiRoute = {
|
||||||
|
route,
|
||||||
|
url,
|
||||||
|
name,
|
||||||
|
handler: module.default as router.MatchHandler,
|
||||||
|
};
|
||||||
|
apiRoutes.push(apiRoute);
|
||||||
|
} else if (!path.startsWith("/_")) {
|
||||||
|
const page: Page = {
|
||||||
|
route,
|
||||||
|
url,
|
||||||
|
name,
|
||||||
|
component: module.default as rt.ComponentType<PageProps>,
|
||||||
|
};
|
||||||
|
pages.push(page);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
sortRoutes(pages);
|
||||||
|
sortRoutes(apiRoutes);
|
||||||
|
|
||||||
|
return new ServerContext(pages, apiRoutes);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* This function returns all routes required by fresh as an extended
|
||||||
|
* path-to-regex, to handler mapping.
|
||||||
|
*/
|
||||||
|
routes(): router.Routes {
|
||||||
|
const routes: router.Routes = {};
|
||||||
|
|
||||||
|
for (const page of this.#pages) {
|
||||||
|
const bundlePath = `/${page.name}.js`;
|
||||||
|
const imports = [bundleAssetUrl(bundlePath)];
|
||||||
|
routes[page.route] = (_, match) => {
|
||||||
|
const preloads = this.#bundler.getPreloads(bundlePath).map(
|
||||||
|
bundleAssetUrl,
|
||||||
|
);
|
||||||
|
const body = render({
|
||||||
|
page,
|
||||||
|
imports,
|
||||||
|
preloads,
|
||||||
|
params: match.params,
|
||||||
|
});
|
||||||
|
return new Response(body, {
|
||||||
|
status: 200,
|
||||||
|
headers: {
|
||||||
|
"content-type": "text/html; charset=utf-8",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
for (const apiRoute of this.#apiRoutes) {
|
||||||
|
routes[apiRoute.route] = apiRoute.handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = this
|
||||||
|
.#bundleAssetRoute();
|
||||||
|
|
||||||
|
return routes;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Returns a router that contains all fresh routes. Should be mounted at
|
||||||
|
* constants.INTERNAL_PREFIX
|
||||||
|
*/
|
||||||
|
#bundleAssetRoute = (): router.MatchHandler => {
|
||||||
|
return async (_req, match) => {
|
||||||
|
const path = `/${match.params.path}`;
|
||||||
|
const file = await this.#bundler.get(path);
|
||||||
|
let res;
|
||||||
|
if (file) {
|
||||||
|
const headers = new Headers({
|
||||||
|
"Cache-Control": "public, max-age=604800, immutable",
|
||||||
|
});
|
||||||
|
|
||||||
|
const contentType = mediaTypeLookup(path);
|
||||||
|
if (contentType) {
|
||||||
|
headers.set("Content-Type", contentType);
|
||||||
|
}
|
||||||
|
|
||||||
|
res = new Response(file, {
|
||||||
|
status: 200,
|
||||||
|
headers,
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return res ?? new Response(null, {
|
||||||
|
status: 404,
|
||||||
|
});
|
||||||
|
};
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
function bundleAssetUrl(path: string) {
|
||||||
|
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Sort pages by their relative routing priority, based on the parts in the
|
||||||
|
* route matcher
|
||||||
|
*/
|
||||||
|
function sortRoutes<T extends { route: string }>(routes: T[]) {
|
||||||
|
routes.sort((a, b) => {
|
||||||
|
const partsA = a.route.split("/");
|
||||||
|
const partsB = b.route.split("/");
|
||||||
|
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
|
||||||
|
const partA = partsA[i];
|
||||||
|
const partB = partsB[i];
|
||||||
|
if (partA === undefined) return -1;
|
||||||
|
if (partB === undefined) return 1;
|
||||||
|
if (partA === partB) continue;
|
||||||
|
const priorityA = partA.startsWith(":") ? partA.endsWith("*") ? 0 : 1 : 2;
|
||||||
|
const priorityB = partB.startsWith(":") ? partB.endsWith("*") ? 0 : 1 : 2;
|
||||||
|
return Math.max(Math.min(priorityB - priorityA, 1), -1);
|
||||||
|
}
|
||||||
|
return 0;
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
/** Transform a filesystem URL path to a `path-to-regex` style matcher. */
|
||||||
|
function pathToRoute(path: string): string {
|
||||||
|
const parts = path.split("/");
|
||||||
|
if (parts[parts.length - 1] === "index") {
|
||||||
|
parts.pop();
|
||||||
|
}
|
||||||
|
const route = "/" + parts
|
||||||
|
.map((part) => {
|
||||||
|
if (part.startsWith("[...") && part.endsWith("]")) {
|
||||||
|
return `:${part.slice(4, part.length - 1)}*`;
|
||||||
|
}
|
||||||
|
if (part.startsWith("[") && part.endsWith("]")) {
|
||||||
|
return `:${part.slice(1, part.length - 1)}`;
|
||||||
|
}
|
||||||
|
return part;
|
||||||
|
})
|
||||||
|
.join("/");
|
||||||
|
return route;
|
||||||
|
}
|
||||||
+5
-18
@@ -1,31 +1,18 @@
|
|||||||
|
import { ServerContext } from "./context.ts";
|
||||||
import { router } from "./deps.ts";
|
import { router } from "./deps.ts";
|
||||||
import {
|
import { ApiRouteModule, PageModule } from "./types.ts";
|
||||||
ApiRoute,
|
|
||||||
ApiRouteModule,
|
|
||||||
Page,
|
|
||||||
PageModule,
|
|
||||||
processRoutes,
|
|
||||||
} from "./routes.ts";
|
|
||||||
import { installRoutes } from "./router.ts";
|
|
||||||
|
|
||||||
export interface Routes {
|
export interface Routes {
|
||||||
pages: Record<string, PageModule | ApiRouteModule>;
|
pages: Record<string, PageModule | ApiRouteModule>;
|
||||||
baseUrl: string;
|
baseUrl: string;
|
||||||
}
|
}
|
||||||
|
|
||||||
export { installRoutes, processRoutes, router };
|
export { router, ServerContext };
|
||||||
|
|
||||||
export function start(routes: Routes) {
|
export function start(routes: Routes) {
|
||||||
const [pages, apiRoutes] = processRoutes(routes);
|
const ctx = ServerContext.fromRoutes(routes);
|
||||||
const app = createDefaultRouter(pages, apiRoutes);
|
const app = router.router(ctx.routes());
|
||||||
addEventListener("fetch", (event: FetchEvent) => {
|
addEventListener("fetch", (event: FetchEvent) => {
|
||||||
event.respondWith(app(event.request));
|
event.respondWith(app(event.request));
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
export function createDefaultRouter(
|
|
||||||
pages: Page[],
|
|
||||||
apiRoutes: ApiRoute[],
|
|
||||||
): router.RequestHandler {
|
|
||||||
return router.router(installRoutes(pages, apiRoutes));
|
|
||||||
}
|
|
||||||
|
|||||||
+19
-15
@@ -1,28 +1,32 @@
|
|||||||
import { renderToString } from "./deps.ts";
|
import { renderToString } from "./deps.ts";
|
||||||
import * as rt from "../runtime/deps.ts";
|
import * as rt from "../runtime/deps.ts";
|
||||||
import { Page } from "./routes.ts";
|
import { Page } from "./types.ts";
|
||||||
|
|
||||||
export function render(
|
export interface RenderOptions {
|
||||||
page: Page,
|
page: Page;
|
||||||
imports: string[],
|
imports: string[];
|
||||||
preloads: string[],
|
preloads: string[];
|
||||||
params: Record<string, string>,
|
params: Record<string, string>;
|
||||||
): string {
|
}
|
||||||
const props = { params };
|
|
||||||
|
export function render(options: RenderOptions): string {
|
||||||
|
const props = { params: options.params };
|
||||||
const propsStr = JSON.stringify(props);
|
const propsStr = JSON.stringify(props);
|
||||||
const body = renderToString(rt.h(page.component, props));
|
const body = renderToString(rt.h(options.page.component, props));
|
||||||
return `<!DOCTYPE html>
|
return `<!DOCTYPE html>
|
||||||
<html>
|
<html>
|
||||||
<head>
|
<head>
|
||||||
${
|
${
|
||||||
preloads.map((src) => `<link rel="modulepreload" href="${src}">`).join(
|
options.preloads.map((src) => `<link rel="modulepreload" href="${src}">`)
|
||||||
"\n ",
|
.join(
|
||||||
)
|
"\n ",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
${
|
${
|
||||||
imports.map((src) => `<script src="${src}" type="module"></script>`).join(
|
options.imports.map((src) => `<script src="${src}" type="module"></script>`)
|
||||||
"\n ",
|
.join(
|
||||||
)
|
"\n ",
|
||||||
|
)
|
||||||
}
|
}
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
|
|||||||
@@ -1,76 +0,0 @@
|
|||||||
import { mediaTypeLookup, router } from "./deps.ts";
|
|
||||||
import { Bundler } from "./bundle.ts";
|
|
||||||
import { render } from "./render.ts";
|
|
||||||
import { ApiRoute, Page } from "./routes.ts";
|
|
||||||
import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
|
|
||||||
|
|
||||||
/** This function installs all routes required by fresh onto an oak router. */
|
|
||||||
export function installRoutes(
|
|
||||||
pages: Page[],
|
|
||||||
apiRoutes: ApiRoute[],
|
|
||||||
): router.Routes {
|
|
||||||
const bundler = new Bundler(pages);
|
|
||||||
|
|
||||||
const routes: router.Routes = {};
|
|
||||||
|
|
||||||
for (const page of pages) {
|
|
||||||
const bundlePath = `/${page.name}.js`;
|
|
||||||
const imports = [bundleAssetUrl(bundlePath)];
|
|
||||||
routes[page.route] = (_, match) => {
|
|
||||||
const preloads = bundler.getPreloads(bundlePath).map(bundleAssetUrl);
|
|
||||||
return new Response(
|
|
||||||
render(page, imports, preloads, match.params),
|
|
||||||
{
|
|
||||||
status: 200,
|
|
||||||
headers: {
|
|
||||||
"Content-Type": "text/html; charset=utf-8",
|
|
||||||
},
|
|
||||||
},
|
|
||||||
);
|
|
||||||
};
|
|
||||||
}
|
|
||||||
|
|
||||||
for (const apiRoute of apiRoutes) {
|
|
||||||
routes[apiRoute.route] = apiRoute.handler;
|
|
||||||
}
|
|
||||||
|
|
||||||
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] =
|
|
||||||
internalBundleAssetRoute(bundler);
|
|
||||||
|
|
||||||
return routes;
|
|
||||||
}
|
|
||||||
|
|
||||||
function bundleAssetUrl(path: string) {
|
|
||||||
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Returns a router that contains all fresh routes. Should be mounted at
|
|
||||||
* constants.INTERNAL_PREFIX
|
|
||||||
*/
|
|
||||||
function internalBundleAssetRoute(bundler: Bundler): router.MatchHandler {
|
|
||||||
return async (_req, match) => {
|
|
||||||
const path = `/${match.params.path}`;
|
|
||||||
const file = await bundler.get(path);
|
|
||||||
let res;
|
|
||||||
if (file) {
|
|
||||||
const headers = new Headers({
|
|
||||||
"Cache-Control": "public, max-age=604800, immutable",
|
|
||||||
});
|
|
||||||
|
|
||||||
const contentType = mediaTypeLookup(path);
|
|
||||||
if (contentType) {
|
|
||||||
headers.set("Content-Type", contentType);
|
|
||||||
}
|
|
||||||
|
|
||||||
res = new Response(file, {
|
|
||||||
status: 200,
|
|
||||||
headers,
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return res ?? new Response(null, {
|
|
||||||
status: 404,
|
|
||||||
});
|
|
||||||
};
|
|
||||||
}
|
|
||||||
@@ -1,112 +0,0 @@
|
|||||||
import { extname, router } from "./deps.ts";
|
|
||||||
import * as rt from "../runtime/deps.ts";
|
|
||||||
import { PageProps } from "../runtime/types.ts";
|
|
||||||
import { Routes } from "./mod.ts";
|
|
||||||
|
|
||||||
export interface PageModule {
|
|
||||||
default: rt.ComponentType<PageProps>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface Page {
|
|
||||||
route: string;
|
|
||||||
url: string;
|
|
||||||
name: string;
|
|
||||||
component: rt.ComponentType<PageProps>;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ApiRouteModule {
|
|
||||||
default: router.MatchHandler;
|
|
||||||
}
|
|
||||||
|
|
||||||
export interface ApiRoute {
|
|
||||||
route: string;
|
|
||||||
url: string;
|
|
||||||
name: string;
|
|
||||||
handler: router.MatchHandler;
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Process the routes into individual pages.
|
|
||||||
*/
|
|
||||||
export function processRoutes(routes: Routes): [Page[], ApiRoute[]] {
|
|
||||||
// Get the routes' base URL.
|
|
||||||
const baseUrl = new URL("./", routes.baseUrl).href;
|
|
||||||
|
|
||||||
// Extract all pages, and prepare them into this `Page` structure.
|
|
||||||
const pages: Page[] = [];
|
|
||||||
const apiRoutes: ApiRoute[] = [];
|
|
||||||
for (const [self, module] of Object.entries(routes.pages)) {
|
|
||||||
const url = new URL(self, baseUrl).href;
|
|
||||||
if (!url.startsWith(baseUrl)) {
|
|
||||||
throw new TypeError("Page is not a child of the basepath.");
|
|
||||||
}
|
|
||||||
const path = url.substring(baseUrl.length).substring("pages".length);
|
|
||||||
const baseRoute = path.substring(1, path.length - extname(path).length);
|
|
||||||
const route = pathToRoute(baseRoute);
|
|
||||||
const name = baseRoute.replace("/", "-");
|
|
||||||
if (path.startsWith("/api")) {
|
|
||||||
const apiRoute: ApiRoute = {
|
|
||||||
route,
|
|
||||||
url,
|
|
||||||
name,
|
|
||||||
handler: module.default as router.MatchHandler,
|
|
||||||
};
|
|
||||||
apiRoutes.push(apiRoute);
|
|
||||||
} else {
|
|
||||||
const page: Page = {
|
|
||||||
route,
|
|
||||||
url,
|
|
||||||
name,
|
|
||||||
component: module.default as rt.ComponentType<PageProps>,
|
|
||||||
};
|
|
||||||
pages.push(page);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
sortRoutes(pages);
|
|
||||||
sortRoutes(apiRoutes);
|
|
||||||
|
|
||||||
return [pages, apiRoutes];
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
|
||||||
* Sort pages by their relative routing priority, based on the parts in the
|
|
||||||
* route matcher
|
|
||||||
*/
|
|
||||||
function sortRoutes<T extends { route: string }>(routes: T[]) {
|
|
||||||
routes.sort((a, b) => {
|
|
||||||
const partsA = a.route.split("/");
|
|
||||||
const partsB = b.route.split("/");
|
|
||||||
for (let i = 0; i < Math.max(partsA.length, partsB.length); i++) {
|
|
||||||
const partA = partsA[i];
|
|
||||||
const partB = partsB[i];
|
|
||||||
if (partA === undefined) return -1;
|
|
||||||
if (partB === undefined) return 1;
|
|
||||||
if (partA === partB) continue;
|
|
||||||
const priorityA = partA.startsWith(":") ? partA.endsWith("*") ? 0 : 1 : 2;
|
|
||||||
const priorityB = partB.startsWith(":") ? partB.endsWith("*") ? 0 : 1 : 2;
|
|
||||||
return Math.max(Math.min(priorityB - priorityA, 1), -1);
|
|
||||||
}
|
|
||||||
return 0;
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
/** Transform a filesystem URL path to a `path-to-regex` style matcher. */
|
|
||||||
function pathToRoute(path: string): string {
|
|
||||||
const parts = path.split("/");
|
|
||||||
if (parts[parts.length - 1] === "index") {
|
|
||||||
parts.pop();
|
|
||||||
}
|
|
||||||
const route = "/" + parts
|
|
||||||
.map((part) => {
|
|
||||||
if (part.startsWith("[...") && part.endsWith("]")) {
|
|
||||||
return `:${part.slice(4, part.length - 1)}*`;
|
|
||||||
}
|
|
||||||
if (part.startsWith("[") && part.endsWith("]")) {
|
|
||||||
return `:${part.slice(1, part.length - 1)}`;
|
|
||||||
}
|
|
||||||
return part;
|
|
||||||
})
|
|
||||||
.join("/");
|
|
||||||
return route;
|
|
||||||
}
|
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import { ComponentType } from "../runtime/deps.ts";
|
||||||
|
import { router } from "./deps.ts";
|
||||||
|
import { PageProps } from "../runtime/types.ts";
|
||||||
|
|
||||||
|
export interface PageModule {
|
||||||
|
default: ComponentType<PageProps>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface Page {
|
||||||
|
route: string;
|
||||||
|
url: string;
|
||||||
|
name: string;
|
||||||
|
component: ComponentType<PageProps>;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiRouteModule {
|
||||||
|
default: router.MatchHandler;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ApiRoute {
|
||||||
|
route: string;
|
||||||
|
url: string;
|
||||||
|
name: string;
|
||||||
|
handler: router.MatchHandler;
|
||||||
|
}
|
||||||
+2
-2
@@ -1,8 +1,8 @@
|
|||||||
import { createDefaultRouter, processRoutes } from "../server.ts";
|
import { router as r, ServerContext } from "../server.ts";
|
||||||
import { assert, assertEquals, assertStringIncludes } from "./deps.ts";
|
import { assert, assertEquals, assertStringIncludes } from "./deps.ts";
|
||||||
import routes from "./fixture/routes.gen.ts";
|
import routes from "./fixture/routes.gen.ts";
|
||||||
|
|
||||||
const router = createDefaultRouter(...processRoutes(routes));
|
const router = r.router(ServerContext.fromRoutes(routes).routes());
|
||||||
|
|
||||||
Deno.test("/ page prerender", async () => {
|
Deno.test("/ page prerender", async () => {
|
||||||
const resp = await router(new Request("https://fresh.deno.dev/"));
|
const resp = await router(new Request("https://fresh.deno.dev/"));
|
||||||
|
|||||||
Reference in New Issue
Block a user