diff --git a/src/server/context.ts b/src/server/context.ts
index ff5568ba..b8eff35f 100644
--- a/src/server/context.ts
+++ b/src/server/context.ts
@@ -54,6 +54,7 @@ import {
JSXConfig,
} from "../build/mod.ts";
import { InternalRoute } from "./router.ts";
+import { setAllIslands } from "./rendering/preact_hooks.ts";
const DEFAULT_CONN_INFO: ServeHandlerInfo = {
localAddr: { transport: "tcp", hostname: "localhost", port: 8080 },
@@ -670,6 +671,9 @@ export class ServerContext {
};
}
+ // Tell renderer about all globally available islands
+ setAllIslands(this.#islands);
+
const dependenciesFn = (path: string) => {
const snapshot = this.#maybeBuildSnapshot();
return snapshot?.dependencies(path) ?? [];
@@ -700,7 +704,6 @@ export class ServerContext {
request: req,
context: ctx,
route: notFound,
- islands: this.#islands,
plugins: this.#plugins,
app: this.#app,
layouts,
@@ -755,7 +758,6 @@ export class ServerContext {
},
},
route,
- islands: this.#islands,
plugins: this.#plugins,
app: this.#app,
layouts,
diff --git a/src/server/render.ts b/src/server/render.ts
index 26ab547e..41765918 100644
--- a/src/server/render.ts
+++ b/src/server/render.ts
@@ -1,86 +1,33 @@
-import { renderToString } from "preact-render-to-string";
-import {
- Component,
- ComponentChildren,
- ComponentType,
- Fragment,
- h,
- Options as PreactOptions,
- options as preactOptions,
- VNode,
-} from "preact";
+import { h, VNode } from "preact";
import {
AppModule,
AsyncLayout,
AsyncRoute,
ErrorPage,
- Island,
LayoutRoute,
Plugin,
PluginRenderFunctionResult,
PluginRenderResult,
- PluginRenderStyleTag,
RenderFunction,
Route,
RouteContext,
UnknownPage,
} from "./types.ts";
-import { HEAD_CONTEXT } from "../runtime/head.ts";
-import { CSP_CONTEXT, nonce, NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
+import { NONE, UNSAFE_INLINE } from "../runtime/csp.ts";
import { ContentSecurityPolicy } from "../runtime/csp.ts";
-import { bundleAssetUrl } from "./constants.ts";
-import { assetHashingHook } from "../runtime/utils.ts";
-import { htmlEscapeJsonString } from "./htmlescape.ts";
-import { serialize } from "./serializer.ts";
+import { RenderState } from "./rendering/state.ts";
+import { renderHtml, renderOuterDocument } from "./rendering/template.tsx";
+import { renderFreshTags } from "./rendering/fresh_tags.tsx";
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 {
- /** Attach a hook that is invoked after a tree was mounted or was updated. */
- __c?(vnode: VNode, commitQueue: Component[]): void;
- /** Attach a hook that is invoked before a vnode has rendered. */
- __r?(vnode: VNode): void;
- errorBoundaries?: boolean;
- /** before diff hook */
- __b?(vnode: VNode): void;
-}
-const options = preactOptions as AdvancedPreactOptions;
-
-// Enable error boundaries in Preact.
-options.errorBoundaries = true;
-
-// These values keep track of whether the user rendered the ,
-//
and element. Basically, the outer document. We
-// keep track of this, because we only know the full sets of
-// elements we should put in `` after having completed
-// rendering the page.
-let RENDERING_USER_TEMPLATE = false;
-interface OuterDocument {
- // deno-lint-ignore no-explicit-any
- title: VNode | null;
- html: Record | null;
- head: Record | null;
- body: Record | null;
- headNodes: { type: string; props: Record }[];
-}
-let OUTER_DOCUMENT: OuterDocument = {
- title: null,
- html: null,
- head: null,
- body: null,
- headNodes: [],
-};
-
export interface RenderOptions {
request: Request;
// deno-lint-ignore no-explicit-any
context: any;
route: Route | UnknownPage | ErrorPage;
- islands: Island[];
plugins: Plugin[];
app: AppModule;
layouts: LayoutRoute[];
@@ -210,37 +157,12 @@ export async function render(
const csp: ContentSecurityPolicy | undefined = opts.route.csp
? defaultCsp()
: undefined;
- const headComponents: ComponentChildren[] = [];
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);
-
- // Setup the interesting VNode types
- ISLANDS.splice(0, ISLANDS.length, ...opts.islands);
-
- // Clear the encountered vnodes
- ENCOUNTERED_ISLANDS.clear();
-
- // Clear the island props
- ISLAND_PROPS = [];
- // Clear previous slots
- SLOTS_TRACKER.clear();
-
- // Clear rendering state
- RENDERING_USER_TEMPLATE = false;
- headChildren = false;
- OUTER_DOCUMENT = {
- title: null,
- body: null,
- head: null,
- html: null,
- headNodes: [],
- };
const ctx = new RenderContext(
crypto.randomUUID(),
@@ -308,47 +230,22 @@ export async function render(
}
}
- function render() {
- const routeComponent = componentStack[componentStack.length - 1];
- let finalComp = h(routeComponent, props);
-
- // Skip page component
- let i = componentStack.length - 1;
- while (i--) {
- const component = componentStack[i];
- const curComp = finalComp;
-
- finalComp = h(component, {
- // @ts-ignore weird jsx types
- params: opts.params as Record,
- url: opts.url,
- route: opts.route.pattern,
- data: opts.data,
- state: opts.state!,
- Component() {
- return curComp;
- },
- });
- }
-
- const app = h(CSP_CONTEXT.Provider, {
- value: csp,
- children: h(HEAD_CONTEXT.Provider, {
- value: headComponents,
- children: finalComp,
- }),
- });
-
- let html = renderToString(app);
-
- for (const [id, children] of SLOTS_TRACKER.entries()) {
- const slotHtml = renderToString(h(Fragment, null, children));
- const templateId = id.replace(/:/g, "-");
- html += `${slotHtml}`;
- }
-
- return html;
- }
+ // CAREFUL: Rendering is synchronous internally and all state
+ // should be managed through the `RenderState` instance. That
+ // ensures that each render request is associated with the same
+ // data.
+ const renderState = new RenderState(
+ {
+ url: opts.url,
+ route: opts.route.pattern,
+ data: opts.data,
+ state: opts.state,
+ params: opts.params,
+ },
+ componentStack,
+ csp,
+ opts.error,
+ );
let bodyHtml: string | null = null;
@@ -367,7 +264,7 @@ export async function render(
}
renderResults.push([plugin, res]);
} else {
- bodyHtml = render();
+ bodyHtml = renderHtml(renderState);
}
if (bodyHtml === null) {
throw new Error(
@@ -376,7 +273,7 @@ export async function render(
}
return {
htmlText: bodyHtml,
- requiresHydration: ENCOUNTERED_ISLANDS.size > 0,
+ requiresHydration: renderState.encounteredIslands.size > 0,
};
}
@@ -409,401 +306,46 @@ export async function render(
}
return {
htmlText: bodyHtml,
- requiresHydration: ENCOUNTERED_ISLANDS.size > 0,
+ requiresHydration: renderState.encounteredIslands.size > 0,
};
}
- RENDERING_USER_TEMPLATE = true;
await renderAsync();
- RENDERING_USER_TEMPLATE = false;
- const idx = headComponents.findIndex((vnode) =>
+ const idx = renderState.headVNodes.findIndex((vnode) =>
vnode !== null && typeof vnode === "object" && "type" in vnode &&
props !== null && vnode.type === "title"
);
if (idx !== -1) {
- OUTER_DOCUMENT.title = headComponents[idx] as VNode<{ children: string }>;
- headComponents.splice(idx, 1);
+ renderState.docTitle = renderState.headVNodes[idx] as VNode<
+ { children: string }
+ >;
+ renderState.headVNodes.splice(idx, 1);
}
if (asyncRenderResponse !== undefined) {
return asyncRenderResponse;
}
+ // Includes everything inside ``
bodyHtml = bodyHtml as unknown as string;
- let randomNonce: undefined | string;
- function getRandomNonce(): string {
- if (randomNonce === undefined) {
- randomNonce = crypto.randomUUID().replace(/-/g, "");
- if (csp) {
- csp.directives.scriptSrc = [
- ...csp.directives.scriptSrc ?? [],
- nonce(randomNonce),
- ];
- }
- }
- return randomNonce;
- }
-
- const moduleScripts: [string, string][] = [];
- for (const url of opts.imports) {
- moduleScripts.push([url, getRandomNonce()]);
- }
-
- const preloadSet = new Set();
- function addImport(path: string): string {
- const url = bundleAssetUrl(`/${path}`);
- preloadSet.add(url);
- for (const depPath of opts.dependenciesFn(path)) {
- const url = bundleAssetUrl(`/${depPath}`);
- preloadSet.add(url);
- }
- return url;
- }
-
- const state: [islands: unknown[], plugins: unknown[]] = [ISLAND_PROPS, []];
- const styleTags: PluginRenderStyleTag[] = [];
- const pluginScripts: [string, string, number][] = [];
-
- for (const [plugin, res] of renderResults) {
- for (const hydrate of res.scripts ?? []) {
- const i = state[1].push(hydrate.state) - 1;
- pluginScripts.push([plugin.name, hydrate.entrypoint, i]);
- }
- styleTags.splice(styleTags.length, 0, ...res.styles ?? []);
- }
-
- // The inline script that will hydrate the page.
- let script = "";
-
- // Serialize the state into the `;
-
- if (res.requiresDeserializer) {
- const url = addImport("deserializer.js");
- script += `import { deserialize } from "${url}";`;
- }
- if (res.hasSignals) {
- const url = addImport("signals.js");
- script += `import { signal } from "${url}";`;
- }
- script += `const ST = document.getElementById("__FRSH_STATE").textContent;`;
- script += `const STATE = `;
- if (res.requiresDeserializer) {
- if (res.hasSignals) {
- script += `deserialize(ST, signal);`;
- } else {
- script += `deserialize(ST);`;
- }
- } else {
- script += `JSON.parse(ST).v;`;
- }
- }
-
- // Then it imports all plugin scripts and executes them (with their respective
- // state).
- for (const [pluginName, entrypoint, i] of pluginScripts) {
- const url = addImport(`plugin-${pluginName}-${entrypoint}.js`);
- script += `import p${i} from "${url}";p${i}(STATE[1][${i}]);`;
- }
-
- // Finally, it loads all island scripts and hydrates the islands using the
- // reviver from the "main" script.
- if (ENCOUNTERED_ISLANDS.size > 0) {
- // Load the main.js script
- const url = addImport("main.js");
- script += `import { revive } from "${url}";`;
-
- // Prepare the inline script that loads and revives the islands
- let islandRegistry = "";
- for (const island of ENCOUNTERED_ISLANDS) {
- const url = addImport(`island-${island.id}.js`);
- script +=
- `import * as ${island.name}_${island.exportName} from "${url}";`;
- islandRegistry += `${island.id}:${island.name}_${island.exportName},`;
- }
- script += `revive({${islandRegistry}}, STATE[0]);`;
- }
-
- // Append the inline script.
- if (script !== "") {
- bodyHtml +=
- ``;
- }
-
- if (ctx.styles.length > 0) {
- const node = h("style", {
- id: "__FRSH_STYLE",
- dangerouslySetInnerHTML: { __html: ctx.styles.join("\n") },
- });
- headComponents.splice(0, 0, node);
- }
-
- for (const style of styleTags) {
- const node = h("style", {
- id: style.id,
- dangerouslySetInnerHTML: { __html: style.cssText },
- media: style.media,
- });
- headComponents.splice(0, 0, node);
- }
-
- const preloads = [...preloadSet];
-
- const page = h(
- "html",
- OUTER_DOCUMENT.html ?? { lang: ctx.lang },
- h(
- "head",
- OUTER_DOCUMENT.head,
- // Add some tags ourselves if the user uses the legacy
- // _app template rendering style where we provided the outer
- // HTML document.
- !renderedHtmlTag ? h("meta", { charSet: "UTF-8" }) : null,
- !renderedHtmlTag
- ? h("meta", {
- name: "viewport",
- content: "width=device-width, initial-scale=1.0",
- })
- : null,
- OUTER_DOCUMENT.title,
- OUTER_DOCUMENT.headNodes.map((node) => h(node.type, node.props)),
- // Fresh scripts
- preloads.map((src) => h("link", { rel: "modulepreload", href: src })),
- moduleScripts.map(([src, nonce]) =>
- h("script", { src: src, nonce: nonce, type: "module" })
- ),
- headComponents,
- ),
- h("body", { dangerouslySetInnerHTML: { __html: bodyHtml } }),
- );
- const html = "" + renderToString(page);
+ // Create Fresh script + style tags
+ const result = renderFreshTags(renderState, {
+ bodyHtml,
+ imports: opts.imports,
+ csp,
+ dependenciesFn: opts.dependenciesFn,
+ styles: ctx.styles,
+ pluginRenderResults: renderResults,
+ });
+ // Render outer document up to ``
+ const html = renderOuterDocument(renderState, {
+ bodyHtml: result.bodyHtml,
+ preloads: [...result.preloadSet],
+ moduleScripts: result.moduleScripts,
+ lang: ctx.lang,
+ });
return [html, csp];
}
-
-const supportsUnstableComments = renderToString(h(Fragment, {
- // @ts-ignore unstable features not supported in types
- UNSTABLE_comment: "foo",
-})) !== "";
-
-if (!supportsUnstableComments) {
- console.warn(
- "⚠️ Found old version of 'preact-render-to-string'. Please upgrade it to >=6.1.0",
- );
-}
-
-function wrapWithMarker(vnode: ComponentChildren, markerText: string) {
- // Newer versions of preact-render-to-string allow you to render comments
- if (supportsUnstableComments) {
- return h(
- Fragment,
- null,
- h(Fragment, {
- // @ts-ignore unstable property is not typed
- UNSTABLE_comment: markerText,
- }),
- vnode,
- h(Fragment, {
- // @ts-ignore unstable property is not typed
- UNSTABLE_comment: "/" + markerText,
- }),
- );
- } else {
- return h(
- `!--${markerText}--`,
- null,
- vnode,
- );
- }
-}
-
-// Set up a preact option hook to track when vnode with custom functions are
-// created.
-const ISLANDS: Island[] = [];
-const ENCOUNTERED_ISLANDS: Set = new Set([]);
-let ISLAND_PROPS: unknown[] = [];
-// Track unused slots
-const SLOTS_TRACKER = new Map();
-function SlotTracker(
- props: { id: string; children?: ComponentChildren },
-): VNode {
- SLOTS_TRACKER.delete(props.id);
- // deno-lint-ignore no-explicit-any
- return props.children as any;
-}
-
-// Keep track of which component rendered which vnode. This allows us
-// to detect when an island is rendered within another instead of being
-// passed as children.
-let ownerStack: VNode[] = [];
-const islandOwners = new Map();
-
-const originalHook = options.vnode;
-let ignoreNext = false;
-let headChildren = false;
-let renderedHtmlTag = false;
-options.vnode = (vnode) => {
- assetHashingHook(vnode);
- const originalType = vnode.type as ComponentType;
-
- // Use a labelled statement that allows ous to break out of it
- // whilst still continuing execution. We still want to call previous
- // `options.vnode` hooks if there were any, otherwise we'd break
- // the change for other plugins hooking into Preact.
- patchIslands:
- if (typeof vnode.type === "function") {
- const island = ISLANDS.find((island) => island.component === originalType);
- if (island) {
- const hasOwners = ownerStack.length > 0;
- if (hasOwners) {
- const prevOwner = ownerStack[ownerStack.length - 1];
- islandOwners.set(vnode, prevOwner);
- }
-
- // Check if we already patched this component
- if (ignoreNext) {
- ignoreNext = false;
- break patchIslands;
- }
-
- // Check if an island is rendered inside another island, not just
- // passed as a child. Example:
- // function Island() {}
- // return
- // }
- if (hasOwners) {
- const prevOwner = ownerStack[ownerStack.length - 1];
- if (islandOwners.has(prevOwner)) {
- break patchIslands;
- }
- }
-
- ENCOUNTERED_ISLANDS.add(island);
- vnode.type = (props) => {
- ignoreNext = true;
-
- const id = ISLAND_PROPS.length;
-
- // Only passing children JSX to islands is supported for now
- if ("children" in props) {
- let children = props.children;
- const markerText =
- `frsh-slot-${island.id}:${island.exportName}:${id}:children`;
- // @ts-ignore nonono
- props.children = wrapWithMarker(
- children,
- markerText,
- );
- SLOTS_TRACKER.set(markerText, children);
- children = props.children;
- // deno-lint-ignore no-explicit-any
- (props as any).children = h(
- SlotTracker,
- { id: markerText },
- children,
- );
- }
-
- const child = h(originalType, props);
- ISLAND_PROPS.push(props);
-
- return wrapWithMarker(
- child,
- `frsh-${island.id}:${island.exportName}:${ISLAND_PROPS.length - 1}`,
- );
- };
- }
- } else {
- // Work around `preact/debug` string event handler error which
- // errors when an event handler gets a string. This makes sense
- // on the client where this is a common vector for XSS. On the
- // server when the string was not created through concatenation
- // it is fine. Internally, `preact/debug` only checks for the
- // lowercase variant.
- const props = vnode.props as Record;
- for (const key in props) {
- const value = props[key];
- if (key.startsWith("on") && typeof value === "string") {
- delete props[key];
- props["ON" + key.slice(2)] = value;
- }
- }
- }
-
- if (originalHook) originalHook(vnode);
-};
-
-function excludeChildren(props: Record) {
- const out: Record = {};
- for (const k in props) {
- if (k !== "children") out[k] = props[k];
- }
- return out;
-}
-
-// Keep track of owners
-const oldDiff = options.__b;
-const oldDiffed = options.diffed;
-const oldRender = options.__r;
-const oldCommit = options.__c;
-options.__b = (vnode: VNode>) => {
- if (RENDERING_USER_TEMPLATE && typeof vnode.type === "string") {
- if (vnode.type === "html") {
- renderedHtmlTag = true;
- OUTER_DOCUMENT.html = excludeChildren(vnode.props);
- vnode.type = Fragment;
- } else if (vnode.type === "head") {
- OUTER_DOCUMENT.head = excludeChildren(vnode.props);
- headChildren = true;
- vnode.type = Fragment;
- vnode.props = {
- __freshHead: true,
- children: vnode.props.children,
- };
- } else if (vnode.type === "body") {
- OUTER_DOCUMENT.body = excludeChildren(vnode.props);
- vnode.type = Fragment;
- } else if (headChildren) {
- if (vnode.type === "title") {
- OUTER_DOCUMENT.title = h("title", vnode.props);
- vnode.props = { children: null };
- } else {
- OUTER_DOCUMENT.headNodes.push({ type: vnode.type, props: vnode.props });
- }
- vnode.type = Fragment;
- }
- }
- oldDiff?.(vnode);
-};
-options.__r = (vnode) => {
- if (
- typeof vnode.type === "function" &&
- vnode.type !== Fragment
- ) {
- ownerStack.push(vnode);
- }
- oldRender?.(vnode);
-};
-options.diffed = (vnode: VNode>) => {
- if (typeof vnode.type === "function") {
- if (vnode.type !== Fragment) {
- ownerStack.pop();
- } else if (vnode.props.__freshHead) {
- headChildren = false;
- }
- }
- oldDiffed?.(vnode);
-};
-options.__c = (vnode, queue) => {
- oldCommit?.(vnode, queue);
- ownerStack = [];
- islandOwners.clear();
-};
diff --git a/src/server/rendering/fresh_tags.tsx b/src/server/rendering/fresh_tags.tsx
new file mode 100644
index 00000000..56685511
--- /dev/null
+++ b/src/server/rendering/fresh_tags.tsx
@@ -0,0 +1,151 @@
+import { bundleAssetUrl } from "../constants.ts";
+import { RenderState } from "./state.ts";
+import { htmlEscapeJsonString } from "../htmlescape.ts";
+import { serialize } from "../serializer.ts";
+import { Plugin, PluginRenderResult, PluginRenderStyleTag } from "../types.ts";
+import { ContentSecurityPolicy, nonce } from "../../runtime/csp.ts";
+import { h } from "preact";
+
+function getRandomNonce(
+ opts: { randomNonce?: string; csp?: ContentSecurityPolicy },
+): string {
+ if (opts.randomNonce === undefined) {
+ opts.randomNonce = crypto.randomUUID().replace(/-/g, "");
+ if (opts.csp) {
+ opts.csp.directives.scriptSrc = [
+ ...opts.csp.directives.scriptSrc ?? [],
+ nonce(opts.randomNonce),
+ ];
+ }
+ }
+ return opts.randomNonce;
+}
+
+export function renderFreshTags(
+ renderState: RenderState,
+ opts: {
+ bodyHtml: string;
+ csp?: ContentSecurityPolicy;
+ imports: string[];
+ randomNonce?: string;
+ dependenciesFn: (path: string) => string[];
+ styles: string[];
+ pluginRenderResults: [Plugin, PluginRenderResult][];
+ },
+) {
+ const moduleScripts: [string, string][] = [];
+ for (const url of opts.imports) {
+ moduleScripts.push([url, getRandomNonce(opts)]);
+ }
+
+ const preloadSet = new Set();
+ function addImport(path: string): string {
+ const url = bundleAssetUrl(`/${path}`);
+ preloadSet.add(url);
+ for (const depPath of opts.dependenciesFn(path)) {
+ const url = bundleAssetUrl(`/${depPath}`);
+ preloadSet.add(url);
+ }
+ return url;
+ }
+
+ const state: [islands: unknown[], plugins: unknown[]] = [
+ renderState.islandProps,
+ [],
+ ];
+ const styleTags: PluginRenderStyleTag[] = [];
+ const pluginScripts: [string, string, number][] = [];
+
+ for (const [plugin, res] of opts.pluginRenderResults) {
+ for (const hydrate of res.scripts ?? []) {
+ const i = state[1].push(hydrate.state) - 1;
+ pluginScripts.push([plugin.name, hydrate.entrypoint, i]);
+ }
+ styleTags.splice(styleTags.length, 0, ...res.styles ?? []);
+ }
+
+ // The inline script that will hydrate the page.
+ let script = "";
+
+ // Serialize the state into the `;
+
+ if (res.requiresDeserializer) {
+ const url = addImport("deserializer.js");
+ script += `import { deserialize } from "${url}";`;
+ }
+ if (res.hasSignals) {
+ const url = addImport("signals.js");
+ script += `import { signal } from "${url}";`;
+ }
+ script += `const ST = document.getElementById("__FRSH_STATE").textContent;`;
+ script += `const STATE = `;
+ if (res.requiresDeserializer) {
+ if (res.hasSignals) {
+ script += `deserialize(ST, signal);`;
+ } else {
+ script += `deserialize(ST);`;
+ }
+ } else {
+ script += `JSON.parse(ST).v;`;
+ }
+ }
+
+ // Then it imports all plugin scripts and executes them (with their respective
+ // state).
+ for (const [pluginName, entrypoint, i] of pluginScripts) {
+ const url = addImport(`plugin-${pluginName}-${entrypoint}.js`);
+ script += `import p${i} from "${url}";p${i}(STATE[1][${i}]);`;
+ }
+
+ // Finally, it loads all island scripts and hydrates the islands using the
+ // reviver from the "main" script.
+ if (renderState.encounteredIslands.size > 0) {
+ // Load the main.js script
+ const url = addImport("main.js");
+ script += `import { revive } from "${url}";`;
+
+ // Prepare the inline script that loads and revives the islands
+ let islandRegistry = "";
+ for (const island of renderState.encounteredIslands) {
+ const url = addImport(`island-${island.id}.js`);
+ script +=
+ `import * as ${island.name}_${island.exportName} from "${url}";`;
+ islandRegistry += `${island.id}:${island.name}_${island.exportName},`;
+ }
+ script += `revive({${islandRegistry}}, STATE[0]);`;
+ }
+
+ // Append the inline script.
+ if (script !== "") {
+ opts.bodyHtml += ``;
+ }
+
+ if (opts.styles.length > 0) {
+ const node = h("style", {
+ id: "__FRSH_STYLE",
+ dangerouslySetInnerHTML: { __html: opts.styles.join("\n") },
+ });
+
+ renderState.headVNodes.splice(0, 0, node);
+ }
+
+ for (const style of styleTags) {
+ const node = h("style", {
+ id: style.id,
+ media: style.media,
+ dangerouslySetInnerHTML: { __html: style.cssText },
+ });
+ renderState.headVNodes.splice(0, 0, node);
+ }
+
+ return { bodyHtml: opts.bodyHtml, preloadSet, moduleScripts };
+}
diff --git a/src/server/rendering/preact_hooks.ts b/src/server/rendering/preact_hooks.ts
new file mode 100644
index 00000000..9b0f6626
--- /dev/null
+++ b/src/server/rendering/preact_hooks.ts
@@ -0,0 +1,287 @@
+import {
+ Component,
+ type ComponentChildren,
+ Fragment,
+ h,
+ type Options as PreactOptions,
+ options as preactOptions,
+ type VNode,
+} from "preact";
+import { assetHashingHook } from "../../runtime/utils.ts";
+import { renderToString } from "preact-render-to-string";
+import { RenderState } from "./state.ts";
+import { Island } from "../types.ts";
+
+// These hooks are long stable, but when we originally added them we
+// weren't sure if they should be public.
+interface AdvancedPreactOptions extends PreactOptions {
+ /** Attach a hook that is invoked after a tree was mounted or was updated. */
+ __c?(vnode: VNode, commitQueue: Component[]): void;
+ /** Attach a hook that is invoked before a vnode has rendered. */
+ __r?(vnode: VNode): void;
+ errorBoundaries?: boolean;
+ /** before diff hook */
+ __b?(vnode: VNode): void;
+}
+const options = preactOptions as AdvancedPreactOptions;
+
+// Enable error boundaries in Preact.
+options.errorBoundaries = true;
+
+// Set up a preact option hook to track when vnode with custom functions are
+// created.
+let current: RenderState | null = null;
+// Keep track of which component rendered which vnode. This allows us
+// to detect when an island is rendered within another instead of being
+// passed as children.
+let ownerStack: VNode[] = [];
+// Keep track of all available islands
+const islandByComponent = new Map();
+export function setAllIslands(islands: Island[]) {
+ for (let i = 0; i < islands.length; i++) {
+ const island = islands[i];
+ islandByComponent.set(island.component, island);
+ }
+}
+
+export function setRenderState(state: RenderState | null): void {
+ if (current) current.clearTmpState();
+ current = state;
+ ownerStack = state?.ownerStack ?? [];
+}
+
+// Check if an older version of `preact-render-to-string` is used
+const supportsUnstableComments = renderToString(h(Fragment, {
+ // @ts-ignore unstable features not supported in types
+ UNSTABLE_comment: "foo",
+})) !== "";
+
+if (!supportsUnstableComments) {
+ console.warn(
+ "⚠️ Found old version of 'preact-render-to-string'. Please upgrade it to >=6.1.0",
+ );
+}
+
+/**
+ * Wrap a node with comment markers in the HTML
+ */
+function wrapWithMarker(vnode: ComponentChildren, markerText: string) {
+ // Newer versions of preact-render-to-string allow you to render comments
+ if (supportsUnstableComments) {
+ return h(
+ Fragment,
+ null,
+ h(Fragment, {
+ // @ts-ignore unstable property is not typed
+ UNSTABLE_comment: markerText,
+ }),
+ vnode,
+ h(Fragment, {
+ // @ts-ignore unstable property is not typed
+ UNSTABLE_comment: "/" + markerText,
+ }),
+ );
+ } else {
+ return h(
+ `!--${markerText}--`,
+ null,
+ vnode,
+ );
+ }
+}
+
+/**
+ * Whenever a slot (=jsx children) is rendered, remove this from the slot
+ * tracking Set. After everything was rendered we'll know which slots
+ * weren't and can send them down to the client
+ */
+function SlotTracker(
+ props: { id: string; children?: ComponentChildren },
+): VNode {
+ current?.slots.delete(props.id);
+ // deno-lint-ignore no-explicit-any
+ return props.children as any;
+}
+
+/**
+ * Copy props but exclude children
+ */
+function excludeChildren(props: Record) {
+ const out: Record = {};
+ for (const k in props) {
+ if (k !== "children") out[k] = props[k];
+ }
+ return out;
+}
+
+const patched = new WeakSet();
+
+const oldVNodeHook = options.vnode;
+const oldDiff = options.__b;
+const oldDiffed = options.diffed;
+const oldRender = options.__r;
+
+options.vnode = (vnode) => {
+ assetHashingHook(vnode);
+
+ // Work around `preact/debug` string event handler error which
+ // errors when an event handler gets a string. This makes sense
+ // on the client where this is a common vector for XSS. On the
+ // server when the string was not created through concatenation
+ // it is fine. Internally, `preact/debug` only checks for the
+ // lowercase variant.
+ if (typeof vnode.type === "string") {
+ const props = vnode.props as Record;
+ for (const key in props) {
+ const value = props[key];
+ if (key.startsWith("on") && typeof value === "string") {
+ delete props[key];
+ props["ON" + key.slice(2)] = value;
+ }
+ }
+ } else if (
+ current && typeof vnode.type === "function" && vnode.type !== Fragment &&
+ ownerStack.length > 0
+ ) {
+ current.owners.set(vnode, ownerStack[ownerStack.length - 1]);
+ }
+
+ if (oldVNodeHook) oldVNodeHook(vnode);
+};
+
+options.__b = (vnode: VNode>) => {
+ if (
+ current && current.renderingUserTemplate
+ ) {
+ // Internally rendering happens in two phases. This is done so
+ // that the `` component works. When we do the first render
+ // we cache all attributes on ``, `` + its children, and
+ // ``. When doing so, we'll replace the tags with a Fragment node
+ // so that they don't end up in the rendered HTML. Effectively this
+ // means we'll only serialize the contents of ``.
+ //
+ // After that render is finished we know all additional
+ // meta tags that were inserted via `` and all islands that
+ // we can add as preloads. Then we do a second render of the outer
+ // HTML tags with the updated value and merge in the HTML generate by
+ // the first render into `` directly.
+ if (
+ typeof vnode.type === "string"
+ ) {
+ if (vnode.type === "html") {
+ current.renderedHtmlTag = true;
+ current.docHtml = excludeChildren(vnode.props);
+ vnode.type = Fragment;
+ } else if (vnode.type === "head") {
+ current.docHead = excludeChildren(vnode.props);
+ current.headChildren = true;
+ vnode.type = Fragment;
+ vnode.props = {
+ __freshHead: true,
+ children: vnode.props.children,
+ };
+ } else if (vnode.type === "body") {
+ current.docBody = excludeChildren(vnode.props);
+ vnode.type = Fragment;
+ } else if (current.headChildren) {
+ if (vnode.type === "title") {
+ current.docTitle = h("title", vnode.props);
+ vnode.props = { children: null };
+ } else {
+ current.docHeadNodes.push({
+ type: vnode.type,
+ props: vnode.props,
+ });
+ }
+ vnode.type = Fragment;
+ }
+ } else if (typeof vnode.type === "function" && vnode.type !== Fragment) {
+ // Detect island vnodes and wrap them with a marker
+ const island = islandByComponent.get(vnode.type);
+ patchIsland:
+ if (
+ island &&
+ !patched.has(vnode)
+ ) {
+ // Check if an island is rendered inside another island, not just
+ // passed as a child.In that case we treat it like a normal
+ // Component. Example:
+ // function Island() {}
+ // return
+ // }
+ let tmpVNode = vnode;
+ let owner;
+ while ((owner = current.owners.get(tmpVNode)) !== undefined) {
+ if (islandByComponent.has(owner.type)) {
+ break patchIsland;
+ }
+ tmpVNode = owner;
+ }
+
+ // At this point we know that we need to patch the island. Mark the
+ // island in that we have already patched it.
+ const originalType = vnode.type;
+ patched.add(vnode);
+
+ vnode.type = (props) => {
+ if (!current) return null;
+
+ const { encounteredIslands, islandProps, slots } = current;
+ encounteredIslands.add(island);
+
+ // Only passing children JSX to islands is supported for now
+ const id = islandProps.length;
+ if ("children" in props) {
+ let children = props.children;
+ const markerText =
+ `frsh-slot-${island.id}:${island.exportName}:${id}:children`;
+ // @ts-ignore nonono
+ props.children = wrapWithMarker(
+ children,
+ markerText,
+ );
+ slots.set(markerText, children);
+ children = props.children;
+ // deno-lint-ignore no-explicit-any
+ (props as any).children = h(
+ SlotTracker,
+ { id: markerText },
+ children,
+ );
+ }
+
+ const child = h(originalType, props);
+ patched.add(child);
+ islandProps.push(props);
+
+ return wrapWithMarker(
+ child,
+ `frsh-${island.id}:${island.exportName}:${islandProps.length - 1}`,
+ );
+ };
+ }
+ }
+ }
+ oldDiff?.(vnode);
+};
+options.__r = (vnode) => {
+ if (
+ typeof vnode.type === "function" &&
+ vnode.type !== Fragment
+ ) {
+ ownerStack.push(vnode);
+ }
+ oldRender?.(vnode);
+};
+options.diffed = (vnode: VNode>) => {
+ if (typeof vnode.type === "function") {
+ if (vnode.type !== Fragment) {
+ ownerStack.pop();
+ } else if (vnode.props.__freshHead) {
+ if (current) {
+ current.headChildren = false;
+ }
+ }
+ }
+ oldDiffed?.(vnode);
+};
diff --git a/src/server/rendering/state.ts b/src/server/rendering/state.ts
new file mode 100644
index 00000000..d865e6b2
--- /dev/null
+++ b/src/server/rendering/state.ts
@@ -0,0 +1,58 @@
+import { type ComponentChildren, type VNode } from "preact";
+import { Island } from "../types.ts";
+import { ContentSecurityPolicy } from "../../runtime/csp.ts";
+
+export interface RenderStateRouteOptions {
+ url: URL;
+ route: string;
+ // deno-lint-ignore no-explicit-any
+ data?: any;
+ // deno-lint-ignore no-explicit-any
+ state?: any;
+ error?: unknown;
+ params: Record;
+}
+
+export class RenderState {
+ // deno-lint-ignore no-explicit-any
+ componentStack: any[];
+ renderingUserTemplate = false;
+ encounteredIslands = new Set();
+ islandProps: unknown[] = [];
+ slots = new Map();
+ headChildren = false;
+ renderedHtmlTag = false;
+ // deno-lint-ignore no-explicit-any
+ docTitle: VNode | null = null;
+ docHtml: Record | null = null;
+ docHead: Record | null = null;
+ docBody: Record | null = null;
+ docHeadNodes: { type: string; props: Record }[] = [];
+ headVNodes: ComponentChildren[] = [];
+ // Route options
+ routeOptions: RenderStateRouteOptions;
+ csp: ContentSecurityPolicy | undefined;
+ // Preact state
+ ownerStack: VNode[] = [];
+ owners = new Map();
+
+ constructor(
+ routeOptions: RenderStateRouteOptions,
+ // deno-lint-ignore no-explicit-any
+ componentStack: any[],
+ csp?: ContentSecurityPolicy,
+ error?: unknown,
+ ) {
+ this.routeOptions = routeOptions;
+ this.csp = csp;
+ this.componentStack = componentStack;
+
+ if (error) this.routeOptions.error = error;
+ }
+
+ clearTmpState() {
+ this.renderingUserTemplate = false;
+ this.ownerStack = [];
+ this.owners.clear();
+ }
+}
diff --git a/src/server/rendering/template.tsx b/src/server/rendering/template.tsx
new file mode 100644
index 00000000..05a8a88a
--- /dev/null
+++ b/src/server/rendering/template.tsx
@@ -0,0 +1,103 @@
+import { RenderState } from "./state.ts";
+import { setRenderState } from "./preact_hooks.ts";
+import { renderToString } from "preact-render-to-string";
+import { Fragment, h } from "preact";
+import { HEAD_CONTEXT } from "../../runtime/head.ts";
+import { CSP_CONTEXT } from "../../runtime/csp.ts";
+
+export function renderHtml(state: RenderState) {
+ setRenderState(state);
+ state.renderingUserTemplate = true;
+ state.headChildren = false;
+
+ const componentStack = state.componentStack;
+ try {
+ const routeComponent = componentStack[componentStack.length - 1];
+ let finalComp = h(routeComponent, state.routeOptions);
+
+ // Skip page component
+ let i = componentStack.length - 1;
+ while (i--) {
+ const component = componentStack[i];
+ const curComp = finalComp;
+
+ finalComp = h(component, {
+ ...state.routeOptions,
+ Component() {
+ return curComp;
+ },
+ });
+ }
+
+ const app = h(
+ CSP_CONTEXT.Provider,
+ // deno-lint-ignore no-explicit-any
+ { value: state.csp } as any,
+ h(HEAD_CONTEXT.Provider, {
+ value: state.headVNodes,
+ children: finalComp,
+ }),
+ );
+
+ let html = renderToString(app);
+
+ for (const [id, children] of state.slots.entries()) {
+ const slotHtml = renderToString(h(Fragment, null, children));
+ const templateId = id.replace(/:/g, "-");
+ html += `${slotHtml}`;
+ }
+
+ return html;
+ } finally {
+ setRenderState(null);
+ }
+}
+
+export function renderOuterDocument(
+ state: RenderState,
+ opts: {
+ bodyHtml: string;
+ lang?: string;
+ preloads: string[];
+ moduleScripts: [src: string, nonce: string][];
+ },
+) {
+ const {
+ docHtml,
+ docHead,
+ renderedHtmlTag,
+ docTitle,
+ docHeadNodes,
+ headVNodes,
+ } = state;
+
+ const page = h(
+ "html",
+ docHtml ?? { lang: opts.lang },
+ h(
+ "head",
+ docHead,
+ !renderedHtmlTag ? h("meta", { charSet: "utf-8" }) : null,
+ !renderedHtmlTag
+ ? (h("meta", {
+ name: "viewport",
+ content: "width=device-width, initial-scale=1.0",
+ }))
+ : null,
+ docTitle,
+ docHeadNodes.map((node) => h(node.type, node.props)),
+ opts.preloads.map((src) =>
+ h("link", { rel: "modulepreload", href: src })
+ ),
+ headVNodes,
+ h("body", { dangerouslySetInnerHTML: { __html: opts.bodyHtml } }),
+ ),
+ );
+
+ try {
+ setRenderState(state);
+ return "" + renderToString(page);
+ } finally {
+ setRenderState(null);
+ }
+}
diff --git a/tests/fixture/fresh.gen.ts b/tests/fixture/fresh.gen.ts
index 254e0cbb..310cb341 100644
--- a/tests/fixture/fresh.gen.ts
+++ b/tests/fixture/fresh.gen.ts
@@ -7,75 +7,78 @@ import * as $1 from "./routes/_404.tsx";
import * as $2 from "./routes/_500.tsx";
import * as $3 from "./routes/_app.tsx";
import * as $4 from "./routes/_middleware.ts";
-import * as $5 from "./routes/api/get_only.ts";
-import * as $6 from "./routes/api/head_override.ts";
-import * as $7 from "./routes/assetsCaching/index.tsx";
-import * as $8 from "./routes/books/[id].tsx";
-import * as $9 from "./routes/connInfo.ts";
-import * as $10 from "./routes/error_boundary.tsx";
-import * as $11 from "./routes/event_handler_string.tsx";
-import * as $12 from "./routes/event_handler_string_island.tsx";
-import * as $13 from "./routes/evil.tsx";
-import * as $14 from "./routes/failure.ts";
-import * as $15 from "./routes/index.tsx";
-import * as $16 from "./routes/intercept.tsx";
-import * as $17 from "./routes/intercept_args.tsx";
-import * as $18 from "./routes/islands/index.tsx";
-import * as $19 from "./routes/islands/multiple_island_exports.tsx";
-import * as $20 from "./routes/islands/returning_null.tsx";
-import * as $21 from "./routes/islands/root_fragment.tsx";
-import * as $22 from "./routes/islands/root_fragment_conditional_first.tsx";
-import * as $23 from "./routes/layeredMdw/_middleware.ts";
-import * as $24 from "./routes/layeredMdw/layer2-no-mw/without_mw.ts";
-import * as $25 from "./routes/layeredMdw/layer2-with-params/[tenantId]/[id].ts";
-import * as $26 from "./routes/layeredMdw/layer2-with-params/[tenantId]/_middleware.ts";
-import * as $27 from "./routes/layeredMdw/layer2-with-params/_middleware.ts";
-import * as $28 from "./routes/layeredMdw/layer2/_middleware.ts";
-import * as $29 from "./routes/layeredMdw/layer2/abc.ts";
-import * as $30 from "./routes/layeredMdw/layer2/index.ts";
-import * as $31 from "./routes/layeredMdw/layer2/layer3/[id].ts";
-import * as $32 from "./routes/layeredMdw/layer2/layer3/_middleware.ts";
-import * as $33 from "./routes/layeredMdw/nesting/[tenant]/[environment]/[id].tsx";
-import * as $34 from "./routes/layeredMdw/nesting/[tenant]/[environment]/_middleware.ts";
-import * as $35 from "./routes/layeredMdw/nesting/[tenant]/_middleware.ts";
-import * as $36 from "./routes/layeredMdw/nesting/_middleware.ts";
-import * as $37 from "./routes/middleware-error-handler/_middleware.ts";
-import * as $38 from "./routes/middleware-error-handler/index.tsx";
-import * as $39 from "./routes/middleware_root.ts";
-import * as $40 from "./routes/movies/[foo].json.ts";
-import * as $41 from "./routes/movies/[foo]@[bar].ts";
-import * as $42 from "./routes/not_found.ts";
-import * as $43 from "./routes/params.tsx";
-import * as $44 from "./routes/props/[id].tsx";
-import * as $45 from "./routes/route-groups-islands/index.tsx";
-import * as $46 from "./routes/route-groups/(bar)/(baz)/_layout.tsx";
-import * as $47 from "./routes/route-groups/(bar)/(baz)/baz.tsx";
-import * as $48 from "./routes/route-groups/(bar)/_layout.tsx";
-import * as $49 from "./routes/route-groups/(bar)/bar.tsx";
-import * as $50 from "./routes/route-groups/(bar)/boof/index.tsx";
-import * as $51 from "./routes/route-groups/(foo)/_layout.tsx";
-import * as $52 from "./routes/route-groups/(foo)/index.tsx";
-import * as $53 from "./routes/signal_shared.tsx";
-import * as $54 from "./routes/state-in-props/_middleware.ts";
-import * as $55 from "./routes/state-in-props/index.tsx";
-import * as $56 from "./routes/state-middleware/_middleware.ts";
-import * as $57 from "./routes/state-middleware/foo/_middleware.ts";
-import * as $58 from "./routes/state-middleware/foo/index.tsx";
-import * as $59 from "./routes/static.tsx";
-import * as $60 from "./routes/status_overwrite.tsx";
-import * as $61 from "./routes/umlaut-äöüß.tsx";
-import * as $62 from "./routes/wildcard.tsx";
+import * as $5 from "./routes/admin/[site].tsx";
+import * as $6 from "./routes/api/get_only.ts";
+import * as $7 from "./routes/api/head_override.ts";
+import * as $8 from "./routes/assetsCaching/index.tsx";
+import * as $9 from "./routes/books/[id].tsx";
+import * as $10 from "./routes/connInfo.ts";
+import * as $11 from "./routes/error_boundary.tsx";
+import * as $12 from "./routes/event_handler_string.tsx";
+import * as $13 from "./routes/event_handler_string_island.tsx";
+import * as $14 from "./routes/evil.tsx";
+import * as $15 from "./routes/failure.ts";
+import * as $16 from "./routes/index.tsx";
+import * as $17 from "./routes/intercept.tsx";
+import * as $18 from "./routes/intercept_args.tsx";
+import * as $19 from "./routes/islands/index.tsx";
+import * as $20 from "./routes/islands/multiple_island_exports.tsx";
+import * as $21 from "./routes/islands/returning_null.tsx";
+import * as $22 from "./routes/islands/root_fragment.tsx";
+import * as $23 from "./routes/islands/root_fragment_conditional_first.tsx";
+import * as $24 from "./routes/layeredMdw/_middleware.ts";
+import * as $25 from "./routes/layeredMdw/layer2-no-mw/without_mw.ts";
+import * as $26 from "./routes/layeredMdw/layer2-with-params/[tenantId]/[id].ts";
+import * as $27 from "./routes/layeredMdw/layer2-with-params/[tenantId]/_middleware.ts";
+import * as $28 from "./routes/layeredMdw/layer2-with-params/_middleware.ts";
+import * as $29 from "./routes/layeredMdw/layer2/_middleware.ts";
+import * as $30 from "./routes/layeredMdw/layer2/abc.ts";
+import * as $31 from "./routes/layeredMdw/layer2/index.ts";
+import * as $32 from "./routes/layeredMdw/layer2/layer3/[id].ts";
+import * as $33 from "./routes/layeredMdw/layer2/layer3/_middleware.ts";
+import * as $34 from "./routes/layeredMdw/nesting/[tenant]/[environment]/[id].tsx";
+import * as $35 from "./routes/layeredMdw/nesting/[tenant]/[environment]/_middleware.ts";
+import * as $36 from "./routes/layeredMdw/nesting/[tenant]/_middleware.ts";
+import * as $37 from "./routes/layeredMdw/nesting/_middleware.ts";
+import * as $38 from "./routes/middleware-error-handler/_middleware.ts";
+import * as $39 from "./routes/middleware-error-handler/index.tsx";
+import * as $40 from "./routes/middleware_root.ts";
+import * as $41 from "./routes/movies/[foo].json.ts";
+import * as $42 from "./routes/movies/[foo]@[bar].ts";
+import * as $43 from "./routes/not_found.ts";
+import * as $44 from "./routes/params.tsx";
+import * as $45 from "./routes/props/[id].tsx";
+import * as $46 from "./routes/route-groups-islands/index.tsx";
+import * as $47 from "./routes/route-groups/(bar)/(baz)/_layout.tsx";
+import * as $48 from "./routes/route-groups/(bar)/(baz)/baz.tsx";
+import * as $49 from "./routes/route-groups/(bar)/_layout.tsx";
+import * as $50 from "./routes/route-groups/(bar)/bar.tsx";
+import * as $51 from "./routes/route-groups/(bar)/boof/index.tsx";
+import * as $52 from "./routes/route-groups/(foo)/_layout.tsx";
+import * as $53 from "./routes/route-groups/(foo)/index.tsx";
+import * as $54 from "./routes/signal_shared.tsx";
+import * as $55 from "./routes/state-in-props/_middleware.ts";
+import * as $56 from "./routes/state-in-props/index.tsx";
+import * as $57 from "./routes/state-middleware/_middleware.ts";
+import * as $58 from "./routes/state-middleware/foo/_middleware.ts";
+import * as $59 from "./routes/state-middleware/foo/index.tsx";
+import * as $60 from "./routes/static.tsx";
+import * as $61 from "./routes/status_overwrite.tsx";
+import * as $62 from "./routes/umlaut-äöüß.tsx";
+import * as $63 from "./routes/wildcard.tsx";
import * as $$0 from "./islands/Counter.tsx";
-import * as $$1 from "./islands/MultipleCounters.tsx";
-import * as $$2 from "./islands/ReturningNull.tsx";
-import * as $$3 from "./islands/RootFragment.tsx";
-import * as $$4 from "./islands/RootFragmentWithConditionalFirst.tsx";
-import * as $$5 from "./islands/StringEventIsland.tsx";
-import * as $$6 from "./islands/Test.tsx";
-import * as $$7 from "./islands/folder/Counter.tsx";
-import * as $$8 from "./islands/folder/subfolder/Counter.tsx";
-import * as $$9 from "./islands/kebab-case-counter-test.tsx";
-import * as $$10 from "./routes/route-groups-islands/(_islands)/Counter.tsx";
+import * as $$1 from "./islands/Greeter.tsx";
+import * as $$2 from "./islands/MultipleCounters.tsx";
+import * as $$3 from "./islands/ReturningNull.tsx";
+import * as $$4 from "./islands/RootFragment.tsx";
+import * as $$5 from "./islands/RootFragmentWithConditionalFirst.tsx";
+import * as $$6 from "./islands/StringEventIsland.tsx";
+import * as $$7 from "./islands/Test.tsx";
+import * as $$8 from "./islands/folder/Counter.tsx";
+import * as $$9 from "./islands/folder/subfolder/Counter.tsx";
+import * as $$10 from "./islands/kebab-case-counter-test.tsx";
+import * as $$11 from "./routes/route-groups-islands/(_islands)/Counter.tsx";
+import * as $$12 from "./routes/route-groups-islands/(_islands)/invalid.tsx";
const manifest = {
routes: {
@@ -84,77 +87,80 @@ const manifest = {
"./routes/_500.tsx": $2,
"./routes/_app.tsx": $3,
"./routes/_middleware.ts": $4,
- "./routes/api/get_only.ts": $5,
- "./routes/api/head_override.ts": $6,
- "./routes/assetsCaching/index.tsx": $7,
- "./routes/books/[id].tsx": $8,
- "./routes/connInfo.ts": $9,
- "./routes/error_boundary.tsx": $10,
- "./routes/event_handler_string.tsx": $11,
- "./routes/event_handler_string_island.tsx": $12,
- "./routes/evil.tsx": $13,
- "./routes/failure.ts": $14,
- "./routes/index.tsx": $15,
- "./routes/intercept.tsx": $16,
- "./routes/intercept_args.tsx": $17,
- "./routes/islands/index.tsx": $18,
- "./routes/islands/multiple_island_exports.tsx": $19,
- "./routes/islands/returning_null.tsx": $20,
- "./routes/islands/root_fragment.tsx": $21,
- "./routes/islands/root_fragment_conditional_first.tsx": $22,
- "./routes/layeredMdw/_middleware.ts": $23,
- "./routes/layeredMdw/layer2-no-mw/without_mw.ts": $24,
- "./routes/layeredMdw/layer2-with-params/[tenantId]/[id].ts": $25,
- "./routes/layeredMdw/layer2-with-params/[tenantId]/_middleware.ts": $26,
- "./routes/layeredMdw/layer2-with-params/_middleware.ts": $27,
- "./routes/layeredMdw/layer2/_middleware.ts": $28,
- "./routes/layeredMdw/layer2/abc.ts": $29,
- "./routes/layeredMdw/layer2/index.ts": $30,
- "./routes/layeredMdw/layer2/layer3/[id].ts": $31,
- "./routes/layeredMdw/layer2/layer3/_middleware.ts": $32,
- "./routes/layeredMdw/nesting/[tenant]/[environment]/[id].tsx": $33,
- "./routes/layeredMdw/nesting/[tenant]/[environment]/_middleware.ts": $34,
- "./routes/layeredMdw/nesting/[tenant]/_middleware.ts": $35,
- "./routes/layeredMdw/nesting/_middleware.ts": $36,
- "./routes/middleware-error-handler/_middleware.ts": $37,
- "./routes/middleware-error-handler/index.tsx": $38,
- "./routes/middleware_root.ts": $39,
- "./routes/movies/[foo].json.ts": $40,
- "./routes/movies/[foo]@[bar].ts": $41,
- "./routes/not_found.ts": $42,
- "./routes/params.tsx": $43,
- "./routes/props/[id].tsx": $44,
- "./routes/route-groups-islands/index.tsx": $45,
- "./routes/route-groups/(bar)/(baz)/_layout.tsx": $46,
- "./routes/route-groups/(bar)/(baz)/baz.tsx": $47,
- "./routes/route-groups/(bar)/_layout.tsx": $48,
- "./routes/route-groups/(bar)/bar.tsx": $49,
- "./routes/route-groups/(bar)/boof/index.tsx": $50,
- "./routes/route-groups/(foo)/_layout.tsx": $51,
- "./routes/route-groups/(foo)/index.tsx": $52,
- "./routes/signal_shared.tsx": $53,
- "./routes/state-in-props/_middleware.ts": $54,
- "./routes/state-in-props/index.tsx": $55,
- "./routes/state-middleware/_middleware.ts": $56,
- "./routes/state-middleware/foo/_middleware.ts": $57,
- "./routes/state-middleware/foo/index.tsx": $58,
- "./routes/static.tsx": $59,
- "./routes/status_overwrite.tsx": $60,
- "./routes/umlaut-äöüß.tsx": $61,
- "./routes/wildcard.tsx": $62,
+ "./routes/admin/[site].tsx": $5,
+ "./routes/api/get_only.ts": $6,
+ "./routes/api/head_override.ts": $7,
+ "./routes/assetsCaching/index.tsx": $8,
+ "./routes/books/[id].tsx": $9,
+ "./routes/connInfo.ts": $10,
+ "./routes/error_boundary.tsx": $11,
+ "./routes/event_handler_string.tsx": $12,
+ "./routes/event_handler_string_island.tsx": $13,
+ "./routes/evil.tsx": $14,
+ "./routes/failure.ts": $15,
+ "./routes/index.tsx": $16,
+ "./routes/intercept.tsx": $17,
+ "./routes/intercept_args.tsx": $18,
+ "./routes/islands/index.tsx": $19,
+ "./routes/islands/multiple_island_exports.tsx": $20,
+ "./routes/islands/returning_null.tsx": $21,
+ "./routes/islands/root_fragment.tsx": $22,
+ "./routes/islands/root_fragment_conditional_first.tsx": $23,
+ "./routes/layeredMdw/_middleware.ts": $24,
+ "./routes/layeredMdw/layer2-no-mw/without_mw.ts": $25,
+ "./routes/layeredMdw/layer2-with-params/[tenantId]/[id].ts": $26,
+ "./routes/layeredMdw/layer2-with-params/[tenantId]/_middleware.ts": $27,
+ "./routes/layeredMdw/layer2-with-params/_middleware.ts": $28,
+ "./routes/layeredMdw/layer2/_middleware.ts": $29,
+ "./routes/layeredMdw/layer2/abc.ts": $30,
+ "./routes/layeredMdw/layer2/index.ts": $31,
+ "./routes/layeredMdw/layer2/layer3/[id].ts": $32,
+ "./routes/layeredMdw/layer2/layer3/_middleware.ts": $33,
+ "./routes/layeredMdw/nesting/[tenant]/[environment]/[id].tsx": $34,
+ "./routes/layeredMdw/nesting/[tenant]/[environment]/_middleware.ts": $35,
+ "./routes/layeredMdw/nesting/[tenant]/_middleware.ts": $36,
+ "./routes/layeredMdw/nesting/_middleware.ts": $37,
+ "./routes/middleware-error-handler/_middleware.ts": $38,
+ "./routes/middleware-error-handler/index.tsx": $39,
+ "./routes/middleware_root.ts": $40,
+ "./routes/movies/[foo].json.ts": $41,
+ "./routes/movies/[foo]@[bar].ts": $42,
+ "./routes/not_found.ts": $43,
+ "./routes/params.tsx": $44,
+ "./routes/props/[id].tsx": $45,
+ "./routes/route-groups-islands/index.tsx": $46,
+ "./routes/route-groups/(bar)/(baz)/_layout.tsx": $47,
+ "./routes/route-groups/(bar)/(baz)/baz.tsx": $48,
+ "./routes/route-groups/(bar)/_layout.tsx": $49,
+ "./routes/route-groups/(bar)/bar.tsx": $50,
+ "./routes/route-groups/(bar)/boof/index.tsx": $51,
+ "./routes/route-groups/(foo)/_layout.tsx": $52,
+ "./routes/route-groups/(foo)/index.tsx": $53,
+ "./routes/signal_shared.tsx": $54,
+ "./routes/state-in-props/_middleware.ts": $55,
+ "./routes/state-in-props/index.tsx": $56,
+ "./routes/state-middleware/_middleware.ts": $57,
+ "./routes/state-middleware/foo/_middleware.ts": $58,
+ "./routes/state-middleware/foo/index.tsx": $59,
+ "./routes/static.tsx": $60,
+ "./routes/status_overwrite.tsx": $61,
+ "./routes/umlaut-äöüß.tsx": $62,
+ "./routes/wildcard.tsx": $63,
},
islands: {
"./islands/Counter.tsx": $$0,
- "./islands/MultipleCounters.tsx": $$1,
- "./islands/ReturningNull.tsx": $$2,
- "./islands/RootFragment.tsx": $$3,
- "./islands/RootFragmentWithConditionalFirst.tsx": $$4,
- "./islands/StringEventIsland.tsx": $$5,
- "./islands/Test.tsx": $$6,
- "./islands/folder/Counter.tsx": $$7,
- "./islands/folder/subfolder/Counter.tsx": $$8,
- "./islands/kebab-case-counter-test.tsx": $$9,
- "./routes/route-groups-islands/(_islands)/Counter.tsx": $$10,
+ "./islands/Greeter.tsx": $$1,
+ "./islands/MultipleCounters.tsx": $$2,
+ "./islands/ReturningNull.tsx": $$3,
+ "./islands/RootFragment.tsx": $$4,
+ "./islands/RootFragmentWithConditionalFirst.tsx": $$5,
+ "./islands/StringEventIsland.tsx": $$6,
+ "./islands/Test.tsx": $$7,
+ "./islands/folder/Counter.tsx": $$8,
+ "./islands/folder/subfolder/Counter.tsx": $$9,
+ "./islands/kebab-case-counter-test.tsx": $$10,
+ "./routes/route-groups-islands/(_islands)/Counter.tsx": $$11,
+ "./routes/route-groups-islands/(_islands)/invalid.tsx": $$12,
},
baseUrl: import.meta.url,
};
diff --git a/tests/fixture/islands/Greeter.tsx b/tests/fixture/islands/Greeter.tsx
new file mode 100644
index 00000000..5f679d94
--- /dev/null
+++ b/tests/fixture/islands/Greeter.tsx
@@ -0,0 +1,3 @@
+export default function Greeter(props: { site: string }) {
+ return {props.site}
;
+}
diff --git a/tests/fixture/routes/admin/[site].tsx b/tests/fixture/routes/admin/[site].tsx
new file mode 100644
index 00000000..5faa569e
--- /dev/null
+++ b/tests/fixture/routes/admin/[site].tsx
@@ -0,0 +1,9 @@
+import { Handler, PageProps } from "$fresh/server.ts";
+import Greeter from "../../islands/Greeter.tsx";
+
+export const handler: Handler = (_req, ctx) =>
+ ctx.render({ site: ctx.params.site });
+
+export default function Component(props: PageProps<{ site: string }>) {
+ return ;
+}
diff --git a/tests/main_test.ts b/tests/main_test.ts
index a8fd17d1..8981d6a3 100644
--- a/tests/main_test.ts
+++ b/tests/main_test.ts
@@ -58,10 +58,15 @@ Deno.test("/props/123 page prerender", async () => {
assertEquals(resp.status, Status.OK);
assertEquals(resp.headers.get("content-type"), "text/html; charset=utf-8");
const body = await resp.text();
- assertStringIncludes(
- body,
- `{"params":{"id":"123"},"url":"https://fresh.deno.dev/props/123","route":"/props/:id","state":{"root":"root_mw"}}`,
- );
+ const doc = parseHtml(body);
+ const data = JSON.parse(doc.querySelector("body > div").textContent);
+
+ assertEquals(data, {
+ "params": { "id": "123" },
+ "url": "https://fresh.deno.dev/props/123",
+ "route": "/props/:id",
+ "state": { "root": "root_mw" },
+ });
});
Deno.test("/greet/[name] page prerender", async () => {
diff --git a/tests/render_test.ts b/tests/render_test.ts
new file mode 100644
index 00000000..9b143fd8
--- /dev/null
+++ b/tests/render_test.ts
@@ -0,0 +1,28 @@
+import {
+ assertSelector,
+ fetchHtml,
+ withFresh,
+} from "$fresh/tests/test_utils.ts";
+import { assertEquals } from "$std/testing/asserts.ts";
+
+Deno.test("doesn't leak data across renderers", async () => {
+ // Issue: https://github.com/denoland/fresh/issues/1636
+ await withFresh("./tests/fixture/main.ts", async (address) => {
+ function load(name: string) {
+ return fetchHtml(`${address}/admin/${name}`).then((doc) => {
+ assertSelector(doc, "#__FRSH_STATE");
+ const text = doc.querySelector("#__FRSH_STATE")?.textContent!;
+ const json = JSON.parse(text);
+ assertEquals(json, { "v": [[{ "site": name }], []] });
+ });
+ }
+
+ const promises: Promise[] = [];
+ for (let i = 0; i < 100; i++) {
+ promises.push(load("foo"));
+ promises.push(load("bar"));
+ }
+
+ await Promise.all(promises);
+ });
+});