diff --git a/src/server/context.ts b/src/server/context.ts index f023501d..2d85b212 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -22,6 +22,7 @@ import { Handler, Island, Middleware, + MiddlewareHandlerContext, MiddlewareModule, MiddlewareRoute, Plugin, @@ -310,8 +311,12 @@ export class ServerContext { * by fresh, including static files. */ handler(): RequestHandler { - const inner = router.router(...this.#handlers()); - const withMiddlewares = this.#composeMiddlewares(this.#middlewares); + const handlers = this.#handlers(); + const inner = router.router(handlers); + const withMiddlewares = this.#composeMiddlewares( + this.#middlewares, + handlers.errorHandler, + ); return async function handler(req: Request, connInfo: ConnInfo) { // Redirect requests that end with a trailing slash // to their non-trailing slash counterpart. @@ -346,11 +351,14 @@ export class ServerContext { * Identify which middlewares should be applied for a request, * chain them and return a handler response */ - #composeMiddlewares(middlewares: MiddlewareRoute[]) { + #composeMiddlewares( + middlewares: MiddlewareRoute[], + errorHandler: router.ErrorHandler, + ) { return ( req: Request, connInfo: ConnInfo, - inner: router.Handler, + inner: router.FinalHandler, ) => { // identify middlewares to apply, if any. // middlewares should be already sorted from deepest to shallow layer @@ -358,30 +366,38 @@ export class ServerContext { const handlers: (() => Response | Promise)[] = []; - const ctx = { + const middlewareCtx: MiddlewareHandlerContext = { next() { const handler = handlers.shift()!; return Promise.resolve(handler()); }, ...connInfo, state: {}, + destination: "route", }; for (const mw of mws) { if (mw.handler instanceof Array) { for (const handler of mw.handler) { - handlers.push(() => handler(req, ctx)); + handlers.push(() => handler(req, middlewareCtx)); } } else { const handler = mw.handler; - handlers.push(() => handler(req, ctx)); + handlers.push(() => handler(req, middlewareCtx)); } } - handlers.push(() => inner(req, ctx)); - - const handler = handlers.shift()!; - return handler(); + const ctx = { + ...connInfo, + state: middlewareCtx.state, + }; + const { destination, handler } = inner( + req, + ctx, + ); + handlers.push(handler); + middlewareCtx.destination = destination; + return middlewareCtx.next().catch((e) => errorHandler(req, ctx, e)); }; } @@ -389,20 +405,23 @@ export class ServerContext { * This function returns all routes required by fresh as an extended * path-to-regex, to handler mapping. */ - #handlers(): [ - router.Routes, - { - otherHandler: router.Handler; - errorHandler: router.ErrorHandler; - }, - ] { + #handlers(): { + internalRoutes: router.Routes; + staticRoutes: router.Routes; + routes: router.Routes; + + otherHandler: router.Handler; + errorHandler: router.ErrorHandler; + } { + const internalRoutes: router.Routes = {}; + const staticRoutes: router.Routes = {}; const routes: router.Routes = {}; - routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = { + internalRoutes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = { default: this.#bundleAssetRoute(), }; if (this.#dev) { - routes[REFRESH_JS_URL] = { + internalRoutes[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(); } });`; @@ -413,7 +432,7 @@ export class ServerContext { }); }, }; - routes[ALIVE_URL] = { + internalRoutes[ALIVE_URL] = { default: () => { let timerId: number | undefined = undefined; const body = new ReadableStream({ @@ -446,7 +465,7 @@ export class ServerContext { const { localUrl, path, size, contentType, etag } of this.#staticFiles ) { const route = sanitizePathToRegex(path); - routes[route] = { + staticRoutes[route] = { "GET": this.#staticFileHandler( localUrl, size, @@ -590,7 +609,7 @@ export class ServerContext { ); }; - return [routes, { otherHandler, errorHandler }]; + return { internalRoutes, staticRoutes, routes, otherHandler, errorHandler }; } #staticFileHandler( diff --git a/src/server/router.ts b/src/server/router.ts index f01a2fe5..b0aa1eec 100644 --- a/src/server/router.ts +++ b/src/server/router.ts @@ -7,6 +7,14 @@ export type Handler = ( ctx: HandlerContext, ) => Response | Promise; +export type FinalHandler = ( + req: Request, + ctx: HandlerContext, +) => { + destination: DestinationKind; + handler: () => Response | Promise; +}; + export type ErrorHandler = ( req: Request, ctx: HandlerContext, @@ -30,16 +38,22 @@ export interface Routes { [key: string]: { [K in KnownMethod | "default"]?: MatchHandler }; } +export type DestinationKind = "internal" | "static" | "route" | "notFound"; + // deno-lint-ignore ban-types export type InternalRoute = { pattern: URLPattern; methods: { [K in KnownMethod]?: MatchHandler }; default?: MatchHandler; + destination: DestinationKind; }; export interface RouterOptions { - otherHandler?: Handler; - errorHandler?: ErrorHandler; + internalRoutes: Routes; + staticRoutes: Routes; + routes: Routes; + otherHandler: Handler; + errorHandler: ErrorHandler; unknownMethodHandler?: UnknownMethodHandler; } @@ -86,24 +100,17 @@ export function defaultUnknownMethodHandler( }); } -export function router( +function processRoutes( + processedRoutes: InternalRoute[], routes: Routes, - { otherHandler, errorHandler, unknownMethodHandler }: RouterOptions = { - otherHandler: defaultOtherHandler, - errorHandler: defaultErrorHandler, - unknownMethodHandler: defaultUnknownMethodHandler, - }, -): Handler { - otherHandler ??= defaultOtherHandler; - errorHandler ??= defaultErrorHandler; - unknownMethodHandler ??= defaultUnknownMethodHandler; - - const internalRoutes: InternalRoute[] = []; + destination: DestinationKind, +) { for (const [path, methods] of Object.entries(routes)) { const entry: InternalRoute = { pattern: new URLPattern({ pathname: path }), methods: {}, default: undefined, + destination, }; for (const [method, handler] of Object.entries(methods)) { @@ -114,42 +121,68 @@ export function router( } } - internalRoutes.push(entry); + processedRoutes.push(entry); } +} - return async (req, ctx) => { - try { - for (const route of internalRoutes) { - const res = route.pattern.exec(req.url); +export function router( + { + internalRoutes, + staticRoutes, + routes, + otherHandler, + unknownMethodHandler, + }: RouterOptions, +): FinalHandler { + unknownMethodHandler ??= defaultUnknownMethodHandler; - if (res !== null) { - const groups = res?.pathname.groups ?? {}; + const processedRoutes: InternalRoute[] = []; + processRoutes(processedRoutes, internalRoutes, "internal"); + processRoutes(processedRoutes, staticRoutes, "static"); + processRoutes(processedRoutes, routes, "route"); - for (const key in groups) { - groups[key] = decodeURIComponent(groups[key]); - } + return (req, ctx) => { + for (const route of processedRoutes) { + const res = route.pattern.exec(req.url); - for (const [method, handler] of Object.entries(route.methods)) { - if (req.method === method) { - return await handler(req, ctx, groups); - } - } + if (res !== null) { + const groups = res?.pathname.groups ?? {}; - if (route.default) { - return await route.default(req, ctx, groups); - } else { - return await unknownMethodHandler!( - req, - ctx, - Object.keys(route.methods) as KnownMethod[], - ); + for (const key in groups) { + groups[key] = decodeURIComponent(groups[key]); + } + + for (const [method, handler] of Object.entries(route.methods)) { + if (req.method === method) { + return { + destination: route.destination, + handler: () => handler(req, ctx, groups), + }; } } - } - return await otherHandler!(req, ctx); - } catch (err) { - return errorHandler!(req, ctx, err); + if (route.default) { + return { + destination: route.destination, + handler: () => route.default!(req, ctx, groups), + }; + } else { + return { + destination: route.destination, + handler: () => + unknownMethodHandler!( + req, + ctx, + Object.keys(route.methods) as KnownMethod[], + ), + }; + } + } } + + return { + destination: "notFound", + handler: () => otherHandler!(req, ctx), + }; }; } diff --git a/src/server/types.ts b/src/server/types.ts index 8f1188d2..e52ab3a4 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -201,6 +201,7 @@ export interface MiddlewareHandlerContext> extends ConnInfo { next: () => Promise; state: State; + destination: router.DestinationKind; } export interface MiddlewareRoute extends Middleware { diff --git a/tests/fixture/routes/_middleware.ts b/tests/fixture/routes/_middleware.ts index 526a865c..99632588 100644 --- a/tests/fixture/routes/_middleware.ts +++ b/tests/fixture/routes/_middleware.ts @@ -50,8 +50,18 @@ async function rootHandler( return resp; } +async function kindHandler( + _req: Request, + ctx: MiddlewareHandlerContext, +) { + const resp = await ctx.next(); + resp.headers.set("destination", ctx.destination); + return resp; +} + export const handler: MiddlewareHandler | MiddlewareHandler[] = [ rootHandler, logHandler, + kindHandler, corsHandler, ]; diff --git a/tests/main_test.ts b/tests/main_test.ts index 5e8f7116..f14d7f90 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -494,6 +494,38 @@ Deno.test({ }, }); +Deno.test("middleware destination", async (t) => { + await t.step("internal", async () => { + const resp = await router( + new Request("https://fresh.deno.dev/_frsh/refresh.js"), + ); + assert(resp); + assertEquals(resp.headers.get("destination"), "internal"); + await resp.body?.cancel(); + }); + + await t.step("static", async () => { + const resp = await router(new Request("https://fresh.deno.dev/foo.txt")); + assert(resp); + assertEquals(resp.headers.get("destination"), "static"); + await resp.body?.cancel(); + }); + + await t.step("route", async () => { + const resp = await router(new Request("https://fresh.deno.dev/")); + assert(resp); + assertEquals(resp.headers.get("destination"), "route"); + await resp.body?.cancel(); + }); + + await t.step("notFound", async () => { + const resp = await router(new Request("https://fresh.deno.dev/bar/bar")); + assert(resp); + assertEquals(resp.headers.get("destination"), "notFound"); + await resp.body?.cancel(); + }); +}); + Deno.test("experimental Deno.serve", { sanitizeOps: false, sanitizeResources: false,