feat: support async route components (#1388)

This commit is contained in:
Marvin Hagemeister
2023-07-12 21:09:56 +02:00
committed by GitHub
parent e2a1bf8643
commit 62a5613a46
20 changed files with 564 additions and 96 deletions
+122 -54
View File
@@ -32,12 +32,17 @@ import {
Route,
RouteModule,
RouterOptions,
RouterState,
ServeHandlerInfo,
UnknownPage,
UnknownPageModule,
} from "./types.ts";
import { render as internalRender } from "./render.ts";
import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts";
import { DEFAULT_RENDER_FN, render as internalRender } from "./render.ts";
import {
ContentSecurityPolicy,
ContentSecurityPolicyDirectives,
SELF,
} from "../runtime/csp.ts";
import { ASSET_CACHE_BUST_KEY, INTERNAL_PREFIX } from "../runtime/utils.ts";
import {
Builder,
@@ -52,10 +57,6 @@ const DEFAULT_CONN_INFO: ServeHandlerInfo = {
remoteAddr: { transport: "tcp", hostname: "localhost", port: 1234 },
};
interface RouterState {
state: Record<string, unknown>;
}
function isObject(value: unknown) {
return typeof value === "object" &&
!Array.isArray(value) &&
@@ -595,6 +596,58 @@ export class ServerContext {
};
}
const dependenciesFn = (path: string) => {
const snapshot = this.#maybeBuildSnapshot();
return snapshot?.dependencies(path) ?? [];
};
const renderNotFound = async <Data = undefined>(
req: Request,
params: Record<string, string>,
// deno-lint-ignore no-explicit-any
ctx?: any,
data?: Data,
error?: unknown,
) => {
const notFound = this.#notFound;
if (!notFound.component) {
return sendResponse(["Not found.", undefined], {
status: Status.NotFound,
isDev: this.#dev,
statusText: undefined,
headers: undefined,
});
}
const imports: string[] = [];
const resp = await internalRender({
request: req,
context: ctx,
route: notFound,
islands: this.#islands,
plugins: this.#plugins,
app: this.#app,
imports,
dependenciesFn,
renderFn: this.#renderFn,
url: new URL(req.url),
params,
data,
state: ctx?.state,
error,
});
if (resp instanceof Response) {
return resp;
}
return sendResponse(resp, {
status: Status.NotFound,
isDev: this.#dev,
statusText: undefined,
headers: undefined,
});
};
const genRender = <Data = undefined>(
route: Route<Data> | UnknownPage | ErrorPage,
status: number,
@@ -604,7 +657,8 @@ export class ServerContext {
return (
req: Request,
params: Record<string, string>,
state?: Record<string, unknown>,
// deno-lint-ignore no-explicit-any
ctx?: any,
error?: unknown,
) => {
return async (data?: Data, options?: RenderOptions) => {
@@ -612,65 +666,42 @@ export class ServerContext {
throw new Error("This page does not have a component to render.");
}
if (
typeof route.component === "function" &&
route.component.constructor.name === "AsyncFunction"
) {
throw new Error(
"Async components are not supported. Fetch data inside of a route handler, as described in the docs: https://fresh.deno.dev/docs/getting-started/fetching-data",
);
}
const resp = await internalRender({
request: req,
context: {
...ctx,
async renderNotFound() {
return await renderNotFound(req, params, ctx, data, error);
},
},
route,
islands: this.#islands,
plugins: this.#plugins,
app: this.#app,
imports,
dependenciesFn: (path) => {
const snapshot = this.#maybeBuildSnapshot();
return snapshot?.dependencies(path) ?? [];
},
dependenciesFn,
renderFn: this.#renderFn,
url: new URL(req.url),
params,
data,
state,
state: ctx?.state,
error,
});
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
const [body, csp] = resp;
if (csp) {
if (this.#dev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers["content-security-policy-report-only"] = directive;
} else {
headers["content-security-policy"] = directive;
}
if (resp instanceof Response) {
return resp;
}
return new Response(body, {
return sendResponse(resp, {
status: options?.status ?? status,
statusText: options?.statusText,
headers: options?.headers
? { ...headers, ...options.headers }
: headers,
headers: options?.headers,
isDev: this.#dev,
});
};
};
};
const createUnknownRender = genRender(this.#notFound, Status.NotFound);
for (const route of this.#routes) {
if (this.#routerOptions.trailingSlash && route.pattern != "/") {
route.pattern += "/";
@@ -682,8 +713,10 @@ export class ServerContext {
(route.handler as Handler)(req, {
...ctx,
params,
render: createRender(req, params, ctx.state),
renderNotFound: createUnknownRender(req, params, ctx.state),
render: createRender(req, params, ctx),
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
}),
};
} else {
@@ -697,8 +730,10 @@ export class ServerContext {
handler(req, {
...ctx,
params,
render: createRender(req, params, ctx.state),
renderNotFound: createUnknownRender(req, params, ctx.state),
render: createRender(req, params, ctx),
async renderNotFound<Data = undefined>(data: Data) {
return await renderNotFound(req, params, ctx, data);
},
});
}
}
@@ -712,7 +747,9 @@ export class ServerContext {
req,
{
...ctx,
render: createUnknownRender(req, {}),
render() {
return renderNotFound(req, {}, ctx);
},
},
);
@@ -843,10 +880,6 @@ export class ServerContext {
};
}
const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
render();
};
const DEFAULT_ROUTER_OPTIONS: RouterOptions = {
trailingSlash: false,
};
@@ -1099,3 +1132,38 @@ async function readDenoConfig(
dir = parent;
}
}
function sendResponse(
resp: [string, ContentSecurityPolicy | undefined],
options: {
status: number;
statusText: string | undefined;
headers?: HeadersInit;
isDev: boolean;
},
) {
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
const [body, csp] = resp;
if (csp) {
if (options.isDev) {
csp.directives.connectSrc = [
...(csp.directives.connectSrc ?? []),
SELF,
];
}
const directive = serializeCSPDirectives(csp.directives);
if (csp.reportOnly) {
headers["content-security-policy-report-only"] = directive;
} else {
headers["content-security-policy"] = directive;
}
}
return new Response(body, {
status: options.status,
statusText: options.statusText,
headers: options.headers ? { ...headers, ...options.headers } : headers,
});
}
+1
View File
@@ -37,6 +37,7 @@ export type {
PluginRenderStyleTag,
RenderFunction,
RouteConfig,
RouteContext,
ServeHandlerInfo,
StartOptions,
UnknownHandler,
+80 -31
View File
@@ -11,6 +11,7 @@ import {
} from "preact";
import {
AppModule,
AsyncRoute,
ErrorPage,
Island,
Plugin,
@@ -29,6 +30,10 @@ import { assetHashingHook } from "../runtime/utils.ts";
import { htmlEscapeJsonString } from "./htmlescape.ts";
import { serialize } from "./serializer.ts";
export const DEFAULT_RENDER_FN: RenderFunction = (_ctx, render) => {
render();
};
// These hooks are long stable, but when we originally added them we
// weren't sure if they should be public.
export interface AdvancedPreactOptions extends PreactOptions {
@@ -44,6 +49,9 @@ const options = preactOptions as AdvancedPreactOptions;
options.errorBoundaries = true;
export interface RenderOptions<Data> {
request: Request;
// deno-lint-ignore no-explicit-any
context: any;
route: Route<Data> | UnknownPage | ErrorPage;
islands: Island[];
plugins: Plugin[];
@@ -133,7 +141,11 @@ function defaultCsp() {
*/
export async function render<Data>(
opts: RenderOptions<Data>,
): Promise<[string, ContentSecurityPolicy | undefined]> {
): Promise<[string, ContentSecurityPolicy | undefined] | Response> {
const component = opts.route.component;
const isAsyncComponent = typeof component === "function" &&
component.constructor.name === "AsyncFunction";
const props: Record<string, unknown> = {
params: opts.params,
url: opts.url,
@@ -149,31 +161,6 @@ export async function render<Data>(
? defaultCsp()
: undefined;
const headComponents: ComponentChildren[] = [];
const vnode = h(CSP_CONTEXT.Provider, {
value: csp,
children: h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: h(opts.app.default, {
params: opts.params as Record<string, string>,
url: opts.url,
route: opts.route.pattern,
data: opts.data,
state: opts.state!,
Component() {
return h(opts.route.component! as ComponentType<unknown>, props);
},
}),
}),
});
const ctx = new RenderContext(
crypto.randomUUID(),
opts.url,
opts.route.pattern,
opts.lang ?? "en",
);
if (csp) {
// Clear the csp
const newCsp = defaultCsp();
@@ -192,15 +179,46 @@ export async function render<Data>(
// Clear the island props
ISLAND_PROPS = [];
const ctx = new RenderContext(
crypto.randomUUID(),
opts.url,
opts.route.pattern,
opts.lang ?? "en",
);
let bodyHtml: string | null = null;
function renderInner(): string {
bodyHtml = renderToString(vnode);
function renderInner(vnode: ComponentChildren): string {
const root = h(CSP_CONTEXT.Provider, {
value: csp,
children: h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: h(opts.app.default, {
params: opts.params as Record<string, string>,
url: opts.url,
route: opts.route.pattern,
data: opts.data,
state: opts.state!,
Component() {
// deno-lint-ignore no-explicit-any
return vnode as any;
},
}),
}),
});
bodyHtml = renderToString(root);
return bodyHtml;
}
const syncPlugins = opts.plugins.filter((p) => p.render);
const renderResults: [Plugin, PluginRenderResult][] = [];
const syncPlugins = opts.plugins.filter((p) => p.render);
if (isAsyncComponent && syncPlugins.length > 0) {
throw new Error(
`Async server components cannot be rendered synchronously. The following plugins use a synchronous render method: "${
syncPlugins.map((plugin) => plugin.name).join('", "')
}"`,
);
}
function renderSync(): PluginRenderFunctionResult {
const plugin = syncPlugins.shift();
@@ -213,7 +231,7 @@ export async function render<Data>(
}
renderResults.push([plugin, res]);
} else {
renderInner();
renderInner(h(component as ComponentType, props));
}
if (bodyHtml === null) {
throw new Error(
@@ -228,6 +246,7 @@ export async function render<Data>(
const asyncPlugins = opts.plugins.filter((p) => p.renderAsync);
let asyncRenderResponse: Response | undefined;
async function renderAsync(): Promise<PluginRenderFunctionResult> {
const plugin = asyncPlugins.shift();
if (plugin) {
@@ -244,7 +263,33 @@ export async function render<Data>(
);
}
} else {
await opts.renderFn(ctx, () => renderSync().htmlText);
if (isAsyncComponent) {
if (opts.renderFn !== DEFAULT_RENDER_FN) {
throw new Error(
`Async server components are not supported with custom render functions.`,
);
}
// deno-lint-ignore no-explicit-any
const res = await (component as AsyncRoute<any>)(opts.request, {
localAddr: opts.context.localAddr,
remoteAddr: opts.context.remoteAddr,
renderNotFound: opts.context.renderNotFound,
url: opts.url,
route: opts.route.pattern,
params: opts.params as Record<string, string>,
state: opts.state ?? {},
});
if (res instanceof Response) {
asyncRenderResponse = res;
bodyHtml = "";
} else {
renderInner(res);
}
} else {
await opts.renderFn(ctx, () => renderSync().htmlText);
}
if (bodyHtml === null) {
throw new Error(
`The 'render' function was not called by the legacy async render hook.`,
@@ -258,6 +303,10 @@ export async function render<Data>(
}
await renderAsync();
if (asyncRenderResponse !== undefined) {
return asyncRenderResponse;
}
bodyHtml = bodyHtml as unknown as string;
const moduleScripts: [string, string][] = [];
+31 -7
View File
@@ -1,4 +1,4 @@
import { ComponentType } from "preact";
import { ComponentChildren, ComponentType, VNode } from "preact";
import { ServeInit } from "./deps.ts";
import * as router from "./router.ts";
import { InnerRenderFunction, RenderContext } from "./render.ts";
@@ -56,6 +56,16 @@ export interface PageProps<T = any, S = Record<string, unknown>> {
state: S;
}
/**
* Context passed to async route components.
*/
export type RouteContext<T = unknown, S = Record<string, unknown>> =
& Omit<
HandlerContext<T, S>,
"render"
>
& Omit<PageProps<unknown, S>, "data">;
export interface RouteConfig {
/**
* A route override for the page. This is useful for pages where the route
@@ -119,22 +129,36 @@ export type Handlers<T = any, State = Record<string, unknown>> = {
export type MultiHandler<T> = Handlers<T>;
export interface RouteModule {
default?: ComponentType<PageProps>;
default?: PageComponent<PageProps>;
// deno-lint-ignore no-explicit-any
handler?: Handler<any, any> | Handlers<any, any>;
config?: RouteConfig;
}
export type AsyncRoute<T> = (
req: Request,
ctx: RouteContext<T>,
) => Promise<ComponentChildren | Response>;
export type PageComponent<T> =
| ComponentType<PageProps<T>>
| AsyncRoute<T>
// deno-lint-ignore no-explicit-any
| ((props: any) => VNode<any> | ComponentChildren);
// deno-lint-ignore no-explicit-any
export interface Route<Data = any> {
pattern: string;
url: string;
name: string;
component?: ComponentType<PageProps<Data>>;
component?: PageComponent<Data>;
handler: Handler<Data> | Handlers<Data>;
csp: boolean;
}
export interface RouterState {
state: Record<string, unknown>;
}
// --- APP ---
export interface AppProps extends PageProps {
@@ -175,7 +199,7 @@ export type UnknownHandler = (
) => Response | Promise<Response>;
export interface UnknownPageModule {
default?: ComponentType<UnknownPageProps>;
default?: PageComponent<UnknownPageProps>;
handler?: UnknownHandler;
config?: RouteConfig;
}
@@ -184,7 +208,7 @@ export interface UnknownPage {
pattern: string;
url: string;
name: string;
component?: ComponentType<UnknownPageProps>;
component?: PageComponent<UnknownPageProps>;
handler: UnknownHandler;
csp: boolean;
}
@@ -216,7 +240,7 @@ export type ErrorHandler = (
) => Response | Promise<Response>;
export interface ErrorPageModule {
default?: ComponentType<ErrorPageProps>;
default?: PageComponent<ErrorPageProps>;
handler?: ErrorHandler;
config?: RouteConfig;
}
@@ -225,7 +249,7 @@ export interface ErrorPage {
pattern: string;
url: string;
name: string;
component?: ComponentType<ErrorPageProps>;
component?: PageComponent<ErrorPageProps>;
handler: ErrorHandler;
csp: boolean;
}