From 3005c8deac742c9ef054da41cb3398bb6b4bb829 Mon Sep 17 00:00:00 2001 From: 0froq Date: Sun, 22 Nov 2026 10:58:04 +0800 Subject: [PATCH 01/14] feat: recover Pages navigation across deployments A tab that outlives a deployment imports chunks that no longer exist. The loader answers it with the new build's props, the component import 404s, and the navigation dies on an error boundary or on the detached error page. Each build now gets one id, folded into both bundles. A Pages GET carries it, every Pages response names the build that answered, and a request from another build gets the reload response the protocol upgrade path already uses. The tab loads the destination as a document, keeping its query and fragment. Adapter plugins accept `deployRecovery: false` to keep their own error boundaries in charge. --- docs/guide/pages-routing/overview.md | 14 ++ docs/reference/api/pages.md | 4 + packages/edge/src/index.ts | 7 +- packages/edge/src/pages-protocol.ts | 21 +++ packages/react/src/plugin-pages.ts | 1 + packages/react/src/plugin.ts | 8 +- packages/solid/src/plugin-pages.ts | 1 + packages/solid/src/plugin.ts | 8 +- packages/svelte/src/plugin-pages.ts | 1 + packages/svelte/src/plugin.ts | 8 +- packages/void/env.d.ts | 7 + packages/void/src/pages/build-id-source.ts | 117 ++++++++++++ packages/void/src/pages/build-id.ts | 13 ++ packages/void/src/pages/navigation-engine.ts | 62 ++++++- packages/void/src/pages/plugin.ts | 62 ++++++- packages/void/src/pages/protocol.ts | 25 ++- .../void/test/unit/pages-build-id.test.ts | 174 ++++++++++++++++++ packages/void/test/unit/pages-client.test.ts | 114 ++++++++++++ .../test/unit/pages-plugin-adapters.test.ts | 23 ++- .../void/test/unit/pages-protocol.test.ts | 76 +++++++- packages/vue/src/plugin-pages.ts | 1 + packages/vue/src/plugin.ts | 4 +- 22 files changed, 723 insertions(+), 28 deletions(-) create mode 100644 packages/void/env.d.ts create mode 100644 packages/void/src/pages/build-id-source.ts create mode 100644 packages/void/src/pages/build-id.ts create mode 100644 packages/void/test/unit/pages-build-id.test.ts diff --git a/docs/guide/pages-routing/overview.md b/docs/guide/pages-routing/overview.md index 5667d48c1..8dfeeb3dd 100644 --- a/docs/guide/pages-routing/overview.md +++ b/docs/guide/pages-routing/overview.md @@ -128,6 +128,20 @@ Production deploys exclude resources used only by `.dev` pages and their compani The first request receives rendered HTML. Later navigations run the loader and update the page without reloading the document. Form submissions run an action, then refresh page props or redirect. +### After a deploy + +An open tab keeps the code it loaded. Deploy while it stays open, and its next navigation asks for chunks that no longer exist. + +Void recovers that navigation. The tab sends the build it is running with each page request, and an answer from a different build makes it load the requested page as a document instead of rendering it. The destination keeps its query string and fragment, and the current page stays visible until the load starts. + +These never reload the tab: + +- A prefetch drops the response and lets the next navigation decide. +- A form submission renders its response, so the action never runs twice. The next navigation reloads if it has to. +- A failed request is not treated as a deploy. + +Recovery is on by default. Set `deployRecovery: false` in your framework plugin's options to keep your own [error boundaries](./errors.md) in charge instead. + To opt a specific route out of server-rendered component HTML, export `ssr = false` from its companion `.server.ts` file: ```ts diff --git a/docs/reference/api/pages.md b/docs/reference/api/pages.md index 390670498..1ddece7ec 100644 --- a/docs/reference/api/pages.md +++ b/docs/reference/api/pages.md @@ -91,6 +91,7 @@ interface VoidVueOptions { hoverDelay?: number; // default: 75 (ms) cacheFor?: number | string | [string, string]; // default: '30s' }; + deployRecovery?: boolean; // reload a tab whose build is gone. default: true } ``` @@ -147,6 +148,7 @@ interface VoidReactOptions { hoverDelay?: number; // default: 75 (ms) cacheFor?: number | string | [string, string]; // default: '30s' }; + deployRecovery?: boolean; // reload a tab whose build is gone. default: true } ``` @@ -232,6 +234,7 @@ interface VoidSvelteOptions { hoverDelay?: number; // default: 75 (ms) cacheFor?: number | string | [string, string]; // default: '30s' }; + deployRecovery?: boolean; // reload a tab whose build is gone. default: true } ``` @@ -286,6 +289,7 @@ interface VoidSolidOptions { hoverDelay?: number; // default: 75 (ms) cacheFor?: number | string | [string, string]; // default: '30s' }; + deployRecovery?: boolean; // reload a tab whose build is gone. default: true } ``` diff --git a/packages/edge/src/index.ts b/packages/edge/src/index.ts index 54610bc0b..d7166a9f6 100644 --- a/packages/edge/src/index.ts +++ b/packages/edge/src/index.ts @@ -1,5 +1,10 @@ export type { ProjectZeroTrustRouting } from './access.ts'; -export { PAGES_PROTOCOL_VERSION } from './pages-protocol.ts'; +export { + buildHeaders, + isStaleBuild, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, +} from './pages-protocol.ts'; export { redirectToHttps } from './https.ts'; export { applyHeaderRules, diff --git a/packages/edge/src/pages-protocol.ts b/packages/edge/src/pages-protocol.ts index c36071404..43c072bf8 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -1,2 +1,23 @@ /** Current Pages wire version; a missing header identifies legacy clients. */ export const PAGES_PROTOCOL_VERSION = '2'; + +/** + * The build a request or response belongs to. Unlike the protocol version it + * changes with every deploy, so a tab that outlives a deployment can tell that + * the chunks it still holds are gone. + */ +export const PAGES_BUILD_HEADER = 'X-VoidPages-Build'; + +/** + * Whether a build id seen on the wire belongs to another deployment. A peer + * that sends no id (an older Void, or a parse of a partial response) is not + * evidence of a new build, so it never counts as a mismatch. + */ +export function isStaleBuild(buildId: string, seen: string | null | undefined): boolean { + return buildId !== '' && seen != null && seen !== buildId; +} + +/** Request and response headers that carry a build, empty when none is known. */ +export function buildHeaders(buildId: string): Record { + return buildId === '' ? {} : { [PAGES_BUILD_HEADER]: buildId }; +} diff --git a/packages/react/src/plugin-pages.ts b/packages/react/src/plugin-pages.ts index 46ce1ebac..3e359a41b 100644 --- a/packages/react/src/plugin-pages.ts +++ b/packages/react/src/plugin-pages.ts @@ -43,6 +43,7 @@ export function pagesPlugin(pagesDir: string, options?: PagesPluginOptions): Plu return createPagesPlugin(pagesDir, { name: 'void-react:pages', root, + deployRecovery: options?.deployRecovery, generateRenderer(scan, isDev) { return generateRendererModule(scan, pagesDir, isDev); }, diff --git a/packages/react/src/plugin.ts b/packages/react/src/plugin.ts index 1076362a0..d72ecc085 100644 --- a/packages/react/src/plugin.ts +++ b/packages/react/src/plugin.ts @@ -9,6 +9,7 @@ export type VoidReactOptions = Readonly<{ react?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; export function voidReact(options?: VoidReactOptions): Array { @@ -16,11 +17,8 @@ export function voidReact(options?: VoidReactOptions): Array { const pagesDir = resolvePagesDir(root); return [ ...react(options?.react), - pagesPlugin(pagesDir, { - root, - viewTransitions: options?.viewTransitions, - prefetch: options?.prefetch, - }), + // Spread so adapter options the pages plugin owns reach it without per-option glue. + pagesPlugin(pagesDir, { ...options, root }), ...islandsPlugin(pagesDir, { root }), ]; } diff --git a/packages/solid/src/plugin-pages.ts b/packages/solid/src/plugin-pages.ts index 83d7b99ca..d55379696 100644 --- a/packages/solid/src/plugin-pages.ts +++ b/packages/solid/src/plugin-pages.ts @@ -15,6 +15,7 @@ export function pagesPlugin(pagesDir: string, options?: PagesPluginOptions): Plu return createPagesPlugin(pagesDir, { name: 'void-solid:pages', root: options?.root, + deployRecovery: options?.deployRecovery, generateRenderer(scan) { return generateRendererModule(scan, pagesDir); }, diff --git a/packages/solid/src/plugin.ts b/packages/solid/src/plugin.ts index bd00b7855..af66623ed 100644 --- a/packages/solid/src/plugin.ts +++ b/packages/solid/src/plugin.ts @@ -11,6 +11,7 @@ export type VoidSolidOptions = Readonly<{ solid?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; // The runtime entry exports raw `.tsx` source. Without these hints, Vite's SSR @@ -47,11 +48,8 @@ export function voidSolid(options?: VoidSolidOptions): Array { return [ configPlugin(), solid({ ssr: true, ...options?.solid }), - pagesPlugin(pagesDir, { - root, - viewTransitions: options?.viewTransitions, - prefetch: options?.prefetch, - }), + // Spread so adapter options the pages plugin owns reach it without per-option glue. + pagesPlugin(pagesDir, { ...options, root }), ...islandsPlugin(pagesDir, { root }), ]; } diff --git a/packages/svelte/src/plugin-pages.ts b/packages/svelte/src/plugin-pages.ts index 80c4b784e..c57e3ffd4 100644 --- a/packages/svelte/src/plugin-pages.ts +++ b/packages/svelte/src/plugin-pages.ts @@ -47,6 +47,7 @@ export function pagesPlugin(pagesDir: string, options?: PagesPluginOptions): Plu return createPagesPlugin(pagesDir, { name: 'void-svelte:pages', root: options?.root, + deployRecovery: options?.deployRecovery, generateRenderer(scan) { return generateRendererModule(scan, pagesDir); }, diff --git a/packages/svelte/src/plugin.ts b/packages/svelte/src/plugin.ts index 3d46326b6..d72d1a4e0 100644 --- a/packages/svelte/src/plugin.ts +++ b/packages/svelte/src/plugin.ts @@ -9,6 +9,7 @@ export type VoidSvelteOptions = Readonly<{ svelte?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; export function voidSvelte(options?: VoidSvelteOptions): Array { @@ -16,11 +17,8 @@ export function voidSvelte(options?: VoidSvelteOptions): Array { const pagesDir = resolvePagesDir(root); return [ ...(svelte(options?.svelte) as ReadonlyArray), - pagesPlugin(pagesDir, { - root, - viewTransitions: options?.viewTransitions, - prefetch: options?.prefetch, - }), + // Spread so adapter options the pages plugin owns reach it without per-option glue. + pagesPlugin(pagesDir, { ...options, root }), ...islandsPlugin(pagesDir, { root }), ]; } diff --git a/packages/void/env.d.ts b/packages/void/env.d.ts new file mode 100644 index 000000000..3ab5ed917 --- /dev/null +++ b/packages/void/env.d.ts @@ -0,0 +1,7 @@ +/** + * Constants the build folds into both the client and server bundles, such as + * the Pages build id. Vite replaces each key at build time. + */ +interface ImportMeta { + readonly env: Record; +} diff --git a/packages/void/src/pages/build-id-source.ts b/packages/void/src/pages/build-id-source.ts new file mode 100644 index 000000000..b84b545b6 --- /dev/null +++ b/packages/void/src/pages/build-id-source.ts @@ -0,0 +1,117 @@ +import { createHash } from 'node:crypto'; +import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'; +import { isAbsolute, join } from 'pathslash'; + +/** Directories never part of the app source, whatever their position. */ +const alwaysSkipped = new Set(['node_modules']); + +/** Beside the generated types, which the scaffold already ignores. */ +const CACHE_FILE = '.void/pages-build-id.json'; + +const ID_PATTERN = /^[0-9a-f]{12}$/; + +type CacheEntry = { + fingerprint: string; + id: string; +}; + +/** + * A stable id for one build of an app: a hash of its source files. Every + * environment of a Vite build derives the same id from the same tree, which a + * per-process random value cannot guarantee, since Vite may resolve the config + * once per environment. + * + * The id changes with any source change, including server-only ones, which + * reloads a stale tab that did not need it. That is the safe direction: missing + * the id means importing chunks that no longer exist. + * + * Resolving the config per environment means hashing the tree twice. The cache + * turns the second pass into one stat walk, keyed by file size and modification + * time. A write always moves the modification time, so a fingerprint that still + * matches describes the same content. + */ +export function computePagesBuildId(root: string, excludeDirs: Array): string { + const excluded = new Set(excludeDirs.map((dir) => (isAbsolute(dir) ? dir : join(root, dir)))); + const files = sourceFiles(root, excluded); + const fingerprint = fingerprintOf(root, files); + const cached = readCachedId(root, fingerprint); + if (cached) { + return cached; + } + const id = contentIdOf(root, files); + writeCachedId(root, fingerprint, id); + return id; +} + +/** Relative paths of the files under `root` that describe the app, sorted. */ +function sourceFiles(root: string, excluded: Set): Array { + const files: Array = []; + const walk = (directory: string): void => { + for (const entry of readdirSync(join(root, directory), { withFileTypes: true })) { + // Dot directories hold tool state (.git, .void, .wrangler), and dot files + // hold local settings such as .env that a deploy must not depend on. + if (entry.name.startsWith('.') || alwaysSkipped.has(entry.name)) { + continue; + } + const path = directory ? `${directory}/${entry.name}` : entry.name; + if (excluded.has(join(root, path))) { + continue; + } + // Symlinked directories are not followed: they can leave the tree. + if (entry.isDirectory()) { + walk(path); + } else if (entry.isFile()) { + files.push(path); + } + } + }; + walk(''); + return files.sort(); +} + +function fingerprintOf(root: string, files: Array): string { + const hash = createHash('sha256'); + for (const file of files) { + const stats = statSync(join(root, file)); + hash.update(`${file}\0${stats.size}\0${stats.mtimeMs}\0`); + } + return hash.digest('hex'); +} + +function contentIdOf(root: string, files: Array): string { + const hash = createHash('sha256'); + for (const file of files) { + hash.update(file); + hash.update('\0'); + hash.update(readFileSync(join(root, file))); + hash.update('\0'); + } + return hash.digest('hex').slice(0, 12); +} + +/** The last id, when the tree still looks the way it did when the id was made. */ +function readCachedId(root: string, fingerprint: string): string | null { + try { + const entry = JSON.parse(readFileSync(join(root, CACHE_FILE), 'utf8')) as Partial; + if ( + entry.fingerprint === fingerprint && + typeof entry.id === 'string' && + ID_PATTERN.test(entry.id) + ) { + return entry.id; + } + } catch { + // No cache, unreadable cache, or a cache from another tool: hash the tree. + } + return null; +} + +function writeCachedId(root: string, fingerprint: string, id: string): void { + try { + const path = join(root, CACHE_FILE); + mkdirSync(join(root, '.void'), { recursive: true }); + writeFileSync(path, JSON.stringify({ fingerprint, id } satisfies CacheEntry)); + } catch { + // A read-only tree still builds; it just pays for the second pass. + } +} diff --git a/packages/void/src/pages/build-id.ts b/packages/void/src/pages/build-id.ts new file mode 100644 index 000000000..aa786acde --- /dev/null +++ b/packages/void/src/pages/build-id.ts @@ -0,0 +1,13 @@ +/** The define the pages plugin fills in once per build. */ +export const PAGES_BUILD_ID_DEFINE = 'import.meta.env.__VOID_PAGES_BUILD_ID'; + +/** + * The id of the build this code was bundled into. The pages plugin defines it + * per build; it is empty in the dev server and in tests, which turns every + * build check into a no-op. + */ +export function pagesBuildId(): string { + // Spelled out so the build replaces this expression with the id literal. + const value: unknown = import.meta.env.__VOID_PAGES_BUILD_ID; + return typeof value === 'string' ? value : ''; +} diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index b54ba6842..78fa0a908 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -1,10 +1,11 @@ /// -import { PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { buildHeaders, isStaleBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION } from '@void/edge'; import { PRESERVED_QUERY_HEADER, searchWithoutActionKey } from './action-key.ts'; import { createActionErrorFromResponse, isAbortError } from './action-result.ts'; import { pageBoundarySlots, clientPageError, showTerminalPageError } from './boundary-client.ts'; import type { BoundaryManifest } from './boundary-plans.ts'; +import { pagesBuildId } from './build-id.ts'; import { initClientHead, applyClientHead } from './head-client.ts'; import { PrefetchCache, parseCacheFor } from './prefetch.ts'; import type { CacheForInput, CacheForResult, LinkPrefetchValue } from './prefetch.ts'; @@ -237,6 +238,38 @@ function abortError(): DOMException { return new DOMException('Navigation aborted', 'AbortError'); } +const DEPLOY_RELOAD_KEY = '__void_pages_deploy_reload'; +/** A reload that lands on the same stale build must not reload again. */ +const DEPLOY_RELOAD_WINDOW_MS = 10_000; + +/** + * Claims the one reload this tab may spend to recover `url` from `build`. Returns + * false when that reload already happened: a cache can keep serving the document + * from the old build, and reloading it again would loop. + */ +function claimDeployReload(build: string, url: string): boolean { + try { + const now = Date.now(); + const previous = JSON.parse(sessionStorage.getItem(DEPLOY_RELOAD_KEY) ?? 'null') as { + build?: unknown; + url?: unknown; + at?: unknown; + } | null; + if ( + previous?.build === build && + previous.url === url && + typeof previous.at === 'number' && + now - previous.at < DEPLOY_RELOAD_WINDOW_MS + ) { + return false; + } + sessionStorage.setItem(DEPLOY_RELOAD_KEY, JSON.stringify({ build, url, at: now })); + } catch { + // Storage may be blocked or full. A reload is still better than a dead page. + } + return true; +} + function abortSignalPromise(signal: AbortSignal): Promise { if (signal.aborted) { return Promise.reject(abortError()); @@ -630,6 +663,7 @@ export async function createPageNavigationEngine( const headers = { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...buildHeaders(pagesBuildId()), Accept: 'application/json', Purpose: 'prefetch', }; @@ -646,6 +680,11 @@ export async function createPageNavigationEngine( if (!r || result?.redirectedTo) { return null; } + // Another deployment answered: cache nothing, so the visit that follows a + // hover reloads instead of rendering props this build's chunks cannot show. + if (isStaleBuild(pagesBuildId(), r.headers.get(PAGES_BUILD_HEADER))) { + return null; + } if (!r.headers.get('X-VoidPages')) { return ( (await loadStaticPageData(url, r, undefined, !STATIC_PAGE_DATA_FAST_PATH))?.pageData ?? @@ -730,6 +769,7 @@ export async function createPageNavigationEngine( Partial> = { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...buildHeaders(pagesBuildId()), Accept: 'application/json', }; if (options._preservedQuery && method !== 'GET') { @@ -805,7 +845,25 @@ export async function createPageNavigationEngine( ? await fetchPageResponse(url, fetchOptions) : await fetchPages(url, fetchOptions) : null; - const response = fetched?.response ?? null; + let response = fetched?.response ?? null; + + // The destination was rendered by another deployment, so this tab's chunks + // are gone. Treat the payload as absent: the document load below lands on the + // requested destination with its query and hash. A mutation has already run, + // so only a GET is allowed to get here. One reload per destination: when the + // document comes back from the old build anyway, rendering the payload lets + // the error boundaries take over instead of reloading in a loop. A response + // that names no build, from an older Void, is not evidence of a new one. + const servedBy = response?.headers.get(PAGES_BUILD_HEADER) ?? null; + if ( + method === 'GET' && + servedBy !== null && + isStaleBuild(pagesBuildId(), servedBy) && + claimDeployReload(servedBy, url) + ) { + response = null; + pageData = undefined; + } if (pageData === undefined && !response) { window.location.href = url; diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index ee9bfd497..313c3fb25 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -1,7 +1,9 @@ import { existsSync } from 'node:fs'; -import { dirname } from 'pathslash'; +import { dirname, isAbsolute, join } from 'pathslash'; import { normalizePath } from 'vite'; import type { Plugin, ResolvedConfig, UserConfig } from 'vite'; +import { computePagesBuildId } from './build-id-source.ts'; +import { PAGES_BUILD_ID_DEFINE } from './build-id.ts'; import { assertLinkPrefetchValue } from './prefetch.ts'; import type { CacheForInput, LinkPrefetchValue } from './prefetch.ts'; import { scanPages } from './scan.ts'; @@ -30,6 +32,11 @@ export type PagesPluginOptions = { root?: string; viewTransitions?: boolean; prefetch?: PrefetchConfig; + /** + * Reload the destination when a tab navigates against a newer deployment. + * Defaults to `true`. Turn it off to keep error boundaries in charge. + */ + deployRecovery?: boolean; }; /** @@ -51,11 +58,31 @@ export function resolvePrefetchConfig( type CreatePagesPluginOptions = { name: string; root?: string; + deployRecovery?: boolean; generateRenderer: (scan: PageScanResult, isDev: boolean) => string; generateClient: (scan: PageScanResult, staticPageData: StaticPageDataBuildOptions) => string; config: (context: PagesPluginContext) => UserConfig | void | Promise; }; +/** + * The files that are not app source: the build output of every environment, and + * assets that never take part in a chunk hash. + */ +function buildIdExcludes(root: string, userConfig: UserConfig): Array { + const dirs = new Set(['dist']); + const add = (dir: unknown) => { + if (typeof dir === 'string') { + dirs.add(dir); + } + }; + add(userConfig.build?.outDir); + for (const environment of Object.values(userConfig.environments ?? {})) { + add(environment?.build?.outDir); + } + add(userConfig.publicDir === undefined ? 'public' : userConfig.publicDir); + return [...dirs].map((dir) => (isAbsolute(dir) ? dir : join(root, dir))); +} + /** Shared Vite lifecycle; adapters own their generated code and environment configuration. */ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOptions): Plugin { let pageScan: PageScanResult | null = null; @@ -63,6 +90,10 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp let viteConfig: ResolvedConfig | undefined; const root = options.root ?? dirname(pagesDir); const normalizedPagesDir = normalizePath(pagesDir); + // One id for the whole app: both bundles get it from the same define, and Vite + // may resolve this config once per environment, so it is derived from the source + // rather than minted here. + let buildId: string | undefined; let pendingRescan: Promise | null = null; async function rescanPages(): Promise { pageScan = existsSync(pagesDir) @@ -164,19 +195,42 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp viteConfig = config; }, - config(_, env) { + config(userConfig, env) { // Set before the early return: pages/ may be created after the server starts. - isDev = env.command === 'serve'; + const dev = env.command === 'serve'; + isDev = dev; if (!existsSync(pagesDir)) { return; } - return options.config({ + const pagesConfig = options.config({ isDev, async scan() { await runRescan(); return pageScan; }, }); + const withBuildId = (resolved: UserConfig | void): UserConfig | void => { + // The dev server serves a single build, so a tab never outlives the chunks + // it imported, and an app without a client entry has no tab to recover. + // Leaving the id undefined keeps every build check a no-op there. + if (dev || resolved == null || options.deployRecovery === false) { + return resolved; + } + buildId ??= computePagesBuildId(root, buildIdExcludes(root, userConfig)); + return { + ...resolved, + define: { + ...resolved.define, + [PAGES_BUILD_ID_DEFINE]: JSON.stringify(buildId), + // An explicit app define wins: it pins the id for a fixture or forces + // one that outlives this process, such as a commit sha. + ...userConfig.define, + }, + }; + }; + return pagesConfig instanceof Promise + ? pagesConfig.then(withBuildId) + : withBuildId(pagesConfig); }, }; } diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index c9542f900..d4d152d85 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -1,10 +1,11 @@ -import { PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { buildHeaders, isStaleBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION } from '@void/edge'; import type { Context } from 'hono'; import type { HTTPException } from 'hono/http-exception'; import { executeComposedHandler, getHandlerComposition } from '../runtime/handler/composition.ts'; import type { CloudBindings, CloudContext } from '../runtime/handler/index.ts'; import { isConvertedResponse } from '../runtime/handler/response.ts'; import { hasActionKey, searchWithoutActionKey } from './action-key.ts'; +import { pagesBuildId } from './build-id.ts'; import { DEFERRED, separateDeferred } from './defer.ts'; import type { ResolvedDeferredGroup } from './defer.ts'; import { @@ -97,7 +98,17 @@ function isPagesRequest(c: CloudContext): boolean { } function needsPageReload(c: CloudContext): boolean { - return isPagesRequest(c) && c.req.header('X-VoidPages-Version') !== PAGES_PROTOCOL_VERSION; + if (!isPagesRequest(c)) { + return false; + } + // A tab that outlived its deployment holds chunks that are gone. Its next GET + // navigation reloads the destination instead of importing a stale component. + // Mutations keep their response: the action already ran, and a page load would + // throw away its result. + return ( + c.req.header('X-VoidPages-Version') !== PAGES_PROTOCOL_VERSION || + (c.req.method === 'GET' && isStaleBuild(pagesBuildId(), c.req.header(PAGES_BUILD_HEADER))) + ); } /** Old clients reload a successful non-Pages response; form errors stay readable. */ @@ -110,6 +121,8 @@ function legacyPageResponse( 'Content-Type': errors ? 'application/json' : 'text/plain; charset=utf-8', 'Cache-Control': 'no-store', Vary: 'X-VoidPages, X-VoidPages-Version', + // Tells the client why it is reloading, and from which build to reload. + ...buildHeaders(pagesBuildId()), }); headers.delete('X-VoidPages'); return new Response(errors ? JSON.stringify({ errors }) : null, { @@ -301,7 +314,11 @@ function pageJsonResponse(c: CloudContext, pageObj: PageObject): Response { headers: pageResponseHeaders(c, { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...buildHeaders(pagesBuildId()), 'Content-Type': 'application/json', + // Not in Vary: the body does not depend on the build, and a per-build key + // would split every shared cache entry. Only the reload response differs, + // and it is no-store. Vary: 'X-VoidPages, X-VoidPages-Version', ...POWERED_BY, }), @@ -880,6 +897,10 @@ async function runPageGet( // Stream NDJSON: first line is PageObject, subsequent lines are deferred groups c.header('X-VoidPages', 'true'); c.header('X-VoidPages-Version', PAGES_PROTOCOL_VERSION); + const build = pagesBuildId(); + if (build !== '') { + c.header(PAGES_BUILD_HEADER, build); + } return streamDeferredResponse( serializePageData(pageObj) + '\n', deferredMap, diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts new file mode 100644 index 000000000..bc2faca9d --- /dev/null +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -0,0 +1,174 @@ +import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'; +import { tmpdir } from 'node:os'; +import { join } from 'node:path'; +import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; +import { buildHeaders, isStaleBuild } from '../../../edge/src/pages-protocol.ts'; +import { computePagesBuildId } from '../../src/pages/build-id-source.ts'; +import { pagesBuildId } from '../../src/pages/build-id.ts'; +import { createPagesPlugin } from '../../src/pages/plugin.ts'; +import { getHookHandler } from '../helpers/vite-hooks.ts'; + +afterEach(() => { + vi.unstubAllEnvs(); +}); + +describe('pagesBuildId', () => { + it('reads the id the build defines', () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + expect(pagesBuildId()).toBe('build-2'); + }); + + it('is empty where no build defined one, which disables every check', () => { + expect(pagesBuildId()).toBe(''); + }); +}); + +describe('isStaleBuild', () => { + it.each([ + ['another build', 'build-2', 'build-1', true], + ['the same build', 'build-2', 'build-2', false], + ['no id on the wire', 'build-2', null, false], + ['the header missing', 'build-2', undefined, false], + ['no id in this bundle', '', 'build-1', false], + ])('%s', (_, buildId, seen, expected) => { + expect(isStaleBuild(buildId, seen)).toBe(expected); + }); +}); + +describe('buildHeaders', () => { + it('carries the build only when one is known', () => { + expect(buildHeaders('')).toEqual({}); + expect(buildHeaders('build-2')).toEqual({ 'X-VoidPages-Build': 'build-2' }); + }); +}); + +describe('computePagesBuildId', () => { + function createSourceFixture(content: string): string { + const root = mkdtempSync(join(tmpdir(), 'void-build-id-')); + mkdirSync(join(root, 'pages'), { recursive: true }); + writeFileSync(join(root, 'pages/index.tsx'), content); + return root; + } + + it('hashes the source, so identical trees keep the id', () => { + const content = 'export default function Page() {}\n'; + expect(computePagesBuildId(createSourceFixture(content), [])).toBe( + computePagesBuildId(createSourceFixture(content), []), + ); + }); + + it('recomputes when a file changes', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = computePagesBuildId(root, []); + + writeFileSync(join(root, 'pages/index.tsx'), 'export default function Page() { return 1 }\n'); + + expect(computePagesBuildId(root, [])).not.toBe(first); + }); + + it('reuses the id while size and modification time still match', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const path = join(root, 'pages/index.tsx'); + // A whole second, so the restored timestamp is byte for byte the old one. + const stamp = 1_700_000_000; + utimesSync(path, stamp, stamp); + const first = computePagesBuildId(root, []); + + // Same size, and the mtime put back: nothing a build can observe changed. + writeFileSync(path, 'export default function Home() {}\n'); + utimesSync(path, stamp, stamp); + expect(computePagesBuildId(root, [])).toBe(first); + + // The content really did change, so a fresh pass must notice. + rmSync(join(root, '.void'), { recursive: true, force: true }); + expect(computePagesBuildId(root, [])).not.toBe(first); + }); + + it('ignores build output, dot directories and installed packages', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = computePagesBuildId(root, [join(root, 'dist')]); + + for (const dir of ['dist', 'node_modules/pkg', '.void', '.wrangler']) { + mkdirSync(join(root, dir), { recursive: true }); + writeFileSync(join(root, dir, 'generated.js'), 'changed\n'); + } + + expect(computePagesBuildId(root, [join(root, 'dist')])).toBe(first); + }); +}); + +describe('createPagesPlugin build id', () => { + type PagesConfigHook = ( + userConfig: Record, + env: { command: 'build' | 'serve' }, + ) => Promise<{ define?: Record } | undefined>; + + function createConfigHook( + root?: string, + pluginOptions: { deployRecovery?: boolean } = {}, + ): PagesConfigHook { + const appRoot = root ?? createFixture(); + const plugin = createPagesPlugin(join(appRoot, 'pages'), { + name: 'test:pages', + generateRenderer: () => '', + generateClient: () => '', + config: () => ({}), + ...pluginOptions, + }); + return getHookHandler(plugin.config) as unknown as PagesConfigHook; + } + + function createFixture(): string { + const root = mkdtempSync(join(tmpdir(), 'void-pages-build-')); + const pagesDir = join(root, 'pages'); + mkdirSync(pagesDir, { recursive: true }); + writeFileSync(join(pagesDir, 'index.tsx'), 'export default function Page() {}\n'); + return root; + } + + const DEFINE = 'import.meta.env.__VOID_PAGES_BUILD_ID'; + + it('defines one id for a build, shared by every environment', async () => { + const config = createConfigHook(); + + const client = await config({}, { command: 'build' }); + const server = await config({}, { command: 'build' }); + + const id = client!.define![DEFINE]!; + expect(JSON.parse(id)).toMatch(/^[0-9a-f]{12}$/); + // Both bundles must carry the same id, or every navigation would reload. + expect(server!.define![DEFINE]).toBe(id); + }); + + it('derives the id from the app source, so identical sources keep it', async () => { + const root = createFixture(); + const idOf = async () => + (await createConfigHook(root)({}, { command: 'build' }))!.define![DEFINE]; + + const first = await idOf(); + expect(await idOf()).toBe(first); + + writeFileSync(join(root, 'pages', 'index.tsx'), 'export default function Other() {}\n'); + expect(await idOf()).not.toBe(first); + }); + + it('defines nothing when deploy recovery is off', async () => { + const config = createConfigHook(undefined, { deployRecovery: false }); + + expect(await config({}, { command: 'build' })).toEqual({}); + }); + + it('defines nothing in the dev server, which serves one build', async () => { + const config = createConfigHook(); + + expect(await config({}, { command: 'serve' })).toEqual({}); + }); + + it('lets an explicit define pin the id', async () => { + const config = createConfigHook(); + + const pinned = await config({ define: { [DEFINE]: '"commit-abc"' } }, { command: 'build' }); + + expect(pinned!.define![DEFINE]).toBe('"commit-abc"'); + }); +}); diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 33eb2a373..54391f67e 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -133,6 +133,120 @@ function createTestRouter({ adapter, ...config }: TestRouterConfig = {}) { afterEach(() => { vi.unstubAllGlobals(); + vi.unstubAllEnvs(); +}); + +describe('Pages build recovery', () => { + function staleJson(body: unknown): Response { + return Response.json(body, { + headers: { 'X-VoidPages': 'true', 'X-VoidPages-Build': 'build-1' }, + }); + } + + const stalePage = { + component: 'home', + props: { title: 'post' }, + url: '/next?tab=1', + errors: null, + }; + + it('reloads the destination when another build answered the navigation', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const fetch = vi.fn(async () => staleJson(stalePage)); + vi.stubGlobal('fetch', fetch); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/next?tab=1#details'); + + // This tab names its own build, so the server can answer for it. + expect(fetch).toHaveBeenCalledWith( + '/next?tab=1', + expect.objectContaining({ + headers: expect.objectContaining({ 'X-VoidPages-Build': 'build-2' }), + }), + ); + // A document load keeps the query and the fragment, and never renders stale props. + expect(window.location.href).toBe('/next?tab=1#details'); + expect(applyUpdate).not.toHaveBeenCalled(); + }); + + it('drops a prefetch from another build and reloads on the visit instead', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const { router } = await createTestRouter(); + + await router.prefetch('/next'); + expect(window.location.href).toBeUndefined(); + + await router.visit('/next'); + expect(window.location.href).toBe('/next'); + }); + + it('treats a response from a server with no build id as unchanged', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + // An older Void names no build. It is not evidence of a new one. + vi.stubGlobal( + 'fetch', + vi.fn(async () => Response.json(stalePage, { headers: { 'X-VoidPages': 'true' } })), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/next'); + + expect(window.location.href).toBeUndefined(); + expect(applyUpdate).toHaveBeenCalled(); + }); + + it('reloads a destination once, then lets the page render and fail on its own', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const stored = new Map(); + vi.stubGlobal('sessionStorage', { + getItem: (key: string) => stored.get(key) ?? null, + setItem: (key: string, value: string) => void stored.set(key, value), + removeItem: (key: string) => void stored.delete(key), + }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/next'); + expect(window.location.href).toBe('/next'); + + // The document came back from the old build anyway: rendering must not loop. + (window.location as unknown as { href?: string }).href = undefined; + await router.visit('/next'); + expect(window.location.href).toBeUndefined(); + expect(applyUpdate).toHaveBeenCalled(); + }); + + it('applies a mutation answered by another build and never reloads', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/next', { method: 'POST' }); + + // The action already ran: a page load would replay nothing and lose its result. + expect(window.location.href).toBeUndefined(); + expect(applyUpdate).toHaveBeenCalled(); + }); }); describe('Pages serialization compatibility', () => { diff --git a/packages/void/test/unit/pages-plugin-adapters.test.ts b/packages/void/test/unit/pages-plugin-adapters.test.ts index 5dccfde91..e3fcc5b82 100644 --- a/packages/void/test/unit/pages-plugin-adapters.test.ts +++ b/packages/void/test/unit/pages-plugin-adapters.test.ts @@ -39,13 +39,14 @@ describe.each(adapters)('$name Pages plugin contract', (adapter) => { root = undefined; }); - function setup() { + function setup(options: Record = {}) { root = mkdtempSync(join(tmpdir(), `void-${adapter.name}-pages-plugin-`)); const pagesDir = join(root, '_source', '_views'); const plugins = adapter.create(pagesDir, { root, viewTransitions: true, prefetch: { defaultStrategy: ['hover', 'click'], hoverDelay: 123, cacheFor: '45s' }, + ...options, }); const plugin = (Array.isArray(plugins) ? plugins : [plugins]).find( (candidate: Plugin) => candidate.name === `void-${adapter.name}:pages`, @@ -87,7 +88,14 @@ describe.each(adapters)('$name Pages plugin contract', (adapter) => { rollupOptions: { input: { 'pages-client': 'virtual:void-pages-client' } }, }, }; - expect(config).toEqual( + const { define, ...rest } = config as Record & { + define?: Record; + }; + // Every Pages client carries the build it was compiled into. + expect(define).toEqual({ + 'import.meta.env.__VOID_PAGES_BUILD_ID': expect.stringMatching(/^"[0-9a-f]{12}"$/), + }); + expect(rest).toEqual( adapter.name === 'vue' ? { environments: { client: clientConfig } } : adapter.name === 'react' @@ -99,6 +107,17 @@ describe.each(adapters)('$name Pages plugin contract', (adapter) => { } }); + it('omits the build id when deploy recovery is off', async () => { + const { plugin, write } = setup({ deployRecovery: false }); + write(`about.${adapter.extension}`); + + const config = (await handler(plugin.config)({}, { command: 'build' })) as + | { define?: Record } + | undefined; + + expect(config?.define).toBeUndefined(); + }); + it('resolves only the Pages virtual module IDs', async () => { const { plugin } = setup(); const hook = plugin.resolveId as { filter: { id: RegExp } }; diff --git a/packages/void/test/unit/pages-protocol.test.ts b/packages/void/test/unit/pages-protocol.test.ts index c710c8056..dff4451d4 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -1,6 +1,6 @@ import { Hono } from 'hono'; import { HTTPException } from 'hono/http-exception'; -import { describe, expect, it, vi } from 'vite-plus/test'; +import { describe, expect, it, vi, afterEach } from 'vite-plus/test'; import { PAGES_PROTOCOL_VERSION } from '../../../edge/src/pages-protocol.ts'; import { defer } from '../../src/pages/defer.ts'; import { @@ -1604,6 +1604,80 @@ describe('handlePageGet with deferred props', () => { }); }); +describe('Pages build recovery', () => { + afterEach(() => { + vi.unstubAllEnvs(); + }); + + function pagesContext(method: 'GET' | 'POST', build: string | null) { + return createTestContext(method, '/blog/post', { + headers: { + 'x-voidpages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + ...(build === null ? {} : { 'X-VoidPages-Build': build }), + }, + }); + } + + it('answers a tab from another build with a reload instead of page props', async () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const handler = vi.fn(() => ({ title: 'post' })); + const render = vi.fn(async () => 'rendered'); + + const response = await handlePageGet( + handler, + undefined, + await pagesContext('GET', 'build-1'), + 'blog/post', + render, + mockGetAssetTags, + ); + + // Nothing from this build may reach a client that cannot import it. + expect(handler).not.toHaveBeenCalled(); + expect(render).not.toHaveBeenCalled(); + expect(response.headers.get('X-VoidPages')).toBeNull(); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + // The client reloads because this build differs from its own. + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + + it('serves the payload to the build that rendered it', async () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + + const response = await handlePageGet( + () => ({ title: 'post' }), + undefined, + await pagesContext('GET', 'build-2'), + 'blog/post', + mockRenderFn, + mockGetAssetTags, + ); + + expect(response.headers.get('X-VoidPages')).toBe('true'); + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + + it('keeps its response for a stale mutation, so the action never replays', async () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const action = vi.fn(); + + const response = await handlePageMutation( + action, + () => ({ title: 'post' }), + undefined, + await pagesContext('POST', 'build-1'), + 'blog/post', + mockRenderFn, + mockGetAssetTags, + ); + + expect(action).toHaveBeenCalledOnce(); + expect(response.headers.get('X-VoidPages')).toBe('true'); + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); +}); + describe('flattenValidationErrors', () => { it('flattens nested issues format into flat map', () => { const body = { diff --git a/packages/vue/src/plugin-pages.ts b/packages/vue/src/plugin-pages.ts index 03fd617be..3f8bc978a 100644 --- a/packages/vue/src/plugin-pages.ts +++ b/packages/vue/src/plugin-pages.ts @@ -241,6 +241,7 @@ export function pagesPlugin( createPagesPlugin(pagesDir, { name: 'void-vue:pages', root: options?.root, + deployRecovery: options?.deployRecovery, generateRenderer(scan) { return generateRendererModule(scan, pagesDir); }, diff --git a/packages/vue/src/plugin.ts b/packages/vue/src/plugin.ts index 9ea809190..f00c55121 100644 --- a/packages/vue/src/plugin.ts +++ b/packages/vue/src/plugin.ts @@ -9,6 +9,7 @@ export type VoidVueOptions = Readonly<{ vue?: Parameters[0]; viewTransitions?: boolean; prefetch?: PrefetchConfig; + deployRecovery?: boolean; }>; export function voidVue(options?: VoidVueOptions): Array { @@ -18,7 +19,8 @@ export function voidVue(options?: VoidVueOptions): Array { vue(options?.vue) as Plugin, ...pagesPlugin( pagesDir, - { root, viewTransitions: options?.viewTransitions, prefetch: options?.prefetch }, + // Spread so adapter options the pages plugin owns reach it without per-option glue. + { ...options, root }, options?.vue?.script?.babelParserPlugins, ), ...islandsPlugin(pagesDir, { root }), From 52a30a1edb7cef30ae21563cf582fe0c818fc2bc Mon Sep 17 00:00:00 2001 From: 0froq Date: Sun, 22 Nov 2026 10:58:05 +0800 Subject: [PATCH 02/14] fix: serve ISR page data only to the build that rendered it A cached JSON payload now carries the build that rendered it, and a request from another build skips the entry so the app can answer with its reload response. --- packages/isr/src/runtime.ts | 26 +++++++- packages/void/test/unit/isr-cache.test.ts | 77 +++++++++++++++++++++++ 2 files changed, 100 insertions(+), 3 deletions(-) diff --git a/packages/isr/src/runtime.ts b/packages/isr/src/runtime.ts index 79593863d..eb7883d5d 100644 --- a/packages/isr/src/runtime.ts +++ b/packages/isr/src/runtime.ts @@ -1,4 +1,9 @@ -import { matchSegmentPattern, PAGES_PROTOCOL_VERSION } from '@void/edge'; +import { + isStaleBuild, + matchSegmentPattern, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, +} from '@void/edge'; import { buildVariantOriginalUrl, decodeIsrCacheEntry, @@ -324,7 +329,12 @@ function sharedHtmlCacheHeaders(response: Response, ttl: number, state: 'HIT' | return headers; } -function jsonCacheResponse(pageData: string, ttl: number, state: 'HIT' | 'MISS'): Response { +function jsonCacheResponse( + pageData: string, + ttl: number, + state: 'HIT' | 'MISS', + build: string | null, +): Response { const response = new Response(pageData, { headers: { 'content-type': 'application/json', @@ -332,6 +342,9 @@ function jsonCacheResponse(pageData: string, ttl: number, state: 'HIT' | 'MISS') // `X-VoidPages` is present, and otherwise reloads the whole page. 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + // Kept with the payload: a hit for a client from another build must not + // pass off this render's props as its own. + ...(build ? { [PAGES_BUILD_HEADER]: build } : {}), Vary: 'X-VoidPages, X-VoidPages-Version', 'Cache-Control': `public, s-maxage=${ttl}, max-age=0, must-revalidate`, 'x-isr-cache': state, @@ -357,6 +370,7 @@ export async function populateJsonEdgeCache( return; } try { + const build = response.headers.get(PAGES_BUILD_HEADER); const fromHeader = response.headers.get('x-void-page-data'); const pageData = fromHeader ? normalizePageDataForJsonCache(fromHeader) @@ -364,7 +378,7 @@ export async function populateJsonEdgeCache( if (!pageData) { return; } - await cache.put(cacheKey, jsonCacheResponse(pageData, ttl, state)); + await cache.put(cacheKey, jsonCacheResponse(pageData, ttl, state, build)); } catch { // Fail open. } @@ -580,6 +594,12 @@ async function handleIsrInternal( return null; // fail open → caller renders live } if (jsonCached && hasCurrentSharedCachePolicy(jsonCached)) { + // A cached payload from another build would hand this client page props it + // has no components for. Let the app answer, which reloads a stale tab. + const cachedBuild = jsonCached.headers.get(PAGES_BUILD_HEADER) ?? ''; + if (isStaleBuild(cachedBuild, request.headers.get(PAGES_BUILD_HEADER))) { + return render(request); + } return clientRevalidateResponse(jsonCached); } if (jsonCached) { diff --git a/packages/void/test/unit/isr-cache.test.ts b/packages/void/test/unit/isr-cache.test.ts index 6af520c3a..441eb6a66 100644 --- a/packages/void/test/unit/isr-cache.test.ts +++ b/packages/void/test/unit/isr-cache.test.ts @@ -925,6 +925,83 @@ describe('handleIsr', () => { expect(await res!.text()).toBe('{"component":"Blog","props":{}}'); }); + it('bypasses a cached JSON variant that belongs to another build', async () => { + const { kv } = createKvMock(); + const env = makeEnv(kv); + const { render } = createRender( + () => + new Response('live', { + headers: { + 'content-type': 'text/html', + 'x-void-page-data': '{"component":"Blog","props":{}}', + 'X-VoidPages-Build': 'build-1', + }, + }), + ); + const { ctx, flush } = createCtx(); + await handleIsr(htmlRequest(), env, ctx, OPTS, render); + await flush(); + expect(edge.store.has(jsonEdgeKey(HOST, '/blog/post', DPL))).toBe(true); + + const pagesHeaders = (build: string) => ({ + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': build, + }); + + // Same build: the cached payload answers and names the build it came from. + const { render: hitRender, spy: hitSpy } = createRender( + () => new Response('SHOULD-NOT-RENDER'), + ); + const hit = await handleIsr( + htmlRequest('/blog/post', pagesHeaders('build-1')), + env, + createCtx().ctx, + OPTS, + hitRender, + ); + expect(hitSpy).not.toHaveBeenCalled(); + expect(hit!.headers.get('X-VoidPages-Build')).toBe('build-1'); + + // A client that sends no build id cannot be shown a reload; the payload stays. + const { render: legacyRender, spy: legacySpy } = createRender( + () => new Response('SHOULD-NOT-RENDER'), + ); + const legacy = await handleIsr( + htmlRequest('/blog/post', { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + }), + env, + createCtx().ctx, + OPTS, + legacyRender, + ); + expect(legacySpy).not.toHaveBeenCalled(); + expect(legacy!.headers.get('X-VoidPages-Build')).toBe('build-1'); + + // Another build: the app answers instead, which reloads the stale tab. + const { render: liveRender, spy: liveSpy } = createRender( + () => + new Response('{"component":"Blog","props":{"fresh":true}}', { + headers: { + 'content-type': 'application/json', + 'X-VoidPages': 'true', + 'X-VoidPages-Build': 'build-2', + }, + }), + ); + const live = await handleIsr( + htmlRequest('/blog/post', pagesHeaders('build-2')), + env, + createCtx().ctx, + OPTS, + liveRender, + ); + expect(liveSpy).toHaveBeenCalledTimes(1); + expect(live!.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + it.each([ ['getWithMetadata throws', true], ['the KV entry is from an older cache policy', false], From f542f8b3f944dfafb5b5d74f45b309dd627c93ed Mon Sep 17 00:00:00 2001 From: 0froq Date: Mon, 23 Nov 2026 06:24:45 +0800 Subject: [PATCH 03/14] fix: address Pages deploy recovery review findings A stale navigation reloaded again when the reload response itself came back from the old build, since that response skips the page-data branch where the guard lives. The tab now stops on the recovery page instead. ISR deleted the shared HTML entry when a stale client's reload response looked uncacheable, and trusted cached payloads that named no build. Both paths now answer from the app and keep the entry. The build id hashed source files only, so builds that differed in `VITE_` env or `define` values shared an id while emitting different chunks. Both are part of the id now. --- packages/edge/src/index.ts | 1 + packages/edge/src/pages-protocol.ts | 13 ++++ packages/isr/src/runtime.ts | 15 +++- packages/void/src/pages/build-id-source.ts | 22 ++++-- packages/void/src/pages/navigation-engine.ts | 25 +++---- packages/void/src/pages/plugin.ts | 22 +++++- packages/void/test/unit/isr-cache.test.ts | 70 ++++++++++++++++++ .../void/test/unit/pages-build-id.test.ts | 30 +++++++- packages/void/test/unit/pages-client.test.ts | 35 ++++++--- platform/packages/dispatch/src/index.ts | 22 +++++- .../packages/dispatch/test/unit/index.test.ts | 72 +++++++++++++++++++ 11 files changed, 293 insertions(+), 34 deletions(-) diff --git a/packages/edge/src/index.ts b/packages/edge/src/index.ts index d7166a9f6..d35c90317 100644 --- a/packages/edge/src/index.ts +++ b/packages/edge/src/index.ts @@ -2,6 +2,7 @@ export type { ProjectZeroTrustRouting } from './access.ts'; export { buildHeaders, isStaleBuild, + pagesPayloadFitsBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION, } from './pages-protocol.ts'; diff --git a/packages/edge/src/pages-protocol.ts b/packages/edge/src/pages-protocol.ts index 43c072bf8..e0cac9795 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -21,3 +21,16 @@ export function isStaleBuild(buildId: string, seen: string | null | undefined): export function buildHeaders(buildId: string): Record { return buildId === '' ? {} : { [PAGES_BUILD_HEADER]: buildId }; } + +/** + * Whether a cached Pages payload may answer a request. A client that names no + * build cannot tell builds apart, so it keeps the cached payload. A client that + * names one accepts only a payload from that same build, and an entry without an + * id predates ids, so it is not trusted either. + */ +export function pagesPayloadFitsBuild( + cachedBuild: string | null, + requestBuild: string | null, +): boolean { + return requestBuild === null || cachedBuild === requestBuild; +} diff --git a/packages/isr/src/runtime.ts b/packages/isr/src/runtime.ts index eb7883d5d..05ccc3109 100644 --- a/packages/isr/src/runtime.ts +++ b/packages/isr/src/runtime.ts @@ -1,6 +1,6 @@ import { - isStaleBuild, matchSegmentPattern, + pagesPayloadFitsBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION, } from '@void/edge'; @@ -596,8 +596,12 @@ async function handleIsrInternal( if (jsonCached && hasCurrentSharedCachePolicy(jsonCached)) { // A cached payload from another build would hand this client page props it // has no components for. Let the app answer, which reloads a stale tab. - const cachedBuild = jsonCached.headers.get(PAGES_BUILD_HEADER) ?? ''; - if (isStaleBuild(cachedBuild, request.headers.get(PAGES_BUILD_HEADER))) { + if ( + !pagesPayloadFitsBuild( + jsonCached.headers.get(PAGES_BUILD_HEADER), + request.headers.get(PAGES_BUILD_HEADER), + ) + ) { return render(request); } return clientRevalidateResponse(jsonCached); @@ -606,6 +610,11 @@ async function handleIsrInternal( await safeCacheDelete(cache, jsonKey); } const response = await render(request); + // The app answered a stale client with its reload response. That says nothing + // about this path's cached HTML, which other tabs can still use. + if (!response.headers.get('X-VoidPages')) { + return response; + } const ttl = resolveRevalidateTtl(response, isrTtl); if (isUncacheableRender(response, ttl, false)) { ctx.waitUntil( diff --git a/packages/void/src/pages/build-id-source.ts b/packages/void/src/pages/build-id-source.ts index b84b545b6..8de410b72 100644 --- a/packages/void/src/pages/build-id-source.ts +++ b/packages/void/src/pages/build-id-source.ts @@ -29,16 +29,24 @@ type CacheEntry = { * turns the second pass into one stat walk, keyed by file size and modification * time. A write always moves the modification time, so a fingerprint that still * matches describes the same content. + * + * `buildInputs` carries what the client inlines without a source file of its + * own, such as env vars and `define` entries. Two builds that differ only there + * still emit different chunks. */ -export function computePagesBuildId(root: string, excludeDirs: Array): string { +export function computePagesBuildId( + root: string, + excludeDirs: Array, + buildInputs = '', +): string { const excluded = new Set(excludeDirs.map((dir) => (isAbsolute(dir) ? dir : join(root, dir)))); const files = sourceFiles(root, excluded); - const fingerprint = fingerprintOf(root, files); + const fingerprint = fingerprintOf(root, files, buildInputs); const cached = readCachedId(root, fingerprint); if (cached) { return cached; } - const id = contentIdOf(root, files); + const id = contentIdOf(root, files, buildInputs); writeCachedId(root, fingerprint, id); return id; } @@ -69,8 +77,10 @@ function sourceFiles(root: string, excluded: Set): Array { return files.sort(); } -function fingerprintOf(root: string, files: Array): string { +function fingerprintOf(root: string, files: Array, buildInputs: string): string { const hash = createHash('sha256'); + hash.update(buildInputs); + hash.update('\0'); for (const file of files) { const stats = statSync(join(root, file)); hash.update(`${file}\0${stats.size}\0${stats.mtimeMs}\0`); @@ -78,8 +88,10 @@ function fingerprintOf(root: string, files: Array): string { return hash.digest('hex'); } -function contentIdOf(root: string, files: Array): string { +function contentIdOf(root: string, files: Array, buildInputs: string): string { const hash = createHash('sha256'); + hash.update(buildInputs); + hash.update('\0'); for (const file of files) { hash.update(file); hash.update('\0'); diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index 78fa0a908..9a84f34c2 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -850,19 +850,20 @@ export async function createPageNavigationEngine( // The destination was rendered by another deployment, so this tab's chunks // are gone. Treat the payload as absent: the document load below lands on the // requested destination with its query and hash. A mutation has already run, - // so only a GET is allowed to get here. One reload per destination: when the - // document comes back from the old build anyway, rendering the payload lets - // the error boundaries take over instead of reloading in a loop. A response - // that names no build, from an older Void, is not evidence of a new one. + // so only a GET is allowed to get here. A response that names no build, from + // an older Void, is not evidence of a new one. const servedBy = response?.headers.get(PAGES_BUILD_HEADER) ?? null; - if ( - method === 'GET' && - servedBy !== null && - isStaleBuild(pagesBuildId(), servedBy) && - claimDeployReload(servedBy, url) - ) { - response = null; - pageData = undefined; + if (method === 'GET' && servedBy !== null && isStaleBuild(pagesBuildId(), servedBy)) { + if (claimDeployReload(servedBy, url)) { + response = null; + pageData = undefined; + } else { + // The last reload landed on the same old document, so this payload would + // replace the page with components that cannot load here, and reloading + // again would loop. Stop, and leave the tab a way out. + showTerminalPageError(url); + return undefined; + } } if (pageData === undefined && !response) { diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index 313c3fb25..e8a1e67f6 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -1,6 +1,6 @@ import { existsSync } from 'node:fs'; import { dirname, isAbsolute, join } from 'pathslash'; -import { normalizePath } from 'vite'; +import { loadEnv, normalizePath } from 'vite'; import type { Plugin, ResolvedConfig, UserConfig } from 'vite'; import { computePagesBuildId } from './build-id-source.ts'; import { PAGES_BUILD_ID_DEFINE } from './build-id.ts'; @@ -83,6 +83,20 @@ function buildIdExcludes(root: string, userConfig: UserConfig): Array { return [...dirs].map((dir) => (isAbsolute(dir) ? dir : join(root, dir))); } +/** + * Values the client bundle inlines without appearing in a source file: the + * env vars Vite exposes, and the app's `define` entries. Two builds that differ + * only here still emit different chunks, so the id has to cover them. + */ +function clientBuildInputs(root: string, userConfig: UserConfig, mode: string): string { + const envDir = typeof userConfig.envDir === 'string' ? userConfig.envDir : root; + const env = Object.entries(loadEnv(mode, envDir, userConfig.envPrefix ?? 'VITE_')).sort( + ([a], [b]) => a.localeCompare(b), + ); + const define = Object.entries(userConfig.define ?? {}).sort(([a], [b]) => a.localeCompare(b)); + return JSON.stringify({ env, define }); +} + /** Shared Vite lifecycle; adapters own their generated code and environment configuration. */ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOptions): Plugin { let pageScan: PageScanResult | null = null; @@ -216,7 +230,11 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp if (dev || resolved == null || options.deployRecovery === false) { return resolved; } - buildId ??= computePagesBuildId(root, buildIdExcludes(root, userConfig)); + buildId ??= computePagesBuildId( + root, + buildIdExcludes(root, userConfig), + clientBuildInputs(root, userConfig, env.mode), + ); return { ...resolved, define: { diff --git a/packages/void/test/unit/isr-cache.test.ts b/packages/void/test/unit/isr-cache.test.ts index 441eb6a66..3fb02acd1 100644 --- a/packages/void/test/unit/isr-cache.test.ts +++ b/packages/void/test/unit/isr-cache.test.ts @@ -13,6 +13,7 @@ import { markSharedCachePolicy, normalizeIsrPath, packIsrValue, + populateJsonEdgeCache, readIsrCache, SHARED_CACHE_POLICY_VERSION, writeIsrCache, @@ -1002,6 +1003,75 @@ describe('handleIsr', () => { expect(live!.headers.get('X-VoidPages-Build')).toBe('build-2'); }); + it('leaves an entry with no build id to the app when the client names one', async () => { + // An entry from before ids existed cannot answer a client that has one. + await populateJsonEdgeCache( + edge.cache, + jsonEdgeKey(HOST, '/blog/post', DPL), + new Response('', { + headers: { 'x-void-page-data': '{"component":"Blog","props":{}}' }, + }), + 60, + 'HIT', + ); + const env = makeEnv(createKvMock().kv); + const { render, spy } = createRender( + () => + new Response('{"component":"Blog","props":{"fresh":true}}', { + headers: { + 'content-type': 'application/json', + 'X-VoidPages': 'true', + 'X-VoidPages-Build': 'build-2', + }, + }), + ); + + const res = await handleIsr( + htmlRequest('/blog/post', { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }), + env, + createCtx().ctx, + OPTS, + render, + ); + + expect(spy).toHaveBeenCalledTimes(1); + expect(res!.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + + it('keeps cached HTML when a stale client gets its reload response', async () => { + const { store, kv } = createKvMock(); + store.set(isrKey(DPL, HOST, '/blog/post'), corruptCases[0]!.seed()); + const env = makeEnv(kv); + const htmlKey = htmlEdgeKey(HOST, '/blog/post', DPL); + edge.store.set(htmlKey, currentSharedCacheResponse(new Response('cached'))); + const { render } = createRender( + () => new Response(null, { headers: { 'Cache-Control': 'no-store' } }), + ); + const { ctx, flush } = createCtx(); + + const res = await handleIsr( + htmlRequest('/blog/post', { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }), + env, + ctx, + OPTS, + render, + ); + await flush(); + + // The answer belongs to the JSON path only; other tabs still hold this HTML. + expect(res!.headers.get('Cache-Control')).toBe('no-store'); + expect(await edge.store.get(htmlKey)!.text()).toBe('cached'); + expect(store.has(isrKey(DPL, HOST, '/blog/post'))).toBe(true); + }); + it.each([ ['getWithMetadata throws', true], ['the KV entry is from an older cache policy', false], diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts index bc2faca9d..8725c6a44 100644 --- a/packages/void/test/unit/pages-build-id.test.ts +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -115,7 +115,12 @@ describe('createPagesPlugin build id', () => { config: () => ({}), ...pluginOptions, }); - return getHookHandler(plugin.config) as unknown as PagesConfigHook; + const hook = getHookHandler(plugin.config) as unknown as ( + userConfig: Record, + env: { command: 'build' | 'serve'; mode: string }, + ) => ReturnType; + // Vite always passes a mode; the tests only vary the command. + return (userConfig, env) => hook(userConfig, { mode: 'production', ...env }) as never; } function createFixture(): string { @@ -152,6 +157,29 @@ describe('createPagesPlugin build id', () => { expect(await idOf()).not.toBe(first); }); + it('changes the id for env values the client inlines', async () => { + const root = createFixture(); + const idFor = async (value: string) => { + vi.stubEnv('VITE_PROBE', value); + // A new plugin per call: one plugin instance keeps the first id it made. + return (await createConfigHook(root)({}, { command: 'build' }))!.define![DEFINE]; + }; + + // Two builds that differ only here still emit different chunks. + expect(await idFor('one')).not.toBe(await idFor('two')); + }); + + it('changes the id for an app define the client inlines', async () => { + const root = createFixture(); + const idFor = async (value: string) => + (await createConfigHook(root)( + { define: { __PROBE__: JSON.stringify(value) } }, + { command: 'build' }, + ))!.define![DEFINE]; + + expect(await idFor('one')).not.toBe(await idFor('two')); + }); + it('defines nothing when deploy recovery is off', async () => { const config = createConfigHook(undefined, { deployRecovery: false }); diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 54391f67e..4b15f7250 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -43,7 +43,7 @@ type TestRouterConfig = Partial> & { function stubClientGlobals(origin = 'http://localhost') { const documentStub = { - createElement: vi.fn(() => ({})), + createElement: vi.fn(() => ({ appendChild: vi.fn(), style: {} })), getElementById: vi.fn((id: string) => { if (id === '__VOID_PAGE_DATA__') { return { @@ -65,6 +65,7 @@ function stubClientGlobals(origin = 'http://localhost') { querySelector: vi.fn(() => null), querySelectorAll: vi.fn(() => []), }, + body: { replaceChildren: vi.fn() }, querySelector: vi.fn(() => null), }; @@ -205,18 +206,31 @@ describe('Pages build recovery', () => { expect(applyUpdate).toHaveBeenCalled(); }); - it('reloads a destination once, then lets the page render and fail on its own', async () => { - stubClientGlobals(); - vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + function stubReloadGuard(): void { const stored = new Map(); vi.stubGlobal('sessionStorage', { getItem: (key: string) => stored.get(key) ?? null, setItem: (key: string, value: string) => void stored.set(key, value), removeItem: (key: string) => void stored.delete(key), }); + } + + // The shape the server actually sends: a reload response, not page props. + const staleReloadResponse = () => + new Response(null, { + headers: { 'X-VoidPages-Build': 'build-1', 'Cache-Control': 'no-store' }, + }); + + it.each([ + ['page props from another build', () => staleJson(stalePage)], + ['a reload response for another build', staleReloadResponse], + ])('reloads a destination once, then stops on %s', async (_, response) => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); vi.stubGlobal( 'fetch', - vi.fn(async () => staleJson(stalePage)), + vi.fn(async () => response()), ); const applyUpdate = vi.fn(); const { router } = await createTestRouter({ adapter: { applyUpdate } }); @@ -224,11 +238,14 @@ describe('Pages build recovery', () => { await router.visit('/next'); expect(window.location.href).toBe('/next'); - // The document came back from the old build anyway: rendering must not loop. - (window.location as unknown as { href?: string }).href = undefined; + // The document came back from the old build anyway. Reloading again would + // loop, so the tab stops on the recovery page instead. + const documentUrl = 'http://localhost/'; + (window.location as unknown as { href?: string }).href = documentUrl; await router.visit('/next'); - expect(window.location.href).toBeUndefined(); - expect(applyUpdate).toHaveBeenCalled(); + expect(window.location.href).toBe(documentUrl); + expect(applyUpdate).not.toHaveBeenCalled(); + expect(document.body.replaceChildren).toHaveBeenCalled(); }); it('applies a mutation answered by another build and never reloads', async () => { diff --git a/platform/packages/dispatch/src/index.ts b/platform/packages/dispatch/src/index.ts index 125c9d396..029b42f34 100644 --- a/platform/packages/dispatch/src/index.ts +++ b/platform/packages/dispatch/src/index.ts @@ -1,4 +1,10 @@ -import { matchLiteralPattern, PAGES_PROTOCOL_VERSION, redirectToHttps } from '@void/edge'; +import { + matchLiteralPattern, + pagesPayloadFitsBuild, + PAGES_BUILD_HEADER, + PAGES_PROTOCOL_VERSION, + redirectToHttps, +} from '@void/edge'; import { clientRevalidateResponse, isEventStreamResponse } from '@void/isr/runtime'; import { PLATFORM_HEALTH_HOSTNAME_LABEL, @@ -1207,7 +1213,16 @@ const dispatcher = { // Pages protocol: check JSON edge cache, fall through on miss if (isPagesRequest) { const jsonCached = await cache.match(jsonCacheKey); - if (jsonCached && hasCurrentSharedCachePolicy(jsonCached)) { + // A payload rendered by another build carries props this client cannot + // render. Fall through so the app answers and reloads the tab. + if ( + jsonCached && + hasCurrentSharedCachePolicy(jsonCached) && + pagesPayloadFitsBuild( + jsonCached.headers.get(PAGES_BUILD_HEADER), + request.headers.get(PAGES_BUILD_HEADER), + ) + ) { requestType = 'isr'; return meter(clientRevalidateResponse(jsonCached)); } @@ -1798,8 +1813,11 @@ const dispatcher = { } } + // A Pages request only speaks for the JSON path. Its answer can be the app's + // reload response, which must not evict HTML that other tabs still use. if ( sharedIsrEntry && + !request.headers.has('X-VoidPages') && response.status === 200 && !writebackFallbackApplied && (resolveRevalidateTtl( diff --git a/platform/packages/dispatch/test/unit/index.test.ts b/platform/packages/dispatch/test/unit/index.test.ts index 04118b63f..55e31388b 100644 --- a/platform/packages/dispatch/test/unit/index.test.ts +++ b/platform/packages/dispatch/test/unit/index.test.ts @@ -3405,6 +3405,78 @@ describe('ISR JSON edge cache (pages protocol)', () => { expect(await response.json()).toEqual(JSON.parse(pageData)); }); + it('pages request ignores a JSON edge entry rendered by another build', async () => { + edgeCacheStore.set( + 'https://my-app.void.app/dashboard?__void=json&__void_isr=legacy', + currentSharedCacheResponse( + new Response(pageData, { + headers: { + 'content-type': 'application/json', + 'x-isr-cache': 'HIT', + 'X-VoidPages-Build': 'build-1', + }, + }), + ), + ); + + const { env, workerFetch } = createEnv({ + routing: isrRouting, + workerResponse: new Response(pageData, { + headers: { 'content-type': 'application/json', 'X-VoidPages-Build': 'build-2' }, + }), + }); + + const response = await app.fetch( + new Request('https://my-app.void.app/dashboard', { + headers: { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }, + }), + env, + createCtx(), + ); + + // The entry holds props this client cannot render, so the app answers. + expect(workerFetch).toHaveBeenCalledOnce(); + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + + it('keeps cached HTML when a stale client gets its reload response', async () => { + const htmlKey = 'https://my-app.void.app/dashboard?__void_isr=legacy'; + edgeCacheStore.set( + htmlKey, + currentSharedCacheResponse( + new Response(pageHtml(), { headers: { 'Content-Type': 'text/html' } }), + ), + ); + + const { env, workerFetch } = createEnv({ + routing: isrRouting, + workerResponse: new Response(null, { headers: { 'Cache-Control': 'no-store' } }), + }); + const ctx = createCtx(); + + const response = await app.fetch( + new Request('https://my-app.void.app/dashboard', { + headers: { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }, + }), + env, + ctx, + ); + await Promise.all((ctx.waitUntil as ReturnType).mock.calls.map((c) => c[0])); + + // The answer belongs to the JSON path; other tabs still hold this HTML. + expect(workerFetch).toHaveBeenCalledOnce(); + expect(response.headers.get('Cache-Control')).toBe('no-store'); + expect(edgeCacheStore.has(htmlKey)).toBe(true); + }); + it('pages request falls through to worker on JSON cache miss', async () => { const { env, workerFetch } = createEnv({ routing: isrRouting, From dcfccf6a7d9728cca5f3349de1f911ad9ef9b064 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 10:34:24 +0800 Subject: [PATCH 04/14] fix: close gaps in Pages deploy recovery ISR never stored a build with its JSON entries, because the HTML document it copies them from carried none. Every client that names its build skipped the JSON cache. The document now names its build, and hosted dispatch keeps it. Hosted dispatch deleted a valid JSON entry when a stale tab asked for it, and stopped evicting shared HTML for any Pages request rather than only for the reload response. Both now match native ISR. A refresh or back/forward visit to a URL with a fragment only scrolled instead of loading the document, then showed the error page on the next try. Every same-origin fallback to a document load now reloads in that case. The build id covered only the app folder, so a change in a workspace package or the lockfile kept the old id. It now also hashes the workspace packages the app depends on and the workspace lockfile, counts dot files that configure the build, and skips folders it cannot read. One id is kept per build, from the first config pass until buildApp ends, so a time-based define or a file written meanwhile cannot split the client and server ids. An app define of the id is left to Vite without hashing the tree. Co-Authored-By: Claude Opus 5.5 --- docs/guide/pages-routing/overview.md | 6 +- packages/edge/src/pages-protocol.ts | 2 +- packages/void/src/pages/build-id-source.ts | 283 +++++++++++++++--- packages/void/src/pages/navigation-engine.ts | 30 +- packages/void/src/pages/plugin.ts | 53 +++- packages/void/src/pages/protocol.ts | 3 + packages/void/test/unit/isr-cache.test.ts | 2 +- .../void/test/unit/pages-build-id.test.ts | 230 +++++++++++--- packages/void/test/unit/pages-client.test.ts | 56 ++++ .../void/test/unit/pages-protocol.test.ts | 16 + platform/packages/dispatch/src/index.ts | 50 ++-- .../packages/dispatch/test/unit/index.test.ts | 66 +++- 12 files changed, 673 insertions(+), 124 deletions(-) diff --git a/docs/guide/pages-routing/overview.md b/docs/guide/pages-routing/overview.md index 8dfeeb3dd..132a26086 100644 --- a/docs/guide/pages-routing/overview.md +++ b/docs/guide/pages-routing/overview.md @@ -137,9 +137,13 @@ Void recovers that navigation. The tab sends the build it is running with each p These never reload the tab: - A prefetch drops the response and lets the next navigation decide. -- A form submission renders its response, so the action never runs twice. The next navigation reloads if it has to. +- A form submission keeps its response, so the action never runs twice. If the action redirects, the destination loads as a document. - A failed request is not treated as a deploy. +If that document load still returns the old build, for example from a CDN that caches HTML across deploys, the tab shows an error page instead of reloading again. Keep HTML out of shared caches, or purge it on deploy. + +Prerendered pages of an [`output: "static"`](../ssg.md) app are served as files and are not covered: a stale tab still reaches its error boundary there. + Recovery is on by default. Set `deployRecovery: false` in your framework plugin's options to keep your own [error boundaries](./errors.md) in charge instead. To opt a specific route out of server-rendered component HTML, export `ssr = false` from its companion `.server.ts` file: diff --git a/packages/edge/src/pages-protocol.ts b/packages/edge/src/pages-protocol.ts index e0cac9795..3e684df9f 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -14,7 +14,7 @@ export const PAGES_BUILD_HEADER = 'X-VoidPages-Build'; * evidence of a new build, so it never counts as a mismatch. */ export function isStaleBuild(buildId: string, seen: string | null | undefined): boolean { - return buildId !== '' && seen != null && seen !== buildId; + return buildId !== '' && typeof seen === 'string' && seen !== buildId; } /** Request and response headers that carry a build, empty when none is known. */ diff --git a/packages/void/src/pages/build-id-source.ts b/packages/void/src/pages/build-id-source.ts index 8de410b72..02bb7cb07 100644 --- a/packages/void/src/pages/build-id-source.ts +++ b/packages/void/src/pages/build-id-source.ts @@ -1,6 +1,15 @@ import { createHash } from 'node:crypto'; -import { mkdirSync, readFileSync, readdirSync, statSync, writeFileSync } from 'node:fs'; -import { isAbsolute, join } from 'pathslash'; +import { + existsSync, + mkdirSync, + readFileSync, + readdirSync, + realpathSync, + statSync, + writeFileSync, +} from 'node:fs'; +import { isAbsolute, join, relative } from 'pathslash'; +import { searchForWorkspaceRoot } from 'vite'; /** Directories never part of the app source, whatever their position. */ const alwaysSkipped = new Set(['node_modules']); @@ -8,61 +17,231 @@ const alwaysSkipped = new Set(['node_modules']); /** Beside the generated types, which the scaffold already ignores. */ const CACHE_FILE = '.void/pages-build-id.json'; -const ID_PATTERN = /^[0-9a-f]{12}$/; +/** Workspace files that pin what the installed packages contain. */ +const WORKSPACE_FILES = [ + 'package.json', + 'pnpm-workspace.yaml', + 'pnpm-lock.yaml', + 'package-lock.json', + 'npm-shrinkwrap.json', + 'yarn.lock', + 'bun.lock', + 'bun.lockb', +]; + +const DEPENDENCY_FIELDS = [ + 'dependencies', + 'devDependencies', + 'optionalDependencies', + 'peerDependencies', +] as const; + +const HEX_DIGITS = '0123456789abcdef'; + +/** Twelve lowercase hex digits, the shape `contentIdOf` makes. */ +function isBuildId(value: unknown): value is string { + if (typeof value !== 'string' || value.length !== 12) { + return false; + } + for (let index = 0; index < value.length; index++) { + if (!HEX_DIGITS.includes(value.charAt(index))) { + return false; + } + } + return true; +} type CacheEntry = { fingerprint: string; id: string; }; +export type PagesBuildInputs = { + /** Env values the client inlines. They belong to the build, like a source file. */ + env?: string; + /** The app's `define` entries, which the client inlines too. */ + define?: string; +}; + +/** + * The id each app root got in the current build. Vite resolves the config again + * for every environment, with new plugin instances, and the values it sees can + * differ between those passes: a define such as `Date.now()`, or a file another + * task writes meanwhile. The first pass decides, so both bundles get one id. + */ +const currentBuildIds = new Map(); + /** - * A stable id for one build of an app: a hash of its source files. Every - * environment of a Vite build derives the same id from the same tree, which a - * per-process random value cannot guarantee, since Vite may resolve the config - * once per environment. + * A stable id for one build of an app: a hash of what its bundles are made of. + * Every environment of a Vite build derives the same id from the same tree, + * which a per-process random value cannot guarantee. * - * The id changes with any source change, including server-only ones, which - * reloads a stale tab that did not need it. That is the safe direction: missing - * the id means importing chunks that no longer exist. + * The hash covers the app folder, the workspace packages it depends on (found + * through its installed links, transitively), and the workspace manifest and + * lockfile, since a dependency upgrade renames chunks without touching the app. + * Modules imported by a relative path from outside all of these are not seen. * - * Resolving the config per environment means hashing the tree twice. The cache - * turns the second pass into one stat walk, keyed by file size and modification - * time. A write always moves the modification time, so a fingerprint that still - * matches describes the same content. + * The id changes with any change there, including server-only ones, which + * reloads a stale tab that did not need it. That is the safe direction: missing + * a change means importing chunks that no longer exist. * - * `buildInputs` carries what the client inlines without a source file of its - * own, such as env vars and `define` entries. Two builds that differ only there - * still emit different chunks. + * Hashing contents is cached across processes, keyed by file size and + * modification time. A write always moves the modification time, so a + * fingerprint that still matches describes the same content. */ export function computePagesBuildId( root: string, excludeDirs: Array, - buildInputs = '', + inputs: PagesBuildInputs = {}, ): string { + const current = currentBuildIds.get(root); + if (current !== undefined) { + return current; + } + const workspace = searchForWorkspaceRoot(root); const excluded = new Set(excludeDirs.map((dir) => (isAbsolute(dir) ? dir : join(root, dir)))); - const files = sourceFiles(root, excluded); - const fingerprint = fingerprintOf(root, files, buildInputs); - const cached = readCachedId(root, fingerprint); - if (cached) { - return cached; - } - const id = contentIdOf(root, files, buildInputs); - writeCachedId(root, fingerprint, id); + const files = buildSourceFiles(root, workspace, excluded); + const buildInputs = `${inputs.env ?? ''}\0${inputs.define ?? ''}`; + const fingerprint = fingerprintOf(workspace, files, buildInputs); + let id = readCachedId(root, fingerprint); + if (id === null) { + id = contentIdOf(workspace, files, buildInputs); + writeCachedId(root, fingerprint, id); + } + currentBuildIds.set(root, id); return id; } -/** Relative paths of the files under `root` that describe the app, sorted. */ -function sourceFiles(root: string, excluded: Set): Array { +/** Ends the current build of `root`, or of every app, so the next build hashes again. */ +export function endPagesBuild(root?: string): void { + if (root === undefined) { + currentBuildIds.clear(); + } else { + currentBuildIds.delete(root); + } +} + +/** Paths, relative to the workspace, of every file the id covers, sorted. */ +function buildSourceFiles(root: string, workspace: string, excluded: Set): Array { + const files = new Set(); + const add = (directory: string) => { + for (const file of sourceFiles(directory, excluded)) { + files.add(relative(workspace, file)); + } + }; + add(root); + for (const directory of workspaceDependencies(root, workspace)) { + add(directory); + } + if (workspace !== root) { + for (const name of WORKSPACE_FILES) { + if (existsSync(join(workspace, name))) { + files.add(name); + } + } + } + return [...files].sort(); +} + +/** Real path, or null when it cannot be resolved. */ +function realPath(path: string): string | null { + try { + return realpathSync(path); + } catch { + return null; + } +} + +function dependencyNames(directory: string): Array { + try { + const manifest = JSON.parse(readFileSync(join(directory, 'package.json'), 'utf8')) as Record< + string, + unknown + >; + const names: Array = []; + for (const field of DEPENDENCY_FIELDS) { + const deps = manifest[field]; + if (deps !== null && typeof deps === 'object') { + names.push(...Object.keys(deps)); + } + } + return names; + } catch { + return []; + } +} + +/** + * Folders of the workspace packages `root` depends on, directly or through other + * workspace packages. Package managers link them into node_modules, and the link + * leads back into the workspace outside any node_modules. + */ +function workspaceDependencies(root: string, workspace: string): Array { + const realWorkspace = realPath(workspace); + const realRoot = realPath(root); + if (realWorkspace === null || realRoot === null) { + return []; + } + const seen = new Set([realRoot]); + const found: Array = []; + const queue = [realRoot]; + for (let directory = queue.shift(); directory !== undefined; directory = queue.shift()) { + for (const name of dependencyNames(directory)) { + const target = + realPath(join(directory, 'node_modules', name)) ?? + realPath(join(realWorkspace, 'node_modules', name)); + if (target === null || seen.has(target)) { + continue; + } + const inWorkspace = relative(realWorkspace, target); + if ( + inWorkspace.startsWith('..') || + isAbsolute(inWorkspace) || + inWorkspace.split('/').includes('node_modules') + ) { + continue; + } + seen.add(target); + found.push(join(workspace, inWorkspace)); + queue.push(target); + } + } + return found; +} + +/** + * Dot directories hold tool state (.git, .void, .wrangler), and .env files hold + * local settings, whose client values reach the id through `inputs.env`. Other + * dot files can configure the build (.postcssrc, .browserslistrc), so they count. + */ +function isSkipped(name: string, isDirectory: boolean): boolean { + if (alwaysSkipped.has(name)) { + return true; + } + if (!name.startsWith('.')) { + return false; + } + return isDirectory || name.startsWith('.env') || name === '.DS_Store'; +} + +/** Absolute paths of the files under `directory` that describe it. */ +function sourceFiles(directory: string, excluded: Set): Array { const files: Array = []; - const walk = (directory: string): void => { - for (const entry of readdirSync(join(root, directory), { withFileTypes: true })) { - // Dot directories hold tool state (.git, .void, .wrangler), and dot files - // hold local settings such as .env that a deploy must not depend on. - if (entry.name.startsWith('.') || alwaysSkipped.has(entry.name)) { + const walk = (current: string): void => { + let entries; + try { + entries = readdirSync(current, { withFileTypes: true }); + } catch { + // A folder the build cannot read (a database volume, a root-owned cache) + // cannot feed the bundle either. + return; + } + for (const entry of entries) { + if (isSkipped(entry.name, entry.isDirectory())) { continue; } - const path = directory ? `${directory}/${entry.name}` : entry.name; - if (excluded.has(join(root, path))) { + const path = join(current, entry.name); + if (excluded.has(path)) { continue; } // Symlinked directories are not followed: they can leave the tree. @@ -73,29 +252,39 @@ function sourceFiles(root: string, excluded: Set): Array { } } }; - walk(''); - return files.sort(); + walk(directory); + return files; } -function fingerprintOf(root: string, files: Array, buildInputs: string): string { +function fingerprintOf(workspace: string, files: Array, inputs: string): string { const hash = createHash('sha256'); - hash.update(buildInputs); + hash.update(inputs); hash.update('\0'); for (const file of files) { - const stats = statSync(join(root, file)); - hash.update(`${file}\0${stats.size}\0${stats.mtimeMs}\0`); + try { + const stats = statSync(join(workspace, file)); + hash.update(`${file}\0${stats.size}\0${stats.mtimeMs}\0`); + } catch { + // Removed since the walk. + hash.update(`${file}\0-\0`); + } } return hash.digest('hex'); } -function contentIdOf(root: string, files: Array, buildInputs: string): string { +function contentIdOf(workspace: string, files: Array, inputs: string): string { const hash = createHash('sha256'); - hash.update(buildInputs); + hash.update(inputs); hash.update('\0'); for (const file of files) { hash.update(file); hash.update('\0'); - hash.update(readFileSync(join(root, file))); + try { + hash.update(readFileSync(join(workspace, file))); + } catch { + // Removed or unreadable since the walk: the bundle cannot read it either. + hash.update('-'); + } hash.update('\0'); } return hash.digest('hex').slice(0, 12); @@ -105,11 +294,7 @@ function contentIdOf(root: string, files: Array, buildInputs: string): s function readCachedId(root: string, fingerprint: string): string | null { try { const entry = JSON.parse(readFileSync(join(root, CACHE_FILE), 'utf8')) as Partial; - if ( - entry.fingerprint === fingerprint && - typeof entry.id === 'string' && - ID_PATTERN.test(entry.id) - ) { + if (entry.fingerprint === fingerprint && isBuildId(entry.id)) { return entry.id; } } catch { diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index 9a84f34c2..bca718641 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -270,6 +270,26 @@ function claimDeployReload(build: string, url: string): boolean { return true; } +/** + * Loads `url` as a new document. Setting `location.href` to the current URL with + * a fragment only scrolls, and that is the URL a refresh or a back/forward visit + * asks for, so that case reloads the page instead. + */ +function loadDocument(url: string): void { + const { origin, pathname, search, hash } = window.location; + const target = new URL(url, `${origin}${pathname}${search}`); + const sameDocument = + target.origin === origin && target.pathname === pathname && target.search === search; + if (!sameDocument || target.hash === '') { + window.location.href = url; + return; + } + if (target.hash !== hash) { + history.replaceState(history.state, '', url); + } + window.location.reload(); +} + function abortSignalPromise(signal: AbortSignal): Promise { if (signal.aborted) { return Promise.reject(abortError()); @@ -798,7 +818,7 @@ export async function createPageNavigationEngine( const cachedPageData = await cacheEntry.response; _prefetchCache.consume(fetchUrl, method); if (cachedPageData === null) { - window.location.href = url; + loadDocument(url); return undefined; } // Deferred initialization and adapters mutate props; retain the cached wire payload. @@ -867,7 +887,7 @@ export async function createPageNavigationEngine( } if (pageData === undefined && !response) { - window.location.href = url; + loadDocument(url); return undefined; } @@ -903,7 +923,7 @@ export async function createPageNavigationEngine( pageData = staticPageData.pageData; deferredRegistry.setup(pageData, staticPageData.resolvedDeferred); } else { - window.location.href = url; + loadDocument(url); return undefined; } } else { @@ -917,7 +937,7 @@ export async function createPageNavigationEngine( if (pageData !== undefined) { // Static page-data fallback already loaded the page object. } else if (!response) { - window.location.href = url; + loadDocument(url); return undefined; } else if (contentType.includes('application/x-ndjson')) { if (!response.body) { @@ -1014,7 +1034,7 @@ export async function createPageNavigationEngine( // Reuse the preload only if the response selects the matched page; redirects // or rewrites may select another. Cancellation stops waiting for the imports. if (!components[pageData.component]) { - window.location.href = url; + loadDocument(url); return undefined; } let component: Component; diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index e8a1e67f6..e596a4000 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -2,7 +2,8 @@ import { existsSync } from 'node:fs'; import { dirname, isAbsolute, join } from 'pathslash'; import { loadEnv, normalizePath } from 'vite'; import type { Plugin, ResolvedConfig, UserConfig } from 'vite'; -import { computePagesBuildId } from './build-id-source.ts'; +import { computePagesBuildId, endPagesBuild } from './build-id-source.ts'; +import type { PagesBuildInputs } from './build-id-source.ts'; import { PAGES_BUILD_ID_DEFINE } from './build-id.ts'; import { assertLinkPrefetchValue } from './prefetch.ts'; import type { CacheForInput, LinkPrefetchValue } from './prefetch.ts'; @@ -83,18 +84,30 @@ function buildIdExcludes(root: string, userConfig: UserConfig): Array { return [...dirs].map((dir) => (isAbsolute(dir) ? dir : join(root, dir))); } +/** Entries sorted by key, so the order they were written in does not change the id. */ +function sortedEntries(record: Record): Array<[string, unknown]> { + return Object.entries(record).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0)); +} + /** * Values the client bundle inlines without appearing in a source file: the * env vars Vite exposes, and the app's `define` entries. Two builds that differ * only here still emit different chunks, so the id has to cover them. */ -function clientBuildInputs(root: string, userConfig: UserConfig, mode: string): string { - const envDir = typeof userConfig.envDir === 'string' ? userConfig.envDir : root; - const env = Object.entries(loadEnv(mode, envDir, userConfig.envPrefix ?? 'VITE_')).sort( - ([a], [b]) => a.localeCompare(b), - ); - const define = Object.entries(userConfig.define ?? {}).sort(([a], [b]) => a.localeCompare(b)); - return JSON.stringify({ env, define }); +function clientBuildInputs(root: string, userConfig: UserConfig, mode: string): PagesBuildInputs { + const envDir = userConfig.envDir; + const env = + envDir === false + ? {} + : loadEnv( + mode, + typeof envDir === 'string' ? (isAbsolute(envDir) ? envDir : join(root, envDir)) : root, + userConfig.envPrefix ?? 'VITE_', + ); + return { + env: JSON.stringify(sortedEntries(env)), + define: JSON.stringify(sortedEntries(userConfig.define ?? {})), + }; } /** Shared Vite lifecycle; adapters own their generated code and environment configuration. */ @@ -209,6 +222,15 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp viteConfig = config; }, + // Every environment has resolved its config, and so read the id, by now. The + // next build in this process hashes again. + buildApp: { + order: 'post', + async handler() { + endPagesBuild(root); + }, + }, + config(userConfig, env) { // Set before the early return: pages/ may be created after the server starts. const dev = env.command === 'serve'; @@ -227,7 +249,17 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp // The dev server serves a single build, so a tab never outlives the chunks // it imported, and an app without a client entry has no tab to recover. // Leaving the id undefined keeps every build check a no-op there. - if (dev || resolved == null || options.deployRecovery === false) { + if ( + dev || + resolved === null || + resolved === undefined || + options.deployRecovery === false + ) { + return resolved; + } + // An explicit app define pins the id, for a fixture or for one that + // outlives this process such as a commit sha. Vite applies it as written. + if (userConfig.define?.[PAGES_BUILD_ID_DEFINE] !== undefined) { return resolved; } buildId ??= computePagesBuildId( @@ -240,9 +272,6 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp define: { ...resolved.define, [PAGES_BUILD_ID_DEFINE]: JSON.stringify(buildId), - // An explicit app define wins: it pins the id for a fixture or forces - // one that outlives this process, such as a commit sha. - ...userConfig.define, }, }; }; diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index d4d152d85..745f58d7c 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -687,6 +687,9 @@ function renderedResponse( headers: adjustDevCssCsp( pageResponseHeaders(c, { 'content-type': contentType, + // ISR copies the page data out of this document into its JSON cache, and + // keeps the build with it. + ...buildHeaders(pagesBuildId()), ...POWERED_BY, }), assetTags?.devCssNonce, diff --git a/packages/void/test/unit/isr-cache.test.ts b/packages/void/test/unit/isr-cache.test.ts index 3fb02acd1..cbc2534b5 100644 --- a/packages/void/test/unit/isr-cache.test.ts +++ b/packages/void/test/unit/isr-cache.test.ts @@ -1044,7 +1044,7 @@ describe('handleIsr', () => { it('keeps cached HTML when a stale client gets its reload response', async () => { const { store, kv } = createKvMock(); - store.set(isrKey(DPL, HOST, '/blog/post'), corruptCases[0]!.seed()); + store.set(isrKey(DPL, HOST, '/blog/post'), corruptCases[0].seed()); const env = makeEnv(kv); const htmlKey = htmlEdgeKey(HOST, '/blog/post', DPL); edge.store.set(htmlKey, currentSharedCacheResponse(new Response('cached'))); diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts index 8725c6a44..60e049476 100644 --- a/packages/void/test/unit/pages-build-id.test.ts +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -1,15 +1,39 @@ -import { mkdirSync, mkdtempSync, rmSync, utimesSync, writeFileSync } from 'node:fs'; +import { + chmodSync, + existsSync, + mkdirSync, + mkdtempSync, + rmSync, + symlinkSync, + utimesSync, + writeFileSync, +} from 'node:fs'; import { tmpdir } from 'node:os'; -import { join } from 'node:path'; +import { dirname, join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; import { buildHeaders, isStaleBuild } from '../../../edge/src/pages-protocol.ts'; -import { computePagesBuildId } from '../../src/pages/build-id-source.ts'; +import { computePagesBuildId, endPagesBuild } from '../../src/pages/build-id-source.ts'; import { pagesBuildId } from '../../src/pages/build-id.ts'; import { createPagesPlugin } from '../../src/pages/plugin.ts'; import { getHookHandler } from '../helpers/vite-hooks.ts'; +const roots: Array = []; + +/** A fresh folder, removed after the test. */ +function tempRoot(prefix: string): string { + const root = mkdtempSync(join(tmpdir(), prefix)); + roots.push(root); + return root; +} + afterEach(() => { vi.unstubAllEnvs(); + // Each test stands for its own build process. + endPagesBuild(); + for (const root of roots.splice(0)) { + chmodSync(root, 0o700); + rmSync(root, { recursive: true, force: true }); + } }); describe('pagesBuildId', () => { @@ -44,25 +68,41 @@ describe('buildHeaders', () => { describe('computePagesBuildId', () => { function createSourceFixture(content: string): string { - const root = mkdtempSync(join(tmpdir(), 'void-build-id-')); + const root = tempRoot('void-build-id-'); mkdirSync(join(root, 'pages'), { recursive: true }); writeFileSync(join(root, 'pages/index.tsx'), content); return root; } + /** The id a new build of `root` gets. */ + function buildIdOf(root: string, excludeDirs: Array = []): string { + endPagesBuild(root); + return computePagesBuildId(root, excludeDirs); + } + it('hashes the source, so identical trees keep the id', () => { const content = 'export default function Page() {}\n'; - expect(computePagesBuildId(createSourceFixture(content), [])).toBe( - computePagesBuildId(createSourceFixture(content), []), - ); + expect(buildIdOf(createSourceFixture(content))).toBe(buildIdOf(createSourceFixture(content))); }); it('recomputes when a file changes', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = buildIdOf(root); + + writeFileSync(join(root, 'pages/index.tsx'), 'export default function Page() { return 1 }\n'); + + expect(buildIdOf(root)).not.toBe(first); + }); + + it('keeps the first id until the build ends, whatever changes meanwhile', () => { const root = createSourceFixture('export default function Page() {}\n'); const first = computePagesBuildId(root, []); + // Another task writes while Vite resolves the next environment. writeFileSync(join(root, 'pages/index.tsx'), 'export default function Page() { return 1 }\n'); + expect(computePagesBuildId(root, [])).toBe(first); + endPagesBuild(root); expect(computePagesBuildId(root, [])).not.toBe(first); }); @@ -72,36 +112,116 @@ describe('computePagesBuildId', () => { // A whole second, so the restored timestamp is byte for byte the old one. const stamp = 1_700_000_000; utimesSync(path, stamp, stamp); - const first = computePagesBuildId(root, []); + const first = buildIdOf(root); // Same size, and the mtime put back: nothing a build can observe changed. writeFileSync(path, 'export default function Home() {}\n'); utimesSync(path, stamp, stamp); - expect(computePagesBuildId(root, [])).toBe(first); + expect(buildIdOf(root)).toBe(first); // The content really did change, so a fresh pass must notice. rmSync(join(root, '.void'), { recursive: true, force: true }); - expect(computePagesBuildId(root, [])).not.toBe(first); + expect(buildIdOf(root)).not.toBe(first); }); - it('ignores build output, dot directories and installed packages', () => { + it('ignores build output, dot directories, .env files and installed packages', () => { const root = createSourceFixture('export default function Page() {}\n'); - const first = computePagesBuildId(root, [join(root, 'dist')]); + const first = buildIdOf(root, [join(root, 'dist')]); for (const dir of ['dist', 'node_modules/pkg', '.void', '.wrangler']) { mkdirSync(join(root, dir), { recursive: true }); writeFileSync(join(root, dir, 'generated.js'), 'changed\n'); } + writeFileSync(join(root, '.env.local'), 'SECRET=1\n'); - expect(computePagesBuildId(root, [join(root, 'dist')])).toBe(first); + expect(buildIdOf(root, [join(root, 'dist')])).toBe(first); }); + + it('counts dot files that configure the build', () => { + const root = createSourceFixture('export default function Page() {}\n'); + const first = buildIdOf(root); + + writeFileSync(join(root, '.browserslistrc'), 'last 1 chrome version\n'); + + expect(buildIdOf(root)).not.toBe(first); + }); + + describe('in a workspace', () => { + /** A pnpm-style workspace: the app links the ui package into its node_modules. */ + function createWorkspace(appDir = 'apps/web') { + const workspace = tempRoot('void-build-id-workspace-'); + const write = (path: string, content: string) => { + mkdirSync(dirname(join(workspace, path)), { recursive: true }); + writeFileSync(join(workspace, path), content); + }; + write('pnpm-workspace.yaml', 'packages:\n - apps/*\n - packages/*\n'); + write('packages/ui/package.json', '{"name":"ui"}'); + write('packages/ui/index.ts', 'export const label = 1;\n'); + write('apps/docs/package.json', '{"name":"docs"}'); + write(`${appDir}/package.json`, '{"name":"web","dependencies":{"ui":"workspace:*"}}'); + write(`${appDir}/pages/index.tsx`, "import { label } from 'ui';\n"); + mkdirSync(join(workspace, appDir, 'node_modules'), { recursive: true }); + symlinkSync( + join(workspace, 'packages/ui'), + join(workspace, appDir, 'node_modules/ui'), + 'dir', + ); + return { app: join(workspace, appDir), write }; + } + + it('covers the workspace packages the app depends on, and the lockfile', () => { + const { app, write } = createWorkspace(); + const first = buildIdOf(app); + + write('packages/ui/index.ts', 'export const label = 22;\n'); + const second = buildIdOf(app); + expect(second).not.toBe(first); + + write('pnpm-lock.yaml', 'lockfileVersion: 9.0\n'); + expect(buildIdOf(app)).not.toBe(second); + }); + + it('ignores workspace packages the app does not use', () => { + const { app, write } = createWorkspace(); + const first = buildIdOf(app); + + // A sibling app building at the same time. + write('apps/docs/dist/index.js', 'built\n'); + + expect(buildIdOf(app)).toBe(first); + }); + + it('covers an app that sits under a dot folder', () => { + const { app, write } = createWorkspace('.examples/web'); + const first = buildIdOf(app); + + write('.examples/web/pages/index.tsx', 'export default 2;\n'); + + expect(buildIdOf(app)).not.toBe(first); + }); + }); + + it.skipIf(process.platform === 'win32' || process.getuid?.() === 0)( + 'skips a folder the build cannot read', + () => { + const root = createSourceFixture('export default function Page() {}\n'); + mkdirSync(join(root, 'pgdata/base'), { recursive: true }); + chmodSync(join(root, 'pgdata'), 0o000); + try { + expect(buildIdOf(root)).toHaveLength(12); + } finally { + chmodSync(join(root, 'pgdata'), 0o700); + } + }, + ); }); describe('createPagesPlugin build id', () => { + type BuildConfig = { define?: Record } | undefined; type PagesConfigHook = ( userConfig: Record, env: { command: 'build' | 'serve' }, - ) => Promise<{ define?: Record } | undefined>; + ) => Promise; function createConfigHook( root?: string, @@ -118,13 +238,13 @@ describe('createPagesPlugin build id', () => { const hook = getHookHandler(plugin.config) as unknown as ( userConfig: Record, env: { command: 'build' | 'serve'; mode: string }, - ) => ReturnType; + ) => Promise; // Vite always passes a mode; the tests only vary the command. - return (userConfig, env) => hook(userConfig, { mode: 'production', ...env }) as never; + return (userConfig, env) => hook(userConfig, { mode: 'production', ...env }); } function createFixture(): string { - const root = mkdtempSync(join(tmpdir(), 'void-pages-build-')); + const root = tempRoot('void-pages-build-'); const pagesDir = join(root, 'pages'); mkdirSync(pagesDir, { recursive: true }); writeFileSync(join(pagesDir, 'index.tsx'), 'export default function Page() {}\n'); @@ -133,22 +253,58 @@ describe('createPagesPlugin build id', () => { const DEFINE = 'import.meta.env.__VOID_PAGES_BUILD_ID'; + function idIn(config: BuildConfig): string | undefined { + return config?.define?.[DEFINE]; + } + it('defines one id for a build, shared by every environment', async () => { const config = createConfigHook(); - const client = await config({}, { command: 'build' }); - const server = await config({}, { command: 'build' }); - - const id = client!.define![DEFINE]!; - expect(JSON.parse(id)).toMatch(/^[0-9a-f]{12}$/); + const id = idIn(await config({}, { command: 'build' })); + expect(JSON.parse(id ?? '""')).toMatch(/^[0-9a-f]{12}$/); // Both bundles must carry the same id, or every navigation would reload. - expect(server!.define![DEFINE]).toBe(id); + expect(idIn(await config({}, { command: 'build' }))).toBe(id); + }); + + it('keeps one id when each environment evaluates the config to another define', async () => { + const root = createFixture(); + // Vite evaluates vite.config.ts again per environment, with a new plugin each + // time, so a define such as Date.now() differs between the two bundles. + const client = await createConfigHook(root)( + { define: { __BUILT_AT__: '"1"' } }, + { command: 'build' }, + ); + const server = await createConfigHook(root)( + { define: { __BUILT_AT__: '"2"' } }, + { command: 'build' }, + ); + + expect(idIn(server)).toBe(idIn(client)); + }); + + it('hashes again once the build ends, for the next build in this process', async () => { + const root = createFixture(); + const plugin = createPagesPlugin(join(root, 'pages'), { + name: 'test:pages', + generateRenderer: () => '', + generateClient: () => '', + config: () => ({}), + }); + const first = idIn(await createConfigHook(root)({}, { command: 'build' })); + + writeFileSync(join(root, 'pages', 'index.tsx'), 'export default function Other() {}\n'); + const endBuild = getHookHandler(plugin.buildApp) as unknown as () => Promise; + await endBuild(); + + expect(idIn(await createConfigHook(root)({}, { command: 'build' }))).not.toBe(first); }); it('derives the id from the app source, so identical sources keep it', async () => { const root = createFixture(); - const idOf = async () => - (await createConfigHook(root)({}, { command: 'build' }))!.define![DEFINE]; + const idOf = async () => { + endPagesBuild(root); + return idIn(await createConfigHook(root)({}, { command: 'build' })); + }; const first = await idOf(); expect(await idOf()).toBe(first); @@ -161,8 +317,8 @@ describe('createPagesPlugin build id', () => { const root = createFixture(); const idFor = async (value: string) => { vi.stubEnv('VITE_PROBE', value); - // A new plugin per call: one plugin instance keeps the first id it made. - return (await createConfigHook(root)({}, { command: 'build' }))!.define![DEFINE]; + endPagesBuild(root); + return idIn(await createConfigHook(root)({}, { command: 'build' })); }; // Two builds that differ only here still emit different chunks. @@ -170,12 +326,14 @@ describe('createPagesPlugin build id', () => { }); it('changes the id for an app define the client inlines', async () => { - const root = createFixture(); + // Two apps with the same source, built apart, that differ only in a define. const idFor = async (value: string) => - (await createConfigHook(root)( - { define: { __PROBE__: JSON.stringify(value) } }, - { command: 'build' }, - ))!.define![DEFINE]; + idIn( + await createConfigHook(createFixture())( + { define: { __PROBE__: JSON.stringify(value) } }, + { command: 'build' }, + ), + ); expect(await idFor('one')).not.toBe(await idFor('two')); }); @@ -192,11 +350,13 @@ describe('createPagesPlugin build id', () => { expect(await config({}, { command: 'serve' })).toEqual({}); }); - it('lets an explicit define pin the id', async () => { - const config = createConfigHook(); + it('leaves an id the app defines to Vite, without hashing the tree', async () => { + const root = createFixture(); + const config = createConfigHook(root); const pinned = await config({ define: { [DEFINE]: '"commit-abc"' } }, { command: 'build' }); - expect(pinned!.define![DEFINE]).toBe('"commit-abc"'); + expect(idIn(pinned)).toBeUndefined(); + expect(existsSync(join(root, '.void'))).toBe(false); }); }); diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 4b15f7250..1cb64edd7 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -248,6 +248,62 @@ describe('Pages build recovery', () => { expect(document.body.replaceChildren).toHaveBeenCalled(); }); + it('reloads when a refresh of a URL with a fragment is answered by another build', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + const reload = vi.fn(); + Object.assign(window.location, { pathname: '/docs', hash: '#install', reload }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleReloadResponse()), + ); + const { router } = await createTestRouter(); + + await router.refresh(); + + // Assigning the same URL with a fragment only scrolls, so the tab would keep + // its stale page without loading anything. + expect(reload).toHaveBeenCalledOnce(); + expect(window.location.href).toBeUndefined(); + }); + + it('reloads a back/forward visit to an entry with a fragment answered by another build', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + const reload = vi.fn(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleReloadResponse()), + ); + const { router } = await createTestRouter(); + // The browser has already moved the address to the entry it went back to. + Object.assign(window.location, { pathname: '/b', hash: '#h', reload }); + + await router.visit('/b#h', { preserveState: true, _popstate: true }); + + expect(reload).toHaveBeenCalledOnce(); + expect(history.replaceState).not.toHaveBeenCalled(); + }); + + it('reloads a back/forward visit whose prefetch was answered by another build', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + const reload = vi.fn(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const { router } = await createTestRouter(); + await router.prefetch('/b'); + Object.assign(window.location, { pathname: '/b', hash: '#h', reload }); + + await router.visit('/b#h', { preserveState: true, _popstate: true }); + + expect(reload).toHaveBeenCalledOnce(); + }); + it('applies a mutation answered by another build and never reloads', async () => { stubClientGlobals(); vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); diff --git a/packages/void/test/unit/pages-protocol.test.ts b/packages/void/test/unit/pages-protocol.test.ts index dff4451d4..37e328491 100644 --- a/packages/void/test/unit/pages-protocol.test.ts +++ b/packages/void/test/unit/pages-protocol.test.ts @@ -1658,6 +1658,22 @@ describe('Pages build recovery', () => { expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); }); + it('names its build on the HTML document, which ISR copies into its JSON cache', async () => { + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + + const response = await handlePageGet( + () => ({ title: 'post' }), + undefined, + await createTestContext('GET', '/blog/post'), + 'blog/post', + mockRenderFn, + mockGetAssetTags, + ); + + expect(response.headers.get('content-type')).toContain('text/html'); + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + }); + it('keeps its response for a stale mutation, so the action never replays', async () => { vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); const action = vi.fn(); diff --git a/platform/packages/dispatch/src/index.ts b/platform/packages/dispatch/src/index.ts index 029b42f34..8c897a8b2 100644 --- a/platform/packages/dispatch/src/index.ts +++ b/platform/packages/dispatch/src/index.ts @@ -166,12 +166,19 @@ export function isHtmlResponse(response: Response): boolean { ); } -function jsonCacheResponse(pageData: string, ttl: number, state: 'HIT' | 'MISS'): Response { +function jsonCacheResponse( + pageData: string, + ttl: number, + state: 'HIT' | 'MISS', + build: string | null, +): Response { const response = new Response(pageData, { headers: { 'content-type': 'application/json', 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + // Kept with the payload, so a client from another build skips this entry. + ...(build ? { [PAGES_BUILD_HEADER]: build } : {}), Vary: 'X-VoidPages, X-VoidPages-Version', 'Cache-Control': `public, s-maxage=${ttl}, max-age=0, must-revalidate`, 'x-isr-cache': state, @@ -195,7 +202,10 @@ async function populateJsonEdgeCache( if (!pageData) { return; } - await cache.put(cacheKey, jsonCacheResponse(pageData, ttl, state)); + await cache.put( + cacheKey, + jsonCacheResponse(pageData, ttl, state, response.headers.get(PAGES_BUILD_HEADER)), + ); } type SharedIsrEntry = Readonly<{ @@ -1213,20 +1223,20 @@ const dispatcher = { // Pages protocol: check JSON edge cache, fall through on miss if (isPagesRequest) { const jsonCached = await cache.match(jsonCacheKey); - // A payload rendered by another build carries props this client cannot - // render. Fall through so the app answers and reloads the tab. - if ( - jsonCached && - hasCurrentSharedCachePolicy(jsonCached) && - pagesPayloadFitsBuild( - jsonCached.headers.get(PAGES_BUILD_HEADER), - request.headers.get(PAGES_BUILD_HEADER), - ) - ) { - requestType = 'isr'; - return meter(clientRevalidateResponse(jsonCached)); - } - if (jsonCached) { + if (jsonCached && hasCurrentSharedCachePolicy(jsonCached)) { + // A payload rendered by another build carries props this client cannot + // render. Fall through so the app answers and reloads the tab, and keep + // the entry: it is still right for clients of its own build. + if ( + pagesPayloadFitsBuild( + jsonCached.headers.get(PAGES_BUILD_HEADER), + request.headers.get(PAGES_BUILD_HEADER), + ) + ) { + requestType = 'isr'; + return meter(clientRevalidateResponse(jsonCached)); + } + } else if (jsonCached) { await cache.delete(jsonCacheKey); } // Miss — fall through to general dispatch (worker returns JSON for X-VoidPages) @@ -1813,11 +1823,13 @@ const dispatcher = { } } - // A Pages request only speaks for the JSON path. Its answer can be the app's - // reload response, which must not evict HTML that other tabs still use. + // The app answers a stale Pages client with a reload response that carries no + // page data. It says nothing about the cached HTML, which other tabs still use. + const pagesReload = + request.headers.has('X-VoidPages') && !response.headers.has('X-VoidPages'); if ( sharedIsrEntry && - !request.headers.has('X-VoidPages') && + !pagesReload && response.status === 200 && !writebackFallbackApplied && (resolveRevalidateTtl( diff --git a/platform/packages/dispatch/test/unit/index.test.ts b/platform/packages/dispatch/test/unit/index.test.ts index 55e31388b..0179383d8 100644 --- a/platform/packages/dispatch/test/unit/index.test.ts +++ b/platform/packages/dispatch/test/unit/index.test.ts @@ -3441,6 +3441,70 @@ describe('ISR JSON edge cache (pages protocol)', () => { // The entry holds props this client cannot render, so the app answers. expect(workerFetch).toHaveBeenCalledOnce(); expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + // Clients of the build that rendered it can still use it. + expect( + edgeCacheStore.has('https://my-app.void.app/dashboard?__void=json&__void_isr=legacy'), + ).toBe(true); + }); + + it('stores the build of an HTML render with its JSON entry, so that build hits it', async () => { + const { env, workerFetch } = createEnv({ + routing: isrRouting, + workerResponse: new Response(pageHtml(), { + headers: { 'Content-Type': 'text/html', 'X-VoidPages-Build': 'build-2' }, + }), + }); + const documentCtx = createCtx(); + await app.fetch(new Request('https://my-app.void.app/dashboard'), env, documentCtx); + await waitForBackgroundTasks(documentCtx); + + const response = await app.fetch( + new Request('https://my-app.void.app/dashboard', { + headers: { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }, + }), + env, + createCtx(), + ); + + expect(workerFetch).toHaveBeenCalledOnce(); + expect(response.headers.get('X-VoidPages-Build')).toBe('build-2'); + expect(await response.json()).toEqual(JSON.parse(pageData)); + }); + + it('evicts cached HTML when a Pages answer opts out of sharing', async () => { + const htmlKey = 'https://my-app.void.app/dashboard?__void_isr=legacy'; + edgeCacheStore.set( + htmlKey, + currentSharedCacheResponse( + new Response(pageHtml(), { headers: { 'Content-Type': 'text/html' } }), + ), + ); + const { env } = createEnv({ + routing: isrRouting, + workerResponse: new Response(pageData, { + headers: { + 'content-type': 'application/json', + 'X-VoidPages': 'true', + 'Cache-Control': 'no-store', + }, + }), + }); + const ctx = createCtx(); + + await app.fetch( + new Request('https://my-app.void.app/dashboard', { + headers: { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION }, + }), + env, + ctx, + ); + await waitForBackgroundTasks(ctx); + + expect(edgeCacheStore.has(htmlKey)).toBe(false); }); it('keeps cached HTML when a stale client gets its reload response', async () => { @@ -3469,7 +3533,7 @@ describe('ISR JSON edge cache (pages protocol)', () => { env, ctx, ); - await Promise.all((ctx.waitUntil as ReturnType).mock.calls.map((c) => c[0])); + await waitForBackgroundTasks(ctx); // The answer belongs to the JSON path; other tabs still hold this HTML. expect(workerFetch).toHaveBeenCalledOnce(); From 71fea3f26728bee3b7d15901dfb02548c13e3432 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 11:00:51 +0800 Subject: [PATCH 05/14] fix: spend one reload on a stale prefetch too A visit that consumed a prefetch answered by another build reloaded without claiming the one-reload guard. When a cache kept serving the old document, each hover and click on that link reloaded the page again. The visit now claims the same guard as an ordinary navigation and stops on the recovery page. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/pages/navigation-engine.ts | 14 +++++++++- packages/void/test/unit/pages-client.test.ts | 28 ++++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index bca718641..988b21d35 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -356,6 +356,9 @@ export async function createPageNavigationEngine( const hasBoundaries = Object.keys(config.boundaryManifest?.plans ?? {}).length > 0; const _prefetchCache = new PrefetchCache(); const uncachedPayloads = new WeakSet(); + // Prefetched URLs that another deployment answered, with that build. The visit + // that consumes one spends the same single reload as an ordinary navigation. + const stalePrefetches = new Map(); let _nextNavigationId = 0; // The newest visit whose URL is in the address bar: the last commit, or a back/forward // visit, which the browser has already moved to. An older visit must not commit over it. @@ -702,7 +705,9 @@ export async function createPageNavigationEngine( } // Another deployment answered: cache nothing, so the visit that follows a // hover reloads instead of rendering props this build's chunks cannot show. - if (isStaleBuild(pagesBuildId(), r.headers.get(PAGES_BUILD_HEADER))) { + const servedBy = r.headers.get(PAGES_BUILD_HEADER); + if (servedBy !== null && isStaleBuild(pagesBuildId(), servedBy)) { + stalePrefetches.set(url, servedBy); return null; } if (!r.headers.get('X-VoidPages')) { @@ -818,6 +823,13 @@ export async function createPageNavigationEngine( const cachedPageData = await cacheEntry.response; _prefetchCache.consume(fetchUrl, method); if (cachedPageData === null) { + const staleBuild = stalePrefetches.get(fetchUrl); + stalePrefetches.delete(fetchUrl); + if (staleBuild !== undefined && !claimDeployReload(staleBuild, url)) { + // The last reload landed on the same old document; see the visit path below. + showTerminalPageError(url); + return undefined; + } loadDocument(url); return undefined; } diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 1cb64edd7..0359ee152 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -304,6 +304,34 @@ describe('Pages build recovery', () => { expect(reload).toHaveBeenCalledOnce(); }); + it('spends one reload on a stale prefetch, then stops when the retry is stale too', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleJson(stalePage)), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.prefetch('/next'); + await router.visit('/next'); + expect(window.location.href).toBe('/next'); + + // The reload came back from the old build: a new document of the same build, + // where the user hovers and clicks again. + const documentUrl = 'http://localhost/'; + (window.location as unknown as { href?: string }).href = documentUrl; + const { router: reloaded } = await createTestRouter({ adapter: { applyUpdate } }); + await reloaded.prefetch('/next'); + await reloaded.visit('/next'); + + expect(window.location.href).toBe(documentUrl); + expect(applyUpdate).not.toHaveBeenCalled(); + expect(document.body.replaceChildren).toHaveBeenCalled(); + }); + it('applies a mutation answered by another build and never reloads', async () => { stubClientGlobals(); vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); From 6d5c834f65af3ad2085dddb6beac82fe851c872d Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 11:01:51 +0800 Subject: [PATCH 06/14] fix: keep shell env values in the build id when envDir is false `envDir: false` only skips the .env files. Shell `VITE_` values still reach the client bundle, so they must still change the Pages build id. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/pages/plugin.ts | 20 ++++++++++--------- .../void/test/unit/pages-build-id.test.ts | 7 +++++-- 2 files changed, 16 insertions(+), 11 deletions(-) diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index e596a4000..edde789b2 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -95,15 +95,17 @@ function sortedEntries(record: Record): Array<[string, unknown] * only here still emit different chunks, so the id has to cover them. */ function clientBuildInputs(root: string, userConfig: UserConfig, mode: string): PagesBuildInputs { - const envDir = userConfig.envDir; - const env = - envDir === false - ? {} - : loadEnv( - mode, - typeof envDir === 'string' ? (isAbsolute(envDir) ? envDir : join(root, envDir)) : root, - userConfig.envPrefix ?? 'VITE_', - ); + const { envDir } = userConfig; + // `false` skips the .env files, but shell values still reach the client. + const env = loadEnv( + mode, + typeof envDir === 'string' + ? isAbsolute(envDir) + ? envDir + : join(root, envDir) + : (envDir ?? root), + userConfig.envPrefix ?? 'VITE_', + ); return { env: JSON.stringify(sortedEntries(env)), define: JSON.stringify(sortedEntries(userConfig.define ?? {})), diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts index 60e049476..2546bf073 100644 --- a/packages/void/test/unit/pages-build-id.test.ts +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -313,12 +313,15 @@ describe('createPagesPlugin build id', () => { expect(await idOf()).not.toBe(first); }); - it('changes the id for env values the client inlines', async () => { + it.each([ + ['from the default env folder', {}], + ['from the shell when env files are off', { envDir: false }], + ])('changes the id for env values the client inlines, %s', async (_, userConfig) => { const root = createFixture(); const idFor = async (value: string) => { vi.stubEnv('VITE_PROBE', value); endPagesBuild(root); - return idIn(await createConfigHook(root)({}, { command: 'build' })); + return idIn(await createConfigHook(root)(userConfig, { command: 'build' })); }; // Two builds that differ only here still emit different chunks. From 028af5893dcf6920121d09aab20b1979dba74dca Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 11:15:07 +0800 Subject: [PATCH 07/14] fix: hash fixed-prefix client env and Plug'n'Play workspace packages Void folds schema-declared `VITE_` values into the client whatever the app's `envPrefix`, so the build id now always reads that prefix too. A Yarn Plug'n'Play install has no node_modules links, so the build id missed the workspace packages an app depends on. It now resolves them the way the Node target does, through `findPnpApi`. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/installed-packages.ts | 2 +- packages/void/src/pages/build-id-source.ts | 11 ++++---- packages/void/src/pages/plugin.ts | 3 ++- .../void/test/unit/pages-build-id.test.ts | 26 +++++++++++++++++++ 4 files changed, 35 insertions(+), 7 deletions(-) diff --git a/packages/void/src/installed-packages.ts b/packages/void/src/installed-packages.ts index d2b7e03dc..51ff801a2 100644 --- a/packages/void/src/installed-packages.ts +++ b/packages/void/src/installed-packages.ts @@ -26,7 +26,7 @@ function readManifest(dir: string): PackageManifest | undefined { type PnpApi = { resolveToUnqualified(request: string, issuer: string): string | null }; /** The directory Node loads `name` from for code in `fromDir`. Ignores `exports`. */ -function findInstalledPackage(name: string, fromDir: string): string | undefined { +export function findInstalledPackage(name: string, fromDir: string): string | undefined { // A Yarn Plug'n'Play install has no node_modules. Under `yarn`, its runtime adds // `findPnpApi` to `node:module` and serves the packages' files from its archives. const pnp = (module as { findPnpApi?: (path: string) => PnpApi | null }).findPnpApi?.(fromDir); diff --git a/packages/void/src/pages/build-id-source.ts b/packages/void/src/pages/build-id-source.ts index 02bb7cb07..503f672c0 100644 --- a/packages/void/src/pages/build-id-source.ts +++ b/packages/void/src/pages/build-id-source.ts @@ -10,6 +10,7 @@ import { } from 'node:fs'; import { isAbsolute, join, relative } from 'pathslash'; import { searchForWorkspaceRoot } from 'vite'; +import { findInstalledPackage } from '../installed-packages.ts'; /** Directories never part of the app source, whatever their position. */ const alwaysSkipped = new Set(['node_modules']); @@ -173,8 +174,8 @@ function dependencyNames(directory: string): Array { /** * Folders of the workspace packages `root` depends on, directly or through other - * workspace packages. Package managers link them into node_modules, and the link - * leads back into the workspace outside any node_modules. + * workspace packages. Package managers link them into node_modules, or Yarn + * Plug'n'Play maps them, and they lie in the workspace outside any node_modules. */ function workspaceDependencies(root: string, workspace: string): Array { const realWorkspace = realPath(workspace); @@ -187,9 +188,9 @@ function workspaceDependencies(root: string, workspace: string): Array { const queue = [realRoot]; for (let directory = queue.shift(); directory !== undefined; directory = queue.shift()) { for (const name of dependencyNames(directory)) { - const target = - realPath(join(directory, 'node_modules', name)) ?? - realPath(join(realWorkspace, 'node_modules', name)); + // Follows node_modules links, or asks Yarn Plug'n'Play where there are none. + const installed = findInstalledPackage(name, directory); + const target = installed === undefined ? null : (realPath(installed) ?? installed); if (target === null || seen.has(target)) { continue; } diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index edde789b2..3c1d45574 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -104,7 +104,8 @@ function clientBuildInputs(root: string, userConfig: UserConfig, mode: string): ? envDir : join(root, envDir) : (envDir ?? root), - userConfig.envPrefix ?? 'VITE_', + // Fixed-prefix VITE_ keys an env.ts declares reach the client whatever the prefix. + [...new Set(['VITE_', ...[userConfig.envPrefix ?? []].flat()])], ); return { env: JSON.stringify(sortedEntries(env)), diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts index 2546bf073..96eb221ab 100644 --- a/packages/void/test/unit/pages-build-id.test.ts +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -8,6 +8,7 @@ import { utimesSync, writeFileSync, } from 'node:fs'; +import module from 'node:module'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; @@ -191,6 +192,30 @@ describe('computePagesBuildId', () => { expect(buildIdOf(app)).toBe(first); }); + it("asks Yarn Plug'n'Play for workspace packages when there is no node_modules", () => { + const { app, write } = createWorkspace(); + rmSync(join(app, 'node_modules'), { recursive: true, force: true }); + const ui = join(dirname(dirname(app)), 'packages/ui'); + const runtime = module as { + findPnpApi?: (path: string) => { resolveToUnqualified(request: string): string } | null; + }; + runtime.findPnpApi = () => ({ + resolveToUnqualified: (request) => { + if (request !== 'ui/package.json') { + throw new Error(`${request} is not a dependency`); + } + return join(ui, 'package.json'); + }, + }); + try { + const first = buildIdOf(app); + write('packages/ui/index.ts', 'export const label = 22;\n'); + expect(buildIdOf(app)).not.toBe(first); + } finally { + delete runtime.findPnpApi; + } + }); + it('covers an app that sits under a dot folder', () => { const { app, write } = createWorkspace('.examples/web'); const first = buildIdOf(app); @@ -316,6 +341,7 @@ describe('createPagesPlugin build id', () => { it.each([ ['from the default env folder', {}], ['from the shell when env files are off', { envDir: false }], + ['with the fixed VITE_ prefix under a custom envPrefix', { envPrefix: 'PUBLIC_' }], ])('changes the id for env values the client inlines, %s', async (_, userConfig) => { const root = createFixture(); const idFor = async (value: string) => { From fe70fd103f44574566f7d48ad350142b588e276d Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 11:28:56 +0800 Subject: [PATCH 08/14] fix: check the page a mutation redirected to, and hash Vite's built-in env A form POST that redirects comes back as the destination's GET answer, but the build check still saw the POST and let a stale payload through. It now runs after the redirect is applied, so only the mutation's own response is exempt. Vite also inlines MODE, BASE_URL and DEV/PROD into the client, so the build id now covers the mode, the configured base and NODE_ENV. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/pages/navigation-engine.ts | 42 +++++++++++-------- packages/void/src/pages/plugin.ts | 8 +++- .../void/test/unit/pages-build-id.test.ts | 23 ++++++++++ packages/void/test/unit/pages-client.test.ts | 22 ++++++++++ 4 files changed, 76 insertions(+), 19 deletions(-) diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index 988b21d35..2918aea88 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -879,11 +879,33 @@ export async function createPageNavigationEngine( : null; let response = fetched?.response ?? null; + if (pageData === undefined && !response) { + loadDocument(url); + return undefined; + } + + if (fetched?.redirectedTo) { + const redirectUrl = new URL(fetched.redirectedTo, window.location.origin); + if (!isSameOrigin(redirectUrl, window.location.origin)) { + window.location.href = fetched.redirectedTo; + return undefined; + } + // The fetch transport followed the redirect: treat the final response as the GET + // result for the destination instead of fetching it a second time. + method = 'GET'; + fetchUrl = redirectUrl.pathname + redirectUrl.search; + url = fetchUrl + redirectUrl.hash; + commitTarget.fetchUrl = fetchUrl; + commitTarget.hash = redirectUrl.hash; + commitTarget.method = method; + } + // The destination was rendered by another deployment, so this tab's chunks // are gone. Treat the payload as absent: the document load below lands on the // requested destination with its query and hash. A mutation has already run, - // so only a GET is allowed to get here. A response that names no build, from - // an older Void, is not evidence of a new one. + // so only a GET is allowed here, which includes the page a mutation redirected + // to. A response that names no build, from an older Void, is not evidence of a + // new one. const servedBy = response?.headers.get(PAGES_BUILD_HEADER) ?? null; if (method === 'GET' && servedBy !== null && isStaleBuild(pagesBuildId(), servedBy)) { if (claimDeployReload(servedBy, url)) { @@ -903,22 +925,6 @@ export async function createPageNavigationEngine( return undefined; } - if (fetched?.redirectedTo) { - const redirectUrl = new URL(fetched.redirectedTo, window.location.origin); - if (!isSameOrigin(redirectUrl, window.location.origin)) { - window.location.href = fetched.redirectedTo; - return undefined; - } - // The fetch transport followed the redirect: treat the final response as the GET - // result for the destination instead of fetching it a second time. - method = 'GET'; - fetchUrl = redirectUrl.pathname + redirectUrl.search; - url = fetchUrl + redirectUrl.hash; - commitTarget.fetchUrl = fetchUrl; - commitTarget.hash = redirectUrl.hash; - commitTarget.method = method; - } - if (response && method !== 'GET' && !response.ok) { throw await createActionErrorFromResponse(response, fetchUrl); } diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index 3c1d45574..84b3ef39a 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -108,7 +108,13 @@ function clientBuildInputs(root: string, userConfig: UserConfig, mode: string): [...new Set(['VITE_', ...[userConfig.envPrefix ?? []].flat()])], ); return { - env: JSON.stringify(sortedEntries(env)), + // Vite also inlines MODE, BASE_URL, and DEV/PROD from NODE_ENV. + env: JSON.stringify([ + sortedEntries(env), + mode, + userConfig.base ?? null, + process.env.NODE_ENV ?? null, + ]), define: JSON.stringify(sortedEntries(userConfig.define ?? {})), }; } diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts index 96eb221ab..04148e016 100644 --- a/packages/void/test/unit/pages-build-id.test.ts +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -354,6 +354,29 @@ describe('createPagesPlugin build id', () => { expect(await idFor('one')).not.toBe(await idFor('two')); }); + it('changes the id for the mode and base Vite inlines', async () => { + const root = createFixture(); + // A new plugin per build, as Vite makes one. + const idFor = async (userConfig: Record, mode: string) => { + endPagesBuild(root); + const plugin = createPagesPlugin(join(root, 'pages'), { + name: 'test:pages', + generateRenderer: () => '', + generateClient: () => '', + config: () => ({}), + }); + const hook = getHookHandler(plugin.config) as unknown as ( + userConfig: Record, + env: { command: 'build'; mode: string }, + ) => Promise; + return idIn(await hook(userConfig, { command: 'build', mode })); + }; + + const production = await idFor({}, 'production'); + expect(await idFor({}, 'staging')).not.toBe(production); + expect(await idFor({ base: '/app/' }, 'production')).not.toBe(production); + }); + it('changes the id for an app define the client inlines', async () => { // Two apps with the same source, built apart, that differ only in a define. const idFor = async (value: string) => diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 0359ee152..c2429830d 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -332,6 +332,28 @@ describe('Pages build recovery', () => { expect(document.body.replaceChildren).toHaveBeenCalled(); }); + it('reloads the page a mutation redirected to when another build rendered it', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + const redirected = staleJson({ ...stalePage, url: '/items/1' }); + Object.defineProperties(redirected, { + redirected: { value: true }, + url: { value: 'http://localhost/items/1' }, + }); + const fetch = vi.fn().mockResolvedValueOnce(redirected); + vi.stubGlobal('fetch', fetch); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/items', { method: 'POST' }); + + // The action ran once; only the page it redirected to is loaded again. + expect(fetch).toHaveBeenCalledOnce(); + expect(window.location.href).toBe('/items/1'); + expect(applyUpdate).not.toHaveBeenCalled(); + }); + it('applies a mutation answered by another build and never reloads', async () => { stubClientGlobals(); vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); From 2da65a8854df587a8facef0eb068309ad8f3c9ac Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 11:44:11 +0800 Subject: [PATCH 09/14] fix: keep 307/308 mutation answers, and hash client environment defines The build check treated every redirected answer as a GET, so a stale tab lost the result of a POST that a 307 or 308 carried to another URL. The transport now reports the method that got the answer, and only a GET answer can reload. Defines under `environments.client` reach the client bundle too, so the build id covers them. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/pages/navigation-engine.ts | 10 +++-- packages/void/src/pages/plugin.ts | 6 ++- packages/void/src/pages/redirect.ts | 16 ++++++-- .../void/test/unit/pages-build-id.test.ts | 12 ++++++ packages/void/test/unit/pages-client.test.ts | 37 +++++++++++++++---- .../void/test/unit/pages-redirect.test.ts | 1 + 6 files changed, 67 insertions(+), 15 deletions(-) diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index 2918aea88..b42b8bc11 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -878,6 +878,8 @@ export async function createPageNavigationEngine( : await fetchPages(url, fetchOptions) : null; let response = fetched?.response ?? null; + // A 307 or 308 answers a mutation with a mutation, whatever URL it lands on. + const answeredMethod = fetched?.method ?? method; if (pageData === undefined && !response) { loadDocument(url); @@ -903,11 +905,11 @@ export async function createPageNavigationEngine( // The destination was rendered by another deployment, so this tab's chunks // are gone. Treat the payload as absent: the document load below lands on the // requested destination with its query and hash. A mutation has already run, - // so only a GET is allowed here, which includes the page a mutation redirected - // to. A response that names no build, from an older Void, is not evidence of a - // new one. + // so only a GET answer is allowed here, which includes the page a mutation was + // redirected to with a 303. A response that names no build, from an older + // Void, is not evidence of a new one. const servedBy = response?.headers.get(PAGES_BUILD_HEADER) ?? null; - if (method === 'GET' && servedBy !== null && isStaleBuild(pagesBuildId(), servedBy)) { + if (answeredMethod === 'GET' && servedBy !== null && isStaleBuild(pagesBuildId(), servedBy)) { if (claimDeployReload(servedBy, url)) { response = null; pageData = undefined; diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index 84b3ef39a..ec3c26829 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -115,7 +115,11 @@ function clientBuildInputs(root: string, userConfig: UserConfig, mode: string): userConfig.base ?? null, process.env.NODE_ENV ?? null, ]), - define: JSON.stringify(sortedEntries(userConfig.define ?? {})), + // The client environment can add or override defines of its own. + define: JSON.stringify([ + sortedEntries(userConfig.define ?? {}), + sortedEntries(userConfig.environments?.client?.define ?? {}), + ]), }; } diff --git a/packages/void/src/pages/redirect.ts b/packages/void/src/pages/redirect.ts index 2886fddcf..af1ab55ed 100644 --- a/packages/void/src/pages/redirect.ts +++ b/packages/void/src/pages/redirect.ts @@ -22,7 +22,16 @@ export function pagesRedirectResponse(request: Request, response: Response): Res return new Response(response.body, { status: 200, headers }); } -export type PagesFetchResult = { response: Response; redirectedTo?: string }; +export type PagesFetchResult = { + response: Response; + redirectedTo?: string; + /** + * The method of the request that got `response`: a 303 turns a POST into a GET, + * a 307 or 308 keeps it. A redirect the browser followed itself is not seen, so + * it keeps the method that was sent. + */ + method: string; +}; export type PagesFetchOptions = Omit & { headers: Record }; /** Follow negotiated redirects with HTTP method rules and origin checks. */ @@ -34,6 +43,7 @@ export async function fetchPages( const headers: PagesFetchOptions['headers'] = { ...options.headers, [REDIRECT_HEADER]: 'manual' }; const init = { ...options, headers }; let redirectedTo: string | undefined; + const finalMethod = () => (init.method ?? 'GET').toUpperCase(); for (let redirects = 0; redirects <= 20; redirects++) { const response = await fetch(url.split('#')[0], init); const status = Number(response.headers.get(REDIRECT_HEADER)); @@ -48,7 +58,7 @@ export async function fetchPages( } redirectedTo = destination.href; } - return { response, redirectedTo }; + return { response, redirectedTo, method: finalMethod() }; } await response.body?.cancel(); const base = new URL( @@ -71,7 +81,7 @@ export async function fetchPages( !isSameOrigin(destination, window.location.origin) || (!followGetRedirects && (get || method === 'GET' || method === 'HEAD')) ) { - return { response, redirectedTo }; + return { response, redirectedTo, method: finalMethod() }; } if (get) { for (const name of Object.keys(headers)) { diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts index 04148e016..ccc75e18f 100644 --- a/packages/void/test/unit/pages-build-id.test.ts +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -390,6 +390,18 @@ describe('createPagesPlugin build id', () => { expect(await idFor('one')).not.toBe(await idFor('two')); }); + it('changes the id for a define of the client environment', async () => { + const idFor = async (value: string) => + idIn( + await createConfigHook(createFixture())( + { environments: { client: { define: { __API__: JSON.stringify(value) } } } }, + { command: 'build' }, + ), + ); + + expect(await idFor('one')).not.toBe(await idFor('two')); + }); + it('defines nothing when deploy recovery is off', async () => { const config = createConfigHook(undefined, { deployRecovery: false }); diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index c2429830d..843a11a80 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -332,16 +332,23 @@ describe('Pages build recovery', () => { expect(document.body.replaceChildren).toHaveBeenCalled(); }); + /** The transport's redirect handshake, then the destination's answer. */ + function redirectThen(status: 303 | 307, answer: Response) { + return vi + .fn() + .mockResolvedValueOnce( + new Response(null, { + headers: { 'X-VoidPages-Redirect': String(status), Location: '/items/1' }, + }), + ) + .mockResolvedValueOnce(answer); + } + it('reloads the page a mutation redirected to when another build rendered it', async () => { stubClientGlobals(); vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); stubReloadGuard(); - const redirected = staleJson({ ...stalePage, url: '/items/1' }); - Object.defineProperties(redirected, { - redirected: { value: true }, - url: { value: 'http://localhost/items/1' }, - }); - const fetch = vi.fn().mockResolvedValueOnce(redirected); + const fetch = redirectThen(303, staleJson({ ...stalePage, url: '/items/1' })); vi.stubGlobal('fetch', fetch); const applyUpdate = vi.fn(); const { router } = await createTestRouter({ adapter: { applyUpdate } }); @@ -349,11 +356,27 @@ describe('Pages build recovery', () => { await router.visit('/items', { method: 'POST' }); // The action ran once; only the page it redirected to is loaded again. - expect(fetch).toHaveBeenCalledOnce(); + expect(fetch).toHaveBeenCalledTimes(2); + expect(fetch.mock.calls[1]?.[1]).toMatchObject({ method: 'GET' }); expect(window.location.href).toBe('/items/1'); expect(applyUpdate).not.toHaveBeenCalled(); }); + it('keeps a mutation response that a 307 redirect answered, from any build', async () => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + vi.stubGlobal('fetch', redirectThen(307, staleJson({ ...stalePage, url: '/items/1' }))); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + await router.visit('/items', { method: 'POST' }); + + // The POST ran at the new URL, so reloading would lose its result. + expect(window.location.href).toBeUndefined(); + expect(applyUpdate).toHaveBeenCalled(); + }); + it('applies a mutation answered by another build and never reloads', async () => { stubClientGlobals(); vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); diff --git a/packages/void/test/unit/pages-redirect.test.ts b/packages/void/test/unit/pages-redirect.test.ts index 8f194d3ad..315895ea4 100644 --- a/packages/void/test/unit/pages-redirect.test.ts +++ b/packages/void/test/unit/pages-redirect.test.ts @@ -39,6 +39,7 @@ it.each([301, 302, 303, 307, 308] as const)( }); const get = status === 303 || ((status === 301 || status === 302) && method === 'POST'); expect(result.redirectedTo).toBe('https://app.test/to#details'); + expect(result.method).toBe(get ? 'GET' : method); expect(await result.response.json()).toEqual({ method: get ? 'GET' : method, body: get ? '' : '{"id":42}', From abc11183a470ea9ceec12b6b957b5749597543d6 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 12:01:14 +0800 Subject: [PATCH 10/14] fix: keep shared ISR eviction for ordinary Pages answers Native and hosted ISR skipped evicting shared HTML for any Pages answer without page data, so a loader or middleware that answered with an explicit no-store 200 left the public copy in place. Only the reload answer to a client from another build is exempt now: no page data, and a build that differs from the one the client sent. Co-Authored-By: Claude Opus 5.5 --- packages/edge/src/index.ts | 1 + packages/edge/src/pages-protocol.ts | 17 +++++++++++++++ packages/isr/src/runtime.ts | 3 ++- packages/void/test/unit/isr-cache.test.ts | 21 +++++++++++++------ platform/packages/dispatch/src/index.ts | 8 +++---- .../packages/dispatch/test/unit/index.test.ts | 18 +++++++++++----- 6 files changed, 51 insertions(+), 17 deletions(-) diff --git a/packages/edge/src/index.ts b/packages/edge/src/index.ts index d35c90317..34a27048f 100644 --- a/packages/edge/src/index.ts +++ b/packages/edge/src/index.ts @@ -2,6 +2,7 @@ export type { ProjectZeroTrustRouting } from './access.ts'; export { buildHeaders, isStaleBuild, + isStaleBuildReload, pagesPayloadFitsBuild, PAGES_BUILD_HEADER, PAGES_PROTOCOL_VERSION, diff --git a/packages/edge/src/pages-protocol.ts b/packages/edge/src/pages-protocol.ts index 3e684df9f..2c4ca2348 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -34,3 +34,20 @@ export function pagesPayloadFitsBuild( ): boolean { return requestBuild === null || cachedBuild === requestBuild; } + +/** + * Whether `response` is the app's reload answer to a Pages client from another + * build: no page data, and a build that differs from the one the client sent. + * It says nothing about cached copies of the page, which other tabs still use. + */ +export function isStaleBuildReload(request: Request, response: Response): boolean { + const sent = request.headers.get(PAGES_BUILD_HEADER); + const answered = response.headers.get(PAGES_BUILD_HEADER); + return ( + request.headers.has('X-VoidPages') && + !response.headers.has('X-VoidPages') && + sent !== null && + answered !== null && + sent !== answered + ); +} diff --git a/packages/isr/src/runtime.ts b/packages/isr/src/runtime.ts index 05ccc3109..4d516d9c6 100644 --- a/packages/isr/src/runtime.ts +++ b/packages/isr/src/runtime.ts @@ -1,4 +1,5 @@ import { + isStaleBuildReload, matchSegmentPattern, pagesPayloadFitsBuild, PAGES_BUILD_HEADER, @@ -612,7 +613,7 @@ async function handleIsrInternal( const response = await render(request); // The app answered a stale client with its reload response. That says nothing // about this path's cached HTML, which other tabs can still use. - if (!response.headers.get('X-VoidPages')) { + if (isStaleBuildReload(request, response)) { return response; } const ttl = resolveRevalidateTtl(response, isrTtl); diff --git a/packages/void/test/unit/isr-cache.test.ts b/packages/void/test/unit/isr-cache.test.ts index cbc2534b5..8a7940fc8 100644 --- a/packages/void/test/unit/isr-cache.test.ts +++ b/packages/void/test/unit/isr-cache.test.ts @@ -1042,14 +1042,23 @@ describe('handleIsr', () => { expect(res!.headers.get('X-VoidPages-Build')).toBe('build-2'); }); - it('keeps cached HTML when a stale client gets its reload response', async () => { + it.each([ + ['keeps', 'the reload response for a client from another build', 'build-2', true], + ['evicts', 'an ordinary answer that opts out of sharing', null, false], + ])('%s cached HTML on %s', async (_, __, answeredBuild, kept) => { const { store, kv } = createKvMock(); store.set(isrKey(DPL, HOST, '/blog/post'), corruptCases[0].seed()); const env = makeEnv(kv); const htmlKey = htmlEdgeKey(HOST, '/blog/post', DPL); edge.store.set(htmlKey, currentSharedCacheResponse(new Response('cached'))); const { render } = createRender( - () => new Response(null, { headers: { 'Cache-Control': 'no-store' } }), + () => + new Response(null, { + headers: { + 'Cache-Control': 'no-store', + ...(answeredBuild === null ? {} : { 'X-VoidPages-Build': answeredBuild }), + }, + }), ); const { ctx, flush } = createCtx(); @@ -1057,7 +1066,7 @@ describe('handleIsr', () => { htmlRequest('/blog/post', { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, - 'X-VoidPages-Build': 'build-2', + 'X-VoidPages-Build': 'build-1', }), env, ctx, @@ -1066,10 +1075,10 @@ describe('handleIsr', () => { ); await flush(); - // The answer belongs to the JSON path only; other tabs still hold this HTML. + // A reload answer belongs to one stale tab; other tabs still hold this HTML. expect(res!.headers.get('Cache-Control')).toBe('no-store'); - expect(await edge.store.get(htmlKey)!.text()).toBe('cached'); - expect(store.has(isrKey(DPL, HOST, '/blog/post'))).toBe(true); + expect(edge.store.has(htmlKey)).toBe(kept); + expect(store.has(isrKey(DPL, HOST, '/blog/post'))).toBe(kept); }); it.each([ diff --git a/platform/packages/dispatch/src/index.ts b/platform/packages/dispatch/src/index.ts index 8c897a8b2..64392edea 100644 --- a/platform/packages/dispatch/src/index.ts +++ b/platform/packages/dispatch/src/index.ts @@ -1,4 +1,5 @@ import { + isStaleBuildReload, matchLiteralPattern, pagesPayloadFitsBuild, PAGES_BUILD_HEADER, @@ -1823,13 +1824,10 @@ const dispatcher = { } } - // The app answers a stale Pages client with a reload response that carries no - // page data. It says nothing about the cached HTML, which other tabs still use. - const pagesReload = - request.headers.has('X-VoidPages') && !response.headers.has('X-VoidPages'); if ( sharedIsrEntry && - !pagesReload && + // The app's answer to a stale Pages client says nothing about cached HTML. + !isStaleBuildReload(request, response) && response.status === 200 && !writebackFallbackApplied && (resolveRevalidateTtl( diff --git a/platform/packages/dispatch/test/unit/index.test.ts b/platform/packages/dispatch/test/unit/index.test.ts index 0179383d8..832d8f573 100644 --- a/platform/packages/dispatch/test/unit/index.test.ts +++ b/platform/packages/dispatch/test/unit/index.test.ts @@ -3507,7 +3507,10 @@ describe('ISR JSON edge cache (pages protocol)', () => { expect(edgeCacheStore.has(htmlKey)).toBe(false); }); - it('keeps cached HTML when a stale client gets its reload response', async () => { + it.each([ + ['keeps', 'the reload response for a client from another build', 'build-2', true], + ['evicts', 'an ordinary answer that opts out of sharing', null, false], + ])('%s cached HTML on %s', async (_, __, answeredBuild, kept) => { const htmlKey = 'https://my-app.void.app/dashboard?__void_isr=legacy'; edgeCacheStore.set( htmlKey, @@ -3518,7 +3521,12 @@ describe('ISR JSON edge cache (pages protocol)', () => { const { env, workerFetch } = createEnv({ routing: isrRouting, - workerResponse: new Response(null, { headers: { 'Cache-Control': 'no-store' } }), + workerResponse: new Response(null, { + headers: { + 'Cache-Control': 'no-store', + ...(answeredBuild === null ? {} : { 'X-VoidPages-Build': answeredBuild }), + }, + }), }); const ctx = createCtx(); @@ -3527,7 +3535,7 @@ describe('ISR JSON edge cache (pages protocol)', () => { headers: { 'X-VoidPages': 'true', 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, - 'X-VoidPages-Build': 'build-2', + 'X-VoidPages-Build': 'build-1', }, }), env, @@ -3535,10 +3543,10 @@ describe('ISR JSON edge cache (pages protocol)', () => { ); await waitForBackgroundTasks(ctx); - // The answer belongs to the JSON path; other tabs still hold this HTML. + // A reload answer belongs to one stale tab; other tabs still hold this HTML. expect(workerFetch).toHaveBeenCalledOnce(); expect(response.headers.get('Cache-Control')).toBe('no-store'); - expect(edgeCacheStore.has(htmlKey)).toBe(true); + expect(edgeCacheStore.has(htmlKey)).toBe(kept); }); it('pages request falls through to worker on JSON cache miss', async () => { From aca8beec27b422091e843a39bf0ae82598458aca Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 12:20:17 +0800 Subject: [PATCH 11/14] fix: invalidate after an ISR build bypass, and match Capacitor origins on reload Native ISR returned the app's answer straight away when a cached JSON entry belonged to another build, which skipped evicting shared copies for a no-store answer. It now falls through to the normal render path, like hosted dispatch, and still keeps the entry for clients of its own build. `URL.origin` is "null" for capacitor:// URLs, so a same-document reload inside a Capacitor app looked cross-origin and only scrolled. The reload check now uses the shared isSameOrigin helper. Co-Authored-By: Claude Opus 5.5 --- packages/isr/src/runtime.ts | 11 +++-- packages/void/src/pages/navigation-engine.ts | 2 +- packages/void/test/unit/isr-cache.test.ts | 43 ++++++++++++++++++++ packages/void/test/unit/pages-client.test.ts | 19 +++++++++ 4 files changed, 68 insertions(+), 7 deletions(-) diff --git a/packages/isr/src/runtime.ts b/packages/isr/src/runtime.ts index 4d516d9c6..c5c306117 100644 --- a/packages/isr/src/runtime.ts +++ b/packages/isr/src/runtime.ts @@ -596,18 +596,17 @@ async function handleIsrInternal( } if (jsonCached && hasCurrentSharedCachePolicy(jsonCached)) { // A cached payload from another build would hand this client page props it - // has no components for. Let the app answer, which reloads a stale tab. + // has no components for. Let the app answer below, which reloads a stale + // tab, and keep the entry: it is still right for clients of its own build. if ( - !pagesPayloadFitsBuild( + pagesPayloadFitsBuild( jsonCached.headers.get(PAGES_BUILD_HEADER), request.headers.get(PAGES_BUILD_HEADER), ) ) { - return render(request); + return clientRevalidateResponse(jsonCached); } - return clientRevalidateResponse(jsonCached); - } - if (jsonCached) { + } else if (jsonCached) { await safeCacheDelete(cache, jsonKey); } const response = await render(request); diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index b42b8bc11..1eecfa260 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -279,7 +279,7 @@ function loadDocument(url: string): void { const { origin, pathname, search, hash } = window.location; const target = new URL(url, `${origin}${pathname}${search}`); const sameDocument = - target.origin === origin && target.pathname === pathname && target.search === search; + isSameOrigin(target, origin) && target.pathname === pathname && target.search === search; if (!sameDocument || target.hash === '') { window.location.href = url; return; diff --git a/packages/void/test/unit/isr-cache.test.ts b/packages/void/test/unit/isr-cache.test.ts index 8a7940fc8..d06ee6a40 100644 --- a/packages/void/test/unit/isr-cache.test.ts +++ b/packages/void/test/unit/isr-cache.test.ts @@ -1003,6 +1003,49 @@ describe('handleIsr', () => { expect(live!.headers.get('X-VoidPages-Build')).toBe('build-2'); }); + it('still evicts shared copies when the app answers a bypassed entry with no-store', async () => { + const { kv } = createKvMock(); + const env = makeEnv(kv); + const htmlKey = htmlEdgeKey(HOST, '/blog/post', DPL); + const jsonKey = jsonEdgeKey(HOST, '/blog/post', DPL); + edge.store.set(htmlKey, currentSharedCacheResponse(new Response('cached'))); + edge.store.set( + jsonKey, + currentSharedCacheResponse( + new Response('{"component":"Blog","props":{}}', { + headers: { 'content-type': 'application/json', 'X-VoidPages-Build': 'build-1' }, + }), + ), + ); + // The app now answers this page privately, with page data for this client. + const { render } = createRender( + () => + new Response('{"component":"Blog","props":{"me":true}}', { + headers: { + 'content-type': 'application/json', + 'X-VoidPages': 'true', + 'Cache-Control': 'private, no-store', + }, + }), + ); + const { ctx, flush } = createCtx(); + + await handleIsr( + htmlRequest('/blog/post', { + 'X-VoidPages': 'true', + 'X-VoidPages-Version': PAGES_PROTOCOL_VERSION, + 'X-VoidPages-Build': 'build-2', + }), + env, + ctx, + OPTS, + render, + ); + await flush(); + + expect(edge.store.has(htmlKey)).toBe(false); + }); + it('leaves an entry with no build id to the app when the client names one', async () => { // An entry from before ids existed cannot answer a client that has one. await populateJsonEdgeCache( diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 843a11a80..bfae6995b 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -268,6 +268,25 @@ describe('Pages build recovery', () => { expect(window.location.href).toBeUndefined(); }); + it('reloads a refresh with a fragment inside a Capacitor app', async () => { + stubClientGlobals('capacitor://localhost'); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + const reload = vi.fn(); + Object.assign(window.location, { pathname: '/docs', hash: '#install', reload }); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleReloadResponse()), + ); + const { router } = await createTestRouter(); + + await router.refresh(); + + // A custom scheme has an opaque URL origin, so the current page must still match. + expect(reload).toHaveBeenCalledOnce(); + expect(window.location.href).toBeUndefined(); + }); + it('reloads a back/forward visit to an entry with a fragment answered by another build', async () => { stubClientGlobals(); vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); From a75e342240430f3f3f116cc0d76b6b83278e1009 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 12:36:32 +0800 Subject: [PATCH 12/14] fix: match only the empty reload answer, and show the guard page in Capacitor Rendered HTML now names its build, so an island route's page for a client from another build looked like the reload answer, and a no-store render kept shared copies. The exemption now also requires the reload answer's plain-text shape. The guard page compared URL origins directly, which are "null" for capacitor:// URLs, so a stale retry inside a Capacitor app threw instead of showing it. It now uses the shared isSameOrigin helper. Co-Authored-By: Claude Opus 5.5 --- packages/edge/src/pages-protocol.ts | 8 +++- packages/void/src/pages/boundary-client.ts | 3 +- packages/void/test/unit/isr-cache.test.ts | 26 +++++++++++-- .../void/test/unit/pages-build-id.test.ts | 39 ++++++++++++++++++- packages/void/test/unit/pages-client.test.ts | 17 ++++++++ .../packages/dispatch/test/unit/index.test.ts | 26 +++++++++++-- 6 files changed, 109 insertions(+), 10 deletions(-) diff --git a/packages/edge/src/pages-protocol.ts b/packages/edge/src/pages-protocol.ts index 2c4ca2348..a4ea6d02b 100644 --- a/packages/edge/src/pages-protocol.ts +++ b/packages/edge/src/pages-protocol.ts @@ -37,15 +37,19 @@ export function pagesPayloadFitsBuild( /** * Whether `response` is the app's reload answer to a Pages client from another - * build: no page data, and a build that differs from the one the client sent. - * It says nothing about cached copies of the page, which other tabs still use. + * build: an empty plain-text answer without page data, naming a build other than + * the one the client sent. A rendered page, such as an island route's HTML, is + * not one even when it names another build. The reload answer says nothing about + * cached copies of the page, which other tabs still use. */ export function isStaleBuildReload(request: Request, response: Response): boolean { const sent = request.headers.get(PAGES_BUILD_HEADER); const answered = response.headers.get(PAGES_BUILD_HEADER); + const type = (response.headers.get('Content-Type') ?? '').split(';', 1)[0]?.trim(); return ( request.headers.has('X-VoidPages') && !response.headers.has('X-VoidPages') && + type === 'text/plain' && sent !== null && answered !== null && sent !== answered diff --git a/packages/void/src/pages/boundary-client.ts b/packages/void/src/pages/boundary-client.ts index 11cce7d96..b93efcedd 100644 --- a/packages/void/src/pages/boundary-client.ts +++ b/packages/void/src/pages/boundary-client.ts @@ -1,6 +1,7 @@ import { isVoidActionError } from './action-result.ts'; import type { BoundaryManifest } from './boundary-plans.ts'; import type { PageError } from './types.ts'; +import { isSameOrigin } from './url.ts'; export type ClientPageBoundary = { id: string; @@ -49,7 +50,7 @@ export function clientPageError(error: unknown, dev = false): PageError { /** Terminal recovery cannot depend on the failed adapter, imports, or component tree. */ export function showTerminalPageError(url: string = window.location.href): void { const target = new URL(url, window.location.href); - if (target.origin !== window.location.origin) { + if (!isSameOrigin(target, window.location.origin)) { throw new Error('Invalid error page destination'); } try { diff --git a/packages/void/test/unit/isr-cache.test.ts b/packages/void/test/unit/isr-cache.test.ts index d06ee6a40..b6b78eb9f 100644 --- a/packages/void/test/unit/isr-cache.test.ts +++ b/packages/void/test/unit/isr-cache.test.ts @@ -1086,9 +1086,28 @@ describe('handleIsr', () => { }); it.each([ - ['keeps', 'the reload response for a client from another build', 'build-2', true], - ['evicts', 'an ordinary answer that opts out of sharing', null, false], - ])('%s cached HTML on %s', async (_, __, answeredBuild, kept) => { + [ + 'keeps', + 'the reload response for a client from another build', + 'build-2', + 'text/plain; charset=utf-8', + true, + ], + [ + 'evicts', + 'an ordinary answer that opts out of sharing', + null, + 'text/plain; charset=utf-8', + false, + ], + [ + 'evicts', + 'a rendered page from another build that opts out of sharing', + 'build-2', + 'text/html', + false, + ], + ])('%s cached HTML on %s', async (_, __, answeredBuild, contentType, kept) => { const { store, kv } = createKvMock(); store.set(isrKey(DPL, HOST, '/blog/post'), corruptCases[0].seed()); const env = makeEnv(kv); @@ -1099,6 +1118,7 @@ describe('handleIsr', () => { new Response(null, { headers: { 'Cache-Control': 'no-store', + 'Content-Type': contentType, ...(answeredBuild === null ? {} : { 'X-VoidPages-Build': answeredBuild }), }, }), diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts index ccc75e18f..7219b5250 100644 --- a/packages/void/test/unit/pages-build-id.test.ts +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -12,7 +12,11 @@ import module from 'node:module'; import { tmpdir } from 'node:os'; import { dirname, join } from 'node:path'; import { afterEach, describe, expect, it, vi } from 'vite-plus/test'; -import { buildHeaders, isStaleBuild } from '../../../edge/src/pages-protocol.ts'; +import { + buildHeaders, + isStaleBuild, + isStaleBuildReload, +} from '../../../edge/src/pages-protocol.ts'; import { computePagesBuildId, endPagesBuild } from '../../src/pages/build-id-source.ts'; import { pagesBuildId } from '../../src/pages/build-id.ts'; import { createPagesPlugin } from '../../src/pages/plugin.ts'; @@ -67,6 +71,39 @@ describe('buildHeaders', () => { }); }); +describe('isStaleBuildReload', () => { + const request = new Request('https://app.test/next', { + headers: { 'X-VoidPages': 'true', 'X-VoidPages-Build': 'build-1' }, + }); + const answer = (headers: Record) => new Response(null, { headers }); + + it.each([ + [ + 'the reload answer', + { 'Content-Type': 'text/plain; charset=utf-8', 'X-VoidPages-Build': 'build-2' }, + true, + ], + [ + 'page data', + { 'Content-Type': 'application/json', 'X-VoidPages': 'true', 'X-VoidPages-Build': 'build-2' }, + false, + ], + [ + 'rendered HTML from another build', + { 'Content-Type': 'text/html', 'X-VoidPages-Build': 'build-2' }, + false, + ], + [ + 'an answer from the same build', + { 'Content-Type': 'text/plain', 'X-VoidPages-Build': 'build-1' }, + false, + ], + ['an answer that names no build', { 'Content-Type': 'text/plain' }, false], + ])('%s', (_, headers, expected) => { + expect(isStaleBuildReload(request, answer(headers))).toBe(expected); + }); +}); + describe('computePagesBuildId', () => { function createSourceFixture(content: string): string { const root = tempRoot('void-build-id-'); diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index bfae6995b..124cb385c 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -287,6 +287,23 @@ describe('Pages build recovery', () => { expect(window.location.href).toBeUndefined(); }); + it('shows the recovery page inside a Capacitor app when the retry is stale too', async () => { + stubClientGlobals('capacitor://localhost'); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + vi.stubGlobal( + 'fetch', + vi.fn(async () => staleReloadResponse()), + ); + const { router } = await createTestRouter(); + + await router.visit('/next'); + (window.location as unknown as { href?: string }).href = 'capacitor://localhost/'; + await router.visit('/next'); + + expect(document.body.replaceChildren).toHaveBeenCalled(); + }); + it('reloads a back/forward visit to an entry with a fragment answered by another build', async () => { stubClientGlobals(); vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); diff --git a/platform/packages/dispatch/test/unit/index.test.ts b/platform/packages/dispatch/test/unit/index.test.ts index 832d8f573..92534e418 100644 --- a/platform/packages/dispatch/test/unit/index.test.ts +++ b/platform/packages/dispatch/test/unit/index.test.ts @@ -3508,9 +3508,28 @@ describe('ISR JSON edge cache (pages protocol)', () => { }); it.each([ - ['keeps', 'the reload response for a client from another build', 'build-2', true], - ['evicts', 'an ordinary answer that opts out of sharing', null, false], - ])('%s cached HTML on %s', async (_, __, answeredBuild, kept) => { + [ + 'keeps', + 'the reload response for a client from another build', + 'build-2', + 'text/plain; charset=utf-8', + true, + ], + [ + 'evicts', + 'an ordinary answer that opts out of sharing', + null, + 'text/plain; charset=utf-8', + false, + ], + [ + 'evicts', + 'a rendered page from another build that opts out of sharing', + 'build-2', + 'text/html', + false, + ], + ])('%s cached HTML on %s', async (_, __, answeredBuild, contentType, kept) => { const htmlKey = 'https://my-app.void.app/dashboard?__void_isr=legacy'; edgeCacheStore.set( htmlKey, @@ -3524,6 +3543,7 @@ describe('ISR JSON edge cache (pages protocol)', () => { workerResponse: new Response(null, { headers: { 'Cache-Control': 'no-store', + 'Content-Type': contentType, ...(answeredBuild === null ? {} : { 'X-VoidPages-Build': answeredBuild }), }, }), From 7cfaeb9964d4128c76f2201ef03d326524073218 Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 12:50:02 +0800 Subject: [PATCH 13/14] fix: drop the plugin-local build id so a reused plugin hashes again A pages plugin instance kept its own copy of the build id, so a second build through the same instance reused the first id after buildApp had ended the build. The shared per-build memo already gives every environment one id, so the local copy is gone. Co-Authored-By: Claude Opus 5.5 --- packages/void/src/pages/plugin.ts | 8 +++----- packages/void/test/unit/pages-build-id.test.ts | 10 ++++++++-- 2 files changed, 11 insertions(+), 7 deletions(-) diff --git a/packages/void/src/pages/plugin.ts b/packages/void/src/pages/plugin.ts index ec3c26829..9bc59bb46 100644 --- a/packages/void/src/pages/plugin.ts +++ b/packages/void/src/pages/plugin.ts @@ -130,10 +130,6 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp let viteConfig: ResolvedConfig | undefined; const root = options.root ?? dirname(pagesDir); const normalizedPagesDir = normalizePath(pagesDir); - // One id for the whole app: both bundles get it from the same define, and Vite - // may resolve this config once per environment, so it is derived from the source - // rather than minted here. - let buildId: string | undefined; let pendingRescan: Promise | null = null; async function rescanPages(): Promise { pageScan = existsSync(pagesDir) @@ -275,7 +271,9 @@ export function createPagesPlugin(pagesDir: string, options: CreatePagesPluginOp if (userConfig.define?.[PAGES_BUILD_ID_DEFINE] !== undefined) { return resolved; } - buildId ??= computePagesBuildId( + // One id per build for every environment: computePagesBuildId keeps the + // first one until buildApp ends, whichever plugin instance asks. + const buildId = computePagesBuildId( root, buildIdExcludes(root, userConfig), clientBuildInputs(root, userConfig, env.mode), diff --git a/packages/void/test/unit/pages-build-id.test.ts b/packages/void/test/unit/pages-build-id.test.ts index 7219b5250..1eb1e2198 100644 --- a/packages/void/test/unit/pages-build-id.test.ts +++ b/packages/void/test/unit/pages-build-id.test.ts @@ -352,13 +352,19 @@ describe('createPagesPlugin build id', () => { generateClient: () => '', config: () => ({}), }); - const first = idIn(await createConfigHook(root)({}, { command: 'build' })); + // The same plugin instance builds twice, as through Vite's JavaScript API. + const config = getHookHandler(plugin.config) as unknown as ( + userConfig: Record, + env: { command: 'build'; mode: string }, + ) => Promise; + const build = () => config({}, { command: 'build', mode: 'production' }); + const first = idIn(await build()); writeFileSync(join(root, 'pages', 'index.tsx'), 'export default function Other() {}\n'); const endBuild = getHookHandler(plugin.buildApp) as unknown as () => Promise; await endBuild(); - expect(idIn(await createConfigHook(root)({}, { command: 'build' }))).not.toBe(first); + expect(idIn(await build())).not.toBe(first); }); it('derives the id from the app source, so identical sources keep it', async () => { From f337b89cc3bce97e7ceb63f5645268c13032316d Mon Sep 17 00:00:00 2001 From: LongYinan Date: Thu, 26 Nov 2026 13:05:20 +0800 Subject: [PATCH 14/14] fix: skip deploy recovery for a visit a newer one replaced Co-Authored-By: Claude Opus 5.5 --- packages/void/src/pages/navigation-engine.ts | 8 ++++ packages/void/test/unit/pages-client.test.ts | 43 ++++++++++++++++++++ 2 files changed, 51 insertions(+) diff --git a/packages/void/src/pages/navigation-engine.ts b/packages/void/src/pages/navigation-engine.ts index 1eecfa260..53bc93eea 100644 --- a/packages/void/src/pages/navigation-engine.ts +++ b/packages/void/src/pages/navigation-engine.ts @@ -823,6 +823,9 @@ export async function createPageNavigationEngine( const cachedPageData = await cacheEntry.response; _prefetchCache.consume(fetchUrl, method); if (cachedPageData === null) { + if (signal.aborted) { + throw abortError(); + } const staleBuild = stalePrefetches.get(fetchUrl); stalePrefetches.delete(fetchUrl); if (staleBuild !== undefined && !claimDeployReload(staleBuild, url)) { @@ -910,6 +913,11 @@ export async function createPageNavigationEngine( // Void, is not evidence of a new one. const servedBy = response?.headers.get(PAGES_BUILD_HEADER) ?? null; if (answeredMethod === 'GET' && servedBy !== null && isStaleBuild(pagesBuildId(), servedBy)) { + // A newer visit owns the page now. Leaving it is not this visit's call, and + // neither is the reload this tab may spend. + if (signal.aborted) { + throw abortError(); + } if (claimDeployReload(servedBy, url)) { response = null; pageData = undefined; diff --git a/packages/void/test/unit/pages-client.test.ts b/packages/void/test/unit/pages-client.test.ts index 124cb385c..691a17119 100644 --- a/packages/void/test/unit/pages-client.test.ts +++ b/packages/void/test/unit/pages-client.test.ts @@ -248,6 +248,49 @@ describe('Pages build recovery', () => { expect(document.body.replaceChildren).toHaveBeenCalled(); }); + it.each([ + ['the first reload', false], + ['the recovery page', true], + ])('skips %s when a newer visit took over', async (_, reloadSpent) => { + stubClientGlobals(); + vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2'); + stubReloadGuard(); + if (reloadSpent) { + sessionStorage.setItem( + '__void_pages_deploy_reload', + JSON.stringify({ build: 'build-1', url: '/old', at: Date.now() }), + ); + } + // The old visit's response arrives after the newer visit aborted it, as a + // fetch that already resolved does. + const stale = controlledPromise(); + vi.stubGlobal( + 'fetch', + vi.fn(async (url: string) => + url === '/old' + ? stale.promise + : Response.json( + { ...stalePage, url: '/new' }, + { headers: { 'X-VoidPages': 'true', 'X-VoidPages-Build': 'build-2' } }, + ), + ), + ); + const applyUpdate = vi.fn(); + const { router } = await createTestRouter({ adapter: { applyUpdate } }); + + const oldVisit = router.visit('/old'); + await Promise.resolve(); + const newVisit = router.visit('/new'); + stale.resolve(staleReloadResponse()); + + // A superseded GET visit settles quietly. + await expect(oldVisit).resolves.toBeUndefined(); + await newVisit; + expect(window.location.href).toBeUndefined(); + expect(document.body.replaceChildren).not.toHaveBeenCalled(); + expect(applyUpdate).toHaveBeenCalled(); + }); + it('reloads when a refresh of a URL with a fragment is answered by another build', async () => { stubClientGlobals(); vi.stubEnv('__VOID_PAGES_BUILD_ID', 'build-2');