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
+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][] = [];