feat: a new "island" based architechture (#97)

This commit is contained in:
Luca Casonato
2022-03-04 19:49:27 +01:00
committed by GitHub
parent d441bf2489
commit 8daa280862
70 changed files with 820 additions and 972 deletions
+35 -40
View File
@@ -1,5 +1,5 @@
import { denoPlugin, esbuild, esbuildTypes, toFileUrl } from "./deps.ts";
import { Page } from "./types.ts";
import { Island } from "./types.ts";
let esbuildInitalized: boolean | Promise<void> = false;
async function ensureEsbuildInialized() {
@@ -20,22 +20,20 @@ async function ensureEsbuildInialized() {
}
export class Bundler {
#pages: Page[];
#islands: Island[];
#cache: Map<string, Uint8Array> | Promise<void> | undefined = undefined;
#preloads = new Map<string, string[]>();
constructor(pages: Page[]) {
this.#pages = pages;
constructor(islands: Island[]) {
this.#islands = islands;
}
async bundle() {
const entryPoints: Record<string, string> = {};
for (const page of this.#pages) {
if (page.component !== undefined && page.runtimeJS) {
entryPoints[page.name] = `fresh:///${page.name}`;
}
for (const island of this.#islands) {
entryPoints[island.id] = `fresh:///${island.id}`;
}
const absWorkingDir = Deno.cwd();
await ensureEsbuildInialized();
const bundle = await esbuild.build({
@@ -50,21 +48,21 @@ export class Bundler {
absWorkingDir,
outfile: "",
platform: "neutral",
plugins: [freshPlugin(this.#pages), denoPlugin()],
plugins: [freshPlugin(this.#islands), denoPlugin()],
splitting: true,
target: ["chrome90", "firefox88", "safari13"],
treeShaking: true,
write: false,
});
const metafileOutputs = bundle.metafile!.outputs;
// const metafileOutputs = bundle.metafile!.outputs;
for (const path in metafileOutputs) {
const meta = metafileOutputs[path];
const imports = meta.imports
.filter(({ kind }) => kind === "import-statement")
.map(({ path }) => `/${path}`);
this.#preloads.set(`/${path}`, imports);
}
// for (const path in metafileOutputs) {
// const meta = metafileOutputs[path];
// const imports = meta.imports
// .filter(({ kind }) => kind === "import-statement")
// .map(({ path }) => `/${path}`);
// this.#preloads.set(`/${path}`, imports);
// }
const cache = new Map<string, Uint8Array>();
const absDirUrlLength = toFileUrl(absWorkingDir).href.length;
@@ -94,18 +92,18 @@ export class Bundler {
return cache.get(path) ?? null;
}
getPreloads(path: string): string[] {
return this.#preloads.get(path) ?? [];
}
// getPreloads(path: string): string[] {
// return this.#preloads.get(path) ?? [];
// }
}
function freshPlugin(pageList: Page[]): esbuildTypes.Plugin {
function freshPlugin(islands: Island[]): esbuildTypes.Plugin {
const runtime = new URL("../../runtime.ts", import.meta.url);
const pageMap = new Map<string, Page>();
const islandMap = new Map<string, Island>();
for (const page of pageList) {
pageMap.set(`/${page.name}`, page);
for (const island of islands) {
islandMap.set(`/${island.id}`, island);
}
return {
@@ -127,24 +125,21 @@ function freshPlugin(pageList: Page[]): esbuildTypes.Plugin {
): esbuildTypes.OnLoadResult | null | undefined {
const url = new URL(args.path);
const path = url.pathname;
const page = pageMap.get(path);
if (!page) return null;
const island = islandMap.get(path);
if (!island) return null;
const contents = `
import Page from "${page.url}";
import { h, render, DATA_CONTEXT } from "${runtime.href}";
import ${island.name} from "${island.url}";
import { h, render } from "${runtime.href}";
addEventListener("DOMContentLoaded", () => {
const { params, data } = JSON.parse(document.getElementById("__FRSH_PROPS")?.textContent ?? "{}");
try {
render(h(DATA_CONTEXT.Provider, { value: new Map(data ?? []) }, h(Page, { params: params ?? {} })), document.getElementById("__FRSH"));
} catch(err) {
if (err instanceof Promise) {
console.error("Render tried to suspend without a suspense boundary.");
} else {
console.error("Render threw an error:", err);
}
class ${island.name}Island extends HTMLElement {
constructor() {
super();
const props = JSON.parse(this.getAttribute("props"));
render(h(${island.name}, props), this);
}
});
}
customElements.define("frsh-${island.id}", ${island.name}Island);
`;
return { contents, loader: "js" };
},
-36
View File
@@ -1,36 +0,0 @@
(() => {
/** Replace a suspense component with it's final variant. */
window.$SR = (id) => {
const targetStart = document.getElementById("S:" + id);
const targetEnd = document.getElementById("E:" + id);
const replacement = document.getElementById("R:" + id);
replacement.parentNode.removeChild(replacement);
while (targetStart.nextSibling !== targetEnd) {
targetStart.parentNode.removeChild(targetStart.nextSibling);
}
while (replacement.firstChild) {
targetStart.parentNode.insertBefore(replacement.firstChild, targetEnd);
}
targetStart.parentNode.removeChild(targetStart);
targetEnd.parentNode.removeChild(targetEnd);
};
/** @type {HTMLStyleElement} */
const sheetElement = document.getElementById("__FRSH_STYLE");
const rules = sheetElement.childNodes[0]?.textContent.split("\n");
if (rules !== undefined) {
sheetElement.removeChild(sheetElement.firstChild);
for (const rule of rules) {
sheetElement.append(document.createTextNode(rule));
}
}
/** Insert new style rules. */
window.$ST = (inserts) => {
for (const [rule, index] of inserts) {
sheetElement.insertBefore(
document.createTextNode(rule),
sheetElement.childNodes[index],
);
}
};
})();
+79 -88
View File
@@ -6,7 +6,7 @@ import {
toFileUrl,
walk,
} from "./deps.ts";
import { Routes } from "./mod.ts";
import { Manifest } from "./mod.ts";
import { Bundler } from "./bundle.ts";
import { ALIVE_URL, INTERNAL_PREFIX, REFRESH_JS_URL } from "./constants.ts";
import { JS_PREFIX } from "./constants.ts";
@@ -16,6 +16,7 @@ import {
ErrorPage,
ErrorPageModule,
Handler,
Island,
Middleware,
MiddlewareModule,
Page,
@@ -26,11 +27,7 @@ import {
UnknownPageModule,
} from "./types.ts";
import { render as internalRender } from "./render.tsx";
import {
ContentSecurityPolicy,
ContentSecurityPolicyDirectives,
SELF,
} from "../runtime/csp.ts";
import { ContentSecurityPolicyDirectives, SELF } from "../runtime/csp.ts";
import { h } from "../runtime/deps.ts";
interface StaticFile {
@@ -49,6 +46,7 @@ interface StaticFile {
export class ServerContext {
#dev: boolean;
#pages: Page[];
#islands: Island[];
#staticFiles: StaticFile[];
#bundler: Bundler;
#renderer: Renderer;
@@ -59,6 +57,7 @@ export class ServerContext {
constructor(
pages: Page[],
islands: Island[],
staticFiles: StaticFile[],
renderer: Renderer,
middleware: Middleware,
@@ -67,36 +66,38 @@ export class ServerContext {
error: ErrorPage,
) {
this.#pages = pages;
this.#islands = islands;
this.#staticFiles = staticFiles;
this.#renderer = renderer;
this.#middleware = middleware;
this.#app = app;
this.#notFound = notFound;
this.#error = error;
this.#bundler = new Bundler(pages);
this.#bundler = new Bundler(this.#islands);
this.#dev = typeof Deno.env.get("DENO_DEPLOYMENT_ID") !== "string"; // Env var is only set in prod (on Deploy).
}
/**
* Process the routes into individual components and pages.
* Process the manifest into individual components and pages.
*/
static async fromRoutes(routes: Routes): Promise<ServerContext> {
// Get the routes' base URL.
const baseUrl = new URL("./", routes.baseUrl).href;
static async fromManifest(manifest: Manifest): Promise<ServerContext> {
// Get the manifest' base URL.
const baseUrl = new URL("./", manifest.baseUrl).href;
// Extract all routes, and prepare them into the `Page` structure.
const pages: Page[] = [];
const islands: Island[] = [];
let renderer: Renderer = DEFAULT_RENDERER;
let middleware: Middleware = DEFAULT_MIDDLEWARE;
let app: AppModule = DEFAULT_APP;
let notFound: UnknownPage = DEFAULT_NOT_FOUND;
let error: ErrorPage = DEFAULT_ERROR;
for (const [self, module] of Object.entries(routes.pages)) {
for (const [self, module] of Object.entries(manifest.routes)) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl)) {
throw new TypeError("Page is not a child of the basepath.");
}
const path = url.substring(baseUrl.length).substring("pages".length);
const path = url.substring(baseUrl.length).substring("routes".length);
const baseRoute = path.substring(1, path.length - extname(path).length);
const name = baseRoute.replace("/", "-");
if (!path.startsWith("/_")) {
@@ -111,7 +112,7 @@ export class ServerContext {
component &&
typeof handler === "object" && handler.GET === undefined
) {
handler.GET = ({ render }) => render!();
handler.GET = ({ render }) => render();
}
const page: Page = {
route,
@@ -119,7 +120,6 @@ export class ServerContext {
name,
component,
handler,
runtimeJS: Boolean(config?.runtimeJS ?? false),
csp: Boolean(config?.csp ?? false),
};
pages.push(page);
@@ -145,7 +145,7 @@ export class ServerContext {
const { default: component, config } = (module as UnknownPageModule);
let { handler } = (module as UnknownPageModule);
if (component && handler === undefined) {
handler = ({ render }) => render!();
handler = ({ render }) => render();
}
notFound = {
@@ -164,7 +164,7 @@ export class ServerContext {
const { default: component, config } = (module as ErrorPageModule);
let { handler } = (module as ErrorPageModule);
if (component && handler === undefined) {
handler = ({ render }) => render!();
handler = ({ render }) => render();
}
error = {
@@ -181,9 +181,21 @@ export class ServerContext {
}
sortRoutes(pages);
for (const [self, module] of Object.entries(manifest.islands)) {
const url = new URL(self, baseUrl).href;
if (!url.startsWith(baseUrl)) {
throw new TypeError("Page is not a child of the basepath.");
}
const path = url.substring(baseUrl.length).substring("islands".length);
const baseRoute = path.substring(1, path.length - extname(path).length);
const name = baseRoute.replace("/", "");
const id = name.toLowerCase();
islands.push({ id, name, url, component: module.default });
}
const staticFiles: StaticFile[] = [];
try {
const staticFolder = new URL("./static", routes.baseUrl);
const staticFolder = new URL("./static", manifest.baseUrl);
// TODO(lucacasonato): remove the extranious Deno.readDir when
// https://github.com/denoland/deno_std/issues/1310 is fixed.
for await (const _ of Deno.readDir(fromFileUrl(staticFolder))) {
@@ -227,6 +239,7 @@ export class ServerContext {
}
return new ServerContext(
pages,
islands,
staticFiles,
renderer,
middleware,
@@ -277,84 +290,67 @@ export class ServerContext {
);
}
const genRender = (page: Page, status: number) => {
const bundlePath = `/${page.name}.js`;
const imports = page.runtimeJS ? [bundleAssetUrl(bundlePath)] : [];
const genRender = <Data = undefined>(
page: Page<Data> | UnknownPage | ErrorPage,
status: number,
) => {
const imports: string[] = [];
if (this.#dev) {
imports.push(REFRESH_JS_URL);
}
return (
req: Request,
params: Record<string, string | string[]>,
params: Record<string, string>,
error?: unknown,
) => {
if (page.component === undefined) return undefined;
return async (renderData?: Record<string, unknown>) => {
const preloads = page.runtimeJS
? this.#bundler.getPreloads(bundlePath).map(bundleAssetUrl)
: [];
const body = internalRender({
page,
app: this.#app,
imports,
preloads,
renderer: this.#renderer,
url: new URL(req.url),
params,
renderData,
error,
});
const headers: Record<string, string> = {
"content-type": "text/html; charset=utf-8",
};
let firstChunk: string;
const iterator = body[Symbol.asyncIterator]();
return (data?: Data) => {
if (page.component === undefined) {
throw new Error("This page does not have a component to render.");
}
const preloads: string[] = [];
let resp;
try {
const { value, done } = await iterator.next();
if (done) throw new Error("Body is empty.");
firstChunk = value[0];
const csp: ContentSecurityPolicy | undefined = value[1];
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;
}
}
resp = internalRender({
page,
islands: this.#islands,
app: this.#app,
imports,
preloads,
renderer: this.#renderer,
url: new URL(req.url),
params,
data,
error,
});
} catch (err) {
console.error("Error rendering page", err);
throw new Response("500 Internal Server Error", {
return new Response("500 Internal Server Error", {
status: 500,
headers: {
"content-type": "text/plain",
},
});
}
const bodyStream = new ReadableStream<Uint8Array>({
async start(controller) {
controller.enqueue(new TextEncoder().encode(firstChunk));
try {
for await (const chunk of body) {
controller.enqueue(new TextEncoder().encode(chunk as string));
}
} catch (err) {
console.log("Rendering failed:\n", err);
controller.enqueue(
new TextEncoder().encode("500 Internal Server Error"),
);
}
controller.close();
},
});
return new Response(bodyStream, { status, headers });
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;
}
}
return new Response(body, { status, headers });
};
};
};
@@ -378,17 +374,16 @@ export class ServerContext {
const unknownHandlerRender = genRender(this.#notFound, 404);
const unknownHandler = (req: Request) =>
(this.#notFound.handler as Handler)({
this.#notFound.handler({
req,
match: {},
render: unknownHandlerRender(req, {}),
});
const errorHandlerRender = genRender(this.#error, 500);
const errorHandler = (req: Request, error: unknown) =>
(this.#notFound.handler as Handler)({
this.#error.handler({
req,
match: {},
error,
render: errorHandlerRender(req, {}, error),
});
@@ -485,10 +480,6 @@ export class ServerContext {
};
}
function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
const DEFAULT_RENDERER: Renderer = {
render(_ctx, render) {
render();
+1 -1
View File
@@ -1,5 +1,5 @@
// -- preact --
export { renderToString } from "https://esm.sh/preact-render-to-string@5.1.19?deps=preact@10.5.14";
export { renderToString } from "https://esm.sh/preact-render-to-string@5.1.20?deps=preact@10.6.6";
// -- std --
export {
+14 -5
View File
@@ -2,26 +2,35 @@ import { ServerContext } from "./context.ts";
import { listenAndServe } from "./deps.ts";
import {
AppModule,
ErrorPageModule,
IslandModule,
MiddlewareModule,
PageModule,
RendererModule,
UnknownPageModule,
} from "./types.ts";
export type { Handler, HandlerContext, Handlers } from "./types.ts";
export { RenderContext } from "./render.tsx";
export type { RenderFn } from "./render.tsx";
export interface Routes {
pages: Record<
export interface Manifest {
routes: Record<
string,
PageModule | RendererModule | MiddlewareModule | AppModule
| PageModule
| RendererModule
| MiddlewareModule
| AppModule
| ErrorPageModule
| UnknownPageModule
>;
islands: Record<string, IslandModule>;
baseUrl: string;
}
export { ServerContext };
export async function start(routes: Routes) {
const ctx = await ServerContext.fromRoutes(routes);
export async function start(routes: Manifest) {
const ctx = await ServerContext.fromManifest(routes);
console.log("Server listening on http://localhost:8000");
await listenAndServe(":8000", ctx.handler());
}
+89 -204
View File
@@ -1,29 +1,35 @@
/** @jsx h */
import { renderToString } from "./deps.ts";
import { ComponentChildren, h } from "../runtime/deps.ts";
import { DATA_CONTEXT } from "../runtime/hooks.ts";
import { AppModule, ErrorPage, Page, Renderer, UnknownPage } from "./types.ts";
import {
ErrorPageProps,
PageProps,
UnknownPageProps,
} from "../runtime/types.ts";
import { SUSPENSE_CONTEXT } from "../runtime/suspense.ts";
ComponentChildren,
ComponentType,
h,
options,
VNode,
} from "../runtime/deps.ts";
import {
AppModule,
ErrorPage,
Island,
Page,
Renderer,
UnknownPage,
} from "./types.ts";
import { HEAD_CONTEXT } from "../runtime/head.ts";
import { REFRESH_JS_URL } from "./constants.ts";
import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
import { ContentSecurityPolicy } from "../runtime/csp.ts";
import { BUILD_ID, INTERNAL_PREFIX, JS_PREFIX } from "./constants.ts";
export interface RenderOptions {
page: Page | UnknownPage | ErrorPage;
export interface RenderOptions<Data> {
page: Page<Data> | UnknownPage | ErrorPage;
islands: Island[];
app: AppModule;
imports: string[];
preloads: string[];
url: URL;
params: Record<string, string | string[]>;
renderer: Renderer;
renderData?: Record<string, unknown>;
data?: Data;
error?: unknown;
}
@@ -87,8 +93,6 @@ export class RenderContext {
}
}
const MAX_SUSPENSE_DEPTH = 10;
function defaultCsp() {
return {
directives: { defaultSrc: [NONE], styleSrc: [UNSAFE_INLINE] },
@@ -118,14 +122,14 @@ function defaultCsp() {
* sent to the client. On the client the HTML will be slotted into the DOM
* at the location of the original `<Suspense>` node.
*/
export async function* render(
opts: RenderOptions,
): AsyncIterable<string | [string, ContentSecurityPolicy | undefined]> {
export function render<Data>(
opts: RenderOptions<Data>,
): [string, ContentSecurityPolicy | undefined] {
const props: Record<string, unknown> = {
params: opts.params,
url: opts.url,
route: opts.page.route,
renderData: opts.renderData,
data: opts.data,
};
if (opts.error) {
props.error = opts.error;
@@ -134,93 +138,48 @@ export async function* render(
const csp: ContentSecurityPolicy | undefined = opts.page.csp
? defaultCsp()
: undefined;
const dataCache = new Map();
const suspenseQueue: ComponentChildren[] = [];
const headComponents: ComponentChildren[] = [];
const vnode = h(CSP_CONTEXT.Provider, {
value: csp,
children: h(HEAD_CONTEXT.Provider, {
value: headComponents,
children: h(DATA_CONTEXT.Provider, {
value: dataCache,
children: h(SUSPENSE_CONTEXT.Provider, {
value: suspenseQueue,
children: h(opts.app.default, {
Component() {
return h(opts.page.component!, props);
},
}),
}),
children: h(opts.app.default, {
Component() {
return h(opts.page.component! as ComponentType<unknown>, props);
},
}),
}),
});
const ctx = new RenderContext(crypto.randomUUID(), opts.url, opts.page.route);
let suspended = 0;
const renderWithRenderer = (): string | Promise<string> => {
if (csp) {
// Clear the csp
const newCsp = defaultCsp();
csp.directives = newCsp.directives;
csp.reportOnly = newCsp.reportOnly;
}
// Clear the suspense queue
suspenseQueue.splice(0, suspenseQueue.length);
// Clear the head components
headComponents.splice(0, headComponents.length);
if (csp) {
// Clear the csp
const newCsp = defaultCsp();
csp.directives = newCsp.directives;
csp.reportOnly = newCsp.reportOnly;
}
// Clear the head components
headComponents.splice(0, headComponents.length);
if (++suspended > MAX_SUSPENSE_DEPTH) {
throw new Error(
`Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`,
);
}
// Setup the interesting VNode types
ISLANDS.splice(0, ISLANDS.length, ...opts.islands);
let body: string | null = null;
let promise: Promise<unknown> | null = null;
// Clear the encountered vnodes
ENCOUNTERED_ISLANDS.clear();
function render() {
try {
body = renderToString(vnode);
return body;
} catch (e) {
if (e && e.then) {
promise = e;
return "";
}
throw e;
}
}
let bodyHtml: string | null = null;
opts.renderer.render(ctx, render);
if (body !== null) {
return body;
} else if (promise !== null) {
return (promise as Promise<unknown>).then(renderWithRenderer);
} else {
throw new Error("`render` function not called by renderer.");
}
};
const bodyHtml = await renderWithRenderer();
let templateProps: {
props: PageProps | UnknownPageProps | ErrorPageProps;
data?: [string, unknown][];
} | undefined = { props, data: [...dataCache.entries()] };
if (templateProps.data!.length === 0) {
delete templateProps.data;
function render() {
bodyHtml = renderToString(vnode);
return bodyHtml;
}
// If this is a static render (runtimeJS is false), then we don't need to
// render the props into the template.
if (
opts.imports.length === 0 ||
(opts.imports.length === 1 && opts.imports[0] === REFRESH_JS_URL)
) {
templateProps = undefined;
opts.renderer.render(ctx, render);
if (bodyHtml === null) {
throw new Error("`render` function not called by renderer.");
}
const imports = opts.imports.map((url) => {
@@ -234,120 +193,32 @@ export async function* render(
return [url, randomNonce] as const;
});
for (const island of ENCOUNTERED_ISLANDS) {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
const url = bundleAssetUrl(`/${island.id}.js`);
imports.push([url, randomNonce] as const);
}
const html = template({
bodyHtml,
headComponents,
imports,
preloads: opts.preloads,
styles: ctx.styles,
props: templateProps,
lang: ctx.lang,
});
const suspenseNonces = suspenseQueue.map(() => {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
return randomNonce;
});
let suspenseScript = "";
if (suspenseQueue.length > 0) {
const randomNonce = crypto.randomUUID().replace(/-/g, "");
if (csp) {
csp.directives.scriptSrc = [
...csp.directives.scriptSrc ?? [],
nonce(randomNonce),
];
}
// minified client-side JS
suspenseScript = '<script nonce="' + randomNonce +
'">(()=>{window.$SR=t=>{const e=document.getElementById("S:"+t),o=document.getElementById("E:"+t),d=document.getElementById("R:"+t);for(d.parentNode.removeChild(d);e.nextSibling!==o;)e.parentNode.removeChild(e.nextSibling);for(;d.firstChild;)e.parentNode.insertBefore(d.firstChild,o);e.parentNode.removeChild(e),o.parentNode.removeChild(o)};const n=document.getElementById("__FRSH_STYLE"),r=n.childNodes[0]?.textContent.split(`\n`);if(r!==void 0){n.removeChild(n.firstChild);for(const t of r)n.append(document.createTextNode(t))}window.$ST=t=>{for(const[e,o]of t)n.insertBefore(document.createTextNode(e),n.childNodes[o])}})();\n</script>';
}
let clientStyles = [...ctx.styles];
yield [html + suspenseScript, csp];
// TODO(lucacasonato): parallelize this
for (const [id, children] of suspenseQueue.entries()) {
let [fragment, script] = await suspenseRender(
opts.renderer,
ctx,
id + 1,
children,
);
const cssInserts: [string, number][] = [];
for (const [i, style] of ctx.styles.entries()) {
if (!clientStyles.includes(style)) {
cssInserts.push([style, i]);
}
}
clientStyles = [...ctx.styles];
if (cssInserts.length > 0) {
script = `$ST(${JSON.stringify(cssInserts)});\n${script};`;
}
yield `${fragment}<script nonce="${suspenseNonces[id]}">${script}</script>`;
}
return [html, csp];
}
export async function suspenseRender(
renderer: Renderer,
ctx: RenderContext,
id: number,
children: ComponentChildren,
): Promise<[string, string]> {
const dataCache = new Map();
const vnode = h(DATA_CONTEXT.Provider, {
value: dataCache,
children,
});
let suspended = 0;
const renderWithRenderer = (): string | Promise<string> => {
if (++suspended > MAX_SUSPENSE_DEPTH) {
throw new Error(
`Reached maximum suspense depth of ${MAX_SUSPENSE_DEPTH}.`,
);
}
let body: string | null = null;
let promise: Promise<unknown> | null = null;
function render() {
try {
body = renderToString(vnode);
return body;
} catch (e) {
if (e && e.then) {
promise = e;
return "";
}
throw e;
}
}
renderer.render(ctx, render);
if (body !== null) {
return body;
} else if (promise !== null) {
return (promise as Promise<unknown>).then(renderWithRenderer);
} else {
throw new Error("`render` function not called by renderer.");
}
};
const html = await renderWithRenderer();
return [`<div hidden id="R:${id}">${html}</div>`, `$SR(${id});`];
function bundleAssetUrl(path: string) {
return `${INTERNAL_PREFIX}${JS_PREFIX}/${BUILD_ID}${path}`;
}
export interface TemplateOptions {
@@ -356,7 +227,6 @@ export interface TemplateOptions {
imports: (readonly [string, string])[];
styles: string[];
preloads: string[];
props: unknown;
lang: string;
}
@@ -377,20 +247,35 @@ export function template(opts: TemplateOptions): string {
/>
{opts.headComponents}
</head>
<body>
<div dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} id="__FRSH" />
{opts.props !== undefined
? (
<script
id="__FRSH_PROPS"
type="application/json"
dangerouslySetInnerHTML={{ __html: JSON.stringify(opts.props) }}
/>
)
: null}
</body>
<body dangerouslySetInnerHTML={{ __html: opts.bodyHtml }} />
</html>
);
return "<!DOCTYPE html>" + renderToString(page);
}
// Set up a preact option hook to track when vnode with custom functions are
// created.
const ISLANDS: Island[] = [];
const ENCOUNTERED_ISLANDS: Set<Island> = new Set([]);
const originalHook = options.vnode;
let ignoreNext = false;
options.vnode = (vnode) => {
const originalType = vnode.type as ComponentType<unknown>;
if (typeof vnode.type === "function") {
const island = ISLANDS.find((island) => island.component === originalType);
if (island) {
if (ignoreNext) {
ignoreNext = false;
return;
}
ENCOUNTERED_ISLANDS.add(island);
vnode.type = (props) => {
ignoreNext = true;
const child = h(originalType, props);
return h(`frsh-${island.id}`, { props: JSON.stringify(props) }, child);
};
}
}
if (originalHook) originalHook(vnode);
};
+27 -11
View File
@@ -27,24 +27,32 @@ export interface ErrorPageModule {
config?: PageConfig;
}
export interface HandlerContext {
export interface IslandModule {
// deno-lint-ignore no-explicit-any
default: ComponentType<any>;
}
export interface HandlerContext<T = unknown> {
req: Request;
match: Record<string, string>;
render?: (args?: Record<string, unknown>) => Promise<Response>;
render: (data?: T) => Response;
}
export interface UnknownHandlerContext {
req: Request;
render?: () => Promise<Response>;
render: () => Response;
}
export interface ErrorHandlerContext {
req: Request;
error: unknown;
render?: () => Promise<Response>;
render: () => Response;
}
export type Handler = (ctx: HandlerContext) => Response | Promise<Response>;
// deno-lint-ignore no-explicit-any
export type Handler<T = any> = (
ctx: HandlerContext<T>,
) => Response | Promise<Response>;
export type UnknownHandler = (
ctx: UnknownHandlerContext,
) => Response | Promise<Response>;
@@ -52,17 +60,18 @@ export type ErrorHandler = (
ctx: ErrorHandlerContext,
) => Response | Promise<Response>;
export type Handlers = {
[K in typeof router.METHODS[number]]?: Handler;
// deno-lint-ignore no-explicit-any
export type Handlers<T = any> = {
[K in typeof router.METHODS[number]]?: Handler<T>;
};
export interface Page {
// deno-lint-ignore no-explicit-any
export interface Page<Data = any> {
route: string;
url: string;
name: string;
component?: ComponentType<PageProps>;
handler: Handler | Handlers;
runtimeJS: boolean;
component?: ComponentType<PageProps<Data>>;
handler: Handler<Data> | Handlers<Data>;
csp: boolean;
}
@@ -111,3 +120,10 @@ export interface Middleware {
export interface AppModule {
default: ComponentType<AppProps>;
}
export interface Island {
id: string;
name: string;
url: string;
component: ComponentType<unknown>;
}