feat: layered and scoped middleware and context state (#139)
Co-authored-by: Luca Casonato <hello@lcas.dev>
This commit is contained in:
co-authored by
Luca Casonato
parent
b36f2c1a43
commit
8d4e77f4ac
@@ -0,0 +1,7 @@
|
|||||||
|
{
|
||||||
|
"tasks": {
|
||||||
|
"test": "deno test -A --no-check=remote --watch",
|
||||||
|
"fixture": "deno run -A --no-check=remote --watch ./tests/fixture/main.ts",
|
||||||
|
"doc": "deno run -A --no-check=remote --watch=www/static,src/,docs/ www/main.ts"
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -1 +1,66 @@
|
|||||||
> TODO(lucacasonato): this page still needs to be written
|
A middleware is defined in a `_middleware.ts` file. It will intercept the
|
||||||
|
request in order for you to perform custom logic before or after the route
|
||||||
|
handler. This allows modifying or checking requests and responses. Common
|
||||||
|
use-cases for this are logging, authentication, and performance monitoring.
|
||||||
|
|
||||||
|
Each middleware gets passed a `next` function in the context argument that is
|
||||||
|
used trigger child handlers. The `ctx` also has a `state` property that can be
|
||||||
|
used to pass arbituary data to downstream (or upstream) handlers.
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// routes/_middleware.ts
|
||||||
|
import { MiddlewareHandlerContext } from "../server_deps.ts";
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
data: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handler(
|
||||||
|
req: Request,
|
||||||
|
ctx: MiddlewareHandlerContext<State>,
|
||||||
|
) {
|
||||||
|
ctx.state.data = "myData";
|
||||||
|
const resp = await ctx.next();
|
||||||
|
resp.headers.set("server", "fresh server");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```ts
|
||||||
|
// routes/myHandler.ts
|
||||||
|
export const handler: Handlers<any, { data: string }> = {
|
||||||
|
GET(_req, ctx) {
|
||||||
|
return new Response(`middleware data is ${ctx.state.data}`);
|
||||||
|
},
|
||||||
|
};
|
||||||
|
```
|
||||||
|
|
||||||
|
Middlewares are scoped and can be layered. This means a project can have
|
||||||
|
multiple middlewares, each covering a different set of routes. If multiple
|
||||||
|
middlewares cover a route, they will all be run, in order of specificity (least
|
||||||
|
specific first).
|
||||||
|
|
||||||
|
For example, take a project with the following routes:
|
||||||
|
|
||||||
|
- `routes/_middlware.ts`
|
||||||
|
- `routes/index.ts`
|
||||||
|
- `routes/admin/_middleware.ts`
|
||||||
|
- `routes/admin/index.ts`
|
||||||
|
- `routes/admin/signin.ts`
|
||||||
|
|
||||||
|
For a request to `/` the request will flow like this:
|
||||||
|
|
||||||
|
1. The `routes/_middlware.ts` middlware is invoked.
|
||||||
|
2. Calling `ctx.next()` will invoke the `routes/index.ts` handler.
|
||||||
|
|
||||||
|
For a request to `/admin` the request flow like this:
|
||||||
|
|
||||||
|
1. The `routes/_middlware.ts` middlware is invoked.
|
||||||
|
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts` middlware.
|
||||||
|
3. Calling `ctx.next()` will invoke the `routes/admin/index.ts` handler.
|
||||||
|
|
||||||
|
For a request to `/admin/signin` the request flow like this:
|
||||||
|
|
||||||
|
1. The `routes/_middlware.ts` middlware is invoked.
|
||||||
|
2. Calling `ctx.next()` will invoke the `routes/admin/_middleware.ts` middlware.
|
||||||
|
3. Calling `ctx.next()` will invoke the `routes/admin/signin.ts` handler.
|
||||||
|
|||||||
@@ -20,4 +20,7 @@ declare global {
|
|||||||
|
|
||||||
// deno-lint-ignore no-var
|
// deno-lint-ignore no-var
|
||||||
var __FRSH_BUILD_ID: string;
|
var __FRSH_BUILD_ID: string;
|
||||||
|
|
||||||
|
// deno-lint-ignore no-explicit-any no-var
|
||||||
|
var URLPattern: any;
|
||||||
}
|
}
|
||||||
|
|||||||
+106
-30
@@ -11,6 +11,7 @@ import {
|
|||||||
import { Manifest } from "./mod.ts";
|
import { Manifest } from "./mod.ts";
|
||||||
import { Bundler } from "./bundle.ts";
|
import { Bundler } from "./bundle.ts";
|
||||||
import { ALIVE_URL, BUILD_ID, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts";
|
import { ALIVE_URL, BUILD_ID, JS_PREFIX, REFRESH_JS_URL } from "./constants.ts";
|
||||||
|
|
||||||
import DefaultErrorHandler from "./default_error_page.tsx";
|
import DefaultErrorHandler from "./default_error_page.tsx";
|
||||||
import {
|
import {
|
||||||
AppModule,
|
AppModule,
|
||||||
@@ -20,10 +21,12 @@ import {
|
|||||||
Island,
|
Island,
|
||||||
Middleware,
|
Middleware,
|
||||||
MiddlewareModule,
|
MiddlewareModule,
|
||||||
|
MiddlewareRoute,
|
||||||
Page,
|
Page,
|
||||||
PageModule,
|
PageModule,
|
||||||
Renderer,
|
Renderer,
|
||||||
RendererModule,
|
RendererModule,
|
||||||
|
RouterState,
|
||||||
UnknownPage,
|
UnknownPage,
|
||||||
UnknownPageModule,
|
UnknownPageModule,
|
||||||
} from "./types.ts";
|
} from "./types.ts";
|
||||||
@@ -52,7 +55,7 @@ export class ServerContext {
|
|||||||
#staticFiles: StaticFile[];
|
#staticFiles: StaticFile[];
|
||||||
#bundler: Bundler;
|
#bundler: Bundler;
|
||||||
#renderer: Renderer;
|
#renderer: Renderer;
|
||||||
#middleware: Middleware;
|
#middlewares: MiddlewareRoute[];
|
||||||
#app: AppModule;
|
#app: AppModule;
|
||||||
#notFound: UnknownPage;
|
#notFound: UnknownPage;
|
||||||
#error: ErrorPage;
|
#error: ErrorPage;
|
||||||
@@ -62,7 +65,7 @@ export class ServerContext {
|
|||||||
islands: Island[],
|
islands: Island[],
|
||||||
staticFiles: StaticFile[],
|
staticFiles: StaticFile[],
|
||||||
renderer: Renderer,
|
renderer: Renderer,
|
||||||
middleware: Middleware,
|
middlewares: MiddlewareRoute[],
|
||||||
app: AppModule,
|
app: AppModule,
|
||||||
notFound: UnknownPage,
|
notFound: UnknownPage,
|
||||||
error: ErrorPage,
|
error: ErrorPage,
|
||||||
@@ -71,7 +74,7 @@ export class ServerContext {
|
|||||||
this.#islands = islands;
|
this.#islands = islands;
|
||||||
this.#staticFiles = staticFiles;
|
this.#staticFiles = staticFiles;
|
||||||
this.#renderer = renderer;
|
this.#renderer = renderer;
|
||||||
this.#middleware = middleware;
|
this.#middlewares = middlewares;
|
||||||
this.#app = app;
|
this.#app = app;
|
||||||
this.#notFound = notFound;
|
this.#notFound = notFound;
|
||||||
this.#error = error;
|
this.#error = error;
|
||||||
@@ -90,7 +93,7 @@ export class ServerContext {
|
|||||||
const pages: Page[] = [];
|
const pages: Page[] = [];
|
||||||
const islands: Island[] = [];
|
const islands: Island[] = [];
|
||||||
let renderer: Renderer = DEFAULT_RENDERER;
|
let renderer: Renderer = DEFAULT_RENDERER;
|
||||||
let middleware: Middleware = DEFAULT_MIDDLEWARE;
|
const middlewares: MiddlewareRoute[] = [];
|
||||||
let app: AppModule = DEFAULT_APP;
|
let app: AppModule = DEFAULT_APP;
|
||||||
let notFound: UnknownPage = DEFAULT_NOT_FOUND;
|
let notFound: UnknownPage = DEFAULT_NOT_FOUND;
|
||||||
let error: ErrorPage = DEFAULT_ERROR;
|
let error: ErrorPage = DEFAULT_ERROR;
|
||||||
@@ -102,7 +105,10 @@ export class ServerContext {
|
|||||||
const path = url.substring(baseUrl.length).substring("routes".length);
|
const path = url.substring(baseUrl.length).substring("routes".length);
|
||||||
const baseRoute = path.substring(1, path.length - extname(path).length);
|
const baseRoute = path.substring(1, path.length - extname(path).length);
|
||||||
const name = baseRoute.replace("/", "-");
|
const name = baseRoute.replace("/", "-");
|
||||||
if (!path.startsWith("/_")) {
|
const isMiddleware = path.endsWith("/_middleware.tsx") ||
|
||||||
|
path.endsWith("/_middleware.ts") || path.endsWith("/_middleware.jsx") ||
|
||||||
|
path.endsWith("/_middleware.js");
|
||||||
|
if (!path.startsWith("/_") && !isMiddleware) {
|
||||||
const { default: component, config } = (module as PageModule);
|
const { default: component, config } = (module as PageModule);
|
||||||
let route = pathToRoute(baseRoute);
|
let route = pathToRoute(baseRoute);
|
||||||
if (config?.routeOverride) {
|
if (config?.routeOverride) {
|
||||||
@@ -130,11 +136,11 @@ export class ServerContext {
|
|||||||
path === "/_render.jsx" || path === "/_render.js"
|
path === "/_render.jsx" || path === "/_render.js"
|
||||||
) {
|
) {
|
||||||
renderer = module as RendererModule;
|
renderer = module as RendererModule;
|
||||||
} else if (
|
} else if (isMiddleware) {
|
||||||
path === "/_middleware.tsx" || path === "/_middleware.ts" ||
|
middlewares.push({
|
||||||
path === "/_middleware.jsx" || path === "/_middleware.js"
|
...middlewarePathToPattern(baseRoute),
|
||||||
) {
|
...module as MiddlewareModule,
|
||||||
middleware = module as MiddlewareModule;
|
});
|
||||||
} else if (
|
} else if (
|
||||||
path === "/_app.tsx" || path === "/_app.ts" ||
|
path === "/_app.tsx" || path === "/_app.ts" ||
|
||||||
path === "/_app.jsx" || path === "/_app.js"
|
path === "/_app.jsx" || path === "/_app.js"
|
||||||
@@ -180,6 +186,7 @@ export class ServerContext {
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
sortRoutes(pages);
|
sortRoutes(pages);
|
||||||
|
sortRoutes(middlewares);
|
||||||
|
|
||||||
for (const [self, module] of Object.entries(manifest.islands)) {
|
for (const [self, module] of Object.entries(manifest.islands)) {
|
||||||
const url = new URL(self, baseUrl).href;
|
const url = new URL(self, baseUrl).href;
|
||||||
@@ -237,12 +244,13 @@ export class ServerContext {
|
|||||||
throw err;
|
throw err;
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
return new ServerContext(
|
return new ServerContext(
|
||||||
pages,
|
pages,
|
||||||
islands,
|
islands,
|
||||||
staticFiles,
|
staticFiles,
|
||||||
renderer,
|
renderer,
|
||||||
middleware,
|
middlewares,
|
||||||
app,
|
app,
|
||||||
notFound,
|
notFound,
|
||||||
error,
|
error,
|
||||||
@@ -254,8 +262,8 @@ export class ServerContext {
|
|||||||
* by fresh, including static files.
|
* by fresh, including static files.
|
||||||
*/
|
*/
|
||||||
handler(): RequestHandler {
|
handler(): RequestHandler {
|
||||||
const inner = router.router(...this.#routes());
|
const inner = router.router<RouterState>(...this.#routes());
|
||||||
const middleware = this.#middleware;
|
const withMiddlewares = this.#composeMiddlewares(this.#middlewares);
|
||||||
return function handler(req: Request, connInfo: ConnInfo) {
|
return function handler(req: Request, connInfo: ConnInfo) {
|
||||||
// Redirect requests that end with a trailing slash
|
// Redirect requests that end with a trailing slash
|
||||||
// to their non-trailing slash counterpart.
|
// to their non-trailing slash counterpart.
|
||||||
@@ -265,8 +273,43 @@ export class ServerContext {
|
|||||||
url.pathname = url.pathname.slice(0, -1);
|
url.pathname = url.pathname.slice(0, -1);
|
||||||
return Response.redirect(url.href, 307);
|
return Response.redirect(url.href, 307);
|
||||||
}
|
}
|
||||||
const handle = () => Promise.resolve(inner(req, connInfo));
|
return withMiddlewares(req, connInfo, inner);
|
||||||
return middleware.handler(req, { handle, ...connInfo });
|
};
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Identify which middlewares should be applied for a request,
|
||||||
|
* chain them and return a handler response
|
||||||
|
*/
|
||||||
|
#composeMiddlewares(middlewares: MiddlewareRoute[]) {
|
||||||
|
return (
|
||||||
|
req: Request,
|
||||||
|
connInfo: ConnInfo,
|
||||||
|
inner: router.Handler<RouterState>,
|
||||||
|
) => {
|
||||||
|
// identify middlewares to apply, if any.
|
||||||
|
// middlewares should be already sorted from deepest to shallow layer
|
||||||
|
const mws = selectMiddlewares(req.url, middlewares);
|
||||||
|
|
||||||
|
const handlers: (() => Response | Promise<Response>)[] = [];
|
||||||
|
|
||||||
|
const ctx = {
|
||||||
|
next() {
|
||||||
|
const handler = handlers.shift()!;
|
||||||
|
return Promise.resolve(handler());
|
||||||
|
},
|
||||||
|
...connInfo,
|
||||||
|
state: {},
|
||||||
|
};
|
||||||
|
|
||||||
|
for (const mw of mws) {
|
||||||
|
handlers.push(() => mw.handler(req, ctx));
|
||||||
|
}
|
||||||
|
|
||||||
|
handlers.push(() => inner(req, ctx));
|
||||||
|
|
||||||
|
const handler = handlers.shift()!;
|
||||||
|
return handler();
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -274,8 +317,12 @@ export class ServerContext {
|
|||||||
* This function returns all routes required by fresh as an extended
|
* This function returns all routes required by fresh as an extended
|
||||||
* path-to-regex, to handler mapping.
|
* path-to-regex, to handler mapping.
|
||||||
*/
|
*/
|
||||||
#routes(): [router.Routes, RequestHandler, router.ErrorHandler] {
|
#routes(): [
|
||||||
const routes: router.Routes = {};
|
router.Routes<RouterState>,
|
||||||
|
router.Handler<RouterState>,
|
||||||
|
router.ErrorHandler<RouterState>,
|
||||||
|
] {
|
||||||
|
const routes: router.Routes<RouterState> = {};
|
||||||
|
|
||||||
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = this
|
routes[`${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`] = this
|
||||||
.#bundleAssetRoute();
|
.#bundleAssetRoute();
|
||||||
@@ -396,17 +443,17 @@ export class ServerContext {
|
|||||||
for (const page of this.#pages) {
|
for (const page of this.#pages) {
|
||||||
const createRender = genRender(page, 200);
|
const createRender = genRender(page, 200);
|
||||||
if (typeof page.handler === "function") {
|
if (typeof page.handler === "function") {
|
||||||
routes[page.route] = (req, connInfo, params) =>
|
routes[page.route] = (req, ctx, params) =>
|
||||||
(page.handler as Handler)(req, {
|
(page.handler as Handler)(req, {
|
||||||
...connInfo,
|
...ctx,
|
||||||
params,
|
params,
|
||||||
render: createRender(req, params),
|
render: createRender(req, params),
|
||||||
});
|
});
|
||||||
} else {
|
} else {
|
||||||
for (const [method, handler] of Object.entries(page.handler)) {
|
for (const [method, handler] of Object.entries(page.handler)) {
|
||||||
routes[`${method}@${page.route}`] = (req, connInfo, params) =>
|
routes[`${method}@${page.route}`] = (req, ctx, params) =>
|
||||||
handler(req, {
|
handler(req, {
|
||||||
...connInfo,
|
...ctx,
|
||||||
params,
|
params,
|
||||||
render: createRender(req, params),
|
render: createRender(req, params),
|
||||||
});
|
});
|
||||||
@@ -415,17 +462,24 @@ export class ServerContext {
|
|||||||
}
|
}
|
||||||
|
|
||||||
const unknownHandlerRender = genRender(this.#notFound, 404);
|
const unknownHandlerRender = genRender(this.#notFound, 404);
|
||||||
const unknownHandler = (req: Request, connInfo: ConnInfo) =>
|
const unknownHandler: router.Handler<RouterState> = (
|
||||||
|
req,
|
||||||
|
ctx,
|
||||||
|
) =>
|
||||||
this.#notFound.handler(
|
this.#notFound.handler(
|
||||||
req,
|
req,
|
||||||
{
|
{
|
||||||
...connInfo,
|
...ctx,
|
||||||
render: unknownHandlerRender(req, {}),
|
render: unknownHandlerRender(req, {}),
|
||||||
},
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
const errorHandlerRender = genRender(this.#error, 500);
|
const errorHandlerRender = genRender(this.#error, 500);
|
||||||
const errorHandler = (req: Request, connInfo: ConnInfo, error: unknown) => {
|
const errorHandler: router.ErrorHandler<RouterState> = (
|
||||||
|
req,
|
||||||
|
ctx,
|
||||||
|
error,
|
||||||
|
) => {
|
||||||
console.error(
|
console.error(
|
||||||
"%cAn error occured during route handling or page rendering.",
|
"%cAn error occured during route handling or page rendering.",
|
||||||
"color:red",
|
"color:red",
|
||||||
@@ -434,7 +488,7 @@ export class ServerContext {
|
|||||||
return this.#error.handler(
|
return this.#error.handler(
|
||||||
req,
|
req,
|
||||||
{
|
{
|
||||||
...connInfo,
|
...ctx,
|
||||||
error,
|
error,
|
||||||
render: errorHandlerRender(req, {}, error),
|
render: errorHandlerRender(req, {}, error),
|
||||||
},
|
},
|
||||||
@@ -478,7 +532,7 @@ export class ServerContext {
|
|||||||
* constants.INTERNAL_PREFIX
|
* constants.INTERNAL_PREFIX
|
||||||
*/
|
*/
|
||||||
#bundleAssetRoute = (): router.MatchHandler => {
|
#bundleAssetRoute = (): router.MatchHandler => {
|
||||||
return async (_req, _connInfo, params) => {
|
return async (_req, _ctx, params) => {
|
||||||
const path = `/${params.path}`;
|
const path = `/${params.path}`;
|
||||||
const file = await this.#bundler.get(path);
|
const file = await this.#bundler.get(path);
|
||||||
let res;
|
let res;
|
||||||
@@ -511,10 +565,6 @@ const DEFAULT_RENDERER: Renderer = {
|
|||||||
},
|
},
|
||||||
};
|
};
|
||||||
|
|
||||||
const DEFAULT_MIDDLEWARE: Middleware = {
|
|
||||||
handler: (_, ctx) => ctx.handle(),
|
|
||||||
};
|
|
||||||
|
|
||||||
const DEFAULT_APP: AppModule = {
|
const DEFAULT_APP: AppModule = {
|
||||||
default: ({ Component }) => h(Component, {}),
|
default: ({ Component }) => h(Component, {}),
|
||||||
};
|
};
|
||||||
@@ -536,6 +586,25 @@ const DEFAULT_ERROR: ErrorPage = {
|
|||||||
csp: false,
|
csp: false,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Return a list of middlewares that needs to be applied for request url
|
||||||
|
* @param url the request url
|
||||||
|
* @param middlewares Array of middlewares handlers and their routes as path-to-regexp style
|
||||||
|
*/
|
||||||
|
export function selectMiddlewares(url: string, middlewares: MiddlewareRoute[]) {
|
||||||
|
const selectedMws: Middleware[] = [];
|
||||||
|
const reqURL = new URL(url);
|
||||||
|
|
||||||
|
for (const { pattern, handler } of middlewares) {
|
||||||
|
const res = pattern.exec(reqURL);
|
||||||
|
if (res) {
|
||||||
|
selectedMws.push({ handler });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return selectedMws;
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Sort pages by their relative routing priority, based on the parts in the
|
* Sort pages by their relative routing priority, based on the parts in the
|
||||||
* route matcher
|
* route matcher
|
||||||
@@ -612,3 +681,10 @@ function serializeCSPDirectives(csp: ContentSecurityPolicyDirectives): string {
|
|||||||
})
|
})
|
||||||
.join("; ");
|
.join("; ");
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export function middlewarePathToPattern(baseRoute: string) {
|
||||||
|
baseRoute = baseRoute.slice(0, -"_middleware".length);
|
||||||
|
const regRoute = pathToRoute(baseRoute);
|
||||||
|
const pattern = new URLPattern({ pathname: `${regRoute}*` });
|
||||||
|
return { route: regRoute, pattern };
|
||||||
|
}
|
||||||
|
|||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import { assert } from "../../tests/deps.ts";
|
||||||
|
import { middlewarePathToPattern, selectMiddlewares } from "./context.ts";
|
||||||
|
import { MiddlewareRoute } from "./types.ts";
|
||||||
|
|
||||||
|
Deno.test("selectMiddlewares", () => {
|
||||||
|
const url = "https://fresh.deno.dev/api/abc/def";
|
||||||
|
const middlewaresPath = [
|
||||||
|
// should select
|
||||||
|
"_middleware",
|
||||||
|
"api/_middleware",
|
||||||
|
"api/[id]/_middleware",
|
||||||
|
|
||||||
|
// should not select
|
||||||
|
"api/xyz/_middleware",
|
||||||
|
"api/[id]/xyz/_middleware",
|
||||||
|
"api/[id]/[path]/_middleware",
|
||||||
|
"api/[id]/[path]/foo/_middleware",
|
||||||
|
];
|
||||||
|
const mwRoutes = middlewaresPath.map((path) =>
|
||||||
|
middlewarePathToPattern(path)
|
||||||
|
) as MiddlewareRoute[];
|
||||||
|
const mws = selectMiddlewares(url, mwRoutes);
|
||||||
|
assert(mws.length === 3);
|
||||||
|
});
|
||||||
+1
-1
@@ -16,7 +16,7 @@ export type {
|
|||||||
} from "https://deno.land/std@0.128.0/http/server.ts";
|
} from "https://deno.land/std@0.128.0/http/server.ts";
|
||||||
|
|
||||||
// -- router --
|
// -- router --
|
||||||
export * as router from "https://crux.land/router@0.0.6";
|
export * as router from "https://crux.land/router@0.0.7";
|
||||||
|
|
||||||
// -- media types --
|
// -- media types --
|
||||||
export { lookup as mediaTypeLookup } from "https://deno.land/x/media_types@v2.10.2/mod.ts";
|
export { lookup as mediaTypeLookup } from "https://deno.land/x/media_types@v2.10.2/mod.ts";
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ import {
|
|||||||
import { HEAD_CONTEXT } from "../runtime/head.ts";
|
import { HEAD_CONTEXT } from "../runtime/head.ts";
|
||||||
import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
|
import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
|
||||||
import { ContentSecurityPolicy } from "../runtime/csp.ts";
|
import { ContentSecurityPolicy } from "../runtime/csp.ts";
|
||||||
import { BUILD_ID, bundleAssetUrl } from "./constants.ts";
|
import { bundleAssetUrl } from "./constants.ts";
|
||||||
|
|
||||||
export interface RenderOptions<Data> {
|
export interface RenderOptions<Data> {
|
||||||
page: Page<Data> | UnknownPage | ErrorPage;
|
page: Page<Data> | UnknownPage | ErrorPage;
|
||||||
|
|||||||
+41
-15
@@ -9,11 +9,16 @@ import {
|
|||||||
} from "../runtime/types.ts";
|
} from "../runtime/types.ts";
|
||||||
import { RenderContext, RenderFn } from "./render.tsx";
|
import { RenderContext, RenderFn } from "./render.tsx";
|
||||||
|
|
||||||
|
export interface RouterState {
|
||||||
|
state: Record<string, unknown>;
|
||||||
|
}
|
||||||
|
|
||||||
export type StartOptions = ServeInit;
|
export type StartOptions = ServeInit;
|
||||||
|
|
||||||
export interface PageModule {
|
export interface PageModule {
|
||||||
default?: ComponentType<PageProps>;
|
default?: ComponentType<PageProps>;
|
||||||
handler?: Handler | Handlers;
|
// deno-lint-ignore no-explicit-any
|
||||||
|
handler?: Handler<any, any> | Handlers<any, any>;
|
||||||
config?: PageConfig;
|
config?: PageConfig;
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -34,28 +39,36 @@ export interface IslandModule {
|
|||||||
default: ComponentType<any>;
|
default: ComponentType<any>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface HandlerContext<T = unknown> extends ConnInfo {
|
export interface HandlerContext<Data = unknown, State = Record<string, unknown>>
|
||||||
|
extends ConnInfo {
|
||||||
params: Record<string, string>;
|
params: Record<string, string>;
|
||||||
render: (data?: T) => Response | Promise<Response>;
|
render: (data?: Data) => Response | Promise<Response>;
|
||||||
|
state: State;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface UnknownHandlerContext extends ConnInfo {
|
export interface UnknownHandlerContext<State = Record<string, unknown>>
|
||||||
|
extends ConnInfo {
|
||||||
render: () => Response | Promise<Response>;
|
render: () => Response | Promise<Response>;
|
||||||
|
state: State;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface ErrorHandlerContext extends ConnInfo {
|
export interface ErrorHandlerContext<State = Record<string, unknown>>
|
||||||
|
extends ConnInfo {
|
||||||
error: unknown;
|
error: unknown;
|
||||||
render: () => Response | Promise<Response>;
|
render: () => Response | Promise<Response>;
|
||||||
|
state: State;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MiddlewareHandlerContext extends ConnInfo {
|
export interface MiddlewareHandlerContext<State = Record<string, unknown>>
|
||||||
handle: () => Promise<Response>;
|
extends ConnInfo {
|
||||||
|
next: () => Promise<Response>;
|
||||||
|
state: State;
|
||||||
}
|
}
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export type Handler<T = any> = (
|
export type Handler<T = any, State = Record<string, unknown>> = (
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: HandlerContext<T>,
|
ctx: HandlerContext<T, State>,
|
||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
export type UnknownHandler = (
|
export type UnknownHandler = (
|
||||||
req: Request,
|
req: Request,
|
||||||
@@ -67,8 +80,8 @@ export type ErrorHandler = (
|
|||||||
) => Response | Promise<Response>;
|
) => Response | Promise<Response>;
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
export type Handlers<T = any> = {
|
export type Handlers<T = any, State = Record<string, unknown>> = {
|
||||||
[K in typeof router.METHODS[number]]?: Handler<T>;
|
[K in typeof router.METHODS[number]]?: Handler<T, State>;
|
||||||
};
|
};
|
||||||
|
|
||||||
// deno-lint-ignore no-explicit-any
|
// deno-lint-ignore no-explicit-any
|
||||||
@@ -107,20 +120,33 @@ export interface Renderer {
|
|||||||
render(ctx: RenderContext, render: RenderFn): void | Promise<void>;
|
render(ctx: RenderContext, render: RenderFn): void | Promise<void>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface MiddlewareModule {
|
// deno-lint-ignore no-explicit-any
|
||||||
|
export interface MiddlewareModule<State = any> {
|
||||||
handler(
|
handler(
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: MiddlewareHandlerContext,
|
ctx: MiddlewareHandlerContext<State>,
|
||||||
): Response | Promise<Response>;
|
): Response | Promise<Response>;
|
||||||
}
|
}
|
||||||
|
|
||||||
export interface Middleware {
|
export interface Middleware<State = Record<string, unknown>> {
|
||||||
handler(
|
handler(
|
||||||
req: Request,
|
req: Request,
|
||||||
ctx: MiddlewareHandlerContext,
|
ctx: MiddlewareHandlerContext<State>,
|
||||||
): Response | Promise<Response>;
|
): Response | Promise<Response>;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
export interface MiddlewareRoute extends Middleware {
|
||||||
|
/**
|
||||||
|
* path-to-regexp style url path
|
||||||
|
*/
|
||||||
|
route: string;
|
||||||
|
/**
|
||||||
|
* URLPattern of the route
|
||||||
|
*/
|
||||||
|
// deno-lint-ignore no-explicit-any
|
||||||
|
pattern: any;
|
||||||
|
}
|
||||||
|
|
||||||
export interface AppModule {
|
export interface AppModule {
|
||||||
default: ComponentType<AppProps>;
|
default: ComponentType<AppProps>;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -15,10 +15,17 @@ import * as $9 from "./routes/failure.ts";
|
|||||||
import * as $10 from "./routes/index.tsx";
|
import * as $10 from "./routes/index.tsx";
|
||||||
import * as $11 from "./routes/intercept.tsx";
|
import * as $11 from "./routes/intercept.tsx";
|
||||||
import * as $12 from "./routes/intercept_args.tsx";
|
import * as $12 from "./routes/intercept_args.tsx";
|
||||||
import * as $13 from "./routes/params.tsx";
|
import * as $13 from "./routes/layeredMdw/_middleware.ts";
|
||||||
import * as $14 from "./routes/props/[id].tsx";
|
import * as $14 from "./routes/layeredMdw/layer2-no-mw/without_mw.ts";
|
||||||
import * as $15 from "./routes/static.tsx";
|
import * as $15 from "./routes/layeredMdw/layer2/_middleware.ts";
|
||||||
import * as $16 from "./routes/wildcard.tsx";
|
import * as $16 from "./routes/layeredMdw/layer2/abc.ts";
|
||||||
|
import * as $17 from "./routes/layeredMdw/layer2/layer3/[id].ts";
|
||||||
|
import * as $18 from "./routes/layeredMdw/layer2/layer3/_middleware.ts";
|
||||||
|
import * as $19 from "./routes/middleware_root.ts";
|
||||||
|
import * as $20 from "./routes/params.tsx";
|
||||||
|
import * as $21 from "./routes/props/[id].tsx";
|
||||||
|
import * as $22 from "./routes/static.tsx";
|
||||||
|
import * as $23 from "./routes/wildcard.tsx";
|
||||||
import * as $$0 from "./islands/Test.tsx";
|
import * as $$0 from "./islands/Test.tsx";
|
||||||
|
|
||||||
const manifest = {
|
const manifest = {
|
||||||
@@ -36,10 +43,17 @@ const manifest = {
|
|||||||
"./routes/index.tsx": $10,
|
"./routes/index.tsx": $10,
|
||||||
"./routes/intercept.tsx": $11,
|
"./routes/intercept.tsx": $11,
|
||||||
"./routes/intercept_args.tsx": $12,
|
"./routes/intercept_args.tsx": $12,
|
||||||
"./routes/params.tsx": $13,
|
"./routes/layeredMdw/_middleware.ts": $13,
|
||||||
"./routes/props/[id].tsx": $14,
|
"./routes/layeredMdw/layer2-no-mw/without_mw.ts": $14,
|
||||||
"./routes/static.tsx": $15,
|
"./routes/layeredMdw/layer2/_middleware.ts": $15,
|
||||||
"./routes/wildcard.tsx": $16,
|
"./routes/layeredMdw/layer2/abc.ts": $16,
|
||||||
|
"./routes/layeredMdw/layer2/layer3/[id].ts": $17,
|
||||||
|
"./routes/layeredMdw/layer2/layer3/_middleware.ts": $18,
|
||||||
|
"./routes/middleware_root.ts": $19,
|
||||||
|
"./routes/params.tsx": $20,
|
||||||
|
"./routes/props/[id].tsx": $21,
|
||||||
|
"./routes/static.tsx": $22,
|
||||||
|
"./routes/wildcard.tsx": $23,
|
||||||
},
|
},
|
||||||
islands: {
|
islands: {
|
||||||
"./islands/Test.tsx": $$0,
|
"./islands/Test.tsx": $$0,
|
||||||
|
|||||||
@@ -1,7 +1,8 @@
|
|||||||
import { MiddlewareHandlerContext } from "../server_deps.ts";
|
import { MiddlewareHandlerContext } from "../server_deps.ts";
|
||||||
|
|
||||||
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
const resp = await ctx.handle();
|
ctx.state.root = "root_mw";
|
||||||
|
const resp = await ctx.next();
|
||||||
resp.headers.set("server", "fresh test server");
|
resp.headers.set("server", "fresh test server");
|
||||||
return resp;
|
return resp;
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { MiddlewareHandlerContext } from "../../server_deps.ts";
|
||||||
|
|
||||||
|
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
|
ctx.state.layer1 = "layer1_mw";
|
||||||
|
const resp = await ctx.next();
|
||||||
|
resp.headers.set("server", "fresh test server layer1");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { Handlers } from "../../../../../server.ts";
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
root: string;
|
||||||
|
layer1: string;
|
||||||
|
layer3: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const handler: Handlers<undefined, State> = {
|
||||||
|
GET(_req: Request, { state }) {
|
||||||
|
return new Response(JSON.stringify(state));
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
import { MiddlewareHandlerContext } from "../../../server_deps.ts";
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
root: string;
|
||||||
|
layer1: string;
|
||||||
|
layer2: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function handler(
|
||||||
|
_req: Request,
|
||||||
|
ctx: MiddlewareHandlerContext<State>,
|
||||||
|
) {
|
||||||
|
ctx.state.layer2 = "layer2_mw";
|
||||||
|
const resp = await ctx.next();
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import { Handlers } from "../../../../../server.ts";
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
root: string;
|
||||||
|
layer1: string;
|
||||||
|
layer2: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const handler: Handlers<undefined, State> = {
|
||||||
|
GET(_req: Request, { state }) {
|
||||||
|
return new Response(JSON.stringify(state));
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
import { Handlers } from "../../../../../../server.ts";
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
root: string;
|
||||||
|
layer1: string;
|
||||||
|
layer2: string;
|
||||||
|
layer3: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const handler: Handlers<undefined, State> = {
|
||||||
|
GET(_req: Request, { state }) {
|
||||||
|
return new Response(JSON.stringify(state));
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
import { MiddlewareHandlerContext } from "../../../../server_deps.ts";
|
||||||
|
|
||||||
|
export async function handler(_req: Request, ctx: MiddlewareHandlerContext) {
|
||||||
|
ctx.state.layer3 = "layer3_mw";
|
||||||
|
const resp = await ctx.next();
|
||||||
|
resp.headers.set("server", "fresh test server layer3");
|
||||||
|
resp.headers.set("layer3", "fresh test server layer3");
|
||||||
|
return resp;
|
||||||
|
}
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
import { Handlers } from "../../../server.ts";
|
||||||
|
|
||||||
|
interface State {
|
||||||
|
root: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const handler: Handlers<undefined, State> = {
|
||||||
|
GET(_req: Request, { state }) {
|
||||||
|
return new Response(JSON.stringify(state));
|
||||||
|
},
|
||||||
|
};
|
||||||
@@ -245,3 +245,67 @@ Deno.test("/connInfo", async () => {
|
|||||||
const body = await resp.text();
|
const body = await resp.text();
|
||||||
assertEquals(body, "127.0.0.1");
|
assertEquals(body, "127.0.0.1");
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Deno.test({
|
||||||
|
name: "/middleware - root",
|
||||||
|
fn: async () => {
|
||||||
|
const resp = await router(
|
||||||
|
new Request("https://fresh.deno.dev/middleware_root"),
|
||||||
|
);
|
||||||
|
assert(resp);
|
||||||
|
assertEquals(resp.status, 200);
|
||||||
|
const body = await resp.text();
|
||||||
|
assertStringIncludes(body, "root_mw");
|
||||||
|
assert(!body.includes("layer1_mw"));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test({
|
||||||
|
name: "/middleware - layer 2 middleware",
|
||||||
|
fn: async () => {
|
||||||
|
const resp = await router(
|
||||||
|
new Request("https://fresh.deno.dev/layeredMdw/layer2/abc"),
|
||||||
|
);
|
||||||
|
assert(resp);
|
||||||
|
assertEquals(resp.status, 200);
|
||||||
|
const body = await resp.text();
|
||||||
|
assertStringIncludes(body, "root_mw");
|
||||||
|
assertStringIncludes(body, "layer1_mw");
|
||||||
|
assertStringIncludes(body, "layer2_mw");
|
||||||
|
// layered 2 should not run layer 3 middleware
|
||||||
|
assert(!body.includes("layer3_mw"));
|
||||||
|
|
||||||
|
const resp1 = await router(
|
||||||
|
new Request("https://fresh.deno.dev/layeredMdw/layer2-no-mw/without_mw"),
|
||||||
|
);
|
||||||
|
assert(resp1);
|
||||||
|
assertEquals(resp1.status, 200);
|
||||||
|
const body1 = await resp1.text();
|
||||||
|
assertStringIncludes(body1, "root_mw");
|
||||||
|
assertStringIncludes(body1, "layer1_mw");
|
||||||
|
// layered 2 should not run layer 2 or 3 middleware
|
||||||
|
assert(!body1.includes("layer2_mw"));
|
||||||
|
assert(!body1.includes("layer3_mw"));
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
Deno.test({
|
||||||
|
name: "/middleware - layer 3 middleware ",
|
||||||
|
fn: async () => {
|
||||||
|
// layered 3 should contain layer 3 middleware data
|
||||||
|
const resp = await router(
|
||||||
|
new Request("https://fresh.deno.dev/layeredMdw/layer2/layer3/abc"),
|
||||||
|
);
|
||||||
|
assert(resp);
|
||||||
|
assertEquals(resp.status, 200);
|
||||||
|
const body = await resp.text();
|
||||||
|
assertStringIncludes(body, "root_mw");
|
||||||
|
assertStringIncludes(body, "layer1_mw");
|
||||||
|
assertStringIncludes(body, "layer3_mw");
|
||||||
|
assertEquals(resp.headers.get("layer3"), "fresh test server layer3");
|
||||||
|
// the below ensure that the middlewware are applied in the correct order.
|
||||||
|
// i.e response header set from layer3 middleware is overwritten
|
||||||
|
// by the reponse header in layer 0
|
||||||
|
assertEquals(resp.headers.get("server"), "fresh test server");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|||||||
@@ -11,7 +11,7 @@ export function render(ctx: RenderContext, render: RenderFn) {
|
|||||||
const snapshot = ctx.state.get("twindSnapshot") as unknown[] | null;
|
const snapshot = ctx.state.get("twindSnapshot") as unknown[] | null;
|
||||||
sheet.reset(snapshot || undefined);
|
sheet.reset(snapshot || undefined);
|
||||||
render();
|
render();
|
||||||
ctx.styles.splice(0, ctx.styles.length, ...sheet.target);
|
ctx.styles.splice(0, ctx.styles.length, ...(sheet).target);
|
||||||
const newSnapshot = sheet.reset();
|
const newSnapshot = sheet.reset();
|
||||||
ctx.state.set("twindSnapshot", newSnapshot);
|
ctx.state.set("twindSnapshot", newSnapshot);
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user