fix: middleware regressions (#3106)

Fixes some regressions found after merging
https://github.com/denoland/fresh/pull/3086

- Missing 404 middlewares when mounting sub-apps
- revert more staticFiles logic to always require the middleware like
before
This commit is contained in:
Marvin Hagemeister
2025-07-17 15:23:27 +02:00
committed by GitHub
parent c279efa345
commit 226e250386
7 changed files with 69 additions and 71 deletions
+18 -21
View File
@@ -30,7 +30,6 @@ import {
segmentToMiddlewares, segmentToMiddlewares,
} from "./segments.ts"; } from "./segments.ts";
import { isHandlerByMethod, type PageResponse } from "./handlers.ts"; import { isHandlerByMethod, type PageResponse } from "./handlers.ts";
import { staticFiles } from "./middlewares/static_files.ts";
// TODO: Completed type clashes in older Deno versions // TODO: Completed type clashes in older Deno versions
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
@@ -39,9 +38,6 @@ export const DEFAULT_CONN_INFO: any = {
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 }, remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
}; };
/** Used to group mounted apps. Only internal */
let INTERNAL_ID = 0;
const DEFAULT_RENDER = <State>(): Promise<PageResponse<State>> => const DEFAULT_RENDER = <State>(): Promise<PageResponse<State>> =>
// deno-lint-ignore no-explicit-any // deno-lint-ignore no-explicit-any
Promise.resolve({ data: {} as any }); Promise.resolve({ data: {} as any });
@@ -182,7 +178,6 @@ export class App<State> {
method: Method | "ALL"; method: Method | "ALL";
pattern: string; pattern: string;
fns: MiddlewareFn<State>[]; fns: MiddlewareFn<State>[];
unshift: boolean;
}[] = []; }[] = [];
static { static {
@@ -343,7 +338,6 @@ export class App<State> {
method: Method | "ALL", method: Method | "ALL",
path: string, path: string,
fns: MiddlewareFn<State>[], fns: MiddlewareFn<State>[],
unshift = false,
) { ) {
const segment = getOrCreateSegment<State>(this.#root, path, false); const segment = getOrCreateSegment<State>(this.#root, path, false);
const result = segmentToMiddlewares(segment); const result = segmentToMiddlewares(segment);
@@ -351,30 +345,31 @@ export class App<State> {
result.push(...fns); result.push(...fns);
const resPath = mergePath(this.config.basePath, path); const resPath = mergePath(this.config.basePath, path);
this.#addRoute(method, resPath, result, unshift); this.#addRoute(method, resPath, result);
} }
#addRoute( #addRoute(
method: Method | "ALL", method: Method | "ALL",
path: string, path: string,
fns: MiddlewareFn<State>[], fns: MiddlewareFn<State>[],
unshift = false,
) { ) {
this.#routeDefs.push({ method, pattern: path, fns, unshift }); this.#routeDefs.push({ method, pattern: path, fns });
} }
mountApp(path: string, app: App<State>): this { mountApp(path: string, app: App<State>): this {
const segmentPath = mergePath(path, `/__${INTERNAL_ID++}/`); const segmentPath = mergePath("", path);
const segment = getOrCreateSegment(this.#root, segmentPath, true); const segment = getOrCreateSegment(this.#root, segmentPath, true);
const fns = segmentToMiddlewares(segment); const fns = segmentToMiddlewares(segment);
segment.middlewares.push(...app.#root.middlewares);
const routes = app.#routeDefs; const routes = app.#routeDefs;
for (let i = 0; i < routes.length; i++) { for (let i = 0; i < routes.length; i++) {
const route = routes[i]; const route = routes[i];
const merged = mergePath(path, route.pattern); const merged = mergePath(path, route.pattern);
const mergedFns = [...fns, ...route.fns]; const mergedFns = [...fns, ...route.fns];
this.#addRoute(route.method, merged, mergedFns, route.unshift); this.#addRoute(route.method, merged, mergedFns);
} }
app.#islandRegistry.forEach((value, key) => { app.#islandRegistry.forEach((value, key) => {
@@ -408,20 +403,22 @@ export class App<State> {
return missingBuildHandler; return missingBuildHandler;
} }
// Fallthrough
this.#addMiddleware(
"ALL",
"*",
[...this.#root.middlewares, staticFiles()],
true,
);
for (let i = 0; i < this.#routeDefs.length; i++) { for (let i = 0; i < this.#routeDefs.length; i++) {
const route = this.#routeDefs[i]; const route = this.#routeDefs[i];
this.#router.add(route.method, route.pattern, route.fns, route.unshift); if (route.method === "ALL") {
this.#router.add("GET", route.pattern, route.fns);
this.#router.add("DELETE", route.pattern, route.fns);
this.#router.add("HEAD", route.pattern, route.fns);
this.#router.add("OPTIONS", route.pattern, route.fns);
this.#router.add("PATCH", route.pattern, route.fns);
this.#router.add("POST", route.pattern, route.fns);
this.#router.add("PUT", route.pattern, route.fns);
} else {
this.#router.add(route.method, route.pattern, route.fns);
}
} }
const rootMiddlewares = this.#root.middlewares; const rootMiddlewares = segmentToMiddlewares(this.#root);
return async ( return async (
req: Request, req: Request,
+23
View File
@@ -412,6 +412,29 @@ Deno.test(
}, },
); );
Deno.test("App - .mountApp() fallback route", async () => {
let called = "";
const innerApp = new App<{ text: string }>()
.use(function Inner(ctx) {
called += "_Inner";
return ctx.next();
})
.get("/", (ctx) => new Response(ctx.state.text));
const app = new App<{ text: string }>()
.use(function Outer(ctx) {
called += "Outer";
return ctx.next();
})
.mountApp("/", innerApp);
const server = new FakeServer(app.handler());
const res = await server.get("/invalid");
await res.body?.cancel();
expect(called).toEqual("Outer_Inner");
});
Deno.test("App - catches errors", async () => { Deno.test("App - catches errors", async () => {
let thrownErr: unknown | null = null; let thrownErr: unknown | null = null;
const app = new App<{ text: string }>() const app = new App<{ text: string }>()
+18 -44
View File
@@ -21,6 +21,18 @@ export interface DynamicRouteDef<T> {
byMethod: RouteByMethod<T>; byMethod: RouteByMethod<T>;
} }
function newByMethod<T>(): RouteByMethod<T> {
return {
GET: [],
POST: [],
PATCH: [],
DELETE: [],
PUT: [],
HEAD: [],
OPTIONS: [],
};
}
export interface RouteResult<T> { export interface RouteResult<T> {
params: Record<string, string>; params: Record<string, string>;
handlers: T[]; handlers: T[];
@@ -33,7 +45,6 @@ export interface Router<T> {
method: Method | "OPTIONS" | "ALL", method: Method | "OPTIONS" | "ALL",
pathname: string, pathname: string,
handlers: T[], handlers: T[],
unshift?: boolean,
): void; ): void;
match(method: Method, url: URL, init?: T[]): RouteResult<T>; match(method: Method, url: URL, init?: T[]): RouteResult<T>;
getAllowedMethods(pattern: string): string[]; getAllowedMethods(pattern: string): string[];
@@ -56,27 +67,17 @@ export class UrlPatternRouter<T> implements Router<T> {
} }
add( add(
method: Method | "ALL", method: Method,
pathname: string, pathname: string,
handlers: T[], handlers: T[],
unshift = false,
) { ) {
let allowed = this.#allowed.get(pathname); let allowed = this.#allowed.get(pathname);
if (allowed === undefined) { if (allowed === undefined) {
allowed = new Set(); allowed = new Set();
this.#allowed.set(pathname, allowed); this.#allowed.set(pathname, allowed);
} }
if (method === "ALL") {
allowed.add("GET"); allowed.add(method);
allowed.add("POST");
allowed.add("PATCH");
allowed.add("PUT");
allowed.add("DELETE");
allowed.add("HEAD");
allowed.add("OPTIONS");
} else {
allowed.add(method);
}
let byMethod: RouteByMethod<T>; let byMethod: RouteByMethod<T>;
if (IS_PATTERN.test(pathname)) { if (IS_PATTERN.test(pathname)) {
@@ -84,15 +85,7 @@ export class UrlPatternRouter<T> implements Router<T> {
if (def === undefined) { if (def === undefined) {
def = { def = {
pattern: new URLPattern({ pathname }), pattern: new URLPattern({ pathname }),
byMethod: { byMethod: newByMethod(),
DELETE: [],
GET: [],
HEAD: [],
OPTIONS: [],
PATCH: [],
POST: [],
PUT: [],
},
}; };
this.#dynamics.set(pathname, def); this.#dynamics.set(pathname, def);
this.#dynamicArr.push(def); this.#dynamicArr.push(def);
@@ -104,15 +97,7 @@ export class UrlPatternRouter<T> implements Router<T> {
if (def === undefined) { if (def === undefined) {
def = { def = {
pattern: pathname, pattern: pathname,
byMethod: { byMethod: newByMethod(),
DELETE: [],
GET: [],
HEAD: [],
OPTIONS: [],
PATCH: [],
POST: [],
PUT: [],
},
}; };
this.#statics.set(pathname, def); this.#statics.set(pathname, def);
} }
@@ -120,18 +105,7 @@ export class UrlPatternRouter<T> implements Router<T> {
byMethod = def.byMethod; byMethod = def.byMethod;
} }
const fn = unshift ? "unshift" : "push"; byMethod[method].push(...handlers);
if (method === "ALL") {
byMethod.DELETE[fn](...handlers);
byMethod.GET[fn](...handlers);
byMethod.HEAD[fn](...handlers);
byMethod.OPTIONS[fn](...handlers);
byMethod.PATCH[fn](...handlers);
byMethod.POST[fn](...handlers);
byMethod.PUT[fn](...handlers);
} else {
byMethod[method][fn](...handlers);
}
} }
match(method: Method, url: URL, init: T[] = []): RouteResult<T> { match(method: Method, url: URL, init: T[] = []): RouteResult<T> {
+3 -2
View File
@@ -1,4 +1,4 @@
import { App } from "fresh"; import { App, staticFiles } from "fresh";
import { import {
allIslandApp, allIslandApp,
assertNotSelector, assertNotSelector,
@@ -27,7 +27,8 @@ function testApp<T>(): App<T> {
const app = new App<T>() const app = new App<T>()
.island(selfCounter, "SelfCounter", SelfCounter) .island(selfCounter, "SelfCounter", SelfCounter)
.island(partialInIsland, "PartialInIsland", PartialInIsland) .island(partialInIsland, "PartialInIsland", PartialInIsland)
.island(jsonIsland, "JsonIsland", JsonIsland); .island(jsonIsland, "JsonIsland", JsonIsland)
.use(staticFiles());
setBuildCache(app, getBuildCache(allIslandApp)); setBuildCache(app, getBuildCache(allIslandApp));
return app; return app;
} }
+2 -1
View File
@@ -1,4 +1,4 @@
import { App, fsRoutes } from "fresh"; import { App, fsRoutes, staticFiles } from "fresh";
import { Counter } from "./fixtures_islands/Counter.tsx"; import { Counter } from "./fixtures_islands/Counter.tsx";
import { IslandInIsland } from "./fixtures_islands/IslandInIsland.tsx"; import { IslandInIsland } from "./fixtures_islands/IslandInIsland.tsx";
import { JsonIsland } from "./fixtures_islands/JsonIsland.tsx"; import { JsonIsland } from "./fixtures_islands/JsonIsland.tsx";
@@ -37,6 +37,7 @@ await buildProd(allIslandApp);
function testApp(config?: FreshConfig) { function testApp(config?: FreshConfig) {
const app = new App(config); const app = new App(config);
setBuildCache(app, getBuildCache(allIslandApp)); setBuildCache(app, getBuildCache(allIslandApp));
app.use(staticFiles());
return app; return app;
} }
+3 -2
View File
@@ -1,4 +1,4 @@
import { App } from "fresh"; import { App, staticFiles } from "fresh";
import { Partial } from "fresh/runtime"; import { Partial } from "fresh/runtime";
import { import {
allIslandApp, allIslandApp,
@@ -40,7 +40,8 @@ function testApp<T>(): App<T> {
.island(selfCounter, "SelfCounter", SelfCounter) .island(selfCounter, "SelfCounter", SelfCounter)
.island(partialInIsland, "PartialInIsland", PartialInIsland) .island(partialInIsland, "PartialInIsland", PartialInIsland)
.island(jsonIsland, "JsonIsland", JsonIsland) .island(jsonIsland, "JsonIsland", JsonIsland)
.island(optOutPartialLink, "OptOutPartialLink", OptOutPartialLink); .island(optOutPartialLink, "OptOutPartialLink", OptOutPartialLink)
.use(staticFiles());
setBuildCache(app, getBuildCache(allIslandApp)); setBuildCache(app, getBuildCache(allIslandApp));
return app; return app;
+2 -1
View File
@@ -1,6 +1,7 @@
import { App, fsRoutes, trailingSlashes } from "fresh"; import { App, fsRoutes, staticFiles, trailingSlashes } from "fresh";
export const app = new App({ root: import.meta.url }) export const app = new App({ root: import.meta.url })
.use(staticFiles())
.use(trailingSlashes("never")); .use(trailingSlashes("never"));
await fsRoutes(app, { await fsRoutes(app, {