Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
29 changes: 29 additions & 0 deletions docs/reference/api/pages.md
Original file line number Diff line number Diff line change
Expand Up @@ -85,6 +85,7 @@ function voidVue(options?: VoidVueOptions): Plugin[];
```ts
interface VoidVueOptions {
vue?: VuePluginOptions; // passed through to @vitejs/plugin-vue
appSetup?: string; // path from the project root to the Vue app setup module
viewTransitions?: boolean; // enable View Transitions API for navigations
prefetch?: {
defaultStrategy?: boolean | LinkPrefetchStrategy | LinkPrefetchStrategy[]; // default: false
Expand All @@ -95,6 +96,34 @@ interface VoidVueOptions {
}
```

### Vue app setup {#vue-app-setup}

Set `voidVue({ appSetup: './src/vue-app.ts' })` in your Vite config to install Vue plugins, provide values, or configure the app before it renders. Default-export a synchronous setup function from that file. Void calls it on the server for each request that renders a Vue app, and in the browser before mounting the page app and each island app.

Guard browser APIs in the setup module with `if (!import.meta.env.SSR)`.

Return optional synchronous `dehydrate()` and `hydrate(state)` functions to transfer state for server-rendered pages with hydration enabled. Void calls `dehydrate()` as soon as the page finishes rendering, before running deferred callbacks. When `dehydrate()` returns a value, Void includes it in the initial HTML and passes it to `hydrate(state)` before mounting the page app.

Each island in the browser starts with the state its own `setup(app)` creates. Pass server data to islands as props, including any values that the page or its loaders changed on the server.

```ts
// src/vue-app.ts
import { createPinia } from 'pinia';
import type { App } from 'vue';

export default function setup(app: App) {
const pinia = createPinia();
app.use(pinia);

return {
dehydrate: () => pinia.state.value,
hydrate(state: typeof pinia.state.value) {
pinia.state.value = state;
},
};
}
```

### Vue Runtime {#vue-runtime}

Imported from `"@void/vue"`.
Expand Down
10 changes: 6 additions & 4 deletions packages/void/src/pages/islands-plugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -358,14 +358,16 @@ export function recordIslandStyles(
context: IslandBuildContext,
pageScan: PageScanResult | null,
pagesDir: string,
setupModule?: string,
): void {
if (!pageScan || context.environment?.config.consumer !== 'server') {
return;
}
const styles = collectIslandStyles(
(id) => context.getModuleInfo(id),
islandStyleRoots(pageScan, pagesDir),
);
const roots = islandStyleRoots(pageScan, pagesDir);
if (setupModule) {
roots.unshift(setupModule);
}
const styles = collectIslandStyles((id) => context.getModuleInfo(id), roots);
// Another server environment (an auxiliary Worker) does not have the pages.
if (styles) {
islandStylesByPagesDir.set(normalizePath(pagesDir), styles);
Expand Down
24 changes: 15 additions & 9 deletions packages/void/src/pages/protocol.ts
Original file line number Diff line number Diff line change
Expand Up @@ -87,6 +87,7 @@ type RenderPage = (
pageObj: PageObject,
assetTags: AssetTags,
requestUrl: string,
request: CloudContext['req'],
) => Promise<PageRenderResult>;
type RenderPageWithMetadata = RenderPage & {
preambleScript?: string;
Expand Down Expand Up @@ -256,10 +257,10 @@ async function renderWithAssetTags(
renderFn: RenderPage,
pageObj: PageObject,
assetTags: AssetTags,
requestUrl: string,
request: CloudContext,
): Promise<PageRenderResult> {
try {
return await renderFn(pageObj, assetTags, requestUrl);
return await renderFn(pageObj, assetTags, request.req.url, request.req);
} catch (error) {
attachRenderErrorAssetTags(error, assetTags);
}
Expand Down Expand Up @@ -300,7 +301,7 @@ async function renderPageHtml(
const html =
renderMode === 'client'
? renderClientOnlyPage(pageObj, assetTags, renderFn)
: await renderWithAssetTags(renderFn, pageObj, assetTags, c.req.url);
: await renderWithAssetTags(renderFn, pageObj, assetTags, c);
return { html, assetTags };
}

Expand Down Expand Up @@ -437,6 +438,15 @@ function isRecoverableHttpException(error: unknown): error is HTTPException {
);
}

export function isPageResponseError(error: unknown): error is Pick<HTTPException, 'getResponse'> {
return (
!!error &&
typeof error === 'object' &&
'getResponse' in error &&
typeof error.getResponse === 'function'
);
}

/** Recover HTTP failures outside the loader leaf without executing application code again. */
export async function recoverPageHttpException(
error: unknown,
Expand Down Expand Up @@ -466,12 +476,8 @@ async function renderPageFailure(
configHead: HeadConfig | undefined,
options: PageRenderOptions | undefined,
): Promise<Response | undefined> {
const httpError =
error &&
typeof error === 'object' &&
'getResponse' in error &&
typeof error.getResponse === 'function';
const explicit = httpError ? (error as { getResponse(): Response }).getResponse() : original;
const httpError = isPageResponseError(error);
const explicit = httpError ? error.getResponse() : original;
const recoverHttpError = isRecoverableHttpException(error);
if (
explicit &&
Expand Down
34 changes: 33 additions & 1 deletion packages/void/src/pages/serialize.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,20 @@
import { stringify, unflatten } from 'devalue';
import { parse, stringify, unflatten } from 'devalue';
import type { Context } from 'hono';
import { escapeScriptJson } from './script-json.ts';

type AppRequest = Context['req'];
let appSetups: WeakMap<AppRequest, Promise<unknown>> | undefined;

export function requestAppSetup<T>(setup: () => T, request: AppRequest): Promise<T> {
const cache = (appSetups ??= new WeakMap());
let pending = cache.get(request);
if (!pending) {
pending = Promise.resolve().then(setup);
cache.set(request, pending);
}
return pending as Promise<T>;
}

/**
* Serialize Pages data without losing supported JavaScript values. The envelope
* keeps deferred metadata visible to existing ISR caches, which must not cache
Expand Down Expand Up @@ -35,6 +49,24 @@ export function deserializePageData<T = unknown>(text: string): T {
return decodePageData<T>(JSON.parse(text));
}

const APP_STATE_ID = '__VOID_APP_STATE__';

export function appStateScript(hooks?: { dehydrate?: () => unknown }): string {
const state = hooks?.dehydrate ? hooks.dehydrate() : undefined;
return state === undefined
? ''
: `\n <script type="application/json" id="${APP_STATE_ID}">${escapeScriptJson(stringify(state))}</script>`;
}

export function hydrateAppState(hooks?: { hydrate?: (state: unknown) => void }): void {
if (typeof hooks?.hydrate === 'function') {
const state = document.getElementById(APP_STATE_ID)?.textContent;
if (state) {
hooks.hydrate(parse(state));
}
}
}

/** Element id of the Markdown page frontmatter that islands read when they hydrate. */
export const ISLAND_FRONTMATTER_ID = '__void_frontmatter';

Expand Down
9 changes: 7 additions & 2 deletions packages/void/src/runtime/routing/pages.ts
Original file line number Diff line number Diff line change
Expand Up @@ -201,8 +201,13 @@ export function createStaticNotFound(
const handle = createPageGetHandler({
...options,
renderOptions: { ...options.renderOptions, renderMode: 'server' },
render: (page, assets, url) =>
options.render({ ...page, documentOnly: true }, { ...assets, body: '', preloads: '' }, url),
render: (page, assets, url, request) =>
options.render(
{ ...page, documentOnly: true },
{ ...assets, body: '', preloads: '' },
url,
request,
),
});
return (request, env) => handle(new Context(new Request(new URL('/404', request.url)), { env }));
}
Expand Down
28 changes: 28 additions & 0 deletions packages/void/test/unit/pages-protocol.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,11 +12,13 @@ import {
import {
deserializePageData,
decodePageData,
requestAppSetup,
serializePageData,
} from '../../src/pages/serialize.ts';
import { defineHandler } from '../../src/runtime/handler/index.ts';
import type { CloudContext, CloudEnv } from '../../src/runtime/handler/index.ts';
import { createRoutingRuntime } from '../../src/runtime/routing/index.ts';
import { createStaticNotFound } from '../../src/runtime/routing/pages.ts';

type RenderPage = { component: string };
type PageResponse = {
Expand Down Expand Up @@ -73,6 +75,31 @@ function createTestContext(
const mockRenderFn = vi.fn(async (pageObj: RenderPage) => `<html>${pageObj.component}</html>`);
const mockGetAssetTags = vi.fn(async () => ({ css: '', preloads: '', body: '' }));

it('keeps the same setup request when the static 404 tries an error boundary', async () => {
const setup = vi.fn(() => ({ touched: false }));
const render = createStaticNotFound({
componentId: 'missing',
headConfig: null,
renderOptions: {
boundaries: { notFound: 'missing', notFoundErrors: ['error'], errors: ['error'] },
},
load: async () => ({ loader: () => new Response(null, { status: 404 }) }),
assets: mockGetAssetTags,
render: async (page, _assets, _url, request) => {
const state = await requestAppSetup(setup, request);
if (page.component === 'missing') {
state.touched = true;
throw new Error('404 component threw');
}
expect(page.documentOnly).toBe(true);
return `<p>touched ${state.touched}</p>`;
},
});
const response = await render(new Request('http://localhost/'), {});
expect(await response.text()).toContain('touched true');
expect(setup).toHaveBeenCalledTimes(1);
});

describe('handlePageGet', () => {
it.each(['plain', 'validated', 'middleware'] as const)(
'preserves rich loader and shared data for %s handlers and action reloads',
Expand Down Expand Up @@ -314,6 +341,7 @@ describe('handlePageGet', () => {
}),
expect.anything(),
'http://localhost/posts/abc-123',
c.req,
);
});

Expand Down
49 changes: 49 additions & 0 deletions packages/vue/src/app-render.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
export type AppSetupModule = { id: string; file: string };

export function generateSetupCall({ file }: AppSetupModule): string {
const option = `voidVue appSetup (${file})`;
return `
if (typeof setupApp !== "function") {
throw new TypeError(${JSON.stringify(`${option} must default-export a function.`)});
}
const appHooks = setupApp(app);
if (typeof appHooks?.then === "function") {
void Promise.resolve(appHooks).catch(() => {});
throw new TypeError(${JSON.stringify(`${option} must be synchronous.`)});
}`;
}

export function generateSsrAppSetup(appSetup: AppSetupModule): string {
return `
import setupApp from ${JSON.stringify(appSetup.id)};
import { isPageResponseError } from "void/pages-protocol";
async function requestApp(root, request) {
const entry = await requestAppSetup(() => {
const app = createSSRApp({ setup: () => entry.root.setup() });${generateSetupCall(appSetup)}
return { app, root, appHooks };
}, request);
return Object.assign(entry, { root });
}`;
}

export function generateSsrRender(appSetup: AppSetupModule | undefined): string {
const handler = appSetup
? `const setupErrorHandler = app.config.errorHandler;
const boundary = boundaryManifest.pages[pageObj.component];
if (Object.keys(boundaryManifest.plans).length) app.config.errorHandler = (error, ...args) => {
if (!setupErrorHandler || isPageResponseError(error) || boundary?.errors.length ||
boundaryManifest.plans[pageObj.component]) {
renderFailure ??= { error };
}
try {
setupErrorHandler?.(error, ...args);
} catch (error) {
renderFailure ??= { error };
}
};`
: 'if (Object.keys(boundaryManifest.plans).length) app.config.errorHandler = error => { renderFailure ??= { error }; };';
return `let renderFailure;
${handler}
const html = await renderToString(app)${appSetup ? '.finally(() => { app.config.errorHandler = setupErrorHandler; })' : ''};
if (renderFailure) throw renderFailure.error;`;
}
Loading