chore: restructure repository into packages/ folder (#3197)

We're having a growing number of packages in this repository. This PR
moves them into a `packages/` directory like it's commonly done in other
projects.
This commit is contained in:
Marvin Hagemeister
2025-08-06 15:52:45 +02:00
committed by GitHub
parent 27e407a1e3
commit 815b1940e3
184 changed files with 94 additions and 82 deletions
+193
View File
@@ -0,0 +1,193 @@
import type { Context } from "../context.ts";
import type { Middleware } from "./mod.ts";
export type CORSOptions<State> = {
/**
* The value of [`Access-Control-Allow-Origin`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Origin) CORS header
*/
origin:
| string
| string[]
| ((origin: string, ctx: Context<State>) => string | undefined | null);
/**
* Sets the permitted methods for the [`Access-Control-Allow-Methods`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Methods) CORS header.
*/
allowMethods?: string[];
/**
* Indicate the HTTP headers that can be used during the actual request. Sets the [`Access-Control-Allow-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Headers) header
*/
allowHeaders?: string[];
/**
* The value of [`Access-Control-Max-Age`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Max-Age) CORS header
*/
maxAge?: number;
/**
* The value of [`Access-Control-Allow-Credentials`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Allow-Credentials) CORS header
*/
credentials?: boolean;
/**
* The value of [`Access-Control-Expose-Headers`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Headers/Access-Control-Expose-Headers) CORS header
*/
exposeHeaders?: string[];
};
/**
* CORS Middleware to set [`Cross-Origin-Resource-Sharing`](https://developer.mozilla.org/en-US/docs/Web/HTTP/Guides/CORS) headers.
*
* @param [options] - The options for the CORS middleware.
* @returns The Fresh middleware handler function.
*
* @example
* ```ts
* // main.ts or routes/_middleware.ts
* import { cors } from 'fresh';
*
* export const handler = [
* cors({ origin: '*' }), // Allow all origins
* // other middlewares or main route handler
* ];
*
* // Example with options:
* // export const handler = [
* // cors({
* // origin: 'http://example.com',
* // allowHeaders: ['X-Custom-Header', 'Upgrade-Insecure-Requests'],
* // allowMethods: ['POST', 'GET', 'OPTIONS'],
* // exposeHeaders: ['Content-Length', 'X-Kuma-Revision'],
* // maxAge: 600,
* // credentials: true,
* // }),
* // // ...
* // ];
* ```
*/
export function cors<State>(options?: CORSOptions<State>): Middleware<State> {
const opts: CORSOptions<State> = {
origin: "*",
allowMethods: ["GET", "HEAD", "PUT", "POST", "DELETE", "PATCH"],
allowHeaders: [],
exposeHeaders: [],
...options,
};
const addHeaderProperties = (
headers: Headers,
allowOrigin: string | null | undefined,
opts: CORSOptions<State>,
) => {
if (allowOrigin) {
headers.set("Access-Control-Allow-Origin", allowOrigin);
}
if (opts.credentials) {
headers.set("Access-Control-Allow-Credentials", "true");
}
if (opts.exposeHeaders?.length) {
headers.set(
"Access-Control-Expose-Headers",
opts.exposeHeaders.join(","),
);
}
};
const optsOrigin = opts.origin;
return async (ctx) => {
const requestOrigin = ctx.req.headers.get("origin") || "";
let allowOrigin: string | null = null;
if (typeof optsOrigin === "string") {
if (optsOrigin === "*") {
allowOrigin = optsOrigin;
} else {
allowOrigin = optsOrigin === requestOrigin ? requestOrigin : null;
}
} else if (typeof optsOrigin === "function") {
allowOrigin = optsOrigin(requestOrigin, ctx) ?? null;
} else {
allowOrigin = optsOrigin.includes(requestOrigin) ? requestOrigin : null;
}
const vary = new Set<string>();
// Add 'Origin' to Vary if a specific origin is allowed, not '*'
if (opts.origin !== "*" && allowOrigin && allowOrigin !== "*") {
vary.add("Origin");
}
if (ctx.req.method === "OPTIONS") {
const headers = new Headers();
addHeaderProperties(
headers,
allowOrigin,
opts,
);
if (opts.maxAge != null) {
headers.set("Access-Control-Max-Age", opts.maxAge.toString());
}
if (opts.allowMethods?.length) {
headers.set(
"Access-Control-Allow-Methods",
opts.allowMethods.join(","),
);
}
let allowHeaders = opts.allowHeaders;
if (!allowHeaders?.length) {
const reqHeaders = ctx.req.headers.get(
"Access-Control-Request-Headers",
);
if (reqHeaders) {
allowHeaders = reqHeaders.split(/\s*,\s*/);
}
}
if (allowHeaders?.length) {
headers.set(
"Access-Control-Allow-Headers",
allowHeaders.join(","),
);
vary.add("Access-Control-Request-Headers");
}
if (vary.size > 0) {
headers.set("Vary", Array.from(vary).join(", "));
} else {
headers.delete("Vary"); // Ensure Vary is not set if no conditions met
}
headers.delete("Content-Length");
headers.delete("Content-Type");
return new Response(null, {
status: 204,
statusText: "No Content",
headers,
});
}
// For non-OPTIONS requests
const res = await ctx.next();
addHeaderProperties(
res.headers,
allowOrigin,
opts,
);
// Merge our calculated varyValues with any existing Vary from downstream response
if (vary.size > 0) {
const existing = res.headers.get("Vary");
if (existing) {
existing.split(/\s*,\s*/).forEach((v) => vary.add(v));
}
res.headers.set("Vary", Array.from(vary).join(", "));
}
return res;
};
}
+249
View File
@@ -0,0 +1,249 @@
import { App } from "../app.ts";
import { cors } from "./cors.ts";
import { expect } from "@std/expect";
Deno.test("CORS - GET default", async () => {
const handler = new App()
.use(cors())
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("https://localhost/"));
expect(res.status).toBe(200);
expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
expect(res.headers.get("Vary")).toBeNull();
});
Deno.test("CORS - Preflight default", async () => {
const handler = new App()
.use(cors())
.get("/", () => new Response("ok"))
.handler();
const req = new Request("https://localhost/", { method: "OPTIONS" });
req.headers.append(
"Access-Control-Request-Headers",
"X-PINGOTHER, Content-Type",
);
const res = await handler(req);
expect(res.status).toBe(204);
expect(res.headers.get("Access-Control-Allow-Methods")?.split(",")[0])
.toBe("GET");
expect(res.headers.get("Access-Control-Allow-Headers")?.split(","))
.toEqual(["X-PINGOTHER", "Content-Type"]);
});
Deno.test("CORS - Preflight with options", async () => {
const handler = new App()
.use(
cors({
origin: "http://example.com",
allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"],
allowMethods: ["POST", "GET", "OPTIONS"],
exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
maxAge: 600,
credentials: true,
}),
)
.get("/", () => new Response("ok"))
.handler();
const res = await handler(
new Request("https://localhost/", {
method: "OPTIONS",
headers: { origin: "http://example.com" },
}),
);
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
"http://example.com",
);
expect(res.headers.get("Vary")?.split(/\s*,\s*/)).toEqual(
expect.arrayContaining(["Origin"]),
);
expect(res.headers.get("Access-Control-Allow-Headers")?.split(/\s*,\s*/))
.toEqual([
"X-Custom-Header",
"Upgrade-Insecure-Requests",
]);
expect(res.headers.get("Access-Control-Allow-Methods")?.split(/\s*,\s*/))
.toEqual([
"POST",
"GET",
"OPTIONS",
]);
expect(res.headers.get("Access-Control-Expose-Headers")?.split(/\s*,\s*/))
.toEqual([
"Content-Length",
"X-Kuma-Revision",
]);
expect(res.headers.get("Access-Control-Max-Age")).toBe("600");
expect(res.headers.get("Access-Control-Allow-Credentials")).toBe("true");
});
Deno.test("CORS - Disallow an unmatched origin", async () => {
const handler = new App()
.use(
cors({
origin: "http://example.com",
allowHeaders: ["X-Custom-Header", "Upgrade-Insecure-Requests"],
allowMethods: ["POST", "GET", "OPTIONS"],
exposeHeaders: ["Content-Length", "X-Kuma-Revision"],
maxAge: 600,
credentials: true,
}),
)
.get("/", () => new Response("ok"))
.handler();
const res = await handler(
new Request("https://localhost/", {
method: "OPTIONS",
headers: { origin: "http://example.net" },
}),
);
expect(res.headers.has("Access-Control-Allow-Origin")).toBeFalsy();
});
Deno.test("CORS - Allow multiple origins", async () => {
const handler = new App()
.use(cors({
origin: [
"http://example.com",
"http://example.org",
"http://example.dev",
],
}))
.get("/", () => new Response("ok"))
.handler();
let res = await handler(
new Request("http://localhost/", {
headers: {
Origin: "http://example.org",
},
}),
);
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
"http://example.org",
);
res = await handler(new Request("http://localhost/"));
expect(
res.headers.has("Access-Control-Allow-Origin"),
"An unmatched origin should be disallowed",
).toBeFalsy();
res = await handler(
new Request("http://localhost/api3/abc", {
headers: {
Referer: "http://example.net/",
},
}),
);
expect(
res.headers.has("Access-Control-Allow-Origin"),
"An unmatched origin should be disallowed",
).toBeFalsy();
});
Deno.test("CORS - Allow different Vary header value", async () => {
const handler = new App()
.use(cors({
origin: [
"http://example.com",
"http://example.org",
"http://example.dev",
],
}))
.get("/", () => new Response("ok"))
.handler();
const res = await handler(
new Request("http://localhost/", {
headers: {
Vary: "accept-encoding",
Origin: "http://example.com",
},
}),
);
expect(res.status).toBe(200);
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
"http://example.com",
);
expect(res.headers.get("Vary")).toBe("Origin");
});
Deno.test("CORS - Allow origins by function", async () => {
const handler = new App()
.use(cors({
origin: (
origin,
) => (origin.endsWith(".example.com") ? origin : "http://example.com"),
}))
.get("/", () => new Response("ok"))
.handler();
let res = await handler(
new Request("http://localhost/", {
headers: {
Origin: "http://subdomain.example.com",
},
}),
);
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
"http://subdomain.example.com",
);
res = await handler(new Request("http://localhost/"));
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
"http://example.com",
);
res = await handler(
new Request("http://localhost/", {
headers: {
Referer: "http://evil-example.com/",
},
}),
);
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
"http://example.com",
);
});
Deno.test("CORS - With raw Response object", async () => {
const handler = new App()
.use(cors())
.get("/", () => new Response("ok"))
.handler();
const res = await handler(new Request("http://localhost/"));
expect(res.headers.get("Access-Control-Allow-Origin")).toBe("*");
expect(res.headers.get("Vary")).toBeNull();
});
Deno.test("CORS - Should not return duplicate header values", async () => {
const handler = new App()
.use(cors({ origin: "http://example.com" }))
.get("/", () => new Response("ok"))
.handler();
const res = await handler(
new Request("http://localhost/", {
headers: {
origin: "http://example.com",
},
}),
);
expect(res.headers.get("Access-Control-Allow-Origin")).toBe(
"http://example.com",
);
});
+113
View File
@@ -0,0 +1,113 @@
import type { Context } from "../context.ts";
import { HttpError } from "../error.ts";
import type { Middleware } from "./mod.ts";
/** Options for {@linkcode csrf}. **/
// deno-lint-ignore no-explicit-any
export interface CsrfOptions<State = any> {
/**
* origin - Specifies the allowed origin(s) for requests.
* - string: A single allowed origin.
* - string[]: static allowed origins.
* - function: A function to determine if an origin is allowed.
*/
origin?:
| string
| string[]
| ((origin: string, context: Context<State>) => boolean);
}
/**
* CSRF Protection Middleware for Fresh.
*
* @param options Options for the CSRF protection middleware.
* @returns The middleware handler function.
*
* @example Basic usage (with defaults)
* ```ts
* const app = new App<State>()
*
* app.use(csrf())
* ```
*
* @example Specifying static origins
* ```ts
* app.use(csrf({ origin: 'https://myapp.example.com' }))
*
* // string[]
* app.use(
* csrf({
* origin: ['https://myapp.example.com', 'http://development.myapp.example.com'],
* })
* )
* ```
*
* @example Specifying more complex origins
* ```ts
* app.use(
* '*',
* csrf({
* origin: (origin) => ['https://myapp.example.com', 'http://development.myapp.example.com'].includes(origin),
* })
* )
* ```
*/
export function csrf<State>(
options?: CsrfOptions,
): Middleware<State> {
const isAllowedOrigin = (
origin: string | null,
ctx: Context<State>,
) => {
if (origin === null) {
return false;
}
const optsOrigin = options?.origin;
if (!optsOrigin) {
return origin === ctx.url.origin;
}
if (typeof optsOrigin === "string") {
return origin === optsOrigin;
}
if (typeof optsOrigin === "function") {
return optsOrigin(origin, ctx);
}
return Array.isArray(optsOrigin) && optsOrigin.includes(origin);
};
return async (ctx) => {
const { method, headers } = ctx.req;
// Safe methods
if (method === "GET" || method === "HEAD" || method === "OPTIONS") {
return await ctx.next();
}
const secFetchSite = headers.get("Sec-Fetch-Site");
const origin = headers.get("origin");
if (secFetchSite !== null) {
if (
secFetchSite === "same-origin" || secFetchSite === "none" ||
isAllowedOrigin(origin, ctx)
) {
return await ctx.next();
}
throw new HttpError(403);
}
// Neither `Sec-Fetch-Site` or `Origin` is set
if (origin === null) {
return await ctx.next();
}
if (isAllowedOrigin(origin, ctx)) {
return await ctx.next();
}
throw new HttpError(403);
};
}
+101
View File
@@ -0,0 +1,101 @@
import { App } from "../app.ts";
import type { Method } from "../router.ts";
import { csrf, type CsrfOptions } from "./csrf.ts";
import { expect } from "@std/expect";
function testHandler<T>(
options?: CsrfOptions<T>,
): (request: Request) => Promise<Response> {
return new App<T>()
.use(csrf(options))
.all("/", () => new Response("hello"))
.handler();
}
function createTests(trusted: CsrfOptions["origin"]) {
return async function runTest(
method: Method,
expected: 200 | 403,
test: {
secFetchSite?: "cross-site" | "same-origin" | "same-site" | "none";
origin?: string;
} = {},
) {
const handler = testHandler({ origin: trusted });
const headers = new Headers();
if (test.secFetchSite) headers.append("Sec-Fetch-Site", test.secFetchSite);
if (test.origin) {
headers.append("Origin", test.origin);
}
const res = await handler(
new Request("https://example.com", { method, headers }),
);
await res.body?.cancel();
expect(res.status).toEqual(expected);
};
}
Deno.test("CSRF - allow GET/HEAD/OPTIONS", async () => {
const runTest = createTests("https://example.com");
await runTest("GET", 200);
await runTest("HEAD", 200);
await runTest("OPTIONS", 200);
});
Deno.test("CSRF - Sec-Fetch-Site", async () => {
const runTest = createTests("https://example.com");
await runTest("POST", 200, { secFetchSite: "same-origin" });
await runTest("POST", 200, { secFetchSite: "none" });
await runTest("POST", 403, { secFetchSite: "cross-site" });
await runTest("POST", 403, { secFetchSite: "same-site" });
await runTest("POST", 200);
await runTest("POST", 200, { origin: "https://example.com" });
await runTest("POST", 403, { origin: "https://attacker.example.com" });
await runTest("POST", 403, { origin: "null" });
await runTest("GET", 200, { secFetchSite: "cross-site" });
await runTest("HEAD", 200, { secFetchSite: "cross-site" });
await runTest("OPTIONS", 200, { secFetchSite: "cross-site" });
await runTest("PUT", 403, { secFetchSite: "cross-site" });
});
Deno.test("CSRF - cross origin", async () => {
const runTest = createTests("https://trusted.example.com");
await runTest("POST", 200, { origin: "https://trusted.example.com" });
await runTest("POST", 200, {
origin: "https://trusted.example.com",
secFetchSite: "cross-site",
});
await runTest("POST", 403, { origin: "https://attacker.example.com" });
await runTest("POST", 403, {
origin: "https://attacker.example.com",
secFetchSite: "cross-site",
});
});
Deno.test("CSRF - array origin", async () => {
const runTest = createTests(
["https://example.com", "https://trusted.example.com"],
);
await runTest("POST", 200, { origin: "https://trusted.example.com" });
await runTest("POST", 200, { origin: "https://example.com" });
await runTest("POST", 403, { origin: "https://foo.example.com" });
});
Deno.test("CSRF - function origin", async () => {
const runTest = createTests(
(origin) => origin === "https://example.com",
);
await runTest("POST", 200, { origin: "https://example.com" });
await runTest("POST", 403, { origin: "https://trusted.example.com" });
await runTest("POST", 403, { origin: "https://foo.example.com" });
});
+124
View File
@@ -0,0 +1,124 @@
import { type Context, getInternals } from "../context.ts";
import type { App as _App } from "../app.ts";
import type { Define as _Define } from "../define.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 Context.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 Context} 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 _Define.middleware|define.middleware} 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
* // `define.middleware` 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 = define.middleware((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 = define.middleware((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 Middleware<State> = (
ctx: Context<State>,
) => Response | Promise<Response>;
/**
* @deprecated Use {@linkcode Middleware} instead.
*/
export type MiddlewareFn<State> = Middleware<State>;
/**
* A lazy {@linkcode Middleware}
*/
export type MaybeLazyMiddleware<State> = (
ctx: Context<State>,
) => Response | Promise<Response | Middleware<State>>;
export function runMiddlewares<State>(
middlewares: MaybeLazyMiddleware<State>[],
ctx: Context<State>,
): Promise<Response> {
let fn = ctx.next;
let i = middlewares.length;
while (i--) {
const local = fn;
let next = middlewares[i];
const idx = i;
fn = async () => {
const internals = getInternals(ctx);
const { app: prevApp, layouts: prevLayouts } = internals;
ctx.next = local;
try {
const result = await next(ctx);
if (typeof result === "function") {
middlewares[idx] = result;
next = result;
return await result(ctx);
}
return result;
} catch (err) {
ctx.error = err;
throw err;
} finally {
internals.app = prevApp;
internals.layouts = prevLayouts;
}
};
}
return fn();
}
+179
View File
@@ -0,0 +1,179 @@
import { runMiddlewares } from "./mod.ts";
import { expect } from "@std/expect";
import { serveMiddleware } from "../test_utils.ts";
import type { Middleware } from "./mod.ts";
import type { Lazy, MaybeLazy } from "../types.ts";
Deno.test("runMiddleware", async () => {
const middlewares: Middleware<{ 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: Middleware<{ 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: Middleware<State> = (ctx) => {
ctx.state.text += "A";
return ctx.next();
};
const B: Middleware<State> = (ctx) => {
ctx.state.text += "B";
return ctx.next();
};
const C: Middleware<State> = (ctx) => {
ctx.state.text += "C";
return ctx.next();
};
const D: Middleware<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: Middleware<{ 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);
});
Deno.test("runMiddleware - lazy middlewares", async () => {
type State = { text: string };
let called = 0;
// deno-lint-ignore require-await
const lazy: Lazy<Middleware<State>> = async () => {
called++;
return (ctx) => {
ctx.state.text += "_lazy";
return ctx.next();
};
};
const middlewares: MaybeLazy<Middleware<State>>[] = [
async (ctx) => {
ctx.state.text = "A";
return await ctx.next();
},
lazy,
(ctx) => {
ctx.state.text += "_B";
return new Response(ctx.state.text);
},
];
const server = serveMiddleware<{ text: string }>((ctx) =>
runMiddlewares(middlewares, ctx)
);
let res = await server.get("/");
expect(await res.text()).toEqual("A_lazy_B");
expect(called).toEqual(1);
// Lazy middlewares should only be initialized ones
res = await server.get("/");
expect(await res.text()).toEqual("A_lazy_B");
expect(called).toEqual(1);
});
@@ -0,0 +1,111 @@
import type { Middleware } from "./mod.ts";
import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx";
import { BUILD_ID } from "@fresh/build-id";
import { tracer } from "../otel.ts";
import { getBuildCache } from "../context.ts";
/**
* Fresh middleware to serve static files from the `static/` directory.
* ```ts
* // Enable Fresh static file serving
* app.use(staticFiles());
* ```
*/
export function staticFiles<T>(): Middleware<T> {
return async function freshServeStaticFiles(ctx) {
const { req, url, config } = ctx;
const buildCache = getBuildCache(ctx);
if (buildCache === null) return await ctx.next();
let pathname = decodeURIComponent(url.pathname);
if (config.basePath) {
pathname = pathname !== config.basePath
? pathname.slice(config.basePath.length)
: "/";
}
// Fast path bail out
const startTime = performance.now() + performance.timeOrigin;
const file = await buildCache.readFile(pathname);
if (pathname === "/" || file === null) {
// Optimization: Prevent long responses for favicon.ico requests
if (pathname === "/favicon.ico") {
return new Response(null, { status: 404 });
}
return await ctx.next();
}
if (req.method !== "GET" && req.method !== "HEAD") {
file.close();
return new Response("Method Not Allowed", { status: 405 });
}
const span = tracer.startSpan("static file", {
attributes: { "fresh.span_type": "static_file" },
startTime,
});
try {
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;
file.close();
span.setAttribute("fresh.cache", "invalid_bust_key");
span.setAttribute("fresh.cache_key", cacheKey);
return new Response(null, {
status: 307,
headers: {
location,
},
});
}
const etag = file.hash;
const headers = new Headers({
"Content-Type": file.contentType,
vary: "If-None-Match",
});
const ifNoneMatch = req.headers.get("If-None-Match");
if (
ifNoneMatch !== null &&
(ifNoneMatch === etag || ifNoneMatch === `W/"${etag}"`)
) {
file.close();
span.setAttribute("fresh.cache", "not_modified");
return new Response(null, { status: 304, headers });
} else if (etag !== null) {
headers.set("Etag", `W/"${etag}"`);
}
if (
ctx.config.mode !== "development" &&
(BUILD_ID === cacheKey ||
url.pathname.startsWith(
`${ctx.config.basePath}/_fresh/js/${BUILD_ID}/`,
))
) {
span.setAttribute("fresh.cache", "immutable");
headers.append("Cache-Control", "public, max-age=31536000, immutable");
} else {
span.setAttribute("fresh.cache", "no_cache");
headers.append(
"Cache-Control",
"no-cache, no-store, max-age=0, must-revalidate",
);
}
headers.set("Content-Length", String(file.size));
if (req.method === "HEAD") {
file.close();
return new Response(null, { status: 200, headers });
}
return new Response(file.readable, { headers });
} finally {
span.end();
}
};
}
@@ -0,0 +1,227 @@
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 "@fresh/build-id";
import type { Command } from "../commands.ts";
import type { ServerIslandRegistry } from "../context.ts";
import { getContentType } from "../dev/dev_build_cache.ts";
class MockBuildCache implements BuildCache {
root = "";
buildId = "MockId";
files = new Map<string, StaticFile>();
islandRegistry: ServerIslandRegistry = new Map();
clientEntry = "";
features = { errorOverlay: false };
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,
contentType: getContentType(normalized),
close: () => {},
});
}
}
// deno-lint-ignore no-explicit-any
getFsRoutes(): Command<any>[] {
return [];
}
// deno-lint-ignore require-await
async readFile(pathname: string): Promise<StaticFile | null> {
return this.files.get(pathname) ?? 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 cacheUrl = `/foo.css?${ASSET_CACHE_BUST_KEY}=${BUILD_ID}`;
let res = await server.get(cacheUrl);
await res.body?.cancel();
expect(res.headers.get("Etag")).toEqual('W/"123"');
let headers = new Headers();
headers.append("If-None-Match", "123");
res = await server.get(cacheUrl, { headers });
await res.body?.cancel();
expect(res.status).toEqual(304);
headers = new Headers();
headers.append("If-None-Match", 'W/"123"');
res = await server.get(cacheUrl, { headers });
await res.body?.cancel();
expect(res.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: {
root: "",
basePath: "",
mode: "development",
},
},
);
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",
);
});
Deno.test("static files - enables caching in production", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{
buildCache,
config: {
root: "",
basePath: "",
mode: "production",
},
},
);
const res = await server.get(`/foo.css?${ASSET_CACHE_BUST_KEY}=${BUILD_ID}`);
await res.body?.cancel();
expect(res.status).toEqual(200);
expect(res.headers.get("Cache-Control")).toEqual(
"public, max-age=31536000, immutable",
);
});
Deno.test("static files - decoded pathname", async () => {
const buildCache = new MockBuildCache({
"C#.svg": { content: "body {}", hash: null },
"西安市.png": { content: "body {}", hash: null },
"인천.avif": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache },
);
for (
const path of [
"C%23.svg",
"%E8%A5%BF%E5%AE%89%E5%B8%82.png",
"%EC%9D%B8%EC%B2%9C.avif",
]
) {
const res = await server.get("/" + path);
await res.body?.cancel();
expect(res.status).toEqual(200);
}
});
Deno.test("static files - fallthrough", async () => {
const buildCache = new MockBuildCache({
"foo.css": { content: "body {}", hash: null },
});
const server = serveMiddleware(
staticFiles(),
{ buildCache, next: () => Promise.resolve(new Response("it works")) },
);
let res = await server.get("foo.css");
let text = await res.text();
expect(text).toEqual("body {}");
res = await server.get("/");
text = await res.text();
expect(text).toEqual("it works");
});
@@ -0,0 +1,29 @@
import type { Middleware } 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",
): Middleware<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();
};
}
@@ -0,0 +1,53 @@
// 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(middleware, {
next: async () => new Response("ok"),
});
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(middleware, {
next: async () => new Response("ok"),
});
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");
});