import { type CloudflareWorkerdRuntime, enhance, type Get, MiddlewareOrder, params, type UniversalHandler, type UniversalMiddleware, url, } from "@universal-middleware/core"; export const middlewares = { contextSync(_, context) { return { ...context, something: { a: 1, c: 3, }, }; }, updateHeaders() { return async (response: Response) => { response.headers.set("x-test-value", "universal-middleware"); response.headers.delete("x-should-be-removed"); await new Promise((resolve) => setTimeout(resolve, 1000)); return response; }; }, async contextAsync(_request, context, runtime) { await new Promise((resolve) => setTimeout(resolve, 100)); return { ...context, something: { a: (context.something as Record)?.a, }, somethingElse: { b: 2, }, waitUntil: typeof (runtime as CloudflareWorkerdRuntime)?.ctx?.waitUntil, }; }, guard(request) { if (url(request).pathname.endsWith("/guarded")) { return new Response("Unauthorized", { status: 401, statusText: "Unauthorized", }); } }, throwEarly(request) { if (url(request).pathname.endsWith("/throw-early") || url(request).pathname.endsWith("/throw-early-and-late")) { throw new Error("universal-middleware throw early test"); } }, throwLate(request) { // @ts-expect-error return (): Response => { if (url(request).pathname.endsWith("/throw-late") || url(request).pathname.endsWith("/throw-early-and-late")) { throw new Error("universal-middleware throw late test"); } }; }, } satisfies Record; export const enhancedMiddlewares = { contextSync: enhance(middlewares.contextSync, { order: MiddlewareOrder.CUSTOM_PRE_PROCESSING, }), updateHeaders: enhance(middlewares.updateHeaders, { order: MiddlewareOrder.CUSTOM_PRE_PROCESSING, }), contextAsync: enhance(middlewares.contextAsync, { order: MiddlewareOrder.CUSTOM_PRE_PROCESSING, }), guard: enhance(middlewares.guard, { order: MiddlewareOrder.AUTHORIZATION, }), throwEarly: enhance(middlewares.throwEarly, { order: MiddlewareOrder.AUTHORIZATION, }), throwLate: enhance(middlewares.throwLate, { order: MiddlewareOrder.RESPONSE_TRANSFORM, }), }; export const handlerRaw: UniversalHandler = (_request, context) => { context.long = "a".repeat(1024); return new Response(JSON.stringify(context, null, 2), { headers: { "x-should-be-removed": "universal-middleware", "content-type": "application/json; charset=utf-8", }, }); }; export const handler: Get<[], UniversalHandler> = () => enhance(handlerRaw, { path: "/", method: "GET", context: { staticContext: "staticContext" }, }); interface RouteParamOption { route?: string; } export const routeParamHandler = ((options?) => enhance( (request, _context, runtime) => { const myParams = params(request, runtime, options?.route); if (myParams === null || !myParams.name) { // Provide a useful error message to the user throw new Error( "A route parameter named `:name` is required. " + "You can set your server route as `/user/:name`, or use the `route` option of this middleware " + "to achieve the same purpose.", ); } // ... return new Response(`User name is: ${myParams.name}`); }, { path: options?.route ?? "/user/:name", method: "GET", }, )) satisfies (options?: RouteParamOption) => UniversalHandler; export const guarded: Get<[], UniversalHandler> = () => enhance( () => { return new Response("Oups, you should not be able to see this"); }, { path: "/guarded", method: ["GET", "POST"], }, ); export const throwEarlyHandler: Get<[], UniversalHandler> = () => enhance( () => { return new Response("Oups, you should not be able to see this"); }, { path: "/throw-early", method: ["GET", "POST"], }, ); export const throwLateHandler: Get<[], UniversalHandler> = () => enhance( () => { return new Response("Oups, you should not be able to see this"); }, { path: "/throw-late", method: ["GET", "POST"], }, ); export const throwEarlyAndLateHandler: Get<[], UniversalHandler> = () => enhance( () => { return new Response("Oups, you should not be able to see this"); }, { path: "/throw-early-and-late", method: ["GET", "POST"], }, ); let streamCancelled = false; export const streamCancelHandler: Get<[], UniversalHandler> = () => enhance( () => { streamCancelled = false; const stream = new ReadableStream({ pull(controller) { if (streamCancelled) { controller.close(); return; } controller.enqueue(new TextEncoder().encode("data\n")); return new Promise((resolve) => setTimeout(resolve, 100)); }, cancel() { streamCancelled = true; }, }); return new Response(stream, { headers: { "content-type": "application/octet-stream", "transfer-encoding": "chunked", "cache-control": "no-transform", }, }); }, { path: "/stream-cancel", method: "GET", }, ); export const streamCancelStatusHandler: Get<[], UniversalHandler> = () => enhance( () => { return new Response(JSON.stringify({ cancelled: streamCancelled }), { headers: { "content-type": "application/json", }, }); }, { path: "/stream-cancel-status", method: "GET", }, ); // Wraps the body in `name(…)`. The length changes, so `content-length` goes const wrapBody = (name: string | ((context: { user?: string }) => string)) => ((_request, context) => async (response: Response) => { const headers = new Headers(response.headers); headers.delete("content-length"); const label = typeof name === "string" ? name : name(context); return new Response(`${label}(${await response.text()})`, { status: response.status, headers }); }) satisfies UniversalMiddleware<{ user?: string }>; /** * The middlewares of `apply()`'s rule tests, under `/rule/`. `refuses` answers 401 without an `x-auth` header: * - `/rule/answered`: `late(early(refused))`, `side` skipped, `late` sees the context `user` returned * - `/rule/runs`: also `always(…)`, whose late Response is ignored, and `until` skipped despite its positive order * - `/rule/handled` (with `x-auth`): the handler doesn't see what the positive-order `post` returned * - `/rule/late-response` (with `x-auth`): a positive-order middleware returning a Response gets a 500 */ export const ruleMiddlewares = [ enhance( wrapBody((context) => `late:${context.user}`), { name: "late", path: "/rule/**", order: 100 }, ), enhance(wrapBody("until"), { name: "until", path: "/rule/runs", order: 200, runs: "until-response" }), enhance(() => new Response("ignored"), { name: "alwaysLate", path: "/rule/runs", order: 100, runs: "always" }), enhance(wrapBody("always"), { name: "always", path: "/rule/runs", order: -100, runs: "always" }), enhance(wrapBody("side"), { name: "side", path: "/rule/**", order: MiddlewareOrder.CUSTOM_PRE_PROCESSING }), enhance( (request: Request) => (request.headers.has("x-auth") ? undefined : new Response("refused", { status: 401 })), { name: "refuses", path: "/rule/**", order: MiddlewareOrder.AUTHORIZATION }, ), enhance((_request: Request, context: Universal.Context) => ({ ...context, user: "ann" }), { name: "user", path: "/rule/**", order: MiddlewareOrder.AUTHENTICATION, }), enhance(wrapBody("early"), { name: "early", path: "/rule/**", order: MiddlewareOrder.RATE_LIMITING }), enhance((_request: Request, context: Universal.Context) => ({ ...context, post: "yes" }), { name: "post", path: "/rule/handled", order: 100, }), enhance(() => new Response("not modified"), { name: "conditional", path: "/rule/late-response", order: MiddlewareOrder.CONDITIONAL_REQUESTS, }), ]; export const ruleHandler: Get<[], UniversalHandler> = () => enhance( (_request: Request, context: Universal.Context) => { const { user, post } = context as { user?: string; post?: string }; return new Response(`handler:${user}:${post}`); }, { name: "ruleHandler", path: "/rule/**", method: "GET" }, ); /** * A Response whose body never ends, like Server-Sent Events: only `cancel()` releases it. * `cancelled` resolves when it is cancelled. */ export function endlessResponse() { const { promise: cancelled, resolve } = Promise.withResolvers(); const state = { cancelled: false }; const response = new Response( new ReadableStream({ pull: () => Promise.withResolvers().promise, cancel() { state.cancelled = true; resolve(); }, }), { headers: { "content-type": "text/event-stream", "x-kept": "yes" } }, ); return { state, response, cancelled }; } /** Two middlewares that read the request body, and what each read */ export function bodyReaders() { const seen: string[] = []; const reader = (name: string) => enhance( async (request: Request) => { seen.push(await request.text()); }, { name }, ); return { middlewares: [reader("firstReader"), reader("secondReader")], seen }; } /** Responses with immutable headers, as a route may return them (`Response.redirect()`, a proxied `fetch()`) */ export const immutableResponses = [ { name: "Response.redirect()", response: async () => Response.redirect("http://localhost/target", 302), status: 302, body: "", }, { name: "a fetch() response", response: () => fetch("data:text/plain,fetched"), status: 200, body: "fetched" }, ]; /** A response function that changes the headers of the Response it gets, `location` included */ export const changesHeaders = () => (response: Response) => { response.headers.set("x-changed", "yes"); response.headers.set("location", "/changed"); response.headers.append("set-cookie", "changed=1"); return response; }; /** The headers a client gets once `changesHeaders` ran */ export const changedHeaders = { changed: "yes", location: "/changed", cookies: ["changed=1"] }; /** What a client gets: the status, the body and the headers `changesHeaders` sets */ export async function received(response: Response) { return { status: response.status, body: await response.text(), changed: response.headers.get("x-changed"), location: response.headers.get("location"), cookies: response.headers.getSetCookie(), }; }