From 94d3082c45450ba3391d797e2c6bd4cf48dfd5ee Mon Sep 17 00:00:00 2001 From: Leo Kettmeir Date: Tue, 18 Apr 2023 13:27:51 +0200 Subject: [PATCH] refactor: include router directly in fresh (#1122) This PR changes from depending on https://deno.land/x/rutt to instead include a reduced & simplified version of it. --- src/server/context.ts | 131 +++++++++++++++++++---------------- src/server/deps.ts | 3 - src/server/router.ts | 155 ++++++++++++++++++++++++++++++++++++++++++ src/server/types.ts | 5 +- 4 files changed, 230 insertions(+), 64 deletions(-) create mode 100644 src/server/router.ts diff --git a/src/server/context.ts b/src/server/context.ts index 77359bcc..f023501d 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -3,13 +3,13 @@ import { extname, fromFileUrl, RequestHandler, - rutt, Status, toFileUrl, typeByExtension, walk, } from "./deps.ts"; import { h } from "preact"; +import * as router from "./router.ts"; import { Manifest } from "./mod.ts"; import { Bundler, JSXConfig } from "./bundle.ts"; import { ALIVE_URL, BUILD_ID, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts"; @@ -198,7 +198,7 @@ export class ServerContext { url, name, component, - handler: handler ?? ((req) => rutt.defaultOtherHandler(req)), + handler: handler ?? ((req) => router.defaultOtherHandler(req)), csp: Boolean(config?.csp ?? false), }; } else if ( @@ -217,7 +217,7 @@ export class ServerContext { name, component, handler: handler ?? - ((req, ctx) => rutt.defaultErrorHandler(req, ctx, ctx.error)), + ((req, ctx) => router.defaultErrorHandler(req, ctx, ctx.error)), csp: Boolean(config?.csp ?? false), }; } @@ -310,7 +310,7 @@ export class ServerContext { * by fresh, including static files. */ handler(): RequestHandler { - const inner = rutt.router(...this.#handlers()); + const inner = router.router(...this.#handlers()); const withMiddlewares = this.#composeMiddlewares(this.#middlewares); return async function handler(req: Request, connInfo: ConnInfo) { // Redirect requests that end with a trailing slash @@ -350,7 +350,7 @@ export class ServerContext { return ( req: Request, connInfo: ConnInfo, - inner: rutt.Handler, + inner: router.Handler, ) => { // identify middlewares to apply, if any. // middlewares should be already sorted from deepest to shallow layer @@ -390,47 +390,51 @@ export class ServerContext { * path-to-regex, to handler mapping. */ #handlers(): [ - rutt.Routes, + router.Routes, { - otherHandler: rutt.Handler; - errorHandler: rutt.ErrorHandler; + otherHandler: router.Handler; + errorHandler: router.ErrorHandler; }, ] { - const routes: rutt.Routes = {}; - - routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = this - .#bundleAssetRoute(); + const routes: router.Routes = {}; + routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = { + default: this.#bundleAssetRoute(), + }; if (this.#dev) { - routes[REFRESH_JS_URL] = () => { - const js = - `new EventSource("${ALIVE_URL}").addEventListener("message", function listener(e) { if (e.data !== "${BUILD_ID}") { this.removeEventListener('message', listener); location.reload(); } });`; - return new Response(js, { - headers: { - "content-type": "application/javascript; charset=utf-8", - }, - }); + routes[REFRESH_JS_URL] = { + default: () => { + const js = + `new EventSource("${ALIVE_URL}").addEventListener("message", function listener(e) { if (e.data !== "${BUILD_ID}") { this.removeEventListener('message', listener); location.reload(); } });`; + return new Response(js, { + headers: { + "content-type": "application/javascript; charset=utf-8", + }, + }); + }, }; - routes[ALIVE_URL] = () => { - let timerId: number | undefined = undefined; - const body = new ReadableStream({ - start(controller) { - controller.enqueue(`data: ${BUILD_ID}\nretry: 100\n\n`); - timerId = setInterval(() => { - controller.enqueue(`data: ${BUILD_ID}\n\n`); - }, 1000); - }, - cancel() { - if (timerId !== undefined) { - clearInterval(timerId); - } - }, - }); - return new Response(body.pipeThrough(new TextEncoderStream()), { - headers: { - "content-type": "text/event-stream", - }, - }); + routes[ALIVE_URL] = { + default: () => { + let timerId: number | undefined = undefined; + const body = new ReadableStream({ + start(controller) { + controller.enqueue(`data: ${BUILD_ID}\nretry: 100\n\n`); + timerId = setInterval(() => { + controller.enqueue(`data: ${BUILD_ID}\n\n`); + }, 1000); + }, + cancel() { + if (timerId !== undefined) { + clearInterval(timerId); + } + }, + }); + return new Response(body.pipeThrough(new TextEncoderStream()), { + headers: { + "content-type": "text/event-stream", + }, + }); + }, }; } @@ -442,12 +446,14 @@ export class ServerContext { const { localUrl, path, size, contentType, etag } of this.#staticFiles ) { const route = sanitizePathToRegex(path); - routes[`GET@${route}`] = this.#staticFileHandler( - localUrl, - size, - contentType, - etag, - ); + routes[route] = { + "GET": this.#staticFileHandler( + localUrl, + size, + contentType, + etag, + ), + }; } const genRender = ( @@ -521,16 +527,23 @@ export class ServerContext { for (const route of this.#routes) { const createRender = genRender(route, Status.OK); if (typeof route.handler === "function") { - routes[route.pattern] = (req, ctx, params) => - (route.handler as Handler)(req, { - ...ctx, - params, - render: createRender(req, params), - renderNotFound: createUnknownRender(req, {}), - }); + routes[route.pattern] = { + default: (req, ctx, params) => + (route.handler as Handler)(req, { + ...ctx, + params, + render: createRender(req, params), + renderNotFound: createUnknownRender(req, {}), + }), + }; } else { + routes[route.pattern] = {}; for (const [method, handler] of Object.entries(route.handler)) { - routes[`${method}@${route.pattern}`] = (req, ctx, params) => + routes[route.pattern][method as router.KnownMethod] = ( + req, + ctx, + params, + ) => handler(req, { ...ctx, params, @@ -541,7 +554,7 @@ export class ServerContext { } } - const otherHandler: rutt.Handler = ( + const otherHandler: router.Handler = ( req, ctx, ) => @@ -557,7 +570,7 @@ export class ServerContext { this.#error, Status.InternalServerError, ); - const errorHandler: rutt.ErrorHandler = ( + const errorHandler: router.ErrorHandler = ( req, ctx, error, @@ -585,7 +598,7 @@ export class ServerContext { size: number, contentType: string, etag: string, - ): rutt.MatchHandler { + ): router.MatchHandler { return async (req: Request) => { const url = new URL(req.url); const key = url.searchParams.get(ASSET_CACHE_BUST_KEY); @@ -623,7 +636,7 @@ export class ServerContext { * Returns a router that contains all fresh routes. Should be mounted at * constants.INTERNAL_PREFIX */ - #bundleAssetRoute = (): rutt.MatchHandler => { + #bundleAssetRoute = (): router.MatchHandler => { return async (_req, _ctx, params) => { const path = `/${params.path}`; const file = await this.#bundler.get(path); @@ -663,7 +676,7 @@ const DEFAULT_NOT_FOUND: UnknownPage = { pattern: "", url: "", name: "_404", - handler: (req) => rutt.defaultOtherHandler(req), + handler: (req) => router.defaultOtherHandler(req), csp: false, }; diff --git a/src/server/deps.ts b/src/server/deps.ts index 00e7cc52..427b2c97 100644 --- a/src/server/deps.ts +++ b/src/server/deps.ts @@ -16,9 +16,6 @@ export { typeByExtension, } from "https://deno.land/std@0.178.0/media_types/mod.ts"; -// -- rutt -- -export * as rutt from "https://deno.land/x/rutt@0.1.0/mod.ts"; - // -- esbuild -- // @deno-types="https://deno.land/x/esbuild@v0.17.11/mod.d.ts" import * as esbuildWasm from "https://deno.land/x/esbuild@v0.17.11/wasm.js"; diff --git a/src/server/router.ts b/src/server/router.ts new file mode 100644 index 00000000..f01a2fe5 --- /dev/null +++ b/src/server/router.ts @@ -0,0 +1,155 @@ +import type { ConnInfo } from "./deps.ts"; + +type HandlerContext = T & ConnInfo; + +export type Handler = ( + req: Request, + ctx: HandlerContext, +) => Response | Promise; + +export type ErrorHandler = ( + req: Request, + ctx: HandlerContext, + err: unknown, +) => Response | Promise; + +type UnknownMethodHandler = ( + req: Request, + ctx: HandlerContext, + knownMethods: KnownMethod[], +) => Response | Promise; + +export type MatchHandler = ( + req: Request, + ctx: HandlerContext, + match: Record, +) => Response | Promise; + +// deno-lint-ignore ban-types +export interface Routes { + [key: string]: { [K in KnownMethod | "default"]?: MatchHandler }; +} + +// deno-lint-ignore ban-types +export type InternalRoute = { + pattern: URLPattern; + methods: { [K in KnownMethod]?: MatchHandler }; + default?: MatchHandler; +}; + +export interface RouterOptions { + otherHandler?: Handler; + errorHandler?: ErrorHandler; + unknownMethodHandler?: UnknownMethodHandler; +} + +export type KnownMethod = typeof knownMethods[number]; + +export const knownMethods = [ + "GET", + "HEAD", + "POST", + "PUT", + "DELETE", + "OPTIONS", + "PATCH", +] as const; + +export function defaultOtherHandler(_req: Request): Response { + return new Response(null, { + status: 404, + }); +} + +export function defaultErrorHandler( + _req: Request, + _ctx: HandlerContext, + err: unknown, +): Response { + console.error(err); + + return new Response(null, { + status: 500, + }); +} + +export function defaultUnknownMethodHandler( + _req: Request, + _ctx: HandlerContext, + knownMethods: KnownMethod[], +): Response { + return new Response(null, { + status: 405, + headers: { + Accept: knownMethods.join(", "), + }, + }); +} + +export function router( + routes: Routes, + { otherHandler, errorHandler, unknownMethodHandler }: RouterOptions = { + otherHandler: defaultOtherHandler, + errorHandler: defaultErrorHandler, + unknownMethodHandler: defaultUnknownMethodHandler, + }, +): Handler { + otherHandler ??= defaultOtherHandler; + errorHandler ??= defaultErrorHandler; + unknownMethodHandler ??= defaultUnknownMethodHandler; + + const internalRoutes: InternalRoute[] = []; + for (const [path, methods] of Object.entries(routes)) { + const entry: InternalRoute = { + pattern: new URLPattern({ pathname: path }), + methods: {}, + default: undefined, + }; + + for (const [method, handler] of Object.entries(methods)) { + if (method === "default") { + entry.default = handler; + } else if (knownMethods.includes(method as KnownMethod)) { + entry.methods[method as KnownMethod] = handler; + } + } + + internalRoutes.push(entry); + } + + return async (req, ctx) => { + try { + for (const route of internalRoutes) { + const res = route.pattern.exec(req.url); + + if (res !== null) { + const groups = res?.pathname.groups ?? {}; + + for (const key in groups) { + groups[key] = decodeURIComponent(groups[key]); + } + + for (const [method, handler] of Object.entries(route.methods)) { + if (req.method === method) { + return await handler(req, ctx, groups); + } + } + + if (route.default) { + return await route.default(req, ctx, groups); + } else { + return await unknownMethodHandler!( + req, + ctx, + Object.keys(route.methods) as KnownMethod[], + ); + } + } + } + + return await otherHandler!(req, ctx); + } catch (err) { + return errorHandler!(req, ctx, err); + } + }; +} diff --git a/src/server/types.ts b/src/server/types.ts index 0765ce76..8f1188d2 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -1,5 +1,6 @@ import { ComponentType } from "preact"; -import { ConnInfo, rutt, ServeInit } from "./deps.ts"; +import { ConnInfo, ServeInit } from "./deps.ts"; +import * as router from "./router.ts"; import { InnerRenderFunction, RenderContext } from "./render.ts"; // --- APPLICATION CONFIGURATION --- @@ -87,7 +88,7 @@ export type Handler> = ( // deno-lint-ignore no-explicit-any export type Handlers> = { - [K in typeof rutt.knownMethods[number]]?: Handler; + [K in router.KnownMethod]?: Handler; }; export interface RouteModule {