Router cleanup (#2099)
This commit is contained in:
+32
-58
@@ -2,10 +2,8 @@ import { SEP } from "./deps.ts";
|
||||
import { ErrorHandler, FinalHandler, RouteResult } from "./router.ts";
|
||||
import {
|
||||
BaseRoute,
|
||||
MiddlewareHandlerContext,
|
||||
FreshContext,
|
||||
MiddlewareRoute,
|
||||
RouterState,
|
||||
ServeHandlerInfo,
|
||||
UnknownRenderFunction,
|
||||
} from "./types.ts";
|
||||
|
||||
@@ -56,20 +54,20 @@ export function selectSharedRoutes<T extends { baseRoute: BaseRoute }>(
|
||||
*/
|
||||
export function composeMiddlewares(
|
||||
middlewares: MiddlewareRoute[],
|
||||
errorHandler: ErrorHandler<RouterState>,
|
||||
errorHandler: ErrorHandler,
|
||||
paramsAndRoute: (
|
||||
url: string,
|
||||
) => RouteResult<RouterState>,
|
||||
) => RouteResult,
|
||||
renderNotFound: UnknownRenderFunction,
|
||||
basePath: string,
|
||||
) {
|
||||
return (
|
||||
req: Request,
|
||||
connInfo: ServeHandlerInfo,
|
||||
inner: FinalHandler<RouterState>,
|
||||
ctx: FreshContext,
|
||||
inner: FinalHandler,
|
||||
) => {
|
||||
const handlers: (() => Response | Promise<Response>)[] = [];
|
||||
const paramsAndRouteResult = paramsAndRoute(req.url);
|
||||
ctx.params = paramsAndRouteResult.params;
|
||||
|
||||
// identify middlewares to apply, if any.
|
||||
// middlewares should be already sorted from deepest to shallow layer
|
||||
@@ -78,73 +76,49 @@ export function composeMiddlewares(
|
||||
middlewares,
|
||||
);
|
||||
|
||||
let state: Record<string, unknown> = {};
|
||||
const middlewareCtx: MiddlewareHandlerContext = {
|
||||
next() {
|
||||
const handler = handlers.shift()!;
|
||||
try {
|
||||
// As the `handler` can be either sync or async, depending on the user's code,
|
||||
// the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`,
|
||||
// doesn't guarantee that all possible errors will be captured.
|
||||
// `Promise.resolve` accept the value that should be returned to the promise
|
||||
// chain, however, if that value is produced by the external function call,
|
||||
// the possible `Error`, will *not* be caught by any `.catch()` attached to that chain.
|
||||
// Because of that, we need to make sure that the produced value is pushed
|
||||
// through the pipeline only if function was called successfully, and handle
|
||||
// the error case manually, by returning the `Error` as rejected promise.
|
||||
return Promise.resolve(handler());
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound) {
|
||||
return renderNotFound(req, paramsAndRouteResult.params, ctx);
|
||||
}
|
||||
return Promise.reject(e);
|
||||
if (paramsAndRouteResult.route) {
|
||||
ctx.route = paramsAndRouteResult.route.originalPattern;
|
||||
}
|
||||
|
||||
ctx.next = () => {
|
||||
const handler = handlers.shift()!;
|
||||
try {
|
||||
// As the `handler` can be either sync or async, depending on the user's code,
|
||||
// the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`,
|
||||
// doesn't guarantee that all possible errors will be captured.
|
||||
// `Promise.resolve` accept the value that should be returned to the promise
|
||||
// chain, however, if that value is produced by the external function call,
|
||||
// the possible `Error`, will *not* be caught by any `.catch()` attached to that chain.
|
||||
// Because of that, we need to make sure that the produced value is pushed
|
||||
// through the pipeline only if function was called successfully, and handle
|
||||
// the error case manually, by returning the `Error` as rejected promise.
|
||||
return Promise.resolve(handler());
|
||||
} catch (e) {
|
||||
if (e instanceof Deno.errors.NotFound) {
|
||||
return renderNotFound(req, ctx);
|
||||
}
|
||||
},
|
||||
...connInfo,
|
||||
get state() {
|
||||
return state;
|
||||
},
|
||||
set state(v) {
|
||||
state = v;
|
||||
},
|
||||
destination: "route",
|
||||
params: paramsAndRouteResult.params,
|
||||
renderNotFound: async () => {
|
||||
return await renderNotFound(req, paramsAndRouteResult.params, ctx);
|
||||
},
|
||||
isPartial: paramsAndRouteResult.isPartial,
|
||||
basePath,
|
||||
return Promise.reject(e);
|
||||
}
|
||||
};
|
||||
|
||||
for (const { module } of mws) {
|
||||
if (module.handler instanceof Array) {
|
||||
for (const handler of module.handler) {
|
||||
handlers.push(() => handler(req, middlewareCtx));
|
||||
handlers.push(() => handler(req, ctx));
|
||||
}
|
||||
} else {
|
||||
const handler = module.handler;
|
||||
handlers.push(() => handler(req, middlewareCtx));
|
||||
handlers.push(() => handler(req, ctx));
|
||||
}
|
||||
}
|
||||
|
||||
const ctx = {
|
||||
...connInfo,
|
||||
get state() {
|
||||
return state;
|
||||
},
|
||||
set state(v) {
|
||||
state = v;
|
||||
},
|
||||
isPartial: paramsAndRouteResult.isPartial,
|
||||
};
|
||||
const { destination, handler } = inner(
|
||||
req,
|
||||
ctx,
|
||||
paramsAndRouteResult.params,
|
||||
paramsAndRouteResult.route,
|
||||
);
|
||||
handlers.push(handler);
|
||||
middlewareCtx.destination = destination;
|
||||
return middlewareCtx.next().catch((e) => errorHandler(req, ctx, e));
|
||||
ctx.destination = destination;
|
||||
return ctx.next().catch((e) => errorHandler(req, ctx, e));
|
||||
};
|
||||
}
|
||||
|
||||
+84
-124
@@ -1,6 +1,6 @@
|
||||
import { contentType, extname, SEP, STATUS_CODE } from "./deps.ts";
|
||||
import * as router from "./router.ts";
|
||||
import { FreshConfig, Manifest, UnknownHandlerContext } from "./mod.ts";
|
||||
import { FreshConfig, FreshContext, Manifest } from "./mod.ts";
|
||||
import {
|
||||
ALIVE_URL,
|
||||
DEV_CLIENT_URL,
|
||||
@@ -18,7 +18,6 @@ import {
|
||||
RenderFunction,
|
||||
RenderOptions,
|
||||
Route,
|
||||
RouterState,
|
||||
ServeHandlerInfo,
|
||||
UnknownPage,
|
||||
UnknownRenderFunction,
|
||||
@@ -44,12 +43,17 @@ import { extractRoutes, FsExtractResult } from "./fs_extract.ts";
|
||||
import { loadAotSnapshot } from "../build/aot_snapshot.ts";
|
||||
import { ErrorOverlay } from "./error_overlay.tsx";
|
||||
import { withBase } from "./router.ts";
|
||||
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
|
||||
|
||||
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
|
||||
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
|
||||
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
|
||||
};
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
const NOOP_COMPONENT = () => null as any;
|
||||
const NOOP_NEXT = () => Promise.resolve(new Response(null, { status: 500 }));
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FromManifestConfig} instead
|
||||
*/
|
||||
@@ -154,20 +158,17 @@ export class ServerContext {
|
||||
this.#plugins,
|
||||
this.#renderFn,
|
||||
this.#maybeBuildSnapshot(),
|
||||
basePath,
|
||||
);
|
||||
const handlers = this.#handlers(renderNotFound);
|
||||
const inner = router.router<RouterState>(handlers);
|
||||
const inner = router.router(handlers);
|
||||
const withMiddlewares = composeMiddlewares(
|
||||
this.#extractResult.middlewares,
|
||||
handlers.errorHandler,
|
||||
router.getParamsAndRoute<RouterState>(handlers),
|
||||
router.getParamsAndRoute(handlers),
|
||||
renderNotFound,
|
||||
basePath,
|
||||
);
|
||||
const trailingSlashEnabled = this.#state.config.router?.trailingSlash;
|
||||
const isDev = this.#dev;
|
||||
const bundleAssetRoute = this.#bundleAssetRoute();
|
||||
|
||||
if (this.#dev) {
|
||||
this.#revision = Date.now();
|
||||
@@ -215,9 +216,8 @@ export class ServerContext {
|
||||
const bundlePath = (url.pathname.endsWith(".map"))
|
||||
? "fresh_dev_client.js.map"
|
||||
: "fresh_dev_client.js";
|
||||
return bundleAssetRoute(req, { ...connInfo, isPartial: false }, {
|
||||
path: bundlePath,
|
||||
});
|
||||
|
||||
return _self.#bundleAssetRoute(bundlePath);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -254,7 +254,28 @@ export class ServerContext {
|
||||
return Response.redirect(to, 302);
|
||||
}
|
||||
|
||||
return await withMiddlewares(req, connInfo, inner);
|
||||
const ctx: FreshContext = {
|
||||
url,
|
||||
params: {},
|
||||
basePath: _self.#state.config.basePath,
|
||||
localAddr: connInfo.localAddr,
|
||||
remoteAddr: connInfo.remoteAddr,
|
||||
state: {},
|
||||
isPartial: url.searchParams.has(PARTIAL_SEARCH_PARAM),
|
||||
destination: "route",
|
||||
error: undefined,
|
||||
Component: NOOP_COMPONENT,
|
||||
next: NOOP_NEXT,
|
||||
render: NOOP_NEXT,
|
||||
renderNotFound: async (data) => {
|
||||
ctx.data = data;
|
||||
return await renderNotFound(req, ctx);
|
||||
},
|
||||
route: "",
|
||||
data: undefined,
|
||||
};
|
||||
|
||||
return await withMiddlewares(req, ctx, inner);
|
||||
};
|
||||
}
|
||||
|
||||
@@ -287,16 +308,16 @@ export class ServerContext {
|
||||
#handlers(
|
||||
renderNotFound: UnknownRenderFunction,
|
||||
): {
|
||||
internalRoutes: router.Routes<RouterState>;
|
||||
staticRoutes: router.Routes<RouterState>;
|
||||
routes: router.Routes<RouterState>;
|
||||
internalRoutes: router.Routes;
|
||||
staticRoutes: router.Routes;
|
||||
routes: router.Routes;
|
||||
|
||||
otherHandler: router.Handler<RouterState>;
|
||||
errorHandler: router.ErrorHandler<RouterState>;
|
||||
otherHandler: router.Handler;
|
||||
errorHandler: router.ErrorHandler;
|
||||
} {
|
||||
const internalRoutes: router.Routes<RouterState> = {};
|
||||
const staticRoutes: router.Routes<RouterState> = {};
|
||||
const routes: router.Routes<RouterState> = {};
|
||||
const internalRoutes: router.Routes = {};
|
||||
const staticRoutes: router.Routes = {};
|
||||
const routes: router.Routes = {};
|
||||
|
||||
const assetRoute = withBase(
|
||||
`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`,
|
||||
@@ -305,7 +326,7 @@ export class ServerContext {
|
||||
internalRoutes[assetRoute] = {
|
||||
baseRoute: toBaseRoute(assetRoute),
|
||||
methods: {
|
||||
default: this.#bundleAssetRoute(),
|
||||
default: (_req, ctx) => this.#bundleAssetRoute(ctx.params.path),
|
||||
},
|
||||
};
|
||||
|
||||
@@ -352,9 +373,7 @@ export class ServerContext {
|
||||
if (this.#dev) imports.push(this.#state.config.basePath + DEV_CLIENT_URL);
|
||||
return (
|
||||
req: Request,
|
||||
params: Record<string, string>,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
ctx?: any,
|
||||
ctx: FreshContext,
|
||||
error?: unknown,
|
||||
codeFrame?: string,
|
||||
) => {
|
||||
@@ -367,14 +386,11 @@ export class ServerContext {
|
||||
this.#extractResult.layouts,
|
||||
);
|
||||
|
||||
ctx.error = error;
|
||||
ctx.data = data;
|
||||
const resp = await internalRender({
|
||||
request: req,
|
||||
context: {
|
||||
...ctx,
|
||||
async renderNotFound() {
|
||||
return await renderNotFound(req, params, ctx, data, error);
|
||||
},
|
||||
},
|
||||
context: ctx,
|
||||
route,
|
||||
plugins: this.#plugins,
|
||||
app: this.#extractResult.app,
|
||||
@@ -382,13 +398,7 @@ export class ServerContext {
|
||||
imports,
|
||||
dependenciesFn,
|
||||
renderFn: this.#renderFn,
|
||||
url: new URL(req.url),
|
||||
params,
|
||||
data,
|
||||
state: ctx?.state,
|
||||
error,
|
||||
codeFrame,
|
||||
basePath: this.#state.config.basePath,
|
||||
});
|
||||
|
||||
if (resp instanceof Response) {
|
||||
@@ -416,16 +426,10 @@ export class ServerContext {
|
||||
routes[route.pattern] = {
|
||||
baseRoute: route.baseRoute,
|
||||
methods: {
|
||||
default: (req, ctx, params) =>
|
||||
(route.handler as Handler)(req, {
|
||||
...ctx,
|
||||
params,
|
||||
render: createRender(req, params, ctx),
|
||||
async renderNotFound<Data = undefined>(data: Data) {
|
||||
return await renderNotFound(req, params, ctx, data);
|
||||
},
|
||||
basePath: this.#state.config.basePath,
|
||||
}),
|
||||
default: (req, ctx) => {
|
||||
ctx.render = createRender(req, ctx);
|
||||
return (route.handler as Handler)(req, ctx);
|
||||
},
|
||||
},
|
||||
};
|
||||
} else {
|
||||
@@ -437,40 +441,27 @@ export class ServerContext {
|
||||
routes[route.pattern].methods[method as router.KnownMethod] = (
|
||||
req,
|
||||
ctx,
|
||||
params,
|
||||
) =>
|
||||
handler(req, {
|
||||
...ctx,
|
||||
params,
|
||||
render: createRender(req, params, ctx),
|
||||
async renderNotFound<Data = undefined>(data: Data) {
|
||||
return await renderNotFound(req, params, ctx, data);
|
||||
},
|
||||
basePath: this.#state.config.basePath,
|
||||
});
|
||||
) => {
|
||||
ctx.render = createRender(req, ctx);
|
||||
return handler(req, ctx);
|
||||
};
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const otherHandler: router.Handler<RouterState> = (
|
||||
req,
|
||||
ctx,
|
||||
) =>
|
||||
this.#extractResult.notFound.handler(
|
||||
req,
|
||||
{
|
||||
...ctx,
|
||||
render() {
|
||||
return renderNotFound(req, {}, ctx);
|
||||
},
|
||||
},
|
||||
);
|
||||
const otherHandler: router.Handler = (req, ctx) => {
|
||||
ctx.render = (data) => {
|
||||
ctx.data = data;
|
||||
return renderNotFound(req, ctx);
|
||||
};
|
||||
return this.#extractResult.notFound.handler(req, ctx);
|
||||
};
|
||||
|
||||
const errorHandlerRender = genRender(
|
||||
this.#extractResult.error,
|
||||
STATUS_CODE.InternalServerError,
|
||||
);
|
||||
const errorHandler: router.ErrorHandler<RouterState> = async (
|
||||
const errorHandler: router.ErrorHandler = async (
|
||||
req,
|
||||
ctx,
|
||||
error,
|
||||
@@ -490,14 +481,9 @@ export class ServerContext {
|
||||
}
|
||||
console.error(error);
|
||||
|
||||
return this.#extractResult.error.handler(
|
||||
req,
|
||||
{
|
||||
...ctx,
|
||||
error,
|
||||
render: errorHandlerRender(req, {}, ctx, error, codeFrame),
|
||||
},
|
||||
);
|
||||
ctx.error = error;
|
||||
ctx.render = errorHandlerRender(req, ctx, error, codeFrame);
|
||||
return this.#extractResult.error.handler(req, ctx);
|
||||
};
|
||||
|
||||
if (this.#dev) {
|
||||
@@ -520,8 +506,7 @@ export class ServerContext {
|
||||
csp: false,
|
||||
url: req.url,
|
||||
name: "error overlay route",
|
||||
handler: (_req: Request, ctx: UnknownHandlerContext) =>
|
||||
ctx.render(),
|
||||
handler: (_req: Request, ctx: FreshContext) => ctx.render(),
|
||||
baseRoute,
|
||||
pattern: baseRoute,
|
||||
},
|
||||
@@ -531,16 +516,7 @@ export class ServerContext {
|
||||
imports: [],
|
||||
dependenciesFn: () => [],
|
||||
renderFn: this.#renderFn,
|
||||
url: new URL(req.url),
|
||||
params: {},
|
||||
data: undefined,
|
||||
state: {
|
||||
...ctx?.state,
|
||||
error: null,
|
||||
},
|
||||
error: null,
|
||||
codeFrame: undefined,
|
||||
basePath: this.#state.config.basePath,
|
||||
});
|
||||
|
||||
if (resp instanceof Response) {
|
||||
@@ -602,31 +578,25 @@ export class ServerContext {
|
||||
};
|
||||
}
|
||||
|
||||
/**
|
||||
* Returns a router that contains all Fresh routes. Should be mounted at
|
||||
* constants.INTERNAL_PREFIX
|
||||
*/
|
||||
#bundleAssetRoute = (): router.MatchHandler => {
|
||||
return async (_req, _ctx, params) => {
|
||||
const snapshot = await this.buildSnapshot();
|
||||
const contents = await snapshot.read(params.path);
|
||||
if (!contents) return new Response(null, { status: 404 });
|
||||
async #bundleAssetRoute(filePath: string) {
|
||||
const snapshot = await this.buildSnapshot();
|
||||
const contents = await snapshot.read(filePath);
|
||||
if (!contents) return new Response(null, { status: 404 });
|
||||
|
||||
const headers: Record<string, string> = {
|
||||
"Cache-Control": this.#dev
|
||||
? "no-cache, no-store, max-age=0, must-revalidate"
|
||||
: "public, max-age=604800, immutable",
|
||||
};
|
||||
|
||||
const type = contentType(extname(params.path));
|
||||
if (type) headers["Content-Type"] = type;
|
||||
|
||||
return new Response(contents, {
|
||||
status: 200,
|
||||
headers,
|
||||
});
|
||||
const headers: Record<string, string> = {
|
||||
"Cache-Control": this.#dev
|
||||
? "no-cache, no-store, max-age=0, must-revalidate"
|
||||
: "public, max-age=604800, immutable",
|
||||
};
|
||||
};
|
||||
|
||||
const type = contentType(extname(filePath));
|
||||
if (type) headers["Content-Type"] = type;
|
||||
|
||||
return new Response(contents, {
|
||||
status: 200,
|
||||
headers,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const createRenderNotFound = (
|
||||
@@ -635,17 +605,13 @@ const createRenderNotFound = (
|
||||
plugins: Plugin<Record<string, unknown>>[],
|
||||
renderFunction: RenderFunction,
|
||||
buildSnapshot: BuildSnapshot | null,
|
||||
basePath: string,
|
||||
) => {
|
||||
): UnknownRenderFunction => {
|
||||
const dependenciesFn = (path: string) => {
|
||||
const snapshot = buildSnapshot;
|
||||
return snapshot?.dependencies(path) ?? [];
|
||||
};
|
||||
|
||||
return async (
|
||||
...args: Parameters<UnknownRenderFunction>
|
||||
) => {
|
||||
const [req, params, ctx, data, error] = args;
|
||||
return async (req, ctx) => {
|
||||
const notFound = extractResult.notFound;
|
||||
if (!notFound.component) {
|
||||
return sendResponse(["Not found.", undefined], {
|
||||
@@ -672,12 +638,6 @@ const createRenderNotFound = (
|
||||
imports,
|
||||
dependenciesFn,
|
||||
renderFn: renderFunction,
|
||||
url: new URL(req.url),
|
||||
params,
|
||||
data,
|
||||
state: ctx?.state,
|
||||
error,
|
||||
basePath,
|
||||
});
|
||||
|
||||
if (resp instanceof Response) {
|
||||
|
||||
+3
-10
@@ -1,12 +1,5 @@
|
||||
import { ComponentChildren } from "preact";
|
||||
import {
|
||||
AppContext,
|
||||
AsyncLayout,
|
||||
AsyncRoute,
|
||||
FreshConfig,
|
||||
LayoutContext,
|
||||
RouteContext,
|
||||
} from "./types.ts";
|
||||
import { AsyncLayout, AsyncRoute, FreshConfig, RouteContext } from "./types.ts";
|
||||
import { checkAsyncComponent } from "./render.ts";
|
||||
|
||||
export function defineConfig(config: FreshConfig): FreshConfig {
|
||||
@@ -32,7 +25,7 @@ export function defineRoute<
|
||||
export function defineLayout<T>(
|
||||
fn: (
|
||||
req: Request,
|
||||
ctx: LayoutContext<void, T>,
|
||||
ctx: RouteContext<void, T>,
|
||||
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
|
||||
): AsyncLayout<void, T> {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -45,7 +38,7 @@ export function defineLayout<T>(
|
||||
export function defineApp<T>(
|
||||
fn: (
|
||||
req: Request,
|
||||
ctx: AppContext<void, T>,
|
||||
ctx: RouteContext<void, T>,
|
||||
) => ComponentChildren | Response | Promise<ComponentChildren | Response>,
|
||||
): AsyncLayout<void, T> {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
|
||||
@@ -28,6 +28,7 @@ export type {
|
||||
ErrorHandlerContext,
|
||||
ErrorPageProps,
|
||||
FreshConfig,
|
||||
FreshContext,
|
||||
FreshOptions,
|
||||
Handler,
|
||||
HandlerContext,
|
||||
|
||||
+25
-40
@@ -4,13 +4,13 @@ import {
|
||||
AsyncLayout,
|
||||
AsyncRoute,
|
||||
ErrorPage,
|
||||
FreshContext,
|
||||
LayoutRoute,
|
||||
Plugin,
|
||||
PluginRenderFunctionResult,
|
||||
PluginRenderResult,
|
||||
RenderFunction,
|
||||
Route,
|
||||
RouteContext,
|
||||
UnknownPage,
|
||||
} from "./types.ts";
|
||||
import { NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
|
||||
@@ -28,23 +28,16 @@ export const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
|
||||
|
||||
export interface RenderOptions<Data> {
|
||||
request: Request;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
context: any;
|
||||
context: FreshContext;
|
||||
route: Route<Data> | UnknownPage | ErrorPage;
|
||||
plugins: Plugin[];
|
||||
app: AppModule;
|
||||
layouts: LayoutRoute[];
|
||||
imports: string[];
|
||||
dependenciesFn: (path: string) => string[];
|
||||
url: URL;
|
||||
params: Record<string, string | string[]>;
|
||||
renderFn: RenderFunction;
|
||||
data?: Data;
|
||||
state?: Record<string, unknown>;
|
||||
error?: unknown;
|
||||
codeFrame?: string;
|
||||
lang?: string;
|
||||
basePath: string;
|
||||
}
|
||||
|
||||
export type InnerRenderFunction = () => string;
|
||||
@@ -148,15 +141,17 @@ export async function render<Data>(
|
||||
layouts = [];
|
||||
}
|
||||
|
||||
const { params, data, state, error, url, basePath } = opts.context;
|
||||
|
||||
const props: Record<string, unknown> = {
|
||||
params: opts.params,
|
||||
url: opts.url,
|
||||
params,
|
||||
url,
|
||||
route: opts.route.pattern,
|
||||
data: opts.data,
|
||||
state: opts.state,
|
||||
data,
|
||||
state,
|
||||
};
|
||||
if (opts.error) {
|
||||
props.error = opts.error;
|
||||
if (error) {
|
||||
props.error = error;
|
||||
}
|
||||
if (opts.codeFrame) {
|
||||
props.codeFrame = opts.codeFrame;
|
||||
@@ -174,22 +169,12 @@ export async function render<Data>(
|
||||
|
||||
const ctx = new RenderContext(
|
||||
crypto.randomUUID(),
|
||||
opts.url,
|
||||
url,
|
||||
opts.route.pattern,
|
||||
opts.lang ?? "en",
|
||||
);
|
||||
|
||||
const context: RouteContext = {
|
||||
localAddr: opts.context.localAddr,
|
||||
remoteAddr: opts.context.remoteAddr,
|
||||
renderNotFound: opts.context.renderNotFound,
|
||||
url: opts.url,
|
||||
route: opts.route.pattern,
|
||||
params: opts.params as Record<string, string>,
|
||||
state: opts.state ?? {},
|
||||
data: opts.data,
|
||||
isPartial: opts.context.isPartial,
|
||||
};
|
||||
const context = opts.context;
|
||||
|
||||
// Prepare render order
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -253,16 +238,16 @@ export async function render<Data>(
|
||||
// data.
|
||||
const renderState = new RenderState(
|
||||
{
|
||||
url: opts.url,
|
||||
url,
|
||||
route: opts.route.pattern,
|
||||
data: opts.data,
|
||||
state: opts.state,
|
||||
params: opts.params,
|
||||
basePath: opts.basePath,
|
||||
data,
|
||||
state,
|
||||
params,
|
||||
basePath,
|
||||
},
|
||||
componentStack,
|
||||
csp,
|
||||
opts.error,
|
||||
error,
|
||||
);
|
||||
|
||||
let bodyHtml: string | null = null;
|
||||
@@ -370,20 +355,20 @@ export async function render<Data>(
|
||||
});
|
||||
|
||||
// Append error overlay
|
||||
const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, opts.basePath);
|
||||
if (opts.error !== undefined && opts.url.pathname !== devErrorUrl) {
|
||||
const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, basePath);
|
||||
if (error !== undefined && url.pathname !== devErrorUrl) {
|
||||
const url = new URL(devErrorUrl, "https://localhost/");
|
||||
if (opts.error instanceof Error) {
|
||||
let message = opts.error.message;
|
||||
if (error instanceof Error) {
|
||||
let message = error.message;
|
||||
const idx = message.indexOf("\n");
|
||||
if (idx > -1) message = message.slice(0, idx);
|
||||
url.searchParams.append("message", message);
|
||||
if (opts.error.stack) {
|
||||
const stack = colors.stripAnsiCode(opts.error.stack);
|
||||
if (error.stack) {
|
||||
const stack = colors.stripAnsiCode(error.stack);
|
||||
url.searchParams.append("stack", stack);
|
||||
}
|
||||
} else {
|
||||
url.searchParams.append("message", String(opts.error));
|
||||
url.searchParams.append("message", String(error));
|
||||
}
|
||||
if (opts.codeFrame) {
|
||||
const codeFrame = colors.stripAnsiCode(opts.codeFrame);
|
||||
|
||||
+48
-45
@@ -1,72 +1,74 @@
|
||||
import { PARTIAL_SEARCH_PARAM } from "../constants.ts";
|
||||
import { BaseRoute, ErrorHandlerContext, ServeHandlerInfo } from "./types.ts";
|
||||
import {
|
||||
BaseRoute,
|
||||
ErrorHandlerContext,
|
||||
FreshContext,
|
||||
ServeHandlerInfo,
|
||||
} from "./types.ts";
|
||||
import { isIdentifierChar, isIdentifierStart } from "./init_safe_deps.ts";
|
||||
|
||||
type HandlerContext<T = unknown> = T & ServeHandlerInfo & {
|
||||
isPartial: boolean;
|
||||
};
|
||||
|
||||
export type Handler<T = unknown> = (
|
||||
export type Handler<T = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
ctx: FreshContext<T>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export type FinalHandler<T = unknown> = (
|
||||
export type FinalHandler = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
params: Record<string, string>,
|
||||
route?: InternalRoute<T>,
|
||||
ctx: FreshContext,
|
||||
route?: InternalRoute,
|
||||
) => {
|
||||
destination: DestinationKind;
|
||||
handler: () => Response | Promise<Response>;
|
||||
};
|
||||
|
||||
export type ErrorHandler<T = unknown> = (
|
||||
export type ErrorHandler<T = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
ctx: FreshContext<T>,
|
||||
err: unknown,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
type UnknownMethodHandler<T = unknown> = (
|
||||
type UnknownMethodHandler = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
ctx: FreshContext,
|
||||
knownMethods: KnownMethod[],
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export type MatchHandler<T = unknown> = (
|
||||
export type MatchHandler = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T>,
|
||||
match: Record<string, string>,
|
||||
ctx: FreshContext,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
// deno-lint-ignore ban-types
|
||||
export interface Routes<T = {}> {
|
||||
export interface Routes {
|
||||
[key: string]: {
|
||||
baseRoute: BaseRoute;
|
||||
methods: {
|
||||
[K in KnownMethod | "default"]?: MatchHandler<T>;
|
||||
[K in KnownMethod | "default"]?: MatchHandler;
|
||||
};
|
||||
};
|
||||
}
|
||||
|
||||
export type DestinationKind = "internal" | "static" | "route" | "notFound";
|
||||
|
||||
// deno-lint-ignore ban-types
|
||||
export type InternalRoute<T = {}> = {
|
||||
export type InternalRoute = {
|
||||
baseRoute: BaseRoute;
|
||||
originalPattern: string;
|
||||
pattern: RegExp | string;
|
||||
methods: { [K in KnownMethod]?: MatchHandler<T> };
|
||||
default?: MatchHandler<T>;
|
||||
methods: { [K in KnownMethod]?: MatchHandler };
|
||||
default?: MatchHandler;
|
||||
destination: DestinationKind;
|
||||
};
|
||||
|
||||
export interface RouterOptions<T> {
|
||||
internalRoutes: Routes<T>;
|
||||
staticRoutes: Routes<T>;
|
||||
routes: Routes<T>;
|
||||
otherHandler: Handler<T>;
|
||||
errorHandler: ErrorHandler<T>;
|
||||
unknownMethodHandler?: UnknownMethodHandler<T>;
|
||||
export interface RouterOptions {
|
||||
internalRoutes: Routes;
|
||||
staticRoutes: Routes;
|
||||
routes: Routes;
|
||||
otherHandler: Handler;
|
||||
errorHandler: ErrorHandler;
|
||||
unknownMethodHandler?: UnknownMethodHandler;
|
||||
}
|
||||
|
||||
export type KnownMethod = typeof knownMethods[number];
|
||||
@@ -214,9 +216,9 @@ export function patternToRegExp(input: string): RegExp {
|
||||
|
||||
export const IS_PATTERN = /[*:{}+?()]/;
|
||||
|
||||
function processRoutes<T>(
|
||||
processedRoutes: Array<InternalRoute<T> | null>,
|
||||
routes: Routes<T>,
|
||||
function processRoutes(
|
||||
processedRoutes: Array<InternalRoute | null>,
|
||||
routes: Routes,
|
||||
destination: DestinationKind,
|
||||
) {
|
||||
for (const [path, def] of Object.entries(routes)) {
|
||||
@@ -224,9 +226,10 @@ function processRoutes<T>(
|
||||
? path
|
||||
: patternToRegExp(path);
|
||||
|
||||
const entry: InternalRoute<T> = {
|
||||
const entry: InternalRoute = {
|
||||
baseRoute: def.baseRoute,
|
||||
pattern,
|
||||
originalPattern: path,
|
||||
methods: {},
|
||||
default: undefined,
|
||||
destination,
|
||||
@@ -244,27 +247,27 @@ function processRoutes<T>(
|
||||
}
|
||||
}
|
||||
|
||||
export interface RouteResult<T> {
|
||||
route: InternalRoute<T> | undefined;
|
||||
export interface RouteResult {
|
||||
route: InternalRoute | undefined;
|
||||
params: Record<string, string>;
|
||||
isPartial: boolean;
|
||||
}
|
||||
|
||||
export function getParamsAndRoute<T>(
|
||||
export function getParamsAndRoute(
|
||||
{
|
||||
internalRoutes,
|
||||
staticRoutes,
|
||||
routes,
|
||||
}: RouterOptions<T>,
|
||||
}: RouterOptions,
|
||||
): (
|
||||
url: string,
|
||||
) => RouteResult<T> {
|
||||
const processedRoutes: Array<InternalRoute<T> | null> = [];
|
||||
) => RouteResult {
|
||||
const processedRoutes: Array<InternalRoute | null> = [];
|
||||
processRoutes(processedRoutes, internalRoutes, "internal");
|
||||
processRoutes(processedRoutes, staticRoutes, "static");
|
||||
processRoutes(processedRoutes, routes, "route");
|
||||
|
||||
const statics = new Map<string, RouteResult<T>>();
|
||||
const statics = new Map<string, RouteResult>();
|
||||
|
||||
return (url: string) => {
|
||||
const urlObject = new URL(url);
|
||||
@@ -323,15 +326,15 @@ export function getParamsAndRoute<T>(
|
||||
};
|
||||
}
|
||||
|
||||
export function router<T = unknown>(
|
||||
export function router(
|
||||
{
|
||||
otherHandler,
|
||||
unknownMethodHandler,
|
||||
}: RouterOptions<T>,
|
||||
): FinalHandler<T> {
|
||||
}: RouterOptions,
|
||||
): FinalHandler {
|
||||
unknownMethodHandler ??= defaultUnknownMethodHandler;
|
||||
|
||||
return (req, ctx, groups, route) => {
|
||||
return (req, ctx, route) => {
|
||||
if (route) {
|
||||
// If not overridden, HEAD requests should be handled as GET requests but without the body.
|
||||
if (req.method === "HEAD" && !route.methods["HEAD"]) {
|
||||
@@ -342,7 +345,7 @@ export function router<T = unknown>(
|
||||
if (req.method === method) {
|
||||
return {
|
||||
destination: route.destination,
|
||||
handler: () => handler(req, ctx, groups),
|
||||
handler: () => handler(req, ctx),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -350,7 +353,7 @@ export function router<T = unknown>(
|
||||
if (route.default) {
|
||||
return {
|
||||
destination: route.destination,
|
||||
handler: () => route.default!(req, ctx, groups),
|
||||
handler: () => route.default!(req, ctx),
|
||||
};
|
||||
} else {
|
||||
return {
|
||||
|
||||
+106
-96
@@ -22,17 +22,6 @@ export interface DenoConfig {
|
||||
}
|
||||
|
||||
// --- APPLICATION CONFIGURATION ---
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshConfig} instead
|
||||
*/
|
||||
export type StartOptions = FreshConfig;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshConfig} interface instead.
|
||||
*/
|
||||
export type FreshOptions = FreshConfig;
|
||||
|
||||
export interface FreshConfig {
|
||||
build?: {
|
||||
/**
|
||||
@@ -201,22 +190,46 @@ export interface StaticFile {
|
||||
etag: string;
|
||||
}
|
||||
|
||||
export interface FreshContext<
|
||||
State = Record<string, unknown>,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
Data = any,
|
||||
NotFoundData = Data,
|
||||
> {
|
||||
/** @types deprecated */
|
||||
localAddr?: Deno.NetAddr;
|
||||
remoteAddr: Deno.NetAddr;
|
||||
url: URL;
|
||||
basePath: string;
|
||||
route: string;
|
||||
destination: router.DestinationKind;
|
||||
params: Record<string, string>;
|
||||
isPartial: boolean;
|
||||
state: State;
|
||||
/** @deprecated Pass values to state instead */
|
||||
data: Data;
|
||||
error?: unknown;
|
||||
|
||||
// These properties may be different
|
||||
renderNotFound: (data?: NotFoundData) => Response | Promise<Response>;
|
||||
render: (
|
||||
data?: Data,
|
||||
options?: RenderOptions,
|
||||
) => Response | Promise<Response>;
|
||||
Component: () => VNode;
|
||||
next: () => Promise<Response>;
|
||||
}
|
||||
/**
|
||||
* Context passed to async route components.
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type RouteContext<T = any, S = Record<string, unknown>> = {
|
||||
/** @types deprecated */
|
||||
localAddr?: Deno.NetAddr;
|
||||
remoteAddr: Deno.NetAddr;
|
||||
renderNotFound: (data?: T) => Response | Promise<Response>;
|
||||
url: URL;
|
||||
route: string;
|
||||
params: Record<string, string>;
|
||||
state: S;
|
||||
data: T;
|
||||
isPartial: boolean;
|
||||
};
|
||||
export type RouteContext<T = any, S = Record<string, unknown>> = Omit<
|
||||
FreshContext<
|
||||
S,
|
||||
T
|
||||
>,
|
||||
"next" | "render"
|
||||
>;
|
||||
|
||||
export interface RouteConfig {
|
||||
/**
|
||||
@@ -265,26 +278,10 @@ export type ServeHandler = (
|
||||
info: ServeHandlerInfo,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export interface HandlerContext<
|
||||
Data = unknown,
|
||||
State = Record<string, unknown>,
|
||||
NotFoundData = Data,
|
||||
> extends ServeHandlerInfo {
|
||||
params: Record<string, string>;
|
||||
basePath: string;
|
||||
render: (
|
||||
data?: Data,
|
||||
options?: RenderOptions,
|
||||
) => Response | Promise<Response>;
|
||||
renderNotFound: (data?: NotFoundData) => Response | Promise<Response>;
|
||||
state: State;
|
||||
isPartial: boolean;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type Handler<T = any, State = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: HandlerContext<T, State>,
|
||||
ctx: FreshContext<State, T>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -292,11 +289,6 @@ export type Handlers<T = any, State = Record<string, unknown>> = {
|
||||
[K in router.KnownMethod]?: Handler<T, State>;
|
||||
};
|
||||
|
||||
/**
|
||||
* @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead.
|
||||
*/
|
||||
export type MultiHandler<T> = Handlers<T>;
|
||||
|
||||
export interface RouteModule {
|
||||
default?: PageComponent<PageProps>;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -307,7 +299,7 @@ export interface RouteModule {
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type AsyncRoute<T = any, S = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: RouteContext<T, S>,
|
||||
ctx: FreshContext<S, T>,
|
||||
) => Promise<ComponentChildren | Response>;
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type PageComponent<T = any, S = Record<string, unknown>> =
|
||||
@@ -329,10 +321,6 @@ export interface Route<Data = any> {
|
||||
inheritLayouts: boolean;
|
||||
}
|
||||
|
||||
export interface RouterState {
|
||||
state: Record<string, unknown>;
|
||||
}
|
||||
|
||||
// --- APP ---
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -342,18 +330,6 @@ export interface AppModule {
|
||||
default: ComponentType<AppProps> | AsyncLayout;
|
||||
}
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type AppContext<T = any, S = Record<string, unknown>> =
|
||||
& RouteContext<T, S>
|
||||
& {
|
||||
Component: () => VNode;
|
||||
};
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type LayoutContext<T = any, S = Record<string, unknown>> = AppContext<
|
||||
T,
|
||||
S
|
||||
>;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export interface LayoutProps<T = any, S = Record<string, unknown>>
|
||||
extends PageProps<T, S> {
|
||||
@@ -362,7 +338,7 @@ export interface LayoutProps<T = any, S = Record<string, unknown>>
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type AsyncLayout<T = any, S = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: LayoutContext<T, S>,
|
||||
ctx: FreshContext<S, T>,
|
||||
) => Promise<ComponentChildren | Response>;
|
||||
|
||||
export interface LayoutConfig {
|
||||
@@ -413,15 +389,9 @@ export interface UnknownPageProps<T = any, S = Record<string, unknown>> {
|
||||
state: S;
|
||||
}
|
||||
|
||||
export interface UnknownHandlerContext<State = Record<string, unknown>>
|
||||
extends ServeHandlerInfo {
|
||||
render: () => Response | Promise<Response>;
|
||||
state: State;
|
||||
}
|
||||
|
||||
export type UnknownHandler = (
|
||||
req: Request,
|
||||
ctx: UnknownHandlerContext,
|
||||
ctx: FreshContext,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export interface UnknownPageModule {
|
||||
@@ -444,11 +414,7 @@ export interface UnknownPage {
|
||||
|
||||
export type UnknownRenderFunction = (
|
||||
req: Request,
|
||||
params: Record<string, string>,
|
||||
// deno-lint-ignore no-explicit-any
|
||||
ctx?: any,
|
||||
data?: unknown,
|
||||
error?: unknown,
|
||||
ctx: FreshContext,
|
||||
) => Promise<Response>;
|
||||
|
||||
// --- ERROR PAGE ---
|
||||
@@ -468,19 +434,12 @@ export interface ErrorPageProps {
|
||||
codeFrame?: string;
|
||||
}
|
||||
|
||||
export interface ErrorHandlerContext<State = Record<string, unknown>>
|
||||
extends ServeHandlerInfo {
|
||||
error: unknown;
|
||||
render: () => Response | Promise<Response>;
|
||||
state: State;
|
||||
}
|
||||
|
||||
// Nominal/Branded type. Ensures that the string has the expected format
|
||||
export type BaseRoute = string & { readonly __brand: unique symbol };
|
||||
|
||||
export type ErrorHandler = (
|
||||
req: Request,
|
||||
ctx: ErrorHandlerContext,
|
||||
ctx: FreshContext,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
export interface ErrorPageModule {
|
||||
@@ -502,18 +461,6 @@ export interface ErrorPage {
|
||||
}
|
||||
|
||||
// --- MIDDLEWARES ---
|
||||
|
||||
export interface MiddlewareHandlerContext<State = Record<string, unknown>>
|
||||
extends ServeHandlerInfo {
|
||||
next: () => Promise<Response>;
|
||||
renderNotFound: (state?: State) => Response | Promise<Response>;
|
||||
state: State;
|
||||
destination: router.DestinationKind;
|
||||
params: Record<string, string>;
|
||||
isPartial: boolean;
|
||||
basePath: string;
|
||||
}
|
||||
|
||||
export interface MiddlewareRoute {
|
||||
baseRoute: BaseRoute;
|
||||
module: Middleware;
|
||||
@@ -521,7 +468,7 @@ export interface MiddlewareRoute {
|
||||
|
||||
export type MiddlewareHandler<State = Record<string, unknown>> = (
|
||||
req: Request,
|
||||
ctx: MiddlewareHandlerContext<State>,
|
||||
ctx: FreshContext<State>,
|
||||
) => Response | Promise<Response>;
|
||||
|
||||
// deno-lint-ignore no-explicit-any
|
||||
@@ -688,3 +635,66 @@ export interface PluginIslands {
|
||||
baseLocation: string;
|
||||
paths: string[];
|
||||
}
|
||||
|
||||
// --- Deprecated types ---
|
||||
|
||||
/**
|
||||
* @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead.
|
||||
*/
|
||||
export type MultiHandler<T> = Handlers<T>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshConfig} instead
|
||||
*/
|
||||
export type StartOptions = FreshConfig;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshConfig} interface instead.
|
||||
*/
|
||||
export type FreshOptions = FreshConfig;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
export type HandlerContext<
|
||||
Data = unknown,
|
||||
State = Record<string, unknown>,
|
||||
NotFoundData = Data,
|
||||
> = FreshContext<State, Data, NotFoundData>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type AppContext<T = any, S = Record<string, unknown>> = FreshContext<
|
||||
S,
|
||||
T
|
||||
>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
// deno-lint-ignore no-explicit-any
|
||||
export type LayoutContext<T = any, S = Record<string, unknown>> = FreshContext<
|
||||
S,
|
||||
T
|
||||
>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
export type UnknownHandlerContext<State = Record<string, unknown>> =
|
||||
FreshContext<State>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
export type ErrorHandlerContext<State = Record<string, unknown>> = FreshContext<
|
||||
State
|
||||
>;
|
||||
|
||||
/**
|
||||
* @deprecated Use {@linkcode FreshContext} interface instead
|
||||
*/
|
||||
export type MiddlewareHandlerContext<State = Record<string, unknown>> =
|
||||
FreshContext<State>;
|
||||
|
||||
Reference in New Issue
Block a user