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.
This commit is contained in:
+72
-59
@@ -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<RouterState>(...this.#handlers());
|
||||
const inner = router.router<RouterState>(...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<RouterState>,
|
||||
inner: router.Handler<RouterState>,
|
||||
) => {
|
||||
// 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<RouterState>,
|
||||
router.Routes<RouterState>,
|
||||
{
|
||||
otherHandler: rutt.Handler<RouterState>;
|
||||
errorHandler: rutt.ErrorHandler<RouterState>;
|
||||
otherHandler: router.Handler<RouterState>;
|
||||
errorHandler: router.ErrorHandler<RouterState>;
|
||||
},
|
||||
] {
|
||||
const routes: rutt.Routes<RouterState> = {};
|
||||
|
||||
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = this
|
||||
.#bundleAssetRoute();
|
||||
const routes: router.Routes<RouterState> = {};
|
||||
|
||||
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 = <Data = undefined>(
|
||||
@@ -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<RouterState> = (
|
||||
const otherHandler: router.Handler<RouterState> = (
|
||||
req,
|
||||
ctx,
|
||||
) =>
|
||||
@@ -557,7 +570,7 @@ export class ServerContext {
|
||||
this.#error,
|
||||
Status.InternalServerError,
|
||||
);
|
||||
const errorHandler: rutt.ErrorHandler<RouterState> = (
|
||||
const errorHandler: router.ErrorHandler<RouterState> = (
|
||||
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,
|
||||
};
|
||||
|
||||
|
||||
@@ -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";
|
||||
|
||||
@@ -0,0 +1,155 @@
|
||||
import type { ConnInfo } from "./deps.ts";
|
||||
|
||||
type HandlerContext<T = unknown> = T & ConnInfo;
|
||||
|
||||
export type Handler<T = unknown> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export type ErrorHandler<T = unknown> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
err: unknown,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
type UnknownMethodHandler<T = unknown> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
knownMethods: KnownMethod[],
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export type MatchHandler<T = unknown> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
match: Record<string, string>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
// deno-lint-ignore ban-types
|
||||
export interface Routes<T = {}> {
|
||||
[key: string]: { [K in KnownMethod | "default"]?: MatchHandler<T> };
|
||||
}
|
||||
|
||||
// deno-lint-ignore ban-types
|
||||
export type InternalRoute<T = {}> = {
|
||||
pattern: URLPattern;
|
||||
methods: { [K in KnownMethod]?: MatchHandler<T> };
|
||||
default?: MatchHandler<T>;
|
||||
};
|
||||
|
||||
export interface RouterOptions<T> {
|
||||
otherHandler?: Handler<T>;
|
||||
errorHandler?: ErrorHandler<T>;
|
||||
unknownMethodHandler?: UnknownMethodHandler<T>;
|
||||
}
|
||||
|
||||
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<T = unknown>(
|
||||
routes: Routes<T>,
|
||||
{ otherHandler, errorHandler, unknownMethodHandler }: RouterOptions<T> = {
|
||||
otherHandler: defaultOtherHandler,
|
||||
errorHandler: defaultErrorHandler,
|
||||
unknownMethodHandler: defaultUnknownMethodHandler,
|
||||
},
|
||||
): Handler<T> {
|
||||
otherHandler ??= defaultOtherHandler;
|
||||
errorHandler ??= defaultErrorHandler;
|
||||
unknownMethodHandler ??= defaultUnknownMethodHandler;
|
||||
|
||||
const internalRoutes: InternalRoute<T>[] = [];
|
||||
for (const [path, methods] of Object.entries(routes)) {
|
||||
const entry: InternalRoute<T> = {
|
||||
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);
|
||||
}
|
||||
};
|
||||
}
|
||||
+3
-2
@@ -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<T = any, State = Record<string, unknown>> = (
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type Handlers<T = any, State = Record<string, unknown>> = {
|
||||
[K in typeof rutt.knownMethods[number]]?: Handler<T, State>;
|
||||
[K in router.KnownMethod]?: Handler<T, State>;
|
||||
};
|
||||
|
||||
export interface RouteModule {
|
||||
|
||||
Reference in New Issue
Block a user