From 31dbd99beacb71713cf3cb838ff31f3d866d4938 Mon Sep 17 00:00:00 2001 From: Luca Casonato Date: Tue, 1 Jun 2021 23:19:33 +0200 Subject: [PATCH] chore: improve bundling + refactor router (#10) This commit changes how bundling works, by bundling all routes at once. Static JS assets are now cached immutably. Additionally this PR completly refactors how the router works to make it more modular. This allows users to opt out of the default oak server, and instead create their own. --- .vscode/settings.json | 2 +- README.md | 8 +- example/README.md | 5 +- example/main.ts | 4 + example/pages/[name].tsx | 4 +- example/{server.ts => routes.gen.ts} | 12 ++- example/tsconfig.json | 2 +- makefile | 8 ++ src/cli/init.ts | 17 +++- src/cli/routes.ts | 20 +++-- src/server/bundle.ts | 112 ++++++++++++++++++++++----- src/server/constants.ts | 5 ++ src/server/deps.ts | 3 +- src/server/mod.ts | 32 ++++++-- src/server/{routes.ts => page.ts} | 20 +++-- src/server/render.ts | 5 +- src/server/router.ts | 50 ++++++++++++ src/server/server.ts | 30 ------- tsconfig.json | 2 +- 19 files changed, 249 insertions(+), 92 deletions(-) create mode 100644 example/main.ts rename example/{server.ts => routes.gen.ts} (62%) create mode 100644 makefile create mode 100644 src/server/constants.ts rename src/server/{routes.ts => page.ts} (77%) create mode 100644 src/server/router.ts delete mode 100644 src/server/server.ts diff --git a/.vscode/settings.json b/.vscode/settings.json index 5010129f..3f90500c 100644 --- a/.vscode/settings.json +++ b/.vscode/settings.json @@ -3,4 +3,4 @@ "deno.lint": true, "deno.unstable": false, "deno.config": "./tsconfig.json" -} \ No newline at end of file +} diff --git a/README.md b/README.md index c9926e8f..758e9cee 100644 --- a/README.md +++ b/README.md @@ -10,7 +10,7 @@ and without the need of a build step. Fresh embraces isomorphic JavaScript like never before. Write a JSX component, have it render on the edge just-in-time, and then enhance it with client side JS for great interactivity. -Fresh does not have a build step - you write your code, deploy it to +Fresh does not have a build step - you write your code, deploy it to [Deno Deploy](https://deno.com/deploy), and from there everything is handled by the framework. @@ -25,7 +25,7 @@ the framework. ## Install To install, run the following command. This will add `fresh` CLI to your PATH. -Make sure to have Deno 1.9.1 or later installed. +Make sure to have Deno 1.10.3 or later installed. ```sh deno install -A -f --no-check https://deno.land/x/fresh/cli.ts @@ -43,11 +43,11 @@ fresh init myproject To now start the project, use [`deployctl`](https://deno.land/x/deploy): ``` -deployctl run --no-check --watch server.ts +deployctl run --no-check --watch main.ts ``` To deploy the script to [Deno Deploy](https://deno.com/deploy), push your -project to GitHub, create a `fresh` project, and link it to `server.ts` file in +project to GitHub, create a `fresh` project, and link it to `main.ts` file in the created repository. To learn more about how to use `fresh`, visit the documentation. diff --git a/example/README.md b/example/README.md index d9095a25..5ace786b 100644 --- a/example/README.md +++ b/example/README.md @@ -1,5 +1,5 @@ # fresh project - + ### Usage Install deployctl: @@ -11,7 +11,7 @@ deno install --allow-read --allow-write --allow-env --allow-net --allow-run --no Start the project: ``` -deployctl run --no-check --watch server.ts +deployctl run --no-check --watch main.ts ``` After adding, removing, or moving a page in the `pages` directory, run: @@ -19,4 +19,3 @@ After adding, removing, or moving a page in the `pages` directory, run: ``` fresh routes ``` - diff --git a/example/main.ts b/example/main.ts new file mode 100644 index 00000000..8d2b7ce2 --- /dev/null +++ b/example/main.ts @@ -0,0 +1,4 @@ +import { start } from "../server.ts"; +import routes from "./routes.gen.ts"; + +start(routes); diff --git a/example/pages/[name].tsx b/example/pages/[name].tsx index e03bf76b..db752c84 100644 --- a/example/pages/[name].tsx +++ b/example/pages/[name].tsx @@ -1,9 +1,7 @@ import { h } from "../deps.ts"; interface Props { - params: { - name: string; - }; + params: Record; } export default function Greet(props: Props) { diff --git a/example/server.ts b/example/routes.gen.ts similarity index 62% rename from example/server.ts rename to example/routes.gen.ts index 2b41ef2d..2f296a87 100644 --- a/example/server.ts +++ b/example/routes.gen.ts @@ -1,10 +1,16 @@ // DO NOT EDIT. This file is generated by `fresh`. // This file SHOULD be checked into source version control. // To update this file, run `fresh routes`. - -import { setup } from "../server.ts"; import * as $0 from "./pages/[name].tsx"; import * as $1 from "./pages/index.tsx"; -setup([[$0, "./pages/[name].tsx"], [$1, "./pages/index.tsx"]], import.meta.url); +const routes = { + pages: { + "./pages/[name].tsx": $0, + "./pages/index.tsx": $1, + }, + baseUrl: import.meta.url, +}; + +export default routes; diff --git a/example/tsconfig.json b/example/tsconfig.json index bc269e44..798d070e 100644 --- a/example/tsconfig.json +++ b/example/tsconfig.json @@ -3,4 +3,4 @@ "jsxFactory": "h", "jsxFragmentFactory": "Fragment" } -} \ No newline at end of file +} diff --git a/makefile b/makefile new file mode 100644 index 00000000..901b613f --- /dev/null +++ b/makefile @@ -0,0 +1,8 @@ +fmt: + deno fmt + +lint: + deno lint + +watch_example: + deployctl run --watch --no-check example/main.ts \ No newline at end of file diff --git a/src/cli/init.ts b/src/cli/init.ts index 64f0c4b3..f6bbc299 100644 --- a/src/cli/init.ts +++ b/src/cli/init.ts @@ -24,6 +24,7 @@ export interface Args { help: boolean; } +// deno-lint-ignore no-explicit-any export async function initSubcommand(rawArgs: Record) { const args: Args = { help: !!rawArgs.help, @@ -95,9 +96,7 @@ function Counter() { const PAGES_GREET_TSX = `import { h } from "../deps.ts"; interface Props { - params: { - name: string; - }; + params: Record; } export default function Greet(props: Props) { @@ -122,6 +121,16 @@ export default function Greet(props: Props) { join(directory, "tsconfig.json"), TSCONFIG_JSON, ); + const serverUrl = new URL("../../server.ts", import.meta.url); + const MAIN_TS = `import { start } from "${serverUrl}"; +import routes from "./routes.gen.ts"; + +start(routes); +`; + await Deno.writeTextFile( + join(directory, "main.ts"), + MAIN_TS, + ); const README_MD = `# fresh project ### Usage @@ -135,7 +144,7 @@ deno install --allow-read --allow-write --allow-env --allow-net --allow-run --no Start the project: \`\`\` -deployctl run --no-check --watch server.ts +deployctl run --no-check --watch main.ts \`\`\` After adding, removing, or moving a page in the \`pages\` directory, run: diff --git a/src/cli/routes.ts b/src/cli/routes.ts index 2c502b14..3c8bc5ef 100644 --- a/src/cli/routes.ts +++ b/src/cli/routes.ts @@ -21,6 +21,7 @@ export interface Args { help: boolean; } +// deno-lint-ignore no-explicit-any export async function routesSubcommand(rawArgs: Record) { const args: Args = { help: !!rawArgs.help, @@ -54,16 +55,21 @@ export async function routes(directory: string) { const output = `// DO NOT EDIT. This file is generated by \`fresh\`. // This file SHOULD be checked into source version control. // To update this file, run \`fresh routes\`. - -import { setup } from "${new URL("../../server.ts", import.meta.url)}"; ${files.map((file, i) => `import * as $${i} from "./pages${file}";`).join("\n")} -setup([${ - files.map((file, i) => `[$${i}, "./pages${file}"]`) - .join(", ") - }], import.meta.url); +const routes = { + pages: { + ${ + files.map((file, i) => `${JSON.stringify(`./pages${file}`)}: $${i},`) + .join("\n ") + } + }, + baseUrl: import.meta.url, +}; + +export default routes; `; - await Deno.writeTextFile(join(directory, "./server.ts"), output); + await Deno.writeTextFile(join(directory, "./routes.gen.ts"), output); } diff --git a/src/server/bundle.ts b/src/server/bundle.ts index 72f772ef..be25274f 100644 --- a/src/server/bundle.ts +++ b/src/server/bundle.ts @@ -1,10 +1,10 @@ import { denoPlugin, esbuild } from "./deps.ts"; -import { Page } from "./routes.ts"; +import { Page } from "./page.ts"; let esbuildInitalized: boolean | Promise = false; async function ensureEsbuildInialized() { if (esbuildInitalized === false) { - esbuildInitalized = await esbuild.initialize({ + esbuildInitalized = esbuild.initialize({ wasmURL: "https://unpkg.com/esbuild-wasm@0.11.19/esbuild.wasm", worker: false, }); @@ -15,9 +15,93 @@ async function ensureEsbuildInialized() { } } -export async function bundle(page: Page): Promise { +export class Bundler { + #pages: Page[]; + #cache: Map | Promise | undefined = undefined; + + constructor(pages: Page[]) { + this.#pages = pages; + } + + async bundle() { + const entryPoints: Record = {}; + + for (const page of this.#pages) { + entryPoints[page.name] = `fresh:///${page.name}`; + } + + await ensureEsbuildInialized(); + const bundle = await esbuild.build({ + plugins: [freshPlugin(this.#pages), denoPlugin({ loader: "portable" })], + write: false, + bundle: true, + minify: true, + treeShaking: true, + splitting: true, + platform: "neutral", + outfile: "", + jsxFactory: "h", + jsxFragment: "Fragment", + outdir: `/`, + entryPoints, + }); + + const cache = new Map(); + for (const file of bundle.outputFiles) { + cache.set(file.path, file.contents); + } + this.#cache = cache; + + return; + } + + async cache(): Promise> { + if (this.#cache === undefined) { + this.#cache = this.bundle(); + } + if (this.#cache instanceof Promise) { + await this.#cache; + } + return this.#cache as Map; + } + + async get(path: string): Promise { + const cache = await this.cache(); + return cache.get(path) ?? null; + } +} + +function freshPlugin(pageList: Page[]): esbuild.Plugin { const runtime = new URL("../../runtime.ts", import.meta.url); - const contents = ` + + const pageMap = new Map(); + + for (const page of pageList) { + pageMap.set(`/${page.name}`, page); + } + + return { + name: "fresh", + setup(build) { + build.onResolve({ filter: /fresh:\/\/.*/ }, function onResolve( + args: esbuild.OnResolveArgs, + ): esbuild.OnResolveResult | null | undefined { + return ({ + path: args.path, + namespace: "fresh", + }); + }); + + build.onLoad( + { filter: /.*/, namespace: "fresh" }, + function onLoad( + args: esbuild.OnLoadArgs, + ): esbuild.OnLoadResult | null | undefined { + const url = new URL(args.path); + const path = url.pathname; + const page = pageMap.get(path); + if (!page) return null; + const contents = ` import Page from "${page.url}"; import { h, render } from "${runtime.href}"; @@ -26,21 +110,9 @@ addEventListener("DOMContentLoaded", () => { render(h(Page, props), document.body); }); `; - await ensureEsbuildInialized(); - const bundle = await esbuild.build({ - plugins: [denoPlugin({ loader: "portable" })], - write: false, - bundle: true, - minify: true, - treeShaking: true, - platform: "neutral", - outfile: "", - jsxFactory: "h", - jsxFragment: "Fragment", - stdin: { - contents, - sourcefile: `fresh://entrypoint/${page.name}`, + return { contents, loader: "js" }; + }, + ); }, - }); - return bundle.outputFiles[0].text; + }; } diff --git a/src/server/constants.ts b/src/server/constants.ts new file mode 100644 index 00000000..e1edba0d --- /dev/null +++ b/src/server/constants.ts @@ -0,0 +1,5 @@ +import { generateUuid } from "./deps.ts"; + +export const INTERNAL_PREFIX = "/_frsh"; +export const BUILD_ID = Deno.env.get("DENO_DEPLOYMENT_ID") || generateUuid(); +export const JS_PREFIX = `/js`; diff --git a/src/server/deps.ts b/src/server/deps.ts index 03a457e0..7ef7db54 100644 --- a/src/server/deps.ts +++ b/src/server/deps.ts @@ -3,12 +3,13 @@ export { renderToString } from "https://x.lcas.dev/preact@10.5.12/ssr.js"; // -- std -- export { extname } from "https://deno.land/std@0.95.0/path/mod.ts"; +export { generate as generateUuid } from "https://deno.land/std@0.95.0/uuid/v4.ts"; // -- oak -- export * as oak from "https://deno.land/x/oak@v7.4.0/mod.ts"; // -- esbuild -- -let start = new Date().getTime(); +const start = new Date().getTime(); globalThis.performance = { now() { return new Date().getTime() - start; diff --git a/src/server/mod.ts b/src/server/mod.ts index 2cd435d5..5a2c93bc 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -1,13 +1,33 @@ -import { createPages, PageModules } from "./routes.ts"; -import { createServer } from "./server.ts"; +import { oak } from "./deps.ts"; +import { Page, PageModule, processRoutes } from "./page.ts"; +import { installRoutes } from "./router.ts"; -export function setup(pageModules: [PageModules, string][], selfUrl: string) { - const baseUrl = new URL("./", selfUrl).href; - const pages = createPages(pageModules, baseUrl); - const app = createServer(pages); +export interface Routes { + pages: Record; + baseUrl: string; +} + +export { installRoutes }; + +export function start(routes: Routes) { + const pages = processRoutes(routes); + const app = createDefaultServer(pages); app.addEventListener("error", (err) => { console.error(err.error); }); addEventListener("fetch", app.fetchEventHandler()); } + +export function createDefaultServer(pages: Page[]): oak.Application { + const router = new oak.Router(); + + installRoutes(router, pages); + + const app = new oak.Application(); + + app.use(router.routes()); + app.use(router.allowedMethods()); + + return app; +} diff --git a/src/server/routes.ts b/src/server/page.ts similarity index 77% rename from src/server/routes.ts rename to src/server/page.ts index a947b4e1..6e0e6190 100644 --- a/src/server/routes.ts +++ b/src/server/page.ts @@ -1,8 +1,9 @@ import { extname } from "./deps.ts"; import * as rt from "../runtime/deps.ts"; import { PageProps } from "../runtime/types.ts"; +import { Routes } from "./mod.ts"; -export interface PageModules { +export interface PageModule { default: rt.ComponentType; } @@ -13,12 +14,16 @@ export interface Page { component: rt.ComponentType; } -export function createPages( - pageModules: [PageModules, string][], - baseUrl: string, -): Page[] { +/** + * Process the routes into individual pages. + */ +export function processRoutes(routes: Routes): Page[] { + // 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[] = []; - for (const [pageModule, self] of pageModules) { + for (const [self, pageModule] 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."); @@ -35,6 +40,8 @@ export function createPages( pages.push(page); } + // Sort pages by theur relative routing priority, based on the parts in the + // route matcher. pages.sort((a, b) => { const partsA = a.route.split("/"); const partsB = b.route.split("/"); @@ -54,6 +61,7 @@ export function createPages( return pages; } +/** 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") { diff --git a/src/server/render.ts b/src/server/render.ts index 39a341bb..bfe1924e 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -1,11 +1,12 @@ import { renderToString } from "./deps.ts"; import * as rt from "../runtime/deps.ts"; -import { Page } from "./routes.ts"; +import { Page } from "./page.ts"; +import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts"; export function render(page: Page, params: Record): string { const props = { params }; const body = renderToString(rt.h(page.component, props)); - return `${body}${body}`; } diff --git a/src/server/router.ts b/src/server/router.ts new file mode 100644 index 00000000..adae2214 --- /dev/null +++ b/src/server/router.ts @@ -0,0 +1,50 @@ +import { extname, oak } from "./deps.ts"; +import { Bundler } from "./bundle.ts"; +import { render } from "./render.ts"; +import { Page } from "./page.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(router: oak.Router, pages: Page[]) { + for (const page of pages) { + router.get>(page.route, (ctx) => { + ctx.response.status = 200; + ctx.response.type = "html"; + ctx.response.body = render(page, ctx.params); + }); + } + + const internal = internalRouter(pages); + + router.use( + INTERNAL_PREFIX, + internal.routes(), + internal.allowedMethods(), + ); +} + +/** + * Returns a router that contains all fresh routes. Should be mounted at + * constants.INTERNAL_PREFIX + */ +function internalRouter(pages: Page[]): oak.Router { + const bundler = new Bundler(pages); + + const router = new oak.Router(); + + router.get(`${JS_PREFIX}/${BUILD_ID}/:path*`, async (ctx) => { + const path = `/${ctx.params.path}`; + const file = await bundler.get(path); + if (file) { + ctx.response.status = 200; + ctx.response.type = extname(path); + ctx.response.body = file; + ctx.response.headers.set( + "Cache-Control", + "public, max-age=604800, immutable", + ); + } + }); + + return router; +} diff --git a/src/server/server.ts b/src/server/server.ts deleted file mode 100644 index 523ec894..00000000 --- a/src/server/server.ts +++ /dev/null @@ -1,30 +0,0 @@ -import { oak } from "./deps.ts"; -import { bundle } from "./bundle.ts"; -import { render } from "./render.ts"; -import { Page } from "./routes.ts"; - -export function createServer(pages: Page[]): oak.Application { - const router = new oak.Router(); - - for (const page of pages) { - router.get>(page.route, (ctx) => { - ctx.response.status = 200; - ctx.response.type = "html"; - ctx.response.body = render(page, ctx.params); - }); - - router.get(`/_frsh/s/p/${page.name}.module.js`, async (ctx) => { - const js = await bundle(page); - ctx.response.status = 200; - ctx.response.type = "js"; - ctx.response.body = js; - }); - } - - const app = new oak.Application(); - - app.use(router.routes()); - app.use(router.allowedMethods()); - - return app; -} diff --git a/tsconfig.json b/tsconfig.json index bc269e44..798d070e 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -3,4 +3,4 @@ "jsxFactory": "h", "jsxFragmentFactory": "Fragment" } -} \ No newline at end of file +}