diff --git a/src/server/compose.ts b/src/server/compose.ts index ea14af2a..dee8c307 100644 --- a/src/server/compose.ts +++ b/src/server/compose.ts @@ -2,10 +2,8 @@ import { SEP } from "./deps.ts"; import { ErrorHandler, FinalHandler, RouteResult } from "./router.ts"; import { BaseRoute, - MiddlewareHandlerContext, + FreshContext, MiddlewareRoute, - RouterState, - ServeHandlerInfo, UnknownRenderFunction, } from "./types.ts"; @@ -56,20 +54,20 @@ export function selectSharedRoutes( */ export function composeMiddlewares( middlewares: MiddlewareRoute[], - errorHandler: ErrorHandler, + errorHandler: ErrorHandler, paramsAndRoute: ( url: string, - ) => RouteResult, + ) => RouteResult, renderNotFound: UnknownRenderFunction, - basePath: string, ) { return ( req: Request, - connInfo: ServeHandlerInfo, - inner: FinalHandler, + ctx: FreshContext, + inner: FinalHandler, ) => { const handlers: (() => Response | Promise)[] = []; const paramsAndRouteResult = paramsAndRoute(req.url); + ctx.params = paramsAndRouteResult.params; // identify middlewares to apply, if any. // middlewares should be already sorted from deepest to shallow layer @@ -78,73 +76,49 @@ export function composeMiddlewares( middlewares, ); - let state: Record = {}; - const middlewareCtx: MiddlewareHandlerContext = { - next() { - const handler = handlers.shift()!; - try { - // As the `handler` can be either sync or async, depending on the user's code, - // the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`, - // doesn't guarantee that all possible errors will be captured. - // `Promise.resolve` accept the value that should be returned to the promise - // chain, however, if that value is produced by the external function call, - // the possible `Error`, will *not* be caught by any `.catch()` attached to that chain. - // Because of that, we need to make sure that the produced value is pushed - // through the pipeline only if function was called successfully, and handle - // the error case manually, by returning the `Error` as rejected promise. - return Promise.resolve(handler()); - } catch (e) { - if (e instanceof Deno.errors.NotFound) { - return renderNotFound(req, paramsAndRouteResult.params, ctx); - } - return Promise.reject(e); + if (paramsAndRouteResult.route) { + ctx.route = paramsAndRouteResult.route.originalPattern; + } + + ctx.next = () => { + const handler = handlers.shift()!; + try { + // As the `handler` can be either sync or async, depending on the user's code, + // the current shape of our wrapper, that is `() => handler(req, middlewareCtx)`, + // doesn't guarantee that all possible errors will be captured. + // `Promise.resolve` accept the value that should be returned to the promise + // chain, however, if that value is produced by the external function call, + // the possible `Error`, will *not* be caught by any `.catch()` attached to that chain. + // Because of that, we need to make sure that the produced value is pushed + // through the pipeline only if function was called successfully, and handle + // the error case manually, by returning the `Error` as rejected promise. + return Promise.resolve(handler()); + } catch (e) { + if (e instanceof Deno.errors.NotFound) { + return renderNotFound(req, ctx); } - }, - ...connInfo, - get state() { - return state; - }, - set state(v) { - state = v; - }, - destination: "route", - params: paramsAndRouteResult.params, - renderNotFound: async () => { - return await renderNotFound(req, paramsAndRouteResult.params, ctx); - }, - isPartial: paramsAndRouteResult.isPartial, - basePath, + return Promise.reject(e); + } }; for (const { module } of mws) { if (module.handler instanceof Array) { for (const handler of module.handler) { - handlers.push(() => handler(req, middlewareCtx)); + handlers.push(() => handler(req, ctx)); } } else { const handler = module.handler; - handlers.push(() => handler(req, middlewareCtx)); + handlers.push(() => handler(req, ctx)); } } - const ctx = { - ...connInfo, - get state() { - return state; - }, - set state(v) { - state = v; - }, - isPartial: paramsAndRouteResult.isPartial, - }; const { destination, handler } = inner( req, ctx, - paramsAndRouteResult.params, paramsAndRouteResult.route, ); handlers.push(handler); - middlewareCtx.destination = destination; - return middlewareCtx.next().catch((e) => errorHandler(req, ctx, e)); + ctx.destination = destination; + return ctx.next().catch((e) => errorHandler(req, ctx, e)); }; } diff --git a/src/server/context.ts b/src/server/context.ts index e558efb0..d96fa398 100644 --- a/src/server/context.ts +++ b/src/server/context.ts @@ -1,6 +1,6 @@ import { contentType, extname, SEP, STATUS_CODE } from "./deps.ts"; import * as router from "./router.ts"; -import { FreshConfig, Manifest, UnknownHandlerContext } from "./mod.ts"; +import { FreshConfig, FreshContext, Manifest } from "./mod.ts"; import { ALIVE_URL, DEV_CLIENT_URL, @@ -18,7 +18,6 @@ import { RenderFunction, RenderOptions, Route, - RouterState, ServeHandlerInfo, UnknownPage, UnknownRenderFunction, @@ -44,12 +43,17 @@ import { extractRoutes, FsExtractResult } from "./fs_extract.ts"; import { loadAotSnapshot } from "../build/aot_snapshot.ts"; import { ErrorOverlay } from "./error_overlay.tsx"; import { withBase } from "./router.ts"; +import { PARTIAL_SEARCH_PARAM } from "../constants.ts"; const DEFAULT_CONN_INFO: ServeHandlerInfo = { localAddr: { transport: "tcp", hostname: "localhost", port: 8080 }, remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 }, }; +// deno-lint-ignore no-explicit-any +const NOOP_COMPONENT = () => null as any; +const NOOP_NEXT = () => Promise.resolve(new Response(null, { status: 500 })); + /** * @deprecated Use {@linkcode FromManifestConfig} instead */ @@ -154,20 +158,17 @@ export class ServerContext { this.#plugins, this.#renderFn, this.#maybeBuildSnapshot(), - basePath, ); const handlers = this.#handlers(renderNotFound); - const inner = router.router(handlers); + const inner = router.router(handlers); const withMiddlewares = composeMiddlewares( this.#extractResult.middlewares, handlers.errorHandler, - router.getParamsAndRoute(handlers), + router.getParamsAndRoute(handlers), renderNotFound, - basePath, ); const trailingSlashEnabled = this.#state.config.router?.trailingSlash; const isDev = this.#dev; - const bundleAssetRoute = this.#bundleAssetRoute(); if (this.#dev) { this.#revision = Date.now(); @@ -215,9 +216,8 @@ export class ServerContext { const bundlePath = (url.pathname.endsWith(".map")) ? "fresh_dev_client.js.map" : "fresh_dev_client.js"; - return bundleAssetRoute(req, { ...connInfo, isPartial: false }, { - path: bundlePath, - }); + + return _self.#bundleAssetRoute(bundlePath); } } @@ -254,7 +254,28 @@ export class ServerContext { return Response.redirect(to, 302); } - return await withMiddlewares(req, connInfo, inner); + const ctx: FreshContext = { + url, + params: {}, + basePath: _self.#state.config.basePath, + localAddr: connInfo.localAddr, + remoteAddr: connInfo.remoteAddr, + state: {}, + isPartial: url.searchParams.has(PARTIAL_SEARCH_PARAM), + destination: "route", + error: undefined, + Component: NOOP_COMPONENT, + next: NOOP_NEXT, + render: NOOP_NEXT, + renderNotFound: async (data) => { + ctx.data = data; + return await renderNotFound(req, ctx); + }, + route: "", + data: undefined, + }; + + return await withMiddlewares(req, ctx, inner); }; } @@ -287,16 +308,16 @@ export class ServerContext { #handlers( renderNotFound: UnknownRenderFunction, ): { - internalRoutes: router.Routes; - staticRoutes: router.Routes; - routes: router.Routes; + internalRoutes: router.Routes; + staticRoutes: router.Routes; + routes: router.Routes; - otherHandler: router.Handler; - errorHandler: router.ErrorHandler; + otherHandler: router.Handler; + errorHandler: router.ErrorHandler; } { - const internalRoutes: router.Routes = {}; - const staticRoutes: router.Routes = {}; - const routes: router.Routes = {}; + const internalRoutes: router.Routes = {}; + const staticRoutes: router.Routes = {}; + const routes: router.Routes = {}; const assetRoute = withBase( `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}/:path*`, @@ -305,7 +326,7 @@ export class ServerContext { internalRoutes[assetRoute] = { baseRoute: toBaseRoute(assetRoute), methods: { - default: this.#bundleAssetRoute(), + default: (_req, ctx) => this.#bundleAssetRoute(ctx.params.path), }, }; @@ -352,9 +373,7 @@ export class ServerContext { if (this.#dev) imports.push(this.#state.config.basePath + DEV_CLIENT_URL); return ( req: Request, - params: Record, - // deno-lint-ignore no-explicit-any - ctx?: any, + ctx: FreshContext, error?: unknown, codeFrame?: string, ) => { @@ -367,14 +386,11 @@ export class ServerContext { this.#extractResult.layouts, ); + ctx.error = error; + ctx.data = data; const resp = await internalRender({ request: req, - context: { - ...ctx, - async renderNotFound() { - return await renderNotFound(req, params, ctx, data, error); - }, - }, + context: ctx, route, plugins: this.#plugins, app: this.#extractResult.app, @@ -382,13 +398,7 @@ export class ServerContext { imports, dependenciesFn, renderFn: this.#renderFn, - url: new URL(req.url), - params, - data, - state: ctx?.state, - error, codeFrame, - basePath: this.#state.config.basePath, }); if (resp instanceof Response) { @@ -416,16 +426,10 @@ export class ServerContext { routes[route.pattern] = { baseRoute: route.baseRoute, methods: { - default: (req, ctx, params) => - (route.handler as Handler)(req, { - ...ctx, - params, - render: createRender(req, params, ctx), - async renderNotFound(data: Data) { - return await renderNotFound(req, params, ctx, data); - }, - basePath: this.#state.config.basePath, - }), + default: (req, ctx) => { + ctx.render = createRender(req, ctx); + return (route.handler as Handler)(req, ctx); + }, }, }; } else { @@ -437,40 +441,27 @@ export class ServerContext { routes[route.pattern].methods[method as router.KnownMethod] = ( req, ctx, - params, - ) => - handler(req, { - ...ctx, - params, - render: createRender(req, params, ctx), - async renderNotFound(data: Data) { - return await renderNotFound(req, params, ctx, data); - }, - basePath: this.#state.config.basePath, - }); + ) => { + ctx.render = createRender(req, ctx); + return handler(req, ctx); + }; } } } - const otherHandler: router.Handler = ( - req, - ctx, - ) => - this.#extractResult.notFound.handler( - req, - { - ...ctx, - render() { - return renderNotFound(req, {}, ctx); - }, - }, - ); + const otherHandler: router.Handler = (req, ctx) => { + ctx.render = (data) => { + ctx.data = data; + return renderNotFound(req, ctx); + }; + return this.#extractResult.notFound.handler(req, ctx); + }; const errorHandlerRender = genRender( this.#extractResult.error, STATUS_CODE.InternalServerError, ); - const errorHandler: router.ErrorHandler = async ( + const errorHandler: router.ErrorHandler = async ( req, ctx, error, @@ -490,14 +481,9 @@ export class ServerContext { } console.error(error); - return this.#extractResult.error.handler( - req, - { - ...ctx, - error, - render: errorHandlerRender(req, {}, ctx, error, codeFrame), - }, - ); + ctx.error = error; + ctx.render = errorHandlerRender(req, ctx, error, codeFrame); + return this.#extractResult.error.handler(req, ctx); }; if (this.#dev) { @@ -520,8 +506,7 @@ export class ServerContext { csp: false, url: req.url, name: "error overlay route", - handler: (_req: Request, ctx: UnknownHandlerContext) => - ctx.render(), + handler: (_req: Request, ctx: FreshContext) => ctx.render(), baseRoute, pattern: baseRoute, }, @@ -531,16 +516,7 @@ export class ServerContext { imports: [], dependenciesFn: () => [], renderFn: this.#renderFn, - url: new URL(req.url), - params: {}, - data: undefined, - state: { - ...ctx?.state, - error: null, - }, - error: null, codeFrame: undefined, - basePath: this.#state.config.basePath, }); if (resp instanceof Response) { @@ -602,31 +578,25 @@ export class ServerContext { }; } - /** - * Returns a router that contains all Fresh routes. Should be mounted at - * constants.INTERNAL_PREFIX - */ - #bundleAssetRoute = (): router.MatchHandler => { - return async (_req, _ctx, params) => { - const snapshot = await this.buildSnapshot(); - const contents = await snapshot.read(params.path); - if (!contents) return new Response(null, { status: 404 }); + async #bundleAssetRoute(filePath: string) { + const snapshot = await this.buildSnapshot(); + const contents = await snapshot.read(filePath); + if (!contents) return new Response(null, { status: 404 }); - const headers: Record = { - "Cache-Control": this.#dev - ? "no-cache, no-store, max-age=0, must-revalidate" - : "public, max-age=604800, immutable", - }; - - const type = contentType(extname(params.path)); - if (type) headers["Content-Type"] = type; - - return new Response(contents, { - status: 200, - headers, - }); + const headers: Record = { + "Cache-Control": this.#dev + ? "no-cache, no-store, max-age=0, must-revalidate" + : "public, max-age=604800, immutable", }; - }; + + const type = contentType(extname(filePath)); + if (type) headers["Content-Type"] = type; + + return new Response(contents, { + status: 200, + headers, + }); + } } const createRenderNotFound = ( @@ -635,17 +605,13 @@ const createRenderNotFound = ( plugins: Plugin>[], renderFunction: RenderFunction, buildSnapshot: BuildSnapshot | null, - basePath: string, -) => { +): UnknownRenderFunction => { const dependenciesFn = (path: string) => { const snapshot = buildSnapshot; return snapshot?.dependencies(path) ?? []; }; - return async ( - ...args: Parameters - ) => { - const [req, params, ctx, data, error] = args; + return async (req, ctx) => { const notFound = extractResult.notFound; if (!notFound.component) { return sendResponse(["Not found.", undefined], { @@ -672,12 +638,6 @@ const createRenderNotFound = ( imports, dependenciesFn, renderFn: renderFunction, - url: new URL(req.url), - params, - data, - state: ctx?.state, - error, - basePath, }); if (resp instanceof Response) { diff --git a/src/server/defines.ts b/src/server/defines.ts index 46929dcc..b01940e5 100644 --- a/src/server/defines.ts +++ b/src/server/defines.ts @@ -1,12 +1,5 @@ import { ComponentChildren } from "preact"; -import { - AppContext, - AsyncLayout, - AsyncRoute, - FreshConfig, - LayoutContext, - RouteContext, -} from "./types.ts"; +import { AsyncLayout, AsyncRoute, FreshConfig, RouteContext } from "./types.ts"; import { checkAsyncComponent } from "./render.ts"; export function defineConfig(config: FreshConfig): FreshConfig { @@ -32,7 +25,7 @@ export function defineRoute< export function defineLayout( fn: ( req: Request, - ctx: LayoutContext, + ctx: RouteContext, ) => ComponentChildren | Response | Promise, ): AsyncLayout { // deno-lint-ignore no-explicit-any @@ -45,7 +38,7 @@ export function defineLayout( export function defineApp( fn: ( req: Request, - ctx: AppContext, + ctx: RouteContext, ) => ComponentChildren | Response | Promise, ): AsyncLayout { // deno-lint-ignore no-explicit-any diff --git a/src/server/mod.ts b/src/server/mod.ts index 9e837c0a..d0fcb3d3 100644 --- a/src/server/mod.ts +++ b/src/server/mod.ts @@ -28,6 +28,7 @@ export type { ErrorHandlerContext, ErrorPageProps, FreshConfig, + FreshContext, FreshOptions, Handler, HandlerContext, diff --git a/src/server/render.ts b/src/server/render.ts index c4f574f1..6cd8956f 100644 --- a/src/server/render.ts +++ b/src/server/render.ts @@ -4,13 +4,13 @@ import { AsyncLayout, AsyncRoute, ErrorPage, + FreshContext, LayoutRoute, Plugin, PluginRenderFunctionResult, PluginRenderResult, RenderFunction, Route, - RouteContext, UnknownPage, } from "./types.ts"; import { NONE, UNSAFE_INLINE } from "../runtime/csp.ts"; @@ -28,23 +28,16 @@ export const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => { export interface RenderOptions { request: Request; - // deno-lint-ignore no-explicit-any - context: any; + context: FreshContext; route: Route | UnknownPage | ErrorPage; plugins: Plugin[]; app: AppModule; layouts: LayoutRoute[]; imports: string[]; dependenciesFn: (path: string) => string[]; - url: URL; - params: Record; renderFn: RenderFunction; - data?: Data; - state?: Record; - error?: unknown; codeFrame?: string; lang?: string; - basePath: string; } export type InnerRenderFunction = () => string; @@ -148,15 +141,17 @@ export async function render( layouts = []; } + const { params, data, state, error, url, basePath } = opts.context; + const props: Record = { - params: opts.params, - url: opts.url, + params, + url, route: opts.route.pattern, - data: opts.data, - state: opts.state, + data, + state, }; - if (opts.error) { - props.error = opts.error; + if (error) { + props.error = error; } if (opts.codeFrame) { props.codeFrame = opts.codeFrame; @@ -174,22 +169,12 @@ export async function render( const ctx = new RenderContext( crypto.randomUUID(), - opts.url, + url, opts.route.pattern, opts.lang ?? "en", ); - const context: RouteContext = { - localAddr: opts.context.localAddr, - remoteAddr: opts.context.remoteAddr, - renderNotFound: opts.context.renderNotFound, - url: opts.url, - route: opts.route.pattern, - params: opts.params as Record, - state: opts.state ?? {}, - data: opts.data, - isPartial: opts.context.isPartial, - }; + const context = opts.context; // Prepare render order // deno-lint-ignore no-explicit-any @@ -253,16 +238,16 @@ export async function render( // data. const renderState = new RenderState( { - url: opts.url, + url, route: opts.route.pattern, - data: opts.data, - state: opts.state, - params: opts.params, - basePath: opts.basePath, + data, + state, + params, + basePath, }, componentStack, csp, - opts.error, + error, ); let bodyHtml: string | null = null; @@ -370,20 +355,20 @@ export async function render( }); // Append error overlay - const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, opts.basePath); - if (opts.error !== undefined && opts.url.pathname !== devErrorUrl) { + const devErrorUrl = withBase(DEV_ERROR_OVERLAY_URL, basePath); + if (error !== undefined && url.pathname !== devErrorUrl) { const url = new URL(devErrorUrl, "https://localhost/"); - if (opts.error instanceof Error) { - let message = opts.error.message; + if (error instanceof Error) { + let message = error.message; const idx = message.indexOf("\n"); if (idx > -1) message = message.slice(0, idx); url.searchParams.append("message", message); - if (opts.error.stack) { - const stack = colors.stripAnsiCode(opts.error.stack); + if (error.stack) { + const stack = colors.stripAnsiCode(error.stack); url.searchParams.append("stack", stack); } } else { - url.searchParams.append("message", String(opts.error)); + url.searchParams.append("message", String(error)); } if (opts.codeFrame) { const codeFrame = colors.stripAnsiCode(opts.codeFrame); diff --git a/src/server/router.ts b/src/server/router.ts index b66020e4..81394c48 100644 --- a/src/server/router.ts +++ b/src/server/router.ts @@ -1,72 +1,74 @@ import { PARTIAL_SEARCH_PARAM } from "../constants.ts"; -import { BaseRoute, ErrorHandlerContext, ServeHandlerInfo } from "./types.ts"; +import { + BaseRoute, + ErrorHandlerContext, + FreshContext, + ServeHandlerInfo, +} from "./types.ts"; import { isIdentifierChar, isIdentifierStart } from "./init_safe_deps.ts"; type HandlerContext = T & ServeHandlerInfo & { isPartial: boolean; }; -export type Handler = ( +export type Handler> = ( req: Request, - ctx: HandlerContext, + ctx: FreshContext, ) => Response | Promise; -export type FinalHandler = ( +export type FinalHandler = ( req: Request, - ctx: HandlerContext, - params: Record, - route?: InternalRoute, + ctx: FreshContext, + route?: InternalRoute, ) => { destination: DestinationKind; handler: () => Response | Promise; }; -export type ErrorHandler = ( +export type ErrorHandler> = ( req: Request, - ctx: HandlerContext, + ctx: FreshContext, err: unknown, ) => Response | Promise; -type UnknownMethodHandler = ( +type UnknownMethodHandler = ( req: Request, - ctx: HandlerContext, + ctx: FreshContext, knownMethods: KnownMethod[], ) => Response | Promise; -export type MatchHandler = ( +export type MatchHandler = ( req: Request, - ctx: HandlerContext, - match: Record, + ctx: FreshContext, ) => Response | Promise; -// deno-lint-ignore ban-types -export interface Routes { +export interface Routes { [key: string]: { baseRoute: BaseRoute; methods: { - [K in KnownMethod | "default"]?: MatchHandler; + [K in KnownMethod | "default"]?: MatchHandler; }; }; } export type DestinationKind = "internal" | "static" | "route" | "notFound"; -// deno-lint-ignore ban-types -export type InternalRoute = { +export type InternalRoute = { baseRoute: BaseRoute; + originalPattern: string; pattern: RegExp | string; - methods: { [K in KnownMethod]?: MatchHandler }; - default?: MatchHandler; + methods: { [K in KnownMethod]?: MatchHandler }; + default?: MatchHandler; destination: DestinationKind; }; -export interface RouterOptions { - internalRoutes: Routes; - staticRoutes: Routes; - routes: Routes; - otherHandler: Handler; - errorHandler: ErrorHandler; - unknownMethodHandler?: UnknownMethodHandler; +export interface RouterOptions { + internalRoutes: Routes; + staticRoutes: Routes; + routes: Routes; + otherHandler: Handler; + errorHandler: ErrorHandler; + unknownMethodHandler?: UnknownMethodHandler; } export type KnownMethod = typeof knownMethods[number]; @@ -214,9 +216,9 @@ export function patternToRegExp(input: string): RegExp { export const IS_PATTERN = /[*:{}+?()]/; -function processRoutes( - processedRoutes: Array | null>, - routes: Routes, +function processRoutes( + processedRoutes: Array, + routes: Routes, destination: DestinationKind, ) { for (const [path, def] of Object.entries(routes)) { @@ -224,9 +226,10 @@ function processRoutes( ? path : patternToRegExp(path); - const entry: InternalRoute = { + const entry: InternalRoute = { baseRoute: def.baseRoute, pattern, + originalPattern: path, methods: {}, default: undefined, destination, @@ -244,27 +247,27 @@ function processRoutes( } } -export interface RouteResult { - route: InternalRoute | undefined; +export interface RouteResult { + route: InternalRoute | undefined; params: Record; isPartial: boolean; } -export function getParamsAndRoute( +export function getParamsAndRoute( { internalRoutes, staticRoutes, routes, - }: RouterOptions, + }: RouterOptions, ): ( url: string, -) => RouteResult { - const processedRoutes: Array | null> = []; +) => RouteResult { + const processedRoutes: Array = []; processRoutes(processedRoutes, internalRoutes, "internal"); processRoutes(processedRoutes, staticRoutes, "static"); processRoutes(processedRoutes, routes, "route"); - const statics = new Map>(); + const statics = new Map(); return (url: string) => { const urlObject = new URL(url); @@ -323,15 +326,15 @@ export function getParamsAndRoute( }; } -export function router( +export function router( { otherHandler, unknownMethodHandler, - }: RouterOptions, -): FinalHandler { + }: RouterOptions, +): FinalHandler { unknownMethodHandler ??= defaultUnknownMethodHandler; - return (req, ctx, groups, route) => { + return (req, ctx, route) => { if (route) { // If not overridden, HEAD requests should be handled as GET requests but without the body. if (req.method === "HEAD" && !route.methods["HEAD"]) { @@ -342,7 +345,7 @@ export function router( if (req.method === method) { return { destination: route.destination, - handler: () => handler(req, ctx, groups), + handler: () => handler(req, ctx), }; } } @@ -350,7 +353,7 @@ export function router( if (route.default) { return { destination: route.destination, - handler: () => route.default!(req, ctx, groups), + handler: () => route.default!(req, ctx), }; } else { return { diff --git a/src/server/types.ts b/src/server/types.ts index d7c53b4c..fbbbbf2f 100644 --- a/src/server/types.ts +++ b/src/server/types.ts @@ -22,17 +22,6 @@ export interface DenoConfig { } // --- APPLICATION CONFIGURATION --- - -/** - * @deprecated Use {@linkcode FreshConfig} instead - */ -export type StartOptions = FreshConfig; - -/** - * @deprecated Use {@linkcode FreshConfig} interface instead. - */ -export type FreshOptions = FreshConfig; - export interface FreshConfig { build?: { /** @@ -201,22 +190,46 @@ export interface StaticFile { etag: string; } +export interface FreshContext< + State = Record, + // deno-lint-ignore no-explicit-any + Data = any, + NotFoundData = Data, +> { + /** @types deprecated */ + localAddr?: Deno.NetAddr; + remoteAddr: Deno.NetAddr; + url: URL; + basePath: string; + route: string; + destination: router.DestinationKind; + params: Record; + isPartial: boolean; + state: State; + /** @deprecated Pass values to state instead */ + data: Data; + error?: unknown; + + // These properties may be different + renderNotFound: (data?: NotFoundData) => Response | Promise; + render: ( + data?: Data, + options?: RenderOptions, + ) => Response | Promise; + Component: () => VNode; + next: () => Promise; +} /** * Context passed to async route components. */ // deno-lint-ignore no-explicit-any -export type RouteContext> = { - /** @types deprecated */ - localAddr?: Deno.NetAddr; - remoteAddr: Deno.NetAddr; - renderNotFound: (data?: T) => Response | Promise; - url: URL; - route: string; - params: Record; - state: S; - data: T; - isPartial: boolean; -}; +export type RouteContext> = Omit< + FreshContext< + S, + T + >, + "next" | "render" +>; export interface RouteConfig { /** @@ -265,26 +278,10 @@ export type ServeHandler = ( info: ServeHandlerInfo, ) => Response | Promise; -export interface HandlerContext< - Data = unknown, - State = Record, - NotFoundData = Data, -> extends ServeHandlerInfo { - params: Record; - basePath: string; - render: ( - data?: Data, - options?: RenderOptions, - ) => Response | Promise; - renderNotFound: (data?: NotFoundData) => Response | Promise; - state: State; - isPartial: boolean; -} - // deno-lint-ignore no-explicit-any export type Handler> = ( req: Request, - ctx: HandlerContext, + ctx: FreshContext, ) => Response | Promise; // deno-lint-ignore no-explicit-any @@ -292,11 +289,6 @@ export type Handlers> = { [K in router.KnownMethod]?: Handler; }; -/** - * @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead. - */ -export type MultiHandler = Handlers; - export interface RouteModule { default?: PageComponent; // deno-lint-ignore no-explicit-any @@ -307,7 +299,7 @@ export interface RouteModule { // deno-lint-ignore no-explicit-any export type AsyncRoute> = ( req: Request, - ctx: RouteContext, + ctx: FreshContext, ) => Promise; // deno-lint-ignore no-explicit-any export type PageComponent> = @@ -329,10 +321,6 @@ export interface Route { inheritLayouts: boolean; } -export interface RouterState { - state: Record; -} - // --- APP --- // deno-lint-ignore no-explicit-any @@ -342,18 +330,6 @@ export interface AppModule { default: ComponentType | AsyncLayout; } -// deno-lint-ignore no-explicit-any -export type AppContext> = - & RouteContext - & { - Component: () => VNode; - }; -// deno-lint-ignore no-explicit-any -export type LayoutContext> = AppContext< - T, - S ->; - // deno-lint-ignore no-explicit-any export interface LayoutProps> extends PageProps { @@ -362,7 +338,7 @@ export interface LayoutProps> // deno-lint-ignore no-explicit-any export type AsyncLayout> = ( req: Request, - ctx: LayoutContext, + ctx: FreshContext, ) => Promise; export interface LayoutConfig { @@ -413,15 +389,9 @@ export interface UnknownPageProps> { state: S; } -export interface UnknownHandlerContext> - extends ServeHandlerInfo { - render: () => Response | Promise; - state: State; -} - export type UnknownHandler = ( req: Request, - ctx: UnknownHandlerContext, + ctx: FreshContext, ) => Response | Promise; export interface UnknownPageModule { @@ -444,11 +414,7 @@ export interface UnknownPage { export type UnknownRenderFunction = ( req: Request, - params: Record, - // deno-lint-ignore no-explicit-any - ctx?: any, - data?: unknown, - error?: unknown, + ctx: FreshContext, ) => Promise; // --- ERROR PAGE --- @@ -468,19 +434,12 @@ export interface ErrorPageProps { codeFrame?: string; } -export interface ErrorHandlerContext> - extends ServeHandlerInfo { - error: unknown; - render: () => Response | Promise; - state: State; -} - // Nominal/Branded type. Ensures that the string has the expected format export type BaseRoute = string & { readonly __brand: unique symbol }; export type ErrorHandler = ( req: Request, - ctx: ErrorHandlerContext, + ctx: FreshContext, ) => Response | Promise; export interface ErrorPageModule { @@ -502,18 +461,6 @@ export interface ErrorPage { } // --- MIDDLEWARES --- - -export interface MiddlewareHandlerContext> - extends ServeHandlerInfo { - next: () => Promise; - renderNotFound: (state?: State) => Response | Promise; - state: State; - destination: router.DestinationKind; - params: Record; - isPartial: boolean; - basePath: string; -} - export interface MiddlewareRoute { baseRoute: BaseRoute; module: Middleware; @@ -521,7 +468,7 @@ export interface MiddlewareRoute { export type MiddlewareHandler> = ( req: Request, - ctx: MiddlewareHandlerContext, + ctx: FreshContext, ) => Response | Promise; // deno-lint-ignore no-explicit-any @@ -688,3 +635,66 @@ export interface PluginIslands { baseLocation: string; paths: string[]; } + +// --- Deprecated types --- + +/** + * @deprecated This type was a short-lived alternative to `Handlers`. Please use `Handlers` instead. + */ +export type MultiHandler = Handlers; + +/** + * @deprecated Use {@linkcode FreshConfig} instead + */ +export type StartOptions = FreshConfig; + +/** + * @deprecated Use {@linkcode FreshConfig} interface instead. + */ +export type FreshOptions = FreshConfig; + +/** + * @deprecated Use {@linkcode FreshContext} interface instead + */ +export type HandlerContext< + Data = unknown, + State = Record, + NotFoundData = Data, +> = FreshContext; + +/** + * @deprecated Use {@linkcode FreshContext} interface instead + */ +// deno-lint-ignore no-explicit-any +export type AppContext> = FreshContext< + S, + T +>; + +/** + * @deprecated Use {@linkcode FreshContext} interface instead + */ +// deno-lint-ignore no-explicit-any +export type LayoutContext> = FreshContext< + S, + T +>; + +/** + * @deprecated Use {@linkcode FreshContext} interface instead + */ +export type UnknownHandlerContext> = + FreshContext; + +/** + * @deprecated Use {@linkcode FreshContext} interface instead + */ +export type ErrorHandlerContext> = FreshContext< + State +>; + +/** + * @deprecated Use {@linkcode FreshContext} interface instead + */ +export type MiddlewareHandlerContext> = + FreshContext; diff --git a/tests/dev_command_test.ts b/tests/dev_command_test.ts index c0aca3e2..640e87ac 100644 --- a/tests/dev_command_test.ts +++ b/tests/dev_command_test.ts @@ -36,17 +36,14 @@ Deno.test("dev_command config: shows codeframe", async () => { ); }); -Deno.test({ - name: "dev_command legacy", - async fn() { - await withPageName( - "./tests/fixture_dev_legacy/main.ts", - async (page, address) => { - await page.goto(`${address}`); - await waitForStyle(page, "h1", "color", "rgb(220, 38, 38)"); - }, - ); - }, +Deno.test("dev_command legacy", async () => { + await withPageName( + "./tests/fixture_dev_legacy/main.ts", + async (page, address) => { + await page.goto(`${address}`); + await waitForStyle(page, "h1", "color", "rgb(220, 38, 38)"); + }, + ); }); Deno.test("dev_command legacy: shows codeframe", async () => { diff --git a/tests/fixture/fresh.gen.ts b/tests/fixture/fresh.gen.ts index 86a53b23..37001680 100644 --- a/tests/fixture/fresh.gen.ts +++ b/tests/fixture/fresh.gen.ts @@ -79,22 +79,22 @@ import * as $static from "./routes/static.tsx"; import * as $status_overwrite from "./routes/status_overwrite.tsx"; import * as $umlaut_äöüß from "./routes/umlaut-äöüß.tsx"; import * as $wildcard from "./routes/wildcard.tsx"; -import * as $$Counter from "./islands/Counter.tsx"; -import * as $$FormIsland from "./islands/FormIsland.tsx"; -import * as $$Greeter from "./islands/Greeter.tsx"; -import * as $$HookIsland from "./islands/HookIsland.tsx"; -import * as $$MultipleCounters from "./islands/MultipleCounters.tsx"; -import * as $$ReturningNull from "./islands/ReturningNull.tsx"; -import * as $$RootFragment from "./islands/RootFragment.tsx"; -import * as $$RootFragmentWithConditionalFirst from "./islands/RootFragmentWithConditionalFirst.tsx"; -import * as $$StringEventIsland from "./islands/StringEventIsland.tsx"; -import * as $$Test from "./islands/Test.tsx"; -import * as $$folder_Counter from "./islands/folder/Counter.tsx"; -import * as $$folder_subfolder_Counter from "./islands/folder/subfolder/Counter.tsx"; -import * as $$kebab_case_counter_test from "./islands/kebab-case-counter-test.tsx"; -import * as $$route_groups_islands_islands_Counter from "./routes/route-groups-islands/(_islands)/Counter.tsx"; -import * as $$route_groups_islands_islands_invalid from "./routes/route-groups-islands/(_islands)/invalid.tsx"; -import { Manifest } from "$fresh/server.ts"; +import * as $Counter from "./islands/Counter.tsx"; +import * as $FormIsland from "./islands/FormIsland.tsx"; +import * as $Greeter from "./islands/Greeter.tsx"; +import * as $HookIsland from "./islands/HookIsland.tsx"; +import * as $MultipleCounters from "./islands/MultipleCounters.tsx"; +import * as $ReturningNull from "./islands/ReturningNull.tsx"; +import * as $RootFragment from "./islands/RootFragment.tsx"; +import * as $RootFragmentWithConditionalFirst from "./islands/RootFragmentWithConditionalFirst.tsx"; +import * as $StringEventIsland from "./islands/StringEventIsland.tsx"; +import * as $Test from "./islands/Test.tsx"; +import * as $folder_Counter from "./islands/folder/Counter.tsx"; +import * as $folder_subfolder_Counter from "./islands/folder/subfolder/Counter.tsx"; +import * as $kebab_case_counter_test from "./islands/kebab-case-counter-test.tsx"; +import * as $route_groups_islands_islands_Counter from "./routes/route-groups-islands/(_islands)/Counter.tsx"; +import * as $route_groups_islands_islands_invalid from "./routes/route-groups-islands/(_islands)/invalid.tsx"; +import { type Manifest } from "$fresh/server.ts"; const manifest = { routes: { @@ -195,28 +195,24 @@ const manifest = { "./routes/wildcard.tsx": $wildcard, }, islands: { - "./islands/Counter.tsx": $$Counter, - "./islands/FormIsland.tsx": $$FormIsland, - "./islands/Greeter.tsx": $$Greeter, - "./islands/HookIsland.tsx": $$HookIsland, - "./islands/MultipleCounters.tsx": { - CounterOne: $$MultipleCounters.CounterOne, - CounterTwo: $$MultipleCounters.CounterTwo, - default: $$MultipleCounters.default, - }, - "./islands/ReturningNull.tsx": $$ReturningNull, - "./islands/RootFragment.tsx": $$RootFragment, + "./islands/Counter.tsx": $Counter, + "./islands/FormIsland.tsx": $FormIsland, + "./islands/Greeter.tsx": $Greeter, + "./islands/HookIsland.tsx": $HookIsland, + "./islands/MultipleCounters.tsx": $MultipleCounters, + "./islands/ReturningNull.tsx": $ReturningNull, + "./islands/RootFragment.tsx": $RootFragment, "./islands/RootFragmentWithConditionalFirst.tsx": - $$RootFragmentWithConditionalFirst, - "./islands/StringEventIsland.tsx": $$StringEventIsland, - "./islands/Test.tsx": $$Test, - "./islands/folder/Counter.tsx": $$folder_Counter, - "./islands/folder/subfolder/Counter.tsx": $$folder_subfolder_Counter, - "./islands/kebab-case-counter-test.tsx": $$kebab_case_counter_test, + $RootFragmentWithConditionalFirst, + "./islands/StringEventIsland.tsx": $StringEventIsland, + "./islands/Test.tsx": $Test, + "./islands/folder/Counter.tsx": $folder_Counter, + "./islands/folder/subfolder/Counter.tsx": $folder_subfolder_Counter, + "./islands/kebab-case-counter-test.tsx": $kebab_case_counter_test, "./routes/route-groups-islands/(_islands)/Counter.tsx": - $$route_groups_islands_islands_Counter, + $route_groups_islands_islands_Counter, "./routes/route-groups-islands/(_islands)/invalid.tsx": - $$route_groups_islands_islands_invalid, + $route_groups_islands_islands_invalid, }, baseUrl: import.meta.url, } satisfies Manifest; diff --git a/tests/fixture/routes/404-from-middleware/_middleware.ts b/tests/fixture/routes/404-from-middleware/_middleware.ts index f1d28ab2..fa06e05b 100644 --- a/tests/fixture/routes/404-from-middleware/_middleware.ts +++ b/tests/fixture/routes/404-from-middleware/_middleware.ts @@ -1,8 +1,5 @@ -import { MiddlewareHandlerContext } from "$fresh/server.ts"; +import { FreshContext } from "$fresh/server.ts"; -export async function handler( - _req: Request, - ctx: MiddlewareHandlerContext, -) { +export async function handler(_req: Request, ctx: FreshContext) { return await ctx.renderNotFound(); } diff --git a/tests/fixture/routes/_middleware.ts b/tests/fixture/routes/_middleware.ts index 99632588..4c5a0749 100644 --- a/tests/fixture/routes/_middleware.ts +++ b/tests/fixture/routes/_middleware.ts @@ -1,10 +1,7 @@ -import { MiddlewareHandler, MiddlewareHandlerContext } from "$fresh/server.ts"; +import { FreshContext, MiddlewareHandler } from "$fresh/server.ts"; // cors middleware -async function corsHandler( - _req: Request, - ctx: MiddlewareHandlerContext, -) { +async function corsHandler(_req: Request, ctx: FreshContext) { if (_req.method == "OPTIONS") { return new Response(null, { status: 204, @@ -29,10 +26,7 @@ async function corsHandler( } // log middleware -async function logHandler( - _req: Request, - ctx: MiddlewareHandlerContext, -) { +async function logHandler(_req: Request, ctx: FreshContext) { const since = new Date(); const resp = await ctx.next(); const latency = (+new Date()) - (+since); @@ -40,20 +34,14 @@ async function logHandler( return resp; } -async function rootHandler( - _req: Request, - ctx: MiddlewareHandlerContext, -) { +async function rootHandler(_req: Request, ctx: FreshContext) { ctx.state.root = "root_mw"; const resp = await ctx.next(); resp.headers.set("server", "fresh test server"); return resp; } -async function kindHandler( - _req: Request, - ctx: MiddlewareHandlerContext, -) { +async function kindHandler(_req: Request, ctx: FreshContext) { const resp = await ctx.next(); resp.headers.set("destination", ctx.destination); return resp; diff --git a/tests/fixture_server_components/fresh.gen.ts b/tests/fixture_server_components/fresh.gen.ts index d59ad262..2386d97f 100644 --- a/tests/fixture_server_components/fresh.gen.ts +++ b/tests/fixture_server_components/fresh.gen.ts @@ -9,8 +9,8 @@ import * as $index from "./routes/index.tsx"; import * as $island from "./routes/island.tsx"; import * as $response from "./routes/response.tsx"; import * as $twind from "./routes/twind.tsx"; -import * as $$FooIsland from "./islands/FooIsland.tsx"; -import { Manifest } from "$fresh/server.ts"; +import * as $FooIsland from "./islands/FooIsland.tsx"; +import { type Manifest } from "$fresh/server.ts"; const manifest = { routes: { @@ -23,7 +23,7 @@ const manifest = { "./routes/twind.tsx": $twind, }, islands: { - "./islands/FooIsland.tsx": $$FooIsland, + "./islands/FooIsland.tsx": $FooIsland, }, baseUrl: import.meta.url, } satisfies Manifest; diff --git a/tests/main_test.ts b/tests/main_test.ts index 7bd5aa89..e33e20a4 100644 --- a/tests/main_test.ts +++ b/tests/main_test.ts @@ -671,17 +671,14 @@ Deno.test({ }, }); -Deno.test({ - name: "/not_found", - fn: async () => { - const resp = await handler(new Request("https://fresh.deno.dev/not_found")); - assert(resp); - assertEquals(resp.status, 404); - const body = await resp.text(); - assertStringIncludes(body, "404 not found: /not_found"); - assertStringIncludes(body, "Hello Dino"); - assertStringIncludes(body, "State root: root_mw"); - }, +Deno.test("/not_found", async () => { + const resp = await handler(new Request("https://fresh.deno.dev/not_found")); + assert(resp); + assertEquals(resp.status, 404); + const body = await resp.text(); + assertStringIncludes(body, "404 not found: /not_found"); + assertStringIncludes(body, "Hello Dino"); + assertStringIncludes(body, "State root: root_mw"); }); Deno.test("middleware destination", async (t) => { diff --git a/tests/server_components_test.ts b/tests/server_components_test.ts index df2eae8a..a451fe5a 100644 --- a/tests/server_components_test.ts +++ b/tests/server_components_test.ts @@ -58,47 +58,48 @@ Deno.test({ }, }); -Deno.test({ - name: "passes context to server component", +Deno.test("passes context to server component", async () => { + await withFresh( + "./tests/fixture_server_components/main.ts", + async (address) => { + const res = await fetch(`${address}/context/foo`); + const json = await res.json(); - async fn() { - await withFresh( - "./tests/fixture_server_components/main.ts", - async (address) => { - const res = await fetch(`${address}/context/foo`); - const json = await res.json(); + assertEquals(typeof json.localAddr, "object"); + assertEquals(typeof json.remoteAddr, "object"); + json.localAddr.port = 8000; + json.remoteAddr.port = 8000; - assertEquals(typeof json.localAddr, "object"); - assertEquals(typeof json.remoteAddr, "object"); - json.localAddr.port = 8000; - json.remoteAddr.port = 8000; - - assertEquals( - json, - { - localAddr: { - hostname: "localhost", - port: 8000, - transport: "tcp", - }, - remoteAddr: { - hostname: "127.0.0.1", - port: 8000, - transport: "tcp", - }, - renderNotFound: "AsyncFunction", - url: `${address}/context/foo`, - route: "/context/:id", - params: { - id: "foo", - }, - state: {}, - isPartial: false, + assertEquals( + json, + { + localAddr: { + hostname: "localhost", + port: 8000, + transport: "tcp", }, - ); - }, - ); - }, + remoteAddr: { + hostname: "127.0.0.1", + port: 8000, + transport: "tcp", + }, + render: "AsyncFunction", + Component: "Function", + destination: "route", + next: "Function", + basePath: "", + renderNotFound: "AsyncFunction", + url: `${address}/context/foo`, + route: "/context/:id", + params: { + id: "foo", + }, + state: {}, + isPartial: false, + }, + ); + }, + ); }); Deno.test({ diff --git a/www/routes/_middleware.ts b/www/routes/_middleware.ts index ed047227..1bca5fca 100644 --- a/www/routes/_middleware.ts +++ b/www/routes/_middleware.ts @@ -1,4 +1,4 @@ -import { MiddlewareHandlerContext } from "$fresh/server.ts"; +import { type FreshContext } from "$fresh/server.ts"; import type { Event } from "$ga4"; import { GA4Report, isDocument, isServerError } from "$ga4"; @@ -8,7 +8,7 @@ let showedMissingEnvWarning = false; function ga4( request: Request, - conn: MiddlewareHandlerContext, + conn: FreshContext, response: Response, _start: number, error?: unknown, @@ -80,7 +80,7 @@ function ga4( export async function handler( req: Request, - ctx: MiddlewareHandlerContext, + ctx: FreshContext, ): Promise { let err; let res: Response;