diff --git a/init/src/init.ts b/init/src/init.ts index 95d1f4be..d6676a95 100644 --- a/init/src/init.ts +++ b/init/src/init.ts @@ -360,13 +360,11 @@ ${GRADIENT_CSS}`; // Skip this and be silent if there is a network issue. } - const MAIN_TS = `import { App, fsRoutes, staticFiles } from "fresh"; + const MAIN_TS = `import { App, fsRoutes } from "fresh"; import { define, type State } from "./utils.ts"; export const app = new App(); -app.use(staticFiles()); - // this is the same as the /api/:name route defined via a file. feel free to delete this! app.get("/api2/:name", (ctx) => { const name = ctx.params.name; diff --git a/src/app.ts b/src/app.ts index 8f2fd4ee..4836fd0b 100644 --- a/src/app.ts +++ b/src/app.ts @@ -5,18 +5,32 @@ import { trace } from "@opentelemetry/api"; import { DENO_DEPLOYMENT_ID } from "./runtime/build_id.ts"; import * as colors from "@std/fmt/colors"; import { type MiddlewareFn, runMiddlewares } from "./middlewares/mod.ts"; -import { FreshReqContext } from "./context.ts"; -import { type Method, type Router, UrlPatternRouter } from "./router.ts"; +import { Context, type ServerIslandRegistry } from "./context.ts"; +import { + mergePath, + type Method, + type Router, + UrlPatternRouter, +} from "./router.ts"; import { type FreshConfig, normalizeConfig, type ResolvedFreshConfig, } from "./config.ts"; import { type BuildCache, ProdBuildCache } from "./build_cache.ts"; -import type { ServerIslandRegistry } from "./context.ts"; import { FinishSetup, ForgotBuild } from "./finish_setup.tsx"; import { HttpError } from "./error.ts"; -import { mergePaths, pathToExportName } from "./utils.ts"; +import { pathToExportName } from "./utils.ts"; +import type { LayoutConfig, Route } from "./types.ts"; +import { + getOrCreateSegment, + newSegment, + renderRoute, + type RouteComponent, + segmentToMiddlewares, +} from "./segments.ts"; +import { isHandlerByMethod, type PageResponse } from "./handlers.ts"; +import { serveInternalStaticFiles } from "./middlewares/static_files.ts"; // TODO: Completed type clashes in older Deno versions // deno-lint-ignore no-explicit-any @@ -25,12 +39,44 @@ export const DEFAULT_CONN_INFO: any = { remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 }, }; -const DEFAULT_NOT_FOUND = () => { +/** Used to group mounted apps. Only internal */ +let INTERNAL_ID = 0; + +const DEFAULT_RENDER = (): Promise> => + // deno-lint-ignore no-explicit-any + Promise.resolve({ data: {} as any }); + +const DEFAULT_NOT_FOUND = (): Promise => { throw new HttpError(404); }; -const DEFAULT_NOT_ALLOWED_METHOD = () => { +const DEFAULT_NOT_ALLOWED_METHOD = (): Promise => { throw new HttpError(405); }; +const defaultOptionsHandler = (methods: string[]): () => Promise => { + return () => + Promise.resolve( + new Response(null, { + status: 204, + headers: { Allow: methods.join(", ") }, + }), + ); +}; +// deno-lint-ignore require-await +const DEFAULT_ERROR_HANDLER = async (ctx: Context) => { + const { error } = ctx; + + if (error instanceof HttpError) { + if (error.status >= 500) { + // deno-lint-ignore no-console + console.error(error); + } + return new Response(error.message, { status: error.status }); + } + + // deno-lint-ignore no-console + console.error(error); + return new Response("Internal server error", { status: 500 }); +}; export type ListenOptions = & Partial< @@ -117,7 +163,6 @@ async function listenOnFreePort( throw firstError; } -export let getRouter: (app: App) => Router>; // deno-lint-ignore no-explicit-any export let getIslandRegistry: (app: App) => ServerIslandRegistry; // deno-lint-ignore no-explicit-any @@ -132,9 +177,15 @@ export class App { #islandRegistry: ServerIslandRegistry = new Map(); #buildCache: BuildCache | null = null; #islandNames = new Set(); + #root = newSegment("", null); + #routeDefs: { + method: Method | "ALL"; + pattern: string; + fns: MiddlewareFn[]; + unshift: boolean; + }[] = []; static { - getRouter = (app) => app.#router; getIslandRegistry = (app) => app.#islandRegistry; getBuildCache = (app) => app.#buildCache; setBuildCache = (app, cache) => app.#buildCache = cache; @@ -175,76 +226,170 @@ export class App { return this; } - use(middleware: MiddlewareFn): this { - this.#router.addMiddleware(middleware); + use(...middleware: MiddlewareFn[]): this; + use(path: string, ...middleware: MiddlewareFn[]): this; + use( + pathOrMiddleware: string | MiddlewareFn, + ...middlewares: MiddlewareFn[] + ): this { + let path: string; + let fns: MiddlewareFn[]; + if (typeof pathOrMiddleware === "string") { + path = pathOrMiddleware; + fns = middlewares!; + } else { + path = "*"; + middlewares.unshift(pathOrMiddleware); + fns = middlewares; + } + + const segment = getOrCreateSegment(this.#root, path, false); + segment.middlewares.push(...fns); + + return this; + } + + notFound(routeOrMiddleware: Route | MiddlewareFn): this { + const route = typeof routeOrMiddleware === "function" + ? { handler: routeOrMiddleware } + : routeOrMiddleware; + ensureHandler(route); + this.#root.notFound = (ctx) => renderRoute(ctx, route); + + return this; + } + + onError( + path: string, + routeOrMiddleware: Route | MiddlewareFn, + ): this { + const segment = getOrCreateSegment(this.#root, path, true); + segment.errorRoute = typeof routeOrMiddleware === "function" + ? { handler: routeOrMiddleware } + : routeOrMiddleware; + + ensureHandler(segment.errorRoute); + + return this; + } + + appWrapper(component: RouteComponent) { + const segment = getOrCreateSegment(this.#root, "", false); + segment.app = component; + } + + layout( + path: string, + component: RouteComponent, + config?: LayoutConfig, + ): this { + const segment = getOrCreateSegment(this.#root, path, true); + segment.layout = { component, config: config ?? null }; + + return this; + } + + route(path: string, route: Route): this { + const segment = getOrCreateSegment(this.#root, path, false); + const middlewares = segmentToMiddlewares(segment); + + ensureHandler(route); + middlewares.push((ctx) => renderRoute(ctx, route)); + + const routePath = route.config?.routeOverride ?? path; + + if (typeof route.handler === "function") { + this.#addRoute("ALL", routePath, middlewares); + } else if (isHandlerByMethod(route.handler!)) { + for (const method of Object.keys(route.handler)) { + this.#addRoute(method as Method, routePath, middlewares); + } + } + return this; } get(path: string, ...middlewares: MiddlewareFn[]): this { - return this.#addRoutes("GET", path, middlewares); + this.#addMiddleware("GET", path, middlewares); + return this; } post(path: string, ...middlewares: MiddlewareFn[]): this { - return this.#addRoutes("POST", path, middlewares); + this.#addMiddleware("POST", path, middlewares); + return this; } patch(path: string, ...middlewares: MiddlewareFn[]): this { - return this.#addRoutes("PATCH", path, middlewares); + this.#addMiddleware("PATCH", path, middlewares); + return this; } put(path: string, ...middlewares: MiddlewareFn[]): this { - return this.#addRoutes("PUT", path, middlewares); + this.#addMiddleware("PUT", path, middlewares); + return this; } delete(path: string, ...middlewares: MiddlewareFn[]): this { - return this.#addRoutes("DELETE", path, middlewares); + this.#addMiddleware("DELETE", path, middlewares); + return this; } head(path: string, ...middlewares: MiddlewareFn[]): this { - return this.#addRoutes("HEAD", path, middlewares); + this.#addMiddleware("HEAD", path, middlewares); + return this; } + all(path: string, ...middlewares: MiddlewareFn[]): this { - return this.#addRoutes("ALL", path, middlewares); + this.#addMiddleware("ALL", path, middlewares); + return this; + } + + #addMiddleware( + method: Method | "ALL", + path: string, + fns: MiddlewareFn[], + unshift = false, + ) { + const segment = getOrCreateSegment(this.#root, path, false); + const result = segmentToMiddlewares(segment); + + result.push(...fns); + + const resPath = mergePath(this.config.basePath, path); + this.#addRoute(method, resPath, result, unshift); + } + + #addRoute( + method: Method | "ALL", + path: string, + fns: MiddlewareFn[], + unshift = false, + ) { + this.#routeDefs.push({ method, pattern: path, fns, unshift }); } mountApp(path: string, app: App): this { - const routes = app.#router._routes; + const segmentPath = mergePath(path, `/__${INTERNAL_ID++}/`); + const segment = getOrCreateSegment(this.#root, segmentPath, true); + const fns = segmentToMiddlewares(segment); + + const routes = app.#routeDefs; + for (let i = 0; i < routes.length; i++) { + const route = routes[i]; + + const merged = mergePath(path, route.pattern); + const mergedFns = [...fns, ...route.fns]; + this.#addRoute(route.method, merged, mergedFns, route.unshift); + } + app.#islandRegistry.forEach((value, key) => { this.#islandRegistry.set(key, value); }); - const middlewares = app.#router._middlewares; - - // Special case when user calls one of these: - // - `app.mountApp("/", otherApp)` - // - `app.mountApp("/*", otherApp)` - const isSelf = path === "/*" || path === "/"; - if (isSelf && middlewares.length > 0) { - this.#router._middlewares.push(...middlewares); - } - - for (let i = 0; i < routes.length; i++) { - const route = routes[i]; - - const merged = typeof route.path === "string" - ? mergePaths(path, route.path) - : route.path; - const combined = isSelf - ? route.handlers - : middlewares.concat(route.handlers); - this.#router.add(route.method, merged, combined); - } + app.#root.notFound = this.#root.notFound; return this; } - #addRoutes( - method: Method | "ALL", - pathname: string | URLPattern, - middlewares: MiddlewareFn[], - ): this { - const merged = typeof pathname === "string" - ? mergePaths(this.config.basePath, pathname) - : pathname; - this.#router.add(method, merged, middlewares); - return this; - } - + /** + * Create handler function for `Deno.serve` or to be used in + * testing. + */ handler(): ( request: Request, info?: Deno.ServeHandlerInfo, @@ -263,6 +408,27 @@ export class App { return missingBuildHandler; } + const staticMids: MiddlewareFn[] = []; + if (this.#root.middlewares.length > 0) { + staticMids.push(...this.#root.middlewares); + } + + staticMids.push(serveInternalStaticFiles()); + + this.#addMiddleware( + "ALL", + "*", + staticMids, + true, + ); + + for (let i = 0; i < this.#routeDefs.length; i++) { + const route = this.#routeDefs[i]; + this.#router.add(route.method, route.pattern, route.fns, route.unshift); + } + + const rootMiddlewares = this.#root.middlewares; + return async ( req: Request, conn: Deno.ServeHandlerInfo = DEFAULT_CONN_INFO, @@ -273,13 +439,32 @@ export class App { const method = req.method.toUpperCase() as Method; const matched = this.#router.match(method, url); + let { params, pattern, handlers, methodMatch } = matched; - const next = matched.patternMatch && !matched.methodMatch - ? DEFAULT_NOT_ALLOWED_METHOD - : DEFAULT_NOT_FOUND; + const span = trace.getActiveSpan(); + if (span && pattern) { + span.updateName(`${method} ${pattern}`); + span.setAttribute("http.route", pattern); + } - const { params, handlers, pattern } = matched; - const ctx = new FreshReqContext( + let next: () => Promise; + + if (pattern === null || !methodMatch) { + handlers = rootMiddlewares; + } + + if (matched.pattern !== null && !methodMatch) { + if (method === "OPTIONS") { + const allowed = this.#router.getAllowedMethods(matched.pattern); + next = defaultOptionsHandler(allowed); + } else { + next = DEFAULT_NOT_ALLOWED_METHOD; + } + } else { + next = DEFAULT_NOT_FOUND; + } + + const ctx = new Context( req, url, conn, @@ -290,19 +475,10 @@ export class App { this.#buildCache!, ); - const span = trace.getActiveSpan(); - if (span && pattern) { - span.updateName(`${method} ${pattern}`); - span.setAttribute("http.route", pattern); - } - try { - let result: unknown; - if (handlers.length === 1 && handlers[0].length === 1) { - result = await handlers[0][0](ctx); - } else { - result = await runMiddlewares(handlers, ctx); - } + if (handlers.length === 0) return await next(); + + const result = await runMiddlewares(handlers, ctx); if (!(result instanceof Response)) { throw new Error( `Expected a "Response" instance to be returned, but got: ${result}`, @@ -311,17 +487,8 @@ export class App { return result; } catch (err) { - if (err instanceof HttpError) { - if (err.status >= 500) { - // deno-lint-ignore no-console - console.error(err); - } - return new Response(err.message, { status: err.status }); - } - - // deno-lint-ignore no-console - console.error(err); - return new Response("Internal server error", { status: 500 }); + ctx.error = err; + return await DEFAULT_ERROR_HANDLER(ctx); } }; } @@ -331,7 +498,7 @@ export class App { options.onListen = createOnListen(this.config.basePath, options); } - const handler = await this.handler(); + const handler = this.handler(); if (options.port) { await Deno.serve(options, handler); return; @@ -351,3 +518,15 @@ const missingBuildHandler = async (): Promise => { : renderToString(h(ForgotBuild, null)); return new Response(html, { headers, status: 500 }); }; + +function ensureHandler(route: Route) { + if (route.handler === undefined) { + route.handler = route.component !== undefined + ? DEFAULT_RENDER + : DEFAULT_NOT_FOUND; + } else if (isHandlerByMethod(route.handler)) { + if (route.component !== undefined && !route.handler.GET) { + route.handler.GET = DEFAULT_RENDER; + } + } +} diff --git a/src/app_test.tsx b/src/app_test.tsx index 7bb10f20..f5757090 100644 --- a/src/app_test.tsx +++ b/src/app_test.tsx @@ -2,6 +2,7 @@ import { expect } from "@std/expect"; import { App, getIslandRegistry, setBuildCache } from "./app.ts"; import { FakeServer } from "./test_utils.ts"; import { ProdBuildCache } from "./build_cache.ts"; +import { HttpError } from "./error.ts"; Deno.test("App - .use()", async () => { const app = new App<{ text: string }>() @@ -35,8 +36,6 @@ Deno.test("App - .use() #2", async () => { Deno.test("App - .get()", async () => { const app = new App() - .post("/", () => new Response("ok")) - .post("/foo", () => new Response("ok")) .get("/", () => new Response("ok")) .get("/foo", () => new Response("ok")); @@ -323,11 +322,11 @@ Deno.test( "App - .mountApp() self mount, different order", async () => { const innerApp = new App<{ text: string }>() - .get("/foo", (ctx) => new Response(ctx.state.text)) .use(function B(ctx) { ctx.state.text += "B"; return ctx.next(); }) + .get("/foo", (ctx) => new Response(ctx.state.text)) .post("/foo", (ctx) => new Response(ctx.state.text)); const app = new App<{ text: string }>() @@ -392,6 +391,27 @@ Deno.test( }, ); +// https://github.com/denoland/fresh/issues/3033 +Deno.test( + "App - .mountApp() self mount with dynamic routes", + async () => { + const innerApp = new App<{ text: string }>() + .get("/", () => new Response("list authors")) + .get("/:name", (ctx) => new Response(`show: ${ctx.params.name}`)); + + const app = new App<{ text: string }>() + .mountApp("/api/authors", innerApp); + + const server = new FakeServer(app.handler()); + + let res = await server.get("/api/authors"); + expect(await res.text()).toEqual("list authors"); + + res = await server.get("/api/authors/foo"); + expect(await res.text()).toEqual("show: foo"); + }, +); + Deno.test("App - catches errors", async () => { let thrownErr: unknown | null = null; const app = new App<{ text: string }>() @@ -532,3 +552,59 @@ Deno.test("App - adding Island should convert to valid export names", () => { fn: component3, }); }); + +Deno.test("App - overwrite default 404 handler", async () => { + const app = new App() + .notFound(() => new Response("bar", { status: 404 })) + .get("/foo", () => new Response("foo")) + .get("/thrower", () => { + throw new HttpError(404); + }); + + const server = new FakeServer(app.handler()); + + let res = await server.get("/invalid"); + expect(await res.text()).toEqual("bar"); + + res = await server.get("/thrower"); + expect(await res.text()).toEqual("bar"); +}); + +Deno.test("App - uses error route", async () => { + const app = new App() + .onError("*", () => new Response("error route", { status: 200 })) + .get("/thrower", () => { + throw new HttpError(404); + }); + + const server = new FakeServer(app.handler()); + + let res = await server.get("/invalid"); + expect(await res.text()).toEqual("error route"); + + res = await server.get("/thrower"); + expect(await res.text()).toEqual("error route"); +}); + +Deno.test("App - uses notFound route on 404", async () => { + const app = new App() + .notFound(() => new Response("not found route", { status: 404 })) + .onError("*", () => new Response("error route", { status: 500 })) + .get("/thrower", () => { + throw new HttpError(404); + }) + .get("/thrower_2", () => { + throw new HttpError(500); + }); + + const server = new FakeServer(app.handler()); + + let res = await server.get("/invalid"); + expect(await res.text()).toEqual("not found route"); + + res = await server.get("/thrower"); + expect(await res.text()).toEqual("not found route"); + + res = await server.get("/thrower_2"); + expect(await res.text()).toEqual("error route"); +}); diff --git a/src/compat.ts b/src/compat.ts index f37f9c97..94fa09b0 100644 --- a/src/compat.ts +++ b/src/compat.ts @@ -1,5 +1,6 @@ import type { ComponentChildren } from "preact"; -import type { FreshContext, PageProps } from "./context.ts"; +import type { FreshContext } from "./context.ts"; +import type { PageProps } from "./render.ts"; import type { HandlerFn, RouteHandler } from "./handlers.ts"; /** diff --git a/src/compat_test.tsx b/src/compat_test.tsx index fdf0f7d6..cd3ebd42 100644 --- a/src/compat_test.tsx +++ b/src/compat_test.tsx @@ -1,4 +1,4 @@ -import type { PageProps } from "./context.ts"; +import type { PageProps } from "./render.ts"; import { assertType, type IsExact } from "@std/testing/types"; import { expect } from "@std/expect"; import { type defineApp, type defineLayout, defineRoute } from "./compat.ts"; diff --git a/src/context.ts b/src/context.ts index 0bee3ac4..243f2387 100644 --- a/src/context.ts +++ b/src/context.ts @@ -1,22 +1,26 @@ import { + type AnyComponent, type ComponentType, + Fragment, type FunctionComponent, h, isValidElement, type VNode, } from "preact"; -import { renderToString } from "preact-render-to-string"; import { SpanStatusCode } from "@opentelemetry/api"; import type { ResolvedFreshConfig } from "./config.ts"; import type { BuildCache } from "./build_cache.ts"; -import { - FreshScripts, - RenderState, - setRenderState, -} from "./runtime/server/preact_hooks.tsx"; -import { DEV_ERROR_OVERLAY_URL, PARTIAL_SEARCH_PARAM } from "./constants.ts"; -import { BUILD_ID } from "./runtime/build_id.ts"; +import { RenderState, setRenderState } from "./runtime/server/preact_hooks.tsx"; +import { PARTIAL_SEARCH_PARAM } from "./constants.ts"; import { tracer } from "./otel.ts"; +import { + type ComponentDef, + isAsyncAnyComponent, + type PageProps, + preactRender, + renderAsyncAnyComponent, + renderRouteComponent, +} from "./render.ts"; export interface Island { file: string | URL; @@ -27,24 +31,44 @@ export interface Island { export type ServerIslandRegistry = Map; +export const internals: unique symbol = Symbol("fresh_internal"); + +export interface UiTree { + app: AnyComponent> | null; + layouts: ComponentDef[]; +} + +/** + * @deprecated Use {@linkcode Context} instead. + */ +export type FreshContext = Context; + +export let getBuildCache: (ctx: Context) => BuildCache; +export let getInternals: (ctx: Context) => UiTree; + /** * The context passed to every middleware. It is unique for every request. */ -export interface FreshContext { +export class Context { + #internal: UiTree = { + app: null, + layouts: [], + }; /** Reference to the resolved Fresh configuration */ readonly config: ResolvedFreshConfig; - readonly state: State; - /** The original incoming `Request` object` */ - readonly req: Request; /** * The request url parsed into an `URL` instance. This is typically used * to apply logic based on the pathname of the incoming url or when * certain search parameters are set. */ readonly url: URL; + /** The original incoming `Request` object` */ + readonly req: Request; readonly params: Record; - readonly error: unknown; - readonly info: Deno.ServeHandlerInfo; + readonly state: State = {} as State; + data: unknown = undefined; + error: unknown | null = null; + readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo; /** * Whether the current Request is a partial request. * @@ -53,20 +77,7 @@ export interface FreshContext { * be used to determine if only ``'s need to be rendered. */ readonly isPartial: boolean; - /** - * Return a redirect response to the specified path. This is the - * preferred way to do redirects in Fresh. - * - * ```ts - * ctx.redirect("/foo/bar") // redirect user to "/foo/bar" - * - * // Disallows protocol relative URLs for improved security. This - * // redirects the user to `/evil.com` which is safe, - * // instead of redirecting to `http://evil.com`. - * ctx.redirect("//evil.com/"); - * ``` - */ - redirect(path: string, status?: number): Response; + /** * Call the next middleware. * ```ts @@ -90,25 +101,7 @@ export interface FreshContext { * return res * } */ - next(): Promise; - render(vnode: VNode, init?: ResponseInit): Response | Promise; -} - -export let getBuildCache: (ctx: FreshContext) => BuildCache; - -export class FreshReqContext - implements FreshContext, PageProps { - readonly config: ResolvedFreshConfig; - readonly url: URL; - readonly req: Request; - readonly params: Record; - readonly state: State = {} as State; - data: unknown = undefined; - error: unknown | null = null; - readonly info: Deno.ServeHandlerInfo | Deno.ServeHandlerInfo; - readonly isPartial: boolean; - - next: FreshContext["next"]; + next: () => Promise; #islandRegistry: ServerIslandRegistry; #buildCache: BuildCache; @@ -117,7 +110,9 @@ export class FreshReqContext Component!: FunctionComponent; static { - getBuildCache = (ctx) => (ctx as FreshReqContext).#buildCache; + // deno-lint-ignore no-explicit-any + getInternals = (ctx) => (ctx as Context).#internal as any; + getBuildCache = (ctx) => (ctx as Context).#buildCache; } constructor( @@ -126,7 +121,7 @@ export class FreshReqContext info: Deno.ServeHandlerInfo, params: Record, config: ResolvedFreshConfig, - next: FreshContext["next"], + next: () => Promise, islandRegistry: ServerIslandRegistry, buildCache: BuildCache, ) { @@ -141,6 +136,19 @@ export class FreshReqContext this.#buildCache = buildCache; } + /** + * Return a redirect response to the specified path. This is the + * preferred way to do redirects in Fresh. + * + * ```ts + * ctx.redirect("/foo/bar") // redirect user to "/foo/bar" + * + * // Disallows protocol relative URLs for improved security. This + * // redirects the user to `/evil.com` which is safe, + * // instead of redirecting to `http://evil.com`. + * ctx.redirect("//evil.com/"); + * ``` + */ redirect(pathOrUrl: string, status = 302): Response { let location = pathOrUrl; @@ -166,17 +174,61 @@ export class FreshReqContext }); } - render( + async render( // deno-lint-ignore no-explicit-any - vnode: VNode, + vnode: VNode | null, init: ResponseInit | undefined = {}, - ): Response | Promise { + ): Promise { if (arguments.length === 0) { throw new Error(`No arguments passed to: ctx.render()`); } else if (vnode !== null && !isValidElement(vnode)) { throw new Error(`Non-JSX element passed to: ctx.render()`); } + const defs = this.#internal.layouts; + const appDef = this.#internal.app; + const props = this as Context; + + // Compose final vnode tree + for (let i = defs.length - 1; i >= 0; i--) { + const child = vnode; + props.Component = () => child; + + const def = defs[i]; + + const result = await renderRouteComponent(this, def, () => child); + if (result instanceof Response) { + return result; + } + + vnode = result; + } + + if (isAsyncAnyComponent(appDef)) { + const child = vnode; + props.Component = () => child; + const result = await renderAsyncAnyComponent(appDef, props); + if (result instanceof Response) { + return result; + } + + vnode = result; + } else if (appDef !== null) { + const child = vnode; + vnode = h(appDef, { + Component: () => child, + config: this.config, + data: null, + error: this.error, + info: this.info, + isPartial: this.isPartial, + params: this.params, + req: this.req, + state: this.state, + url: this.url, + }); + } + const headers = init.headers !== undefined ? init.headers instanceof Headers ? init.headers @@ -198,13 +250,21 @@ export class FreshReqContext const html = tracer.startActiveSpan("render", (span) => { span.setAttribute("fresh.span_type", "render"); + const state = new RenderState( + this, + this.#islandRegistry, + this.#buildCache, + partialId, + ); + try { + setRenderState(state); + return preactRender( - vnode, + vnode ?? h(Fragment, null), this, - this.#islandRegistry, + state, this.#buildCache, - partialId, headers, ); } catch (err) { @@ -218,6 +278,9 @@ export class FreshReqContext } throw err; } finally { + state.clear(); + setRenderState(null); + span.end(); } }); @@ -225,7 +288,7 @@ export class FreshReqContext } } -Object.defineProperties(FreshReqContext.prototype, { +Object.defineProperties(Context.prototype, { config: { enumerable: true }, url: { enumerable: true }, req: { enumerable: true }, @@ -236,59 +299,3 @@ Object.defineProperties(FreshReqContext.prototype, { next: { enumerable: true }, info: { enumerable: true }, }); - -function preactRender( - vnode: VNode, - ctx: PageProps, - islandRegistry: ServerIslandRegistry, - buildCache: BuildCache, - partialId: string, - headers: Headers, -) { - const state = new RenderState(ctx, islandRegistry, buildCache, partialId); - setRenderState(state); - try { - let res = renderToString(vnode); - // We require a the full outer DOM structure so that browser put - // comment markers in the right place in the DOM. - if (!state.renderedHtmlBody) { - let scripts = ""; - if (ctx.url.pathname !== ctx.config.basePath + DEV_ERROR_OVERLAY_URL) { - scripts = renderToString(h(FreshScripts, null)); - } - res = `${res}${scripts}`; - } - if (!state.renderedHtmlHead) { - res = `${res}`; - } - if (!state.renderedHtmlTag) { - res = `${res}`; - } - - return `${res}`; - } finally { - // Add preload headers - const basePath = ctx.config.basePath; - const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`; - let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`; - state.islands.forEach((island) => { - const chunk = buildCache.getIslandChunkName(island.name); - if (chunk !== null) { - link += `, <${ - encodeURI(`${basePath}${chunk}`) - }>; rel="modulepreload"; as="script"`; - } - }); - - if (link !== "") { - headers.append("Link", link); - } - - state.clear(); - setRenderState(null); - } -} - -export type PageProps = - & Omit, "next" | "render" | "redirect"> - & { data: Data; Component: FunctionComponent }; diff --git a/src/context_test.tsx b/src/context_test.tsx index 7a413b36..d3b6bd89 100644 --- a/src/context_test.tsx +++ b/src/context_test.tsx @@ -1,5 +1,5 @@ import { expect } from "@std/expect"; -import { FreshReqContext } from "./context.ts"; +import { Context } from "./context.ts"; import { App } from "fresh"; import { asset } from "fresh/runtime"; import { FakeServer } from "./test_utils.ts"; @@ -7,23 +7,23 @@ import { BUILD_ID } from "./runtime/build_id.ts"; import { parseHtml } from "../tests/test_utils.tsx"; Deno.test("FreshReqContext.prototype.redirect", () => { - let res = FreshReqContext.prototype.redirect("/"); + let res = Context.prototype.redirect("/"); expect(res.status).toEqual(302); expect(res.headers.get("Location")).toEqual("/"); - res = FreshReqContext.prototype.redirect("//evil.com"); + res = Context.prototype.redirect("//evil.com"); expect(res.status).toEqual(302); expect(res.headers.get("Location")).toEqual("/evil.com"); - res = FreshReqContext.prototype.redirect("//evil.com/foo//bar"); + res = Context.prototype.redirect("//evil.com/foo//bar"); expect(res.status).toEqual(302); expect(res.headers.get("Location")).toEqual("/evil.com/foo/bar"); - res = FreshReqContext.prototype.redirect("https://deno.com"); + res = Context.prototype.redirect("https://deno.com"); expect(res.status).toEqual(302); expect(res.headers.get("Location")).toEqual("https://deno.com"); - res = FreshReqContext.prototype.redirect("/", 307); + res = Context.prototype.redirect("/", 307); expect(res.status).toEqual(307); }); diff --git a/src/define.ts b/src/define.ts index d560fd98..5199cc23 100644 --- a/src/define.ts +++ b/src/define.ts @@ -1,7 +1,7 @@ import type { AnyComponent } from "preact"; import type { HandlerByMethod, HandlerFn, RouteHandler } from "./handlers.ts"; import type { Middleware } from "./middlewares/mod.ts"; -import type { PageProps } from "./context.ts"; +import type { PageProps } from "./render.ts"; /** * A set of define functions that enable better type inference and code diff --git a/src/dev/builder.ts b/src/dev/builder.ts index a91c2d46..f09a842a 100644 --- a/src/dev/builder.ts +++ b/src/dev/builder.ts @@ -48,6 +48,7 @@ export class Builder implements FreshBuilder { #transformer = new FreshFileTransformer(fsAdapter); #addedInternalTransforms = false; #options: { target: string | string[] }; + #chunksReady = Promise.withResolvers(); constructor(options: BuildOptions = {}) { this.#options = { @@ -70,6 +71,11 @@ export class Builder implements FreshBuilder { .use(liveReload()) .use(devErrorOverlay()) .use(automaticWorkspaceFolders(app.config.root)) + // Wait for island chunks to be ready before attempting to serve them + .use(async (ctx) => { + await this.#chunksReady.promise; + return await ctx.next(); + }) .mountApp("/*", app); devApp.config.mode = "development"; @@ -205,6 +211,8 @@ export class Builder implements FreshBuilder { await buildCache.flush(); + this.#chunksReady.resolve(); + if (!dev) { // deno-lint-ignore no-console console.log( diff --git a/src/middlewares/cors_test.ts b/src/middlewares/cors_test.ts index ed11d80a..8eb73db2 100644 --- a/src/middlewares/cors_test.ts +++ b/src/middlewares/cors_test.ts @@ -30,16 +30,10 @@ Deno.test("CORS - Preflight default", async () => { const res = await handler(req); expect(res.status).toBe(204); - expect(res.statusText).toBe("No Content"); - 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", - ], - ); + 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 () => { diff --git a/src/middlewares/mod.ts b/src/middlewares/mod.ts index e6ae6cef..ca0b8f7a 100644 --- a/src/middlewares/mod.ts +++ b/src/middlewares/mod.ts @@ -1,4 +1,4 @@ -import type { FreshContext, FreshReqContext } from "../context.ts"; +import { type Context, getInternals } from "../context.ts"; import type { App as _App } from "../app.ts"; import type { Define as _Define } from "../define.ts"; @@ -6,14 +6,14 @@ 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 FreshContext.next|ctx.next()} inside of the function. + * 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`, Fresh will wait for the promise * to resolve before sending the response. * - * A {@linkcode FreshContext} object is passed to the middleware function. This + * 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. @@ -72,7 +72,7 @@ import type { Define as _Define } from "../define.ts"; * ``` */ export type MiddlewareFn = ( - ctx: FreshContext, + ctx: Context, ) => Response | Promise; /** @@ -82,27 +82,29 @@ export type MiddlewareFn = ( export type Middleware = MiddlewareFn | MiddlewareFn[]; export function runMiddlewares( - middlewares: MiddlewareFn[][], - ctx: FreshReqContext, + middlewares: MiddlewareFn[], + ctx: Context, ): Promise { 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; - } - }; - } + const local = fn; + const next = middlewares[i]; + fn = async () => { + const internals = getInternals(ctx); + const { app: prevApp, layouts: prevLayouts } = internals; + + ctx.next = local; + try { + return await next(ctx); + } catch (err) { + ctx.error = err; + throw err; + } finally { + internals.app = prevApp; + internals.layouts = prevLayouts; + } + }; } return fn(); } diff --git a/src/middlewares/mod_test.ts b/src/middlewares/mod_test.ts index 6176a6ff..de2f8962 100644 --- a/src/middlewares/mod_test.ts +++ b/src/middlewares/mod_test.ts @@ -24,7 +24,7 @@ Deno.test("runMiddleware", async () => { ]; const server = serveMiddleware<{ text: string }>((ctx) => - runMiddlewares([middlewares], ctx) + runMiddlewares(middlewares, ctx) ); const res = await server.get("/"); @@ -43,7 +43,7 @@ Deno.test("runMiddleware - middlewares should only be called once", async () => const server = serveMiddleware<{ count: number }>((ctx) => runMiddlewares( - [[A, (ctx) => new Response(String(ctx.state.count))]], + [A, (ctx) => new Response(String(ctx.state.count))], ctx, ) ); @@ -75,8 +75,11 @@ Deno.test("runMiddleware - runs multiple stacks", async () => { ctx.state.text = ""; return runMiddlewares( [ - [A, B], - [C, D, (ctx) => new Response(String(ctx.state.text))], + A, + B, + C, + D, + (ctx) => new Response(String(ctx.state.text)), ], ctx, ); @@ -122,7 +125,7 @@ Deno.test("runMiddleware - throws errors", async () => { ]; const server = serveMiddleware<{ text: string }>((ctx) => - runMiddlewares([middlewares], ctx) + runMiddlewares(middlewares, ctx) ); try { diff --git a/src/middlewares/static_files.ts b/src/middlewares/static_files.ts index 93dc9135..9a2d7812 100644 --- a/src/middlewares/static_files.ts +++ b/src/middlewares/static_files.ts @@ -3,8 +3,8 @@ import { contentType as getContentType } from "@std/media-types/content-type"; import type { MiddlewareFn } from "./mod.ts"; import { ASSET_CACHE_BUST_KEY } from "../runtime/shared_internal.tsx"; import { BUILD_ID } from "../runtime/build_id.ts"; +import { tracer } from "../otel.ts"; import { getBuildCache } from "../context.ts"; -import { trace, tracer } from "../otel.ts"; /** * Fresh middleware to enable file-system based routing. @@ -12,11 +12,20 @@ import { trace, tracer } from "../otel.ts"; * // Enable Fresh static file serving * app.use(staticFiles()); * ``` + * @deprecated This is not needed anymore. Remove this middleware. */ export function staticFiles(): MiddlewareFn { return async function freshStaticFiles(ctx) { + return await ctx.next(); + }; +} + +export function serveInternalStaticFiles(): MiddlewareFn { + 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) { @@ -33,7 +42,7 @@ export function staticFiles(): MiddlewareFn { if (pathname === "/favicon.ico") { return new Response(null, { status: 404 }); } - return ctx.next(); + return await ctx.next(); } if (req.method !== "GET" && req.method !== "HEAD") { @@ -41,12 +50,6 @@ export function staticFiles(): MiddlewareFn { return new Response("Method Not Allowed", { status: 405 }); } - const parentSpan = trace.getActiveSpan(); - if (parentSpan) { - parentSpan.updateName(`${req.method} /*`); - parentSpan.setAttribute("http.route", "/*"); - } - const span = tracer.startSpan("static file", { attributes: { "fresh.span_type": "static_file" }, startTime, diff --git a/src/middlewares/static_files_test.ts b/src/middlewares/static_files_test.ts index d5219e01..5e6b045d 100644 --- a/src/middlewares/static_files_test.ts +++ b/src/middlewares/static_files_test.ts @@ -1,4 +1,4 @@ -import { staticFiles } from "./static_files.ts"; +import { serveInternalStaticFiles } from "./static_files.ts"; import { serveMiddleware } from "../test_utils.ts"; import type { BuildCache, StaticFile } from "../build_cache.ts"; import { expect } from "@std/expect"; @@ -39,7 +39,7 @@ Deno.test("static files - 200", async () => { "foo.css": { content: "body {}", hash: null }, }); const server = serveMiddleware( - staticFiles(), + serveInternalStaticFiles(), { buildCache }, ); @@ -59,7 +59,7 @@ Deno.test("static files - HEAD 200", async () => { "foo.css": { content: "body {}", hash: null }, }); const server = serveMiddleware( - staticFiles(), + serveInternalStaticFiles(), { buildCache }, ); @@ -76,7 +76,7 @@ Deno.test("static files - etag", async () => { "foo.css": { content: "body {}", hash: "123" }, }); const server = serveMiddleware( - staticFiles(), + serveInternalStaticFiles(), { buildCache }, ); @@ -101,7 +101,7 @@ Deno.test("static files - etag", async () => { Deno.test("static files - 404 on missing favicon.ico", async () => { const buildCache = new MockBuildCache({}); const server = serveMiddleware( - staticFiles(), + serveInternalStaticFiles(), { buildCache }, ); const res = await server.get("favicon.ico"); @@ -114,7 +114,7 @@ Deno.test("static files - 405 on wrong HTTP method", async () => { "foo.css": { content: "body {}", hash: null }, }); const server = serveMiddleware( - staticFiles(), + serveInternalStaticFiles(), { buildCache }, ); @@ -131,7 +131,7 @@ Deno.test("static files - disables caching in development", async () => { "foo.css": { content: "body {}", hash: null }, }); const server = serveMiddleware( - staticFiles(), + serveInternalStaticFiles(), { buildCache, config: { @@ -159,7 +159,7 @@ Deno.test("static files - enables caching in production", async () => { "foo.css": { content: "body {}", hash: null }, }); const server = serveMiddleware( - staticFiles(), + serveInternalStaticFiles(), { buildCache, config: { @@ -189,7 +189,7 @@ Deno.test("static files - decoded pathname", async () => { "인천.avif": { content: "body {}", hash: null }, }); const server = serveMiddleware( - staticFiles(), + serveInternalStaticFiles(), { buildCache }, ); diff --git a/src/mod.ts b/src/mod.ts index 91a1d51b..bd9d35b7 100644 --- a/src/mod.ts +++ b/src/mod.ts @@ -14,7 +14,8 @@ export type { Middleware, MiddlewareFn } from "./middlewares/mod.ts"; export { staticFiles } from "./middlewares/static_files.ts"; export { cors, type CORSOptions } from "./middlewares/cors.ts"; export type { FreshConfig, ResolvedFreshConfig } from "./config.ts"; -export type { FreshContext, Island, PageProps } from "./context.ts"; +export type { Context, FreshContext, Island } from "./context.ts"; export { createDefine, type Define } from "./define.ts"; export type { Method } from "./router.ts"; export { HttpError } from "./error.ts"; +export type { PageProps } from "./render.ts"; diff --git a/src/otel.ts b/src/otel.ts index 6c0d7a23..ce78ac80 100644 --- a/src/otel.ts +++ b/src/otel.ts @@ -1,7 +1,18 @@ -import { trace } from "@opentelemetry/api"; +import { type Span, SpanStatusCode, trace } from "@opentelemetry/api"; import denoJson from "../deno.json" with { type: "json" }; export const CURRENT_FRESH_VERSION = denoJson.version; export const tracer = trace.getTracer("fresh", CURRENT_FRESH_VERSION); export { trace }; + +export function recordSpanError(span: Span, err: unknown) { + if (err instanceof Error) { + span.recordException(err); + } else { + span.setStatus({ + code: SpanStatusCode.ERROR, + message: String(err), + }); + } +} diff --git a/src/plugins/fs_routes/mod.ts b/src/plugins/fs_routes/mod.ts index 5ead0050..81f82585 100644 --- a/src/plugins/fs_routes/mod.ts +++ b/src/plugins/fs_routes/mod.ts @@ -5,16 +5,12 @@ import * as path from "@std/path"; import type { RouteConfig } from "../../types.ts"; import type { RouteHandler } from "../../handlers.ts"; import type { MiddlewareFn } from "../../middlewares/mod.ts"; -import { - type AsyncAnyComponent, - renderMiddleware, -} from "./render_middleware.ts"; -import { type Method, pathToPattern } from "../../router.ts"; +import type { AsyncAnyComponent } from "../../render.ts"; +import { pathToPattern } from "../../router.ts"; import { type HandlerFn, isHandlerByMethod } from "../../handlers.ts"; import { type FsAdapter, fsAdapter } from "../../fs.ts"; -import { HttpError } from "../../error.ts"; import { parseRootPath } from "../../config.ts"; -import type { FreshReqContext, PageProps } from "../../context.ts"; +import type { PageProps } from "../../render.ts"; const TEST_FILE_PATTERN = /[._]test\.(?:[tj]sx?|[mc][tj]s)$/; const GROUP_REG = /(^|[/\\\\])\((_[^/\\\\]+)\)[/\\\\]/; @@ -25,7 +21,7 @@ interface InternalRoute { filePath: string; config: RouteConfig | null; handlers: - | RouteHandler[] + | MiddlewareFn[] | RouteHandler | null; component: AnyComponent> | null; @@ -165,233 +161,108 @@ export async function fsRoutes( ); routeModules.sort((a, b) => sortRoutePaths(a.path, b.path)); - - const stack: InternalRoute[] = []; - let hasApp = false; - - const specialPaths = new Set(); + const errorPaths = new Set(); for (let i = 0; i < routeModules.length; i++) { const routeMod = routeModules[i]; const normalized = routeMod.path; - let j = stack.length - 1; - while ( - j >= 0 && stack[j].base !== "" && - !routeMod.path.startsWith(stack[j].base + "/") - ) { - j--; - stack.pop(); - } - if (normalized.endsWith("/_app")) { - hasApp = true; - stack.push(routeMod); + const component = routeMod.component; + if (component !== null) { + app.appWrapper(component); + } continue; } else if (normalized.endsWith("/_middleware")) { - stack.push(routeMod); + if (routeMod.handlers === null) continue; + + if (isHandlerByMethod(routeMod.handlers)) { + warnInvalidRoute( + "Middleware does not support object handlers with GET, POST, etc.", + ); + continue; + } + const pattern = pathToPattern( + normalized.slice(1, -"/_middleware".length), + { keepGroups: true }, + ); + + const handlers = (Array.isArray(routeMod.handlers) + ? routeMod.handlers + : [routeMod.handlers]) as MiddlewareFn[]; + + app.use(pattern, ...handlers); + continue; } else if (normalized.endsWith("/_layout")) { - stack.push(routeMod); + if (routeMod.handlers !== null) { + warnInvalidRoute("Layout does not support handlers"); + } + + const pattern = pathToPattern(normalized.slice(1, -"/_layout".length), { + keepGroups: true, + }); + const { component, config } = routeMod; + if (component !== null) { + app.layout(pattern, component, config ?? undefined); + } continue; } else if (normalized.endsWith("/_error")) { - stack.push(routeMod); + const pattern = pathToPattern(normalized.slice(1, -"/_error".length), { + keepGroups: true, + }); + errorPaths.add(pattern); + app.onError(pattern, { + config: routeMod.config ?? undefined, + component: routeMod.component ?? undefined, + // deno-lint-ignore no-explicit-any + handler: routeMod.handlers as any ?? undefined, + }); continue; } else if (normalized.endsWith("/_404")) { - stack.push(routeMod); + app.notFound({ + config: routeMod.config ?? undefined, + component: routeMod.component ?? undefined, + // deno-lint-ignore no-explicit-any + handler: routeMod.handlers as any ?? undefined, + }); continue; } else if (normalized.endsWith("/_500")) { - stack.push(routeMod); + const pattern = pathToPattern(normalized.slice(1, -"/_500".length), { + keepGroups: true, + }); + if (errorPaths.has(pattern)) continue; + + app.onError(pattern, { + config: routeMod.config ?? undefined, + component: routeMod.component ?? undefined, + // deno-lint-ignore no-explicit-any + handler: routeMod.handlers as any ?? undefined, + }); continue; } - // Remove any elements not matching our parent path anymore - const middlewares: MiddlewareFn[] = []; - let components: AnyComponent>[] = []; - - let skipApp = !!routeMod.config?.skipAppWrapper; - const skipLayouts = !!routeMod.config?.skipInheritedLayouts; - - for (let k = 0; k < stack.length; k++) { - const mod = stack[k]; - if (mod.path.endsWith("/_middleware")) { - if (Array.isArray(mod.handlers)) { - middlewares.push(...(mod.handlers as MiddlewareFn[])); - } else if (typeof mod.handlers === "function") { - middlewares.push(mod.handlers as MiddlewareFn); - } else if (isHandlerByMethod(mod.handlers)) { - warnInvalidRoute( - "Middleware does not support object handlers with GET, POST, etc.", - ); - } - } - - // _app template - if (skipApp && mod.path === "/_app") { - continue; - } else if (!skipApp && mod.config?.skipAppWrapper) { - skipApp = true; - if (hasApp) { - // _app component is always first - components.shift(); - } - } - - // _layouts - if (skipLayouts && mod.path.endsWith("/_layout")) { - continue; - } else if (mod.handlers !== null && mod.path.endsWith("/_layout")) { - warnInvalidRoute("Layout does not support handlers"); - } else if (!skipLayouts && mod.config?.skipInheritedLayouts) { - const first = components.length > 0 ? components[0] : null; - components = []; - - if (!skipApp && hasApp && first !== null) { - components.push(first); - } - } - - if (mod.path.endsWith("/_error") || mod.path.endsWith("/_500")) { - const handlers = mod.handlers; - const handler = handlers === null || - (isHandlerByMethod(handlers) && Object.keys(handlers).length === 0) - ? undefined - : typeof handlers === "function" - ? handlers - : ((ctx) => { - const { method } = ctx.req; - if (!Array.isArray(handlers)) { - const maybeFn = handlers[method as Method]; - if (maybeFn !== undefined) { - return maybeFn(ctx); - } - } - return ctx.next(); - }) as HandlerFn; - const errorComponents = components.slice(); - if (mod.component !== null) { - errorComponents.push(mod.component); - } - let parent = mod.path.slice(0, -"_error".length); - parent = parent + "*"; - - // Add error route as its own route - if (!specialPaths.has(mod.path)) { - specialPaths.add(mod.path); - app.all( - parent, - errorMiddleware(errorComponents, handler), - ); - } - middlewares.push(errorMiddleware(errorComponents, handler)); - continue; - } - - if (mod.path.endsWith("/_404")) { - const handlers = mod.handlers; - const handler = handlers === null || - (isHandlerByMethod(handlers) && Object.keys(handlers).length === 0) - ? undefined - : typeof handlers === "function" - ? handlers - : ((ctx) => { - const { method } = ctx.req; - if (!Array.isArray(handlers)) { - const maybeFn = handlers[method as Method]; - if (maybeFn !== undefined) { - return maybeFn(ctx); - } - } - return ctx.next(); - }) as HandlerFn; - const notFoundComponents = components.slice(); - if (mod.component !== null) { - notFoundComponents.push(mod.component); - } - app.use(notFoundMiddleware(notFoundComponents, handler)); - continue; - } - - if (mod.component !== null) { - components.push(mod.component); + let pattern = pathToPattern(normalized.slice(1), { keepGroups: true }); + if (normalized.endsWith("/index")) { + if (!pattern.endsWith("/")) { + pattern += "/"; } } - const handlers = routeMod.handlers; - const routePath = routeMod.config?.routeOverride ?? - pathToPattern(normalized.slice(1)); + const routePattern = pathToPattern(normalized.slice(1)); - if (routeMod.component !== null) { - components.push(routeMod.component); - const missingGetHandler = isHandlerByMethod(handlers) && - !Object.keys(handlers).includes("GET"); - if (missingGetHandler) { - const combined = middlewares.concat( - renderMiddleware(components, undefined), - ); - app.get(routePath, ...combined); - } - } - - if ( - handlers === null || - (isHandlerByMethod(handlers) && Object.keys(handlers).length === 0) - ) { - const combined = middlewares.concat( - renderMiddleware(components, undefined), - ); - app.get(routePath, ...combined); - } else if (isHandlerByMethod(handlers)) { - for (const method of Object.keys(handlers) as Method[]) { - const fn = handlers[method]; - - if (fn !== undefined) { - const combined = middlewares.concat(renderMiddleware(components, fn)); - const lower = method.toLowerCase() as Lowercase; - app[lower](routePath, ...combined); - } - } - } else if (typeof handlers === "function") { - const combined = middlewares.concat( - renderMiddleware(components, handlers), - ); - app.all(routePath, ...combined); - } + app.route(pattern, { + config: { + ...routeMod.config ?? undefined, + routeOverride: routeMod.config?.routeOverride ?? routePattern, + }, + component: routeMod.component ?? undefined, + // deno-lint-ignore no-explicit-any + handler: routeMod.handlers as any ?? undefined, + }); } } -function errorMiddleware( - components: AnyComponent>[], - handler: HandlerFn | undefined, -): MiddlewareFn { - const mid = renderMiddleware(components, handler); - return async function errorMiddleware(ctx) { - try { - return await ctx.next(); - } catch (err) { - (ctx as FreshReqContext).error = err; - return mid(ctx); - } - }; -} - -function notFoundMiddleware( - components: AnyComponent>[], - handler: HandlerFn | undefined, -): MiddlewareFn { - const mid = renderMiddleware(components, handler); - return async function notFoundMiddleware(ctx) { - try { - return await ctx.next(); - } catch (err) { - if (err instanceof HttpError && err.status === 404) { - return mid(ctx); - } - throw err; - } - }; -} - function warnInvalidRoute(message: string) { // deno-lint-ignore no-console console.warn( diff --git a/src/plugins/fs_routes/mod_test.tsx b/src/plugins/fs_routes/mod_test.tsx index 291356e0..52fd6089 100644 --- a/src/plugins/fs_routes/mod_test.tsx +++ b/src/plugins/fs_routes/mod_test.tsx @@ -13,7 +13,8 @@ import { stub } from "@std/testing/mock"; import { type HandlerByMethod, type HandlerFn, page } from "../../handlers.ts"; import type { Method } from "../../router.ts"; import { parseHtml } from "../../../tests/test_utils.tsx"; -import type { FreshContext } from "fresh"; +import type { FreshContext } from "../../context.ts"; +import { HttpError } from "../../error.ts"; async function createServer( files: Record>, @@ -193,13 +194,13 @@ Deno.test("fsRoutes - middleware", async () => { Deno.test("fsRoutes - nested middlewares", async () => { const server = await createServer<{ text: string }>({ "routes/_middleware.ts": { - handler: (ctx) => { + handler: function A(ctx) { ctx.state.text = "A"; return ctx.next(); }, }, "routes/foo/_middleware.ts": { - handler: (ctx) => { + handler: function B(ctx) { ctx.state.text += "B"; return ctx.next(); }, @@ -332,18 +333,22 @@ Deno.test("fsRoutes - nested _layout", async () => { default: () => <>foo, }, "routes/foo/_layout.tsx": { - default: (ctx) => ( - <> - layout_foo_bar/ - - ), + default: function fooBar(ctx) { + return ( + <> + layout_foo_bar/ + + ); + }, }, "routes/_layout.tsx": { - default: (ctx) => ( - <> - layout/ - - ), + default: function rootLayout(ctx) { + return ( + <> + layout/ + + ); + }, }, "routes/_app.tsx": { default: (ctx) => ( @@ -806,7 +811,7 @@ Deno.test("fsRoutes - _error render component", async () => { }, "routes/foo/index.tsx": { handlers: () => { - throw new Error("ok"); + throw new Error("failing"); }, }, }); @@ -816,7 +821,8 @@ Deno.test("fsRoutes - _error render component", async () => { expect(doc.body.firstChild?.textContent).toEqual("ok"); }); -Deno.test("fsRoutes - _error render on 404", async () => { +// 404 pages go to the root error page if available +Deno.test.ignore("fsRoutes - _error render on 404", async () => { // deno-lint-ignore no-explicit-any let error: any = null; const server = await createServer({ @@ -828,7 +834,7 @@ Deno.test("fsRoutes - _error render on 404", async () => { }, }, "routes/foo/_error.tsx": { - default: (ctx) => { + default: function foo2(ctx) { // deno-lint-ignore no-explicit-any error = ctx.error as any; return

ok foo

; @@ -1110,34 +1116,23 @@ Deno.test( "fsRoutes - returns response code from error route", async () => { const server = await createServer<{ text: string }>({ - "routes/_app.tsx": { - default: (ctx) => { - return ( -
- _app/ -
- ); - }, - }, "routes/_error.tsx": { default: () =>
fail
, }, - "routes/index.tsx": { - default: () =>
index
, - }, - "routes/bar.tsx": { - default: () =>
index
, - }, - "routes/foo/index.tsx": { - default: () =>
foo/index
, - }, - "routes/foo/_error.tsx": { + "routes/fail.tsx": { default: () => { throw new Error("fail"); }, }, - "routes/foo/bar.tsx": { - default: () =>
foo/index
, + "routes/foo/_error.tsx": { + default: () => { + throw new HttpError(501); + }, + }, + "routes/foo/fail.tsx": { + default: () => { + throw new Error("fail"); + }, }, }); @@ -1145,9 +1140,13 @@ Deno.test( await res.body?.cancel(); expect(res.status).toEqual(404); - res = await server.get("/foo/asdf"); + res = await server.get("/fail"); await res.body?.cancel(); expect(res.status).toEqual(500); + + res = await server.get("/foo/fail"); + await res.body?.cancel(); + expect(res.status).toEqual(501); }, ); diff --git a/src/plugins/fs_routes/render_middleware.ts b/src/plugins/fs_routes/render_middleware.ts deleted file mode 100644 index 526a7645..00000000 --- a/src/plugins/fs_routes/render_middleware.ts +++ /dev/null @@ -1,139 +0,0 @@ -import { type AnyComponent, h, type RenderableProps, type VNode } from "preact"; -import type { MiddlewareFn } from "../../middlewares/mod.ts"; -import type { HandlerFn, PageResponse } from "../../handlers.ts"; -import type { FreshReqContext, PageProps } from "../../context.ts"; -import { HttpError } from "../../error.ts"; -import { tracer } from "../../otel.ts"; -import { SpanStatusCode } from "@opentelemetry/api"; - -export type AsyncAnyComponent

= { - ( - props: RenderableProps

, - // deno-lint-ignore no-explicit-any - context?: any, - // deno-lint-ignore no-explicit-any - ): Promise | Response | null>; - displayName?: string; - defaultProps?: Partial

| undefined; -}; - -// deno-lint-ignore no-explicit-any -export function isAsyncAnyComponent(fn: any): fn is AsyncAnyComponent { - return typeof fn === "function" && fn.constructor.name === "AsyncFunction"; -} - -export function renderMiddleware( - components: Array< - | AnyComponent> - | AsyncAnyComponent> - >, - handler: HandlerFn | undefined, - init?: ResponseInit | undefined, -): MiddlewareFn { - return async (ctx) => { - let result: PageResponse | undefined; - if (handler !== undefined) { - const res = await tracer.startActiveSpan("handler", { - attributes: { "fresh.span_type": "fs_routes/handler" }, - }, async (span) => { - try { - const res = await handler(ctx); - span.setAttribute( - "fresh.handler_response", - res instanceof Response ? "http" : "data", - ); - return res; - } catch (err) { - if (err instanceof Error) { - span.recordException(err); - } else { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: String(err), - }); - } - throw err; - } finally { - span.end(); - } - }); - - if (res instanceof Response) { - return res; - } - - result = res; - } - - if (components.length === 0) { - throw new Error(`Did not receive any components to render.`); - } - - const props = ctx as FreshReqContext; - props.data = result?.data; - - let vnode: VNode | null = null; - for (let i = components.length - 1; i >= 0; i--) { - const child = vnode; - // FIXME: remove when we're using `` - props.Component = () => child; - - const fn = components[i]; - - if (isAsyncAnyComponent(fn)) { - const result = await tracer.startActiveSpan( - "invoke async component", - async (span) => { - span.setAttribute("fresh.span_type", "fs_routes/async_component"); - try { - const result = (await fn(props)) as VNode | Response; - span.setAttribute( - "fresh.component_response", - result instanceof Response ? "http" : "jsx", - ); - return result; - } catch (err) { - if (err instanceof Error) { - span.recordException(err); - } else { - span.setStatus({ - code: SpanStatusCode.ERROR, - message: String(err), - }); - } - throw err; - } finally { - span.end(); - } - }, - ); - if (result instanceof Response) { - return result; - } - vnode = result; - } else { - // deno-lint-ignore no-explicit-any - vnode = h(components[i] as any, props) as VNode; - } - } - - let status: number | undefined = init?.status ?? result?.status; - if ( - ctx.error !== null && ctx.error !== undefined - ) { - if ( - ctx.error instanceof HttpError - ) { - status = ctx.error.status; - } else { - status = 500; - } - } - - return ctx.render(vnode!, { - status, - statusText: init?.statusText, - headers: init?.headers ?? result?.headers, - }); - }; -} diff --git a/src/plugins/fs_routes/render_middleware_test.tsx b/src/plugins/fs_routes/render_middleware_test.tsx deleted file mode 100644 index 066133b8..00000000 --- a/src/plugins/fs_routes/render_middleware_test.tsx +++ /dev/null @@ -1,125 +0,0 @@ -import { expect } from "@std/expect"; -import { delay, serveMiddleware } from "../../test_utils.ts"; -import { renderMiddleware } from "./render_middleware.ts"; -import { parseHtml } from "../../../tests/test_utils.tsx"; - -Deno.test("renderMiddleware - responds with HTML", async () => { - const server = await serveMiddleware( - renderMiddleware([() =>

ok

], undefined), - ); - - const res = await server.get("/"); - expect(res.headers.get("Content-Type")).toEqual("text/html; charset=utf-8"); - - const doc = parseHtml(await res.text()); - // deno-lint-ignore no-explicit-any - expect((doc.body.firstChild as any).outerHTML).toEqual("

ok

"); -}); - -Deno.test("renderMiddleware - bypass rendering when handler returns Response", async () => { - const server = await serveMiddleware( - renderMiddleware( - [() =>

fail

], - () => new Response(null, { status: 204 }), - ), - ); - - const res = await server.get("/"); - expect(res.status).toEqual(204); - expect(res.body).toEqual(null); -}); - -Deno.test("renderMiddleware - chain components", async () => { - const server = await serveMiddleware( - renderMiddleware( - [ - (ctx) => ( -
- c1 -
- ), - (ctx) => ( - <> - c2 - - ), - () => <>c3, - ], - undefined, - ), - ); - - const res = await server.get("/"); - expect(res.status).toEqual(200); - - const doc = parseHtml(await res.text()); - expect(doc.body.firstChild?.textContent).toEqual("c1c2c3"); -}); - -Deno.test("renderMiddleware - chain async components", async () => { - const server = await serveMiddleware( - renderMiddleware( - [ - async (ctx) => { - await delay(1); - return ( -
- c1 -
- ); - }, - async (ctx) => { - await delay(1); - return ( - <> - c2 - - ); - }, - async () => { - await delay(1); - return <>c3; - }, - ], - undefined, - ), - ); - - const res = await server.get("/"); - expect(res.status).toEqual(200); - - const doc = parseHtml(await res.text()); - expect(doc.body.firstChild!.textContent).toEqual("c1c2c3"); -}); - -Deno.test("renderMiddleware - async components Response bail out", async () => { - const server = await serveMiddleware( - renderMiddleware( - [ - async (ctx) => { - await delay(1); - return ( -
- c1 -
- ); - }, - async () => { - await delay(1); - - return new Response("foo"); - }, - async () => { - await delay(1); - return <>c3; - }, - ], - undefined, - ), - ); - - const res = await server.get("/"); - expect(res.status).toEqual(200); - - expect(await res.text()).toEqual("foo"); -}); diff --git a/src/render.ts b/src/render.ts new file mode 100644 index 00000000..aca3bdf0 --- /dev/null +++ b/src/render.ts @@ -0,0 +1,158 @@ +import { + type AnyComponent, + type FunctionComponent, + h, + type RenderableProps, + type VNode, +} from "preact"; +import { + FreshScripts, + type RenderState, + setRenderState, +} from "./runtime/server/preact_hooks.tsx"; +import type { Context } from "./context.ts"; +import { recordSpanError, tracer } from "./otel.ts"; +import type { BuildCache } from "./build_cache.ts"; +import { DEV_ERROR_OVERLAY_URL } from "./constants.ts"; +import { renderToString } from "preact-render-to-string"; +import { BUILD_ID } from "./runtime/build_id.ts"; + +export type AsyncAnyComponent

= { + ( + props: RenderableProps

, + // deno-lint-ignore no-explicit-any + context?: any, + // deno-lint-ignore no-explicit-any + ): Promise | Response | null>; + displayName?: string; + defaultProps?: Partial

| undefined; +}; + +// deno-lint-ignore no-explicit-any +export function isAsyncAnyComponent(fn: any): fn is AsyncAnyComponent { + return typeof fn === "function" && fn.constructor.name === "AsyncFunction"; +} + +export async function renderAsyncAnyComponent( + fn: AsyncAnyComponent, + props: RenderableProps, +) { + return await tracer.startActiveSpan( + "invoke async component", + async (span) => { + span.setAttribute("fresh.span_type", "fs_routes/async_component"); + try { + const result = (await fn(props)) as VNode | Response; + span.setAttribute( + "fresh.component_response", + result instanceof Response ? "http" : "jsx", + ); + return result; + } catch (err) { + recordSpanError(span, err); + throw err; + } finally { + span.end(); + } + }, + ); +} + +export function preactRender( + vnode: VNode, + ctx: PageProps, + state: RenderState, + buildCache: BuildCache, + headers: Headers, +) { + try { + let res = renderToString(vnode); + // We require a the full outer DOM structure so that browser put + // comment markers in the right place in the DOM. + if (!state.renderedHtmlBody) { + let scripts = ""; + if (ctx.url.pathname !== ctx.config.basePath + DEV_ERROR_OVERLAY_URL) { + scripts = renderToString(h(FreshScripts, null)); + } + res = `${res}${scripts}`; + } + if (!state.renderedHtmlHead) { + res = `${res}`; + } + if (!state.renderedHtmlTag) { + res = `${res}`; + } + + return `${res}`; + } finally { + // Add preload headers + const basePath = ctx.config.basePath; + const runtimeUrl = `${basePath}/_fresh/js/${BUILD_ID}/fresh-runtime.js`; + let link = `<${encodeURI(runtimeUrl)}>; rel="modulepreload"; as="script"`; + state.islands.forEach((island) => { + const chunk = buildCache.getIslandChunkName(island.name); + if (chunk !== null) { + link += `, <${ + encodeURI(`${basePath}${chunk}`) + }>; rel="modulepreload"; as="script"`; + } + }); + + if (link !== "") { + headers.append("Link", link); + } + + state.clear(); + setRenderState(null); + } +} + +export type PageProps = + & Pick< + Context, + | "config" + | "url" + | "req" + | "params" + | "info" + | "state" + | "isPartial" + | "Component" + | "error" + > + & { data: Data }; + +export interface ComponentDef { + props: PageProps | null; + component: AnyComponent>; +} + +export async function renderRouteComponent( + ctx: Context, + def: ComponentDef, + child: FunctionComponent, +): Promise { + const vnodeProps: PageProps = { + Component: child, + config: ctx.config, + data: def.props, + error: ctx.error, + info: ctx.info, + isPartial: ctx.isPartial, + params: ctx.params, + req: ctx.req, + state: ctx.state, + url: ctx.url, + }; + + if (isAsyncAnyComponent(def.component)) { + const result = await renderAsyncAnyComponent(def.component, vnodeProps); + if (result instanceof Response) { + return result; + } + + return result; + } + + return h(def.component, vnodeProps) as VNode; +} diff --git a/src/router.ts b/src/router.ts index e128bacf..588e3dec 100644 --- a/src/router.ts +++ b/src/router.ts @@ -1,119 +1,180 @@ -export type Method = "HEAD" | "GET" | "POST" | "PATCH" | "PUT" | "DELETE"; +export type Method = + | "HEAD" + | "GET" + | "POST" + | "PATCH" + | "PUT" + | "DELETE" + | "OPTIONS"; -export interface Route { - path: string | URLPattern; - method: Method | "ALL"; - handlers: T[]; +export type RouteByMethod = { + [m in Method]: T[]; +}; + +export interface StaticRouteDef { + pattern: string | URLPattern; + byMethod: RouteByMethod; +} + +export interface DynamicRouteDef { + pattern: URLPattern; + byMethod: RouteByMethod; } export interface RouteResult { params: Record; - handlers: T[][]; + handlers: T[]; methodMatch: boolean; - patternMatch: boolean; pattern: string | null; } export interface Router { - _routes: Route[]; - _middlewares: T[]; - addMiddleware(fn: T): void; add( - method: Method | "ALL", - pathname: string | URLPattern, + method: Method | "OPTIONS" | "ALL", + pathname: string, handlers: T[], + unshift?: boolean, ): void; - match(method: Method, url: URL): RouteResult; + match(method: Method, url: URL, init?: T[]): RouteResult; + getAllowedMethods(pattern: string): string[]; } export const IS_PATTERN = /[*:{}+?()]/; -export class UrlPatternRouter implements Router { - readonly _routes: Route[] = []; - readonly _middlewares: T[] = []; +const EMPTY: string[] = []; - addMiddleware(fn: T): void { - this._middlewares.push(fn); +export class UrlPatternRouter implements Router { + #statics = new Map>(); + #dynamics = new Map>(); + #dynamicArr: DynamicRouteDef[] = []; + #allowed = new Map>(); + + getAllowedMethods(pattern: string): string[] { + const allowed = this.#allowed.get(pattern); + if (allowed === undefined) return EMPTY; + return Array.from(allowed); } - add(method: Method | "ALL", pathname: string | URLPattern, handlers: T[]) { - if ( - typeof pathname === "string" && pathname !== "/*" && - IS_PATTERN.test(pathname) - ) { - this._routes.push({ - path: new URLPattern({ pathname }), - handlers, - method, - }); + add( + method: Method | "ALL", + pathname: string, + handlers: T[], + unshift = false, + ) { + let allowed = this.#allowed.get(pathname); + if (allowed === undefined) { + allowed = new Set(); + this.#allowed.set(pathname, allowed); + } + if (method === "ALL") { + allowed.add("GET"); + allowed.add("POST"); + allowed.add("PATCH"); + allowed.add("PUT"); + allowed.add("DELETE"); + allowed.add("HEAD"); + allowed.add("OPTIONS"); } else { - this._routes.push({ - path: pathname, - handlers, - method, - }); + allowed.add(method); + } + + let byMethod: RouteByMethod; + if (IS_PATTERN.test(pathname)) { + let def = this.#dynamics.get(pathname); + if (def === undefined) { + def = { + pattern: new URLPattern({ pathname }), + byMethod: { + DELETE: [], + GET: [], + HEAD: [], + OPTIONS: [], + PATCH: [], + POST: [], + PUT: [], + }, + }; + this.#dynamics.set(pathname, def); + this.#dynamicArr.push(def); + } + + byMethod = def.byMethod; + } else { + let def = this.#statics.get(pathname); + if (def === undefined) { + def = { + pattern: pathname, + byMethod: { + DELETE: [], + GET: [], + HEAD: [], + OPTIONS: [], + PATCH: [], + POST: [], + PUT: [], + }, + }; + this.#statics.set(pathname, def); + } + + byMethod = def.byMethod; + } + + const fn = unshift ? "unshift" : "push"; + if (method === "ALL") { + byMethod.DELETE[fn](...handlers); + byMethod.GET[fn](...handlers); + byMethod.HEAD[fn](...handlers); + byMethod.OPTIONS[fn](...handlers); + byMethod.PATCH[fn](...handlers); + byMethod.POST[fn](...handlers); + byMethod.PUT[fn](...handlers); + } else { + byMethod[method][fn](...handlers); } } - match(method: Method, url: URL): RouteResult { + match(method: Method, url: URL, init: T[] = []): RouteResult { const result: RouteResult = { - params: {}, - handlers: [], + params: Object.create(null), + handlers: init, methodMatch: false, - patternMatch: false, pattern: null, }; - if (this._middlewares.length > 0) { - result.handlers.push(this._middlewares); + const staticMatch = this.#statics.get(url.pathname); + if (staticMatch !== undefined) { + result.pattern = url.pathname; + + const handlers = staticMatch.byMethod[method]; + if (handlers.length > 0) { + result.methodMatch = true; + result.handlers.push(...handlers); + } + + return result; } - for (let i = 0; i < this._routes.length; i++) { - const route = this._routes[i]; + for (let i = 0; i < this.#dynamicArr.length; i++) { + const route = this.#dynamicArr[i]; - // Fast path for string based routes which are expected - // to be either wildcard `*` match or an exact pathname match. - if ( - typeof route.path === "string" && - (route.path === "/*" || route.path === url.pathname) - ) { - if (route.method !== "ALL") result.patternMatch = true; - result.pattern = route.path; + const match = route.pattern.exec(url); + if (match === null) continue; - if (route.method === "ALL" || route.method === method) { - result.handlers.push(route.handlers); + result.pattern = route.pattern.pathname; - if (route.path === "/*" && route.method === "ALL") { - continue; - } + const handlers = route.byMethod[method]; + if (handlers.length > 0) { + result.methodMatch = true; + result.handlers.push(...handlers); - result.methodMatch = true; - - return result; - } - } else if (route.path instanceof URLPattern) { - const match = route.path.exec(url); - if (match !== null) { - if (route.method !== "ALL") result.patternMatch = true; - result.pattern = route.path.pathname; - - if (route.method === "ALL" || route.method === method) { - result.handlers.push(route.handlers); - - // Decode matched params - for (const [key, value] of Object.entries(match.pathname.groups)) { - result.params[key] = value === undefined ? "" : decodeURI(value); - } - - if (route.method === "ALL") { - continue; - } - - result.methodMatch = true; - return result; - } + // Decode matched params + for (const [key, value] of Object.entries(match.pathname.groups)) { + result.params[key] = value === undefined ? "" : decodeURI(value); } } + + break; } return result; @@ -123,7 +184,10 @@ export class UrlPatternRouter implements Router { /** * Transform a filesystem URL path to a `path-to-regex` style matcher. */ -export function pathToPattern(path: string): string { +export function pathToPattern( + path: string, + options?: { keepGroups: boolean }, +): string { const parts = path.split("/"); if (parts[parts.length - 1] === "index") { if (parts.length === 1) { @@ -148,7 +212,7 @@ export function pathToPattern(path: string): string { // Case: /foo/(bar) -> /foo // Case: /foo/(bar)/bob -> /foo/bob // Case: /(foo)/bar -> /bar - if (part.startsWith("(") && part.endsWith(")")) { + if (!options?.keepGroups && part.startsWith("(") && part.endsWith(")")) { continue; } @@ -216,3 +280,42 @@ export function pathToPattern(path: string): string { return route; } + +export function patternToSegments( + path: string, + root: string, + includeLast: boolean = false, +): string[] { + const out: string[] = [root]; + + if (path === "/" || path === "*" || path === "/*") return out; + + let start = -1; + for (let i = 0; i < path.length; i++) { + const ch = path[i]; + + if (ch === "/") { + if (i > 0) { + const raw = path.slice(start + 1, i); + out.push(raw); + } + start = i; + } + } + + if (includeLast && start < path.length - 1) { + out.push(path.slice(start + 1)); + } + + return out; +} + +export function mergePath(basePath: string, path: string): string { + if (basePath.endsWith("*")) basePath = basePath.slice(0, -1); + if (basePath === "/") basePath = ""; + + if (path === "*" || path === "/*") path = "/*"; + + const s = (basePath !== "" && path === "/") ? "" : path; + return basePath + s; +} diff --git a/src/router_test.ts b/src/router_test.ts index f930b13e..b6beffcc 100644 --- a/src/router_test.ts +++ b/src/router_test.ts @@ -1,5 +1,11 @@ import { expect } from "@std/expect"; -import { IS_PATTERN, pathToPattern, UrlPatternRouter } from "./router.ts"; +import { + IS_PATTERN, + mergePath, + pathToPattern, + patternToSegments, + UrlPatternRouter, +} from "./router.ts"; Deno.test("IS_PATTERN", () => { expect(IS_PATTERN.test("/foo")).toEqual(false); @@ -11,66 +17,26 @@ Deno.test("IS_PATTERN", () => { expect(IS_PATTERN.test("/foo/(a)")).toEqual(true); }); -Deno.test("UrlPatternRouter - GET get first match", () => { - const router = new UrlPatternRouter(); - const A = () => {}; - const B = () => {}; - const C = () => {}; - router.add("GET", "/", [A]); - router.add("GET", "/", [B]); - router.add("GET", "/", [C]); - - const res = router.match("GET", new URL("/", "http://localhost")); - expect(res).toEqual({ - params: {}, - handlers: [[A]], - methodMatch: true, - pattern: "/", - patternMatch: true, - }); -}); - -Deno.test("UrlPatternRouter - GET get matches with middlewares", () => { - const router = new UrlPatternRouter(); - const A = () => {}; - const B = () => {}; - const C = () => {}; - router.add("ALL", "/*", [A]); - router.add("ALL", "/*", [B]); - router.add("GET", "/", [C]); - - const res = router.match("GET", new URL("/", "http://localhost")); - expect(res).toEqual({ - params: {}, - handlers: [[A], [B], [C]], - methodMatch: true, - pattern: "/", - patternMatch: true, - }); -}); - Deno.test("UrlPatternRouter - GET extract params", () => { const router = new UrlPatternRouter(); const A = () => {}; - router.add("GET", new URLPattern({ pathname: "/:foo/:bar/c" }), [A]); + router.add("GET", "/:foo/:bar/c", [A]); let res = router.match("GET", new URL("/a/b/c", "http://localhost")); expect(res).toEqual({ params: { foo: "a", bar: "b" }, - handlers: [[A]], + handlers: [A], methodMatch: true, pattern: "/:foo/:bar/c", - patternMatch: true, }); // Decode params res = router.match("GET", new URL("/a%20a/b/c", "http://localhost")); expect(res).toEqual({ params: { foo: "a a", bar: "b" }, - handlers: [[A]], + handlers: [A], methodMatch: true, pattern: "/:foo/:bar/c", - patternMatch: true, }); }); @@ -81,11 +47,10 @@ Deno.test("UrlPatternRouter - Wrong method match", () => { const res = router.match("POST", new URL("/foo", "http://localhost")); expect(res).toEqual({ - params: {}, + params: Object.create(null), handlers: [], methodMatch: false, pattern: "/foo", - patternMatch: true, }); }); @@ -98,11 +63,10 @@ Deno.test("UrlPatternRouter - wrong + correct method", () => { const res = router.match("POST", new URL("/foo", "http://localhost")); expect(res).toEqual({ - params: {}, - handlers: [[B]], + params: Object.create(null), + handlers: [B], methodMatch: true, pattern: "/foo", - patternMatch: true, }); }); @@ -116,10 +80,9 @@ Deno.test("UrlPatternRouter - convert patterns automatically", () => { params: { id: "foo", }, - handlers: [[A]], + handlers: [A], methodMatch: true, pattern: "/books/:id", - patternMatch: true, }); }); @@ -170,4 +133,34 @@ Deno.test("pathToPattern", async (t) => { expect(() => pathToPattern("foo/foo-[[name]]")).toThrow(); expect(() => pathToPattern("foo/[[name]]-bar")).toThrow(); }); + + await t.step("keep groups", () => { + expect(pathToPattern("foo/(foo)/bar", { keepGroups: true })).toEqual( + "/foo/(foo)/bar", + ); + }); +}); + +Deno.test("patternToSegments", () => { + expect(patternToSegments("/", "")).toEqual([""]); + expect(patternToSegments("/foo", "")).toEqual([""]); + expect(patternToSegments("/foo/bar", "")).toEqual(["", "foo"]); + + expect(patternToSegments("/:foo", "")).toEqual([""]); + expect(patternToSegments("/:foo/:bar", "")).toEqual(["", ":foo"]); + expect(patternToSegments("/:foo-:bar/foo", "")).toEqual(["", ":foo-:bar"]); + expect(patternToSegments("/foo/", "")).toEqual(["", "foo"]); + + expect(patternToSegments("/foo/bar", "", true)).toEqual(["", "foo", "bar"]); +}); + +Deno.test("mergePath", () => { + expect(mergePath("", "/foo")).toEqual("/foo"); + expect(mergePath("/", "/foo")).toEqual("/foo"); + expect(mergePath("/foo/bar", "/")).toEqual("/foo/bar"); + expect(mergePath("/foo/bar", "/baz")).toEqual("/foo/bar/baz"); + expect(mergePath("*", "/baz")).toEqual("/baz"); + expect(mergePath("/*", "/baz")).toEqual("/baz"); + expect(mergePath("/foo", "*")).toEqual("/foo/*"); + expect(mergePath("/foo", "/*")).toEqual("/foo/*"); }); diff --git a/src/runtime/server/preact_hooks.tsx b/src/runtime/server/preact_hooks.tsx index d31a9e01..6775a25d 100644 --- a/src/runtime/server/preact_hooks.tsx +++ b/src/runtime/server/preact_hooks.tsx @@ -11,7 +11,7 @@ import { } from "preact"; import type { Signal } from "@preact/signals"; import type { Stringifiers } from "../../jsonify/stringify.ts"; -import type { PageProps } from "../../context.ts"; +import type { PageProps } from "../../render.ts"; import { Partial, type PartialProps } from "../shared.ts"; import { stringify } from "../../jsonify/stringify.ts"; import type { ServerIslandRegistry } from "../../context.ts"; @@ -88,7 +88,8 @@ export class RenderState { hasRuntimeScript = false; constructor( - public ctx: PageProps, + // deno-lint-ignore no-explicit-any + public ctx: PageProps, public islandRegistry: ServerIslandRegistry, public buildCache: BuildCache, public partialId: string, diff --git a/src/segments.ts b/src/segments.ts new file mode 100644 index 00000000..10d2ccdd --- /dev/null +++ b/src/segments.ts @@ -0,0 +1,214 @@ +import type { AnyComponent } from "preact"; +import type { MiddlewareFn } from "./middlewares/mod.ts"; +import { type Method, patternToSegments } from "./router.ts"; +import type { LayoutConfig, Route } from "./types.ts"; +import { type Context, getInternals } from "./context.ts"; +import { recordSpanError, tracer } from "./otel.ts"; +import { isHandlerByMethod } from "./handlers.ts"; +import { + type AsyncAnyComponent, + type PageProps, + renderRouteComponent, +} from "./render.ts"; +import { HttpError } from "./error.ts"; + +export type RouteComponent = + | AsyncAnyComponent> + | AnyComponent>; + +export interface Segment { + pattern: string; + middlewares: MiddlewareFn[]; + layout: { + component: RouteComponent; + config: LayoutConfig | null; + } | null; + errorRoute: Route | null; + notFound: MiddlewareFn | null; + app: RouteComponent | null; + children: Map>; + parent: Segment | null; +} + +export function newSegment( + pattern: string, + parent: Segment | null, +): Segment { + return { + pattern, + middlewares: [], + layout: null, + app: null, + errorRoute: null, + notFound: null, + parent, + children: new Map(), + }; +} + +export function getOrCreateSegment( + root: Segment, + path: string, + includeLast: boolean, +): Segment { + let current = root; + + const segments = patternToSegments(path, root.pattern, includeLast); + for (let i = 0; i < segments.length; i++) { + const seg = segments[i]; + if (seg === root.pattern) { + current = root; + } else { + let child = current.children.get(seg); + if (child === undefined) { + child = newSegment(seg, current); + current.children.set(seg, child); + } + + current = child; + } + } + + return current; +} + +export function segmentToMiddlewares( + segment: Segment, +): MiddlewareFn[] { + const result: MiddlewareFn[] = []; + + const stack: Segment[] = []; + let current: Segment | null = segment; + while (current !== null) { + stack.push(current); + current = current.parent; + } + + const root = stack.at(-1)!; + + for (let i = stack.length - 1; i >= 0; i--) { + const seg = stack[i]; + const { layout, app, errorRoute } = seg; + + result.push(async function segmentMiddleware(ctx) { + const internals = getInternals(ctx); + + const prevApp = internals.app; + const prevLayouts = internals.layouts; + + if (app !== null) { + internals.app = app; + } + + if (layout !== null) { + if (layout.config?.skipAppWrapper) { + internals.app = null; + } + + const def = { props: null, component: layout.component }; + if (layout.config?.skipInheritedLayouts) { + internals.layouts = [def]; + } else { + internals.layouts = [...internals.layouts, def]; + } + } + + try { + return await ctx.next(); + } catch (err) { + const status = err instanceof HttpError ? err.status : 500; + if (root.notFound !== null && status === 404) { + return await root.notFound(ctx); + } + + if (errorRoute !== null) { + return await renderRoute(ctx, errorRoute, status); + } + + throw err; + } finally { + internals.app = prevApp; + internals.layouts = prevLayouts; + } + }); + + if (seg.middlewares.length > 0) { + result.push(...seg.middlewares); + } + } + + return result; +} + +export async function renderRoute( + ctx: Context, + route: Route, + status = 200, +): Promise { + const internals = getInternals(ctx); + if (route.config?.skipAppWrapper) { + internals.app = null; + } + if (route.config?.skipInheritedLayouts) { + internals.layouts = []; + } + + const method = ctx.req.method as Method; + + const handlers = route.handler; + if (handlers === undefined) { + throw new Error(`Unexpected missing handlers`); + } + + const headers = new Headers(); + headers.set("Content-Type", "text/html;charset=utf-8"); + + const res = await tracer.startActiveSpan("handler", { + attributes: { "fresh.span_type": "fs_routes/handler" }, + }, async (span) => { + try { + const fn = isHandlerByMethod(handlers) + ? handlers[method] ?? null + : handlers; + + if (fn === null) return await ctx.next(); + + return await fn(ctx); + } catch (err) { + recordSpanError(span, err); + throw err; + } finally { + span.end(); + } + }); + + if (res instanceof Response) { + return res; + } + + if (typeof res.status === "number") { + status = res.status; + } + if (res.headers) { + for (const [name, value] of Object.entries(res.headers)) { + headers.set(name, value); + } + } + + let vnode = null; + if (route.component !== undefined) { + const result = await renderRouteComponent(ctx, { + component: route.component, + // deno-lint-ignore no-explicit-any + props: res.data as any, + }, () => null); + + if (result instanceof Response) { + return result; + } + + vnode = result; + } + + return ctx.render(vnode, { headers, status }); +} diff --git a/src/segments_test.ts b/src/segments_test.ts new file mode 100644 index 00000000..7d7263ff --- /dev/null +++ b/src/segments_test.ts @@ -0,0 +1,34 @@ +import { expect } from "@std/expect"; +import { getOrCreateSegment, newSegment } from "./segments.ts"; + +Deno.test("findOrCreateSegment - root", () => { + const root = newSegment("", null); + const found = getOrCreateSegment(root, "", false); + expect(found).toEqual(root); +}); + +Deno.test("findOrCreateSegment - /foo/bar", () => { + const root = newSegment("", null); + const found = getOrCreateSegment(root, "/foo/bar", false); + expect(found).toEqual(root.children.get("foo")); +}); + +Deno.test("findOrCreateSegment - /:foo/bar/:baz", () => { + const root = newSegment("", null); + const found = getOrCreateSegment(root, "/:foo/bar/:baz", false); + expect(found).toEqual( + root.children.get(":foo")?.children.get("bar"), + ); +}); + +Deno.test("findOrCreateSegment - /foo/bar/", () => { + const root = newSegment("", null); + const found = getOrCreateSegment(root, "/foo/bar/", false); + expect(found).toEqual(root.children.get("foo")?.children.get("bar")); +}); + +Deno.test("findOrCreateSegment - /foo/bar with last", () => { + const root = newSegment("", null); + const found = getOrCreateSegment(root, "/foo/bar", true); + expect(found).toEqual(root.children.get("foo")?.children.get("bar")); +}); diff --git a/src/test_utils.ts b/src/test_utils.ts index c633c61e..7d7a77a8 100644 --- a/src/test_utils.ts +++ b/src/test_utils.ts @@ -1,4 +1,4 @@ -import { FreshReqContext } from "./context.ts"; +import { Context } from "./context.ts"; import type { FsAdapter } from "./fs.ts"; import { type BuildCache, ProdBuildCache } from "./build_cache.ts"; import type { ResolvedFreshConfig } from "./config.ts"; @@ -45,6 +45,15 @@ export class FakeServer { const req = new Request(url, { method: "head" }); return await this.handler(req, STUB); } + async options(path: string): Promise { + const url = this.toUrl(path); + const req = new Request(url, { method: "options" }); + return await this.handler(req, STUB); + } + + async request(req: Request): Promise { + return await this.handler(req, STUB); + } private toUrl(path: string) { return new URL(path, "http://localhost/"); @@ -62,7 +71,7 @@ const DEFAULT_CONFIG: ResolvedFreshConfig = { }; export function serveMiddleware( - middleware: (ctx: FreshReqContext) => Response | Promise, + middleware: (ctx: Context) => Response | Promise, options: { config?: ResolvedFreshConfig; buildCache?: BuildCache; @@ -76,7 +85,7 @@ export function serveMiddleware( const buildCache = options.buildCache ?? new ProdBuildCache(config, new Map(), new Map(), true); - const ctx = new FreshReqContext( + const ctx = new Context( req, new URL(req.url), DEFAULT_CONN_INFO, diff --git a/src/types.ts b/src/types.ts index 66fe7c19..8410f4a5 100644 --- a/src/types.ts +++ b/src/types.ts @@ -1,3 +1,6 @@ +import type { RouteHandler } from "./handlers.ts"; +import type { RouteComponent } from "./segments.ts"; + export interface RouteConfig { /** * A route override for the page. This is useful for pages where the route @@ -42,6 +45,12 @@ export interface LayoutConfig { skipAppWrapper?: boolean; } +export interface Route { + component?: RouteComponent; + config?: RouteConfig; + handler?: RouteHandler; +} + // TODO: Uncomment once JSR supports global types // declare global { // namespace preact.createElement.JSX { diff --git a/src/utils.ts b/src/utils.ts index a98f8e36..8337216b 100644 --- a/src/utils.ts +++ b/src/utils.ts @@ -14,25 +14,6 @@ export function assertInDir( } } -/** - * Joins two path segments into a single normalized path. - * @example - * ```ts - * mergePaths("/api", "users"); // "/api/users" - * mergePaths("/api/", "/users"); // "/api/users" - * mergePaths("/", "/users"); // "/users" - * mergePaths("", "/users"); // "/users" - * mergePaths("/api", "/users"); // "/api/users" - * ``` - */ -export function mergePaths(a: string, b: string) { - if (a === "" || a === "/" || a === "/*") return b; - if (b === "/") return a; - if (a.endsWith("/")) return a.slice(0, -1) + b; - if (!b.startsWith("/")) return a + "/" + b; - return a + b; -} - /** * Converts a file path to a valid JS export name. * diff --git a/src/utils_test.ts b/src/utils_test.ts index fc016431..8bf2b5e4 100644 --- a/src/utils_test.ts +++ b/src/utils_test.ts @@ -1,14 +1,5 @@ import { expect } from "@std/expect"; -import { escapeScript, mergePaths, pathToExportName } from "./utils.ts"; - -Deno.test("mergePaths", () => { - expect(mergePaths("", "")).toEqual(""); - expect(mergePaths("/", "/foo")).toEqual("/foo"); - expect(mergePaths("/*", "/foo")).toEqual("/foo"); - expect(mergePaths("/foo/bar", "/baz")).toEqual("/foo/bar/baz"); - expect(mergePaths("/foo/bar/", "/baz")).toEqual("/foo/bar/baz"); - expect(mergePaths("/foo/bar", "baz")).toEqual("/foo/bar/baz"); -}); +import { escapeScript, pathToExportName } from "./utils.ts"; Deno.test("filenameToExportName", () => { expect(pathToExportName("/islands/foo.tsx")).toBe("foo"); diff --git a/tests/active_links_test.tsx b/tests/active_links_test.tsx index b522aed0..f9a19057 100644 --- a/tests/active_links_test.tsx +++ b/tests/active_links_test.tsx @@ -1,4 +1,4 @@ -import { App, staticFiles } from "fresh"; +import { App } from "fresh"; import { allIslandApp, assertNotSelector, @@ -27,8 +27,7 @@ function testApp(): App { const app = new App() .island(selfCounter, "SelfCounter", SelfCounter) .island(partialInIsland, "PartialInIsland", PartialInIsland) - .island(jsonIsland, "JsonIsland", JsonIsland) - .use(staticFiles()); + .island(jsonIsland, "JsonIsland", JsonIsland); setBuildCache(app, getBuildCache(allIslandApp)); return app; } diff --git a/tests/islands_test.tsx b/tests/islands_test.tsx index 4382962f..15e21508 100644 --- a/tests/islands_test.tsx +++ b/tests/islands_test.tsx @@ -19,7 +19,6 @@ import { withBrowserApp, } from "./test_utils.tsx"; import { parseHtml, waitForText } from "./test_utils.tsx"; -import { staticFiles } from "../src/middlewares/static_files.ts"; import { expect } from "@std/expect"; import { JsxConditional } from "./fixtures_islands/JsxConditional.tsx"; import { FnIsland } from "./fixtures_islands/FnIsland.tsx"; @@ -47,7 +46,6 @@ Deno.test({ const counterIsland = getIsland("Counter.tsx"); const app = testApp() - .use(staticFiles()) .island(counterIsland, "Counter", Counter) .get("/", (ctx) => { const sig = signal(3); @@ -73,7 +71,6 @@ Deno.test({ const multipleIslands = getIsland("Multiple.tsx"); const app = testApp() - .use(staticFiles()) .island(multipleIslands, "Multiple1", Multiple1) .island(multipleIslands, "Multiple2", Multiple2) .get("/", (ctx) => { @@ -103,7 +100,6 @@ Deno.test({ const counterIsland = getIsland("Counter.tsx"); const app = testApp() - .use(staticFiles()) .island(counterIsland, "Counter", Counter) .get("/", (ctx) => { const sig = signal(0); @@ -132,7 +128,6 @@ Deno.test({ const jsonIsland = getIsland("JsonIsland.tsx"); const app = testApp() - .use(staticFiles()) .island(jsonIsland, "JsonIsland", Counter) .get("/", (ctx) => { return ctx.render( @@ -160,7 +155,6 @@ Deno.test({ const nullIsland = getIsland("NullIsland.tsx"); const app = testApp() - .use(staticFiles()) .island(nullIsland, "NullIsland", NullIsland) .get("/", (ctx) => { return ctx.render( @@ -184,7 +178,6 @@ Deno.test({ const islandInIsland = getIsland("IslandInIsland.tsx"); const app = testApp() - .use(staticFiles()) .island(counter, "Counter", Counter) .island(islandInIsland, "IslandInIsland", IslandInIsland) .get("/", (ctx) => { @@ -213,7 +206,6 @@ Deno.test({ const jsxIsland = getIsland("JsxIsland.tsx"); const app = testApp() - .use(staticFiles()) .island(jsxIsland, "JsxIsland", JsxIsland) .get("/", (ctx) => { return ctx.render( @@ -241,7 +233,6 @@ Deno.test({ const jsxIsland = getIsland("JsxIsland.tsx"); const app = testApp() - .use(staticFiles()) .island(jsxIsland, "JsxIsland", JsxIsland) .get("/", (ctx) => { return ctx.render( @@ -271,7 +262,6 @@ Deno.test({ const jsxChildrenIsland = getIsland("JsxChildrenIsland.tsx"); const app = testApp() - .use(staticFiles()) .island(jsxChildrenIsland, "JsxChildrenIsland", JsxChildrenIsland) .get("/", (ctx) => { return ctx.render( @@ -307,7 +297,6 @@ Deno.test({ const selfCounter = getIsland("SelfCounter.tsx"); const app = testApp() - .use(staticFiles()) .island(passThrough, "PassThrough", PassThrough) .island(selfCounter, "SelfCounter", SelfCounter) .get("/", (ctx) => { @@ -339,7 +328,6 @@ Deno.test({ const selfCounter = getIsland("SelfCounter.tsx"); const app = testApp() - .use(staticFiles()) .island(counterWithSlots, "CounterWithSlots", CounterWithSlots) .island(selfCounter, "SelfCounter", SelfCounter) .get("/", (ctx) => { @@ -382,7 +370,6 @@ Deno.test({ const selfCounter = getIsland("SelfCounter.tsx"); const app = testApp() - .use(staticFiles()) .island(passThrough, "PassThrough", PassThrough) .island(selfCounter, "SelfCounter", SelfCounter) .get("/", (ctx) => { @@ -424,7 +411,6 @@ Deno.test({ const selfCounter = getIsland("SelfCounter.tsx"); const app = testApp() - .use(staticFiles()) .island(jsxConditional, "JsxConditional", JsxConditional) .island(selfCounter, "SelfCounter", SelfCounter) .get("/", (ctx) => { @@ -466,7 +452,6 @@ Deno.test({ const jsxConditional = getIsland("JsxConditional.tsx"); const app = testApp() - .use(staticFiles()) .island(jsxConditional, "JsxConditional", JsxConditional) .get("/", (ctx) => { return ctx.render( @@ -541,7 +526,6 @@ Deno.test({ const fnIsland = getIsland("FnIsland.tsx"); const app = testApp() - .use(staticFiles()) .island(fragmentIsland, "FragmentIsland", FragmentIsland) .island(fnIsland, "FnIsland", FnIsland) .get("/", (ctx) => { @@ -570,7 +554,6 @@ Deno.test({ const escapeIsland = getIsland("EscapeIsland.tsx"); const app = testApp() - .use(staticFiles()) .island(escapeIsland, "EscapeIsland", EscapeIsland) .get("/", (ctx) => { return ctx.render( @@ -667,7 +650,6 @@ Deno.test({ const nodeProcess = getIsland("NodeProcess.tsx"); const app = testApp() - .use(staticFiles()) .island(nodeProcess, "NodeProcess", NodeProcess) .get("/", (ctx) => ctx.render( @@ -695,7 +677,6 @@ Deno.test({ const selfCounter = getIsland("SelfCounter.tsx"); const app = testApp({ basePath: "/foo" }) - .use(staticFiles()) .island(selfCounter, "SelfCounter", SelfCounter) .get("/", (ctx) => ctx.render( @@ -720,7 +701,6 @@ Deno.test({ const freshAttrs = getIsland("FreshAttrs.tsx"); const app = testApp() - .use(staticFiles()) .island(freshAttrs, "FreshAttrs", FreshAttrs) .get("/", (ctx) => ctx.render( @@ -747,8 +727,7 @@ Deno.test({ Deno.test({ name: "fsRoutes - load islands from group folder", fn: async () => { - const app = testApp() - .use(staticFiles()); + const app = testApp(); await fsRoutes(app, { dir: path.join( @@ -778,7 +757,6 @@ Deno.test({ const selfCounter = getIsland("SelfCounter.tsx"); const app = testApp() - .use(staticFiles()) .island(selfCounter, "SelfCounter", SelfCounter) .get("/", (ctx) => ctx.render( diff --git a/tests/partials_test.tsx b/tests/partials_test.tsx index eb66bd66..a74d44d7 100644 --- a/tests/partials_test.tsx +++ b/tests/partials_test.tsx @@ -1,4 +1,4 @@ -import { App, staticFiles } from "fresh"; +import { App } from "fresh"; import { Partial } from "fresh/runtime"; import { allIslandApp, @@ -40,8 +40,7 @@ function testApp(): App { .island(selfCounter, "SelfCounter", SelfCounter) .island(partialInIsland, "PartialInIsland", PartialInIsland) .island(jsonIsland, "JsonIsland", JsonIsland) - .island(optOutPartialLink, "OptOutPartialLink", OptOutPartialLink) - .use(staticFiles()); + .island(optOutPartialLink, "OptOutPartialLink", OptOutPartialLink); setBuildCache(app, getBuildCache(allIslandApp)); return app; diff --git a/www/main.ts b/www/main.ts index cfdbe7eb..b6fc0876 100644 --- a/www/main.ts +++ b/www/main.ts @@ -1,7 +1,6 @@ -import { App, fsRoutes, staticFiles, trailingSlashes } from "fresh"; +import { App, fsRoutes, trailingSlashes } from "fresh"; export const app = new App({ root: import.meta.url }) - .use(staticFiles()) .use(trailingSlashes("never")); await fsRoutes(app, { diff --git a/www/routes/docs/_layout.tsx b/www/routes/docs/_layout.tsx index fbf97789..4e21e868 100644 --- a/www/routes/docs/_layout.tsx +++ b/www/routes/docs/_layout.tsx @@ -1,4 +1,4 @@ -import type { PageProps } from "../../../src/context.ts"; +import type { PageProps } from "@fresh/core"; export default function Layout({ Component }: PageProps) { return (