major: import Fresh 2.0 code (#2449)

🎉
This commit is contained in:
Marvin Hagemeister
2024-05-24 09:40:08 +02:00
committed by GitHub
parent 990357629e
commit 287929e4d2
958 changed files with 15794 additions and 28287 deletions
+107
View File
@@ -0,0 +1,107 @@
import type { FreshContext } from "../context.ts";
import type { App as _App } from "../app.ts";
/**
* A middleware function is the basic building block of Fresh. It allows you
* to respond to an incoming request in any way you want. You can redirect
* routes, serve files, create APIs and much more. Middlewares can be chained by
* calling {@linkcode FreshContext.next|ctx.next()} inside of the function.
*
* Middlewares can be synchronous or asynchronous. If a middleware returns a
* {@linkcode Response} object, the response will be sent back to the client. If
* a middleware returns a `Promise<Response>`, Fresh will wait for the promise
* to resolve before sending the response.
*
* A {@linkcode FreshContext} object is passed to the middleware function. This
* object contains the original request object, as well as any state related to
* the current request. The context object also contains methods to redirect
* the client to another URL, or to call the next middleware in the chain.
*
* Middlewares can be defined as a single function or an array of functions.
* When an array of middlewares is passed to
* {@linkcode _App.prototype.use|app.use}, Fresh will call each middleware in the
* order they are defined.
*
* Middlewares can also be defined using the
* {@linkcode _App.prototype.defineMiddleware|app.defineMiddleware} method. This
* method is optional, but it can be useful for type checking and code
* completion. It does not register the middleware with the app.
*
* ## Examples
*
* ### Logging middleware
*
* This example shows how to create a simple middleware that logs incoming
* requests.
*
* ```ts
* // Define a middleware function that logs incoming requests. Using the
* // `defineMiddleware` method is optional, but it can be useful for type
* // checking and code completion. It does not register the middleware with the
* // app.
* const loggerMiddleware = app.defineMiddleware((ctx) => {
* console.log(`${ctx.req.method} ${ctx.req.url}`);
* // Call the next middleware
* return ctx.next();
* });
*
* // To register the middleware to the app, use `app.use`.
* app.use(loggerMiddleware)
* ```
*
* ### Redirect middleware
*
* This example shows how to create a middleware that redirects requests from
* one URL to another.
*
* ```ts
* // Any request to a URL that starts with "/legacy/" will be redirected to
* // "/modern".
* const redirectMiddleware = app.defineMiddleware((ctx) => {
* if (ctx.url.pathname.startsWith("/legacy/")) {
* return ctx.redirect("/modern");
* }
*
* // Otherwise call the next middleware
* return ctx.next();
* });
*
* // Again, register the middleware with the app.
* app.use(redirectMiddleware);
* ```
*/
export type MiddlewareFn<State> = (
ctx: FreshContext<unknown, State>,
) => Response | Promise<Response>;
/**
* A single middleware function, or an array of middleware functions. For
* further information, see {@link MiddlewareFn}.
*/
export type Middleware<State> = MiddlewareFn<State> | MiddlewareFn<State>[];
export function runMiddlewares<State>(
middlewares: MiddlewareFn<State>[][],
ctx: FreshContext<unknown, State>,
): Promise<Response> {
let fn = ctx.next;
let i = middlewares.length;
while (i--) {
const stack = middlewares[i];
let j = stack.length;
while (j--) {
const local = fn;
const next = stack[j];
fn = async () => {
ctx.next = local;
try {
return await next(ctx);
} catch (err) {
ctx.error = err;
throw err;
}
};
}
}
return fn();
}
+136
View File
@@ -0,0 +1,136 @@
import { runMiddlewares } from "./mod.ts";
import { expect } from "@std/expect";
import { serveMiddleware } from "../test_utils.ts";
import type { MiddlewareFn } from "./mod.ts";
Deno.test("runMiddleware", async () => {
const middlewares: MiddlewareFn<{ text: string }>[] = [
(ctx) => {
ctx.state.text = "A";
return ctx.next();
},
(ctx) => {
ctx.state.text += "B";
return ctx.next();
},
async (ctx) => {
const res = await ctx.next();
ctx.state.text += "C"; // This should not show up
return res;
},
(ctx) => {
return new Response(ctx.state.text);
},
];
const server = serveMiddleware<{ text: string }>((ctx) =>
runMiddlewares([middlewares], ctx)
);
const res = await server.get("/");
expect(await res.text()).toEqual("AB");
});
Deno.test("runMiddleware - middlewares should only be called once", async () => {
const A: MiddlewareFn<{ count: number }> = (ctx) => {
if (ctx.state.count === undefined) {
ctx.state.count = 0;
} else {
ctx.state.count++;
}
return ctx.next();
};
const server = serveMiddleware<{ count: number }>((ctx) =>
runMiddlewares(
[[A, (ctx) => new Response(String(ctx.state.count))]],
ctx,
)
);
const res = await server.get("/");
expect(await res.text()).toEqual("0");
});
Deno.test("runMiddleware - runs multiple stacks", async () => {
type State = { text: string };
const A: MiddlewareFn<State> = (ctx) => {
ctx.state.text += "A";
return ctx.next();
};
const B: MiddlewareFn<State> = (ctx) => {
ctx.state.text += "B";
return ctx.next();
};
const C: MiddlewareFn<State> = (ctx) => {
ctx.state.text += "C";
return ctx.next();
};
const D: MiddlewareFn<State> = (ctx) => {
ctx.state.text += "D";
return ctx.next();
};
const server = serveMiddleware<State>((ctx) => {
ctx.state.text = "";
return runMiddlewares(
[
[A, B],
[C, D, (ctx) => new Response(String(ctx.state.text))],
],
ctx,
);
});
const res = await server.get("/");
expect(await res.text()).toEqual("ABCD");
});
Deno.test("runMiddleware - throws errors", async () => {
let thrownA: unknown = null;
let thrownB: unknown = null;
let thrownC: unknown = null;
const middlewares: MiddlewareFn<{ text: string }>[] = [
async (ctx) => {
try {
return await ctx.next();
} catch (err) {
thrownA = err;
throw err;
}
},
async (ctx) => {
try {
return await ctx.next();
} catch (err) {
thrownB = err;
throw err;
}
},
async (ctx) => {
try {
return await ctx.next();
} catch (err) {
thrownC = err;
throw err;
}
},
() => {
throw new Error("fail");
},
];
const server = serveMiddleware<{ text: string }>((ctx) =>
runMiddlewares([middlewares], ctx)
);
try {
await server.get("/");
} catch {
// ignore
}
expect(thrownA).toBeInstanceOf(Error);
expect(thrownB).toBeInstanceOf(Error);
expect(thrownC).toBeInstanceOf(Error);
});
+77
View File
@@ -0,0 +1,77 @@
import * as path from "@std/path";
import { contentType as getContentType } from "@std/media-types/content-type";
import type { MiddlewareFn } from "@fresh/core";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { BUILD_ID } from "../runtime/build_id.ts";
import { getBuildCache } from "../context.ts";
/**
* Fresh middleware to enable file-system based routing.
* ```ts
* // Enable Fresh static file serving
* app.use(freshStaticFles());
* ```
*/
export function staticFiles<T>(): MiddlewareFn<T> {
return async function freshStaticFiles(ctx) {
const { req, url } = ctx;
const buildCache = getBuildCache(ctx);
// Fast path bail out
const file = await buildCache.readFile(url.pathname);
if (url.pathname === "/" || file === null) {
// Optimization: Prevent long responses for favicon.ico requests
if (url.pathname === "/favicon.ico") {
return new Response(null, { status: 404 });
}
return ctx.next();
}
if (req.method !== "GET" && req.method !== "HEAD") {
return new Response("Method Not Allowed", { status: 405 });
}
const cacheKey = url.searchParams.get(ASSET_CACHE_BUST_KEY);
if (cacheKey !== null && BUILD_ID !== cacheKey) {
url.searchParams.delete(ASSET_CACHE_BUST_KEY);
const location = url.pathname + url.search;
return new Response(null, {
status: 307,
headers: {
location,
},
});
}
const ext = path.extname(url.pathname);
const etag = file.hash;
const contentType = getContentType(ext);
const headers = new Headers({
"Content-Type": contentType ?? "text/plain",
vary: "If-None-Match",
});
if (cacheKey === null || ctx.config.mode === "development") {
headers.append(
"Cache-Control",
"no-cache, no-store, max-age=0, must-revalidate",
);
} else {
const ifNoneMatch = req.headers.get("If-None-Match");
if (
etag !== null &&
(ifNoneMatch === etag || ifNoneMatch === "W/" + etag)
) {
return new Response(null, { status: 304, headers });
}
}
headers.set("Content-Length", String(file.size));
if (req.method === "HEAD") {
return new Response(null, { status: 200, headers });
}
return new Response(file.readable, { headers });
};
}
+150
View File
@@ -0,0 +1,150 @@
import { staticFiles } from "./static_files.ts";
import { serveMiddleware } from "../test_utils.ts";
import type { BuildCache, StaticFile } from "../build_cache.ts";
import { expect } from "@std/expect";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { BUILD_ID } from "../runtime/build_id.ts";
class MockBuildCache implements BuildCache {
buildId = "MockId";
files = new Map<string, StaticFile>();
hasSnapshot = true;
constructor(files: Record<string, { hash: string | null; content: string }>) {
const encoder = new TextEncoder();
for (const [pathname, info] of Object.entries(files)) {
const text = encoder.encode(info.content);
const normalized = pathname.startsWith("/") ? pathname : "/" + pathname;
this.files.set(normalized, {
hash: info.hash,
size: text.byteLength,
readable: text,
});
}
}
// deno-lint-ignore require-await
async readFile(pathname: string): Promise<StaticFile | null> {
return this.files.get(pathname) ?? null;
}
getIslandChunkName(_islandName: string): string | null {
return null;
}
}
Deno.test("static files - 200", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
const res = await server.get("/foo.css");
const content = await res.text();
expect(res.status).toEqual(200);
expect(res.headers.get("Content-Type")).toEqual("text/css; charset=UTF-8");
expect(res.headers.get("Content-Length")).toEqual("7");
expect(res.headers.get("Cache-Control")).toEqual(
"no-cache, no-store, max-age=0, must-revalidate",
);
expect(content).toEqual("body {}");
});
Deno.test("static files - HEAD 200", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
const res = await server.head("/foo.css");
const content = await res.text();
expect(res.status).toEqual(200);
expect(res.headers.get("Content-Type")).toEqual("text/css; charset=UTF-8");
expect(res.headers.get("Content-Length")).toEqual("7");
expect(content).toEqual("");
});
Deno.test("static files - etag", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: "123" },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
const headers = new Headers();
headers.append("If-None-Match", "123");
const cacheUrl = `/foo.css?${ASSET_CACHE_BUST_KEY}=${BUILD_ID}`;
const res = await server.get(cacheUrl, { headers });
await res.body?.cancel();
expect(res.status).toEqual(304);
const headers2 = new Headers();
headers2.append("If-None-Match", "W/123");
const res2 = await server.get(cacheUrl, { headers });
await res2.body?.cancel();
expect(res2.status).toEqual(304);
});
Deno.test("static files - 404 on missing favicon.ico", async () => {
const buildCache = new MockBuildCache({});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
const res = await server.get("favicon.ico");
await res.body?.cancel();
expect(res.status).toEqual(404);
});
Deno.test("static files - 405 on wrong HTTP method", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
for (const method of ["post", "patch", "put", "delete"]) {
// deno-lint-ignore no-explicit-any
const res = await (server as any)[method]("/foo.css");
await res.body?.cancel();
expect(res.status).toEqual(405);
}
});
Deno.test("static files - disables caching in development", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{
buildCache,
config: {
basePath: "",
build: {
outDir: "",
},
mode: "development",
root: ".",
staticDir: "",
},
},
);
const res = await server.get("/foo.css");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Cache-Control")).toEqual(
"no-cache, no-store, max-age=0, must-revalidate",
);
});
+29
View File
@@ -0,0 +1,29 @@
import type { MiddlewareFn } from "./mod.ts";
/**
* Fresh middleware to force URLs to end with a slash or never end with one.
*
* ```ts
* // Always add trailing slash
* app.use(trailingSlashes("always"));
* // Never add trailing slashes to URLs and remove them if present
* app.use(trailingSlashes("never"));
* ```
*/
export function trailingSlashes<State>(
mode: "always" | "never",
): MiddlewareFn<State> {
return function trailingSlashesMiddleware(ctx) {
const url = ctx.url;
if (url.pathname !== "/") {
if (mode === "always" && !url.pathname.endsWith("/")) {
return ctx.redirect(`${url.pathname}/${url.search}`);
} else if (
mode === "never" && url.pathname.endsWith("/")
) {
return ctx.redirect(`${url.pathname.slice(0, -1)}${url.search}`);
}
}
return ctx.next();
};
}
+55
View File
@@ -0,0 +1,55 @@
// deno-lint-ignore-file require-await
import { trailingSlashes } from "./trailing_slashes.ts";
import { expect } from "@std/expect";
import { serveMiddleware } from "../test_utils.ts";
Deno.test("trailingSlashes - always", async () => {
const middleware = trailingSlashes("always");
const server = serveMiddleware(async (ctx) => {
ctx.next = async () => new Response("ok");
return await middleware(ctx);
});
let res = await server.get("/");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Location")).toEqual(null);
res = await server.get("/foo");
await res.body?.cancel();
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/foo/");
res = await server.get("/foo/bar");
await res.body?.cancel();
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/foo/bar/");
res = await server.get("/foo/bar/");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Location")).toEqual(null);
});
Deno.test("trailingSlashes - never", async () => {
const middleware = trailingSlashes("never");
const server = serveMiddleware(async (ctx) => {
ctx.next = async () => new Response("ok");
return await middleware(ctx);
});
let res = await server.get("/");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Location")).toEqual(null);
res = await server.get("/foo");
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Location")).toEqual(null);
res = await server.get("/foo/");
await res.body?.cancel();
expect(res.status).toEqual(302);
expect(res.headers.get("Location")).toEqual("/foo");
});