diff --git a/packages/compiler-test-utils/src/hmr-sync.ts b/packages/compiler-test-utils/src/hmr-sync.ts index 504e270865..6f57f73116 100644 --- a/packages/compiler-test-utils/src/hmr-sync.ts +++ b/packages/compiler-test-utils/src/hmr-sync.ts @@ -4,23 +4,31 @@ * by a quiet period or by counting HMR messages. * * The app's client code includes `hmrSyncModule` (Vite's public client HMR - * API, `import.meta.hot.on`), or the page imports it on every load + * API, `import.meta.hot.on`/`send`), or the page imports it on every load * (`hmrSyncInitScript`, `openPage`'s `initScript`): it records Vite's * `vite:beforeFullReload` event, which Vite's client fires before it * reloads the page, and the token of the last `harness:sync` custom event - * it received. `settlePage` sends that event over the dev server's HMR + * it received, and answers each one with `harness:synced` over the same + * WebSocket. `settlePage` sends that event over the dev server's HMR * channel (`hot.send`) until the page holds its token: one WebSocket * delivers in order, and Vite's client handles one message after the other * (an update once its modules are fetched and its accept callbacks ran), so * by then the page has received and handled every update and full reload * the server sent before it. + * What the page sent back while it handled them (an accept callback's + * `invalidate()`, e.g. a refresh runtime that cannot apply an update) reaches + * the server before the page's answer, on the same WebSocket, and Vite + * handles it as it arrives (the update or full reload it causes is sent + * then): so a page counts as settled only once its answer came back with + * nothing else sent to the client since the token went out; otherwise + * another token follows what was sent meanwhile. * A page that announced a full reload is waited for until its new document * holds the token; a page with requests in flight (an update's modules, a * reload's document) is not settled yet. One overall bound. */ import { waitForOutcome } from './outcome' import type { BrowserPage } from './browser' -import type { DevServer } from './dev-server' +import type { DevServer, HmrMessage } from './dev-server' /** * `src/hmr-sync.ts`: imported by a module the app's client code loads (on @@ -28,11 +36,14 @@ import type { DevServer } from './dev-server' * context but no page). */ export const hmrSyncModule = `if (import.meta.hot && typeof window !== 'undefined') { - import.meta.hot.on('vite:beforeFullReload', () => { + const hot = import.meta.hot + const page = ((window as any).__harnessPage ??= Math.random().toString(36).slice(2)) + hot.on('vite:beforeFullReload', () => { ;(window as any).__harnessFullReload = true }) - import.meta.hot.on('harness:sync', (data: { token: string }) => { + hot.on('harness:sync', (data: { token: string }) => { ;(window as any).__harnessSynced = data.token + hot.send('harness:synced', { token: data.token, page }) }) } ` @@ -61,11 +72,16 @@ export function trackRequests(browser: BrowserPage) { let tokens = 0 +/** A payload of the server's own sync event (`settlePage`). */ +const isSync = (message: HmrMessage) => + message.payload.type === 'custom' && message.payload.event === 'harness:sync' + /** - * Waits until the page took in everything `server` sent it so far (see the - * module comment) and has nothing in flight; call it once the server - * handled the edit (`edit()`/`settle()`). A full reload it announced has - * happened by then (`browser.loads()` counts it). + * Waits until the page took in everything `server` sent it so far, and what + * that made the page ask of the server (see the module comment), and has + * nothing in flight; call it once the server handled the edit + * (`edit()`/`settle()`). A full reload it announced has happened by then + * (`browser.loads()` counts it). */ export async function settlePage( server: DevServer, @@ -73,38 +89,78 @@ export async function settlePage( inFlight: () => number, timeout = 10_000, ): Promise { - const token = `sync-${++tokens}` + const hot = server.vite.environments.client.hot + /** + * The token out now, where the server's messages stood when it went out, + * and per page document that answered it: whether the server sent the + * client nothing else from then until the answer came. + */ + let round: { token: string; from: number; answers: Map } + const nextRound = () => { + round = { + token: `sync-${++tokens}`, + from: server.hmr.length, + answers: new Map(), + } + } + nextRound() + const onSynced = (data: { token: string; page: string }) => { + if (data.token === round.token) { + round.answers.set( + data.page, + !server.hmr + .slice(round.from) + .some( + (message) => message.environment === 'client' && !isSync(message), + ), + ) + } + } + hot.on('harness:synced', onSynced) const state = () => browser.page .evaluate( () => [ (window as any).__harnessSynced, + (window as any).__harnessPage, (window as any).__harnessFullReload === true, document.readyState, ] as const, ) // The page is between two documents - .catch(() => [undefined, true, 'loading'] as const) - await waitForOutcome({ - timeout, - applied: async () => { - const [synced, reloading, readyState] = await state() - if (synced !== token) { - // (again: a page that reloaded meanwhile missed it) - server.vite.environments.client.hot.send({ - type: 'custom', - event: 'harness:sync', - data: { token }, - }) - } - return synced === token && !reloading && readyState === 'complete' - }, - quiet: async () => { - await server.idle() - return inFlight() === 0 - }, - describe: async () => - `the page did not take in the server's HMR messages: ${JSON.stringify(await state())}`, - }) + .catch(() => [undefined, undefined, true, 'loading'] as const) + try { + await waitForOutcome({ + timeout, + applied: async () => { + const [synced, page, reloading, readyState] = await state() + const answered = + synced === round.token && page !== undefined + ? round.answers.get(page) + : undefined + if (answered === false) { + // The server sent the page more meanwhile: sync after it + nextRound() + } + if (synced !== round.token) { + // (again: a page that reloaded meanwhile missed it) + hot.send({ + type: 'custom', + event: 'harness:sync', + data: { token: round.token }, + }) + } + return answered === true && !reloading && readyState === 'complete' + }, + quiet: async () => { + await server.idle() + return inFlight() === 0 + }, + describe: async () => + `the page did not take in the server's HMR messages: ${JSON.stringify(await state())}`, + }) + } finally { + hot.off('harness:synced', onSynced) + } } diff --git a/packages/compiler-test-utils/tests/integration/hmr-sync.test.ts b/packages/compiler-test-utils/tests/integration/hmr-sync.test.ts index a20201d39e..b8a4687a78 100644 --- a/packages/compiler-test-utils/tests/integration/hmr-sync.test.ts +++ b/packages/compiler-test-utils/tests/integration/hmr-sync.test.ts @@ -5,7 +5,10 @@ * (the page shows it at once, without waiting), and an update nothing * accepts has reloaded the page (its load count tells), whether the page's * code imports the sync module or the page imports it on every load - * (`hmrSyncInitScript`). + * (`hmrSyncInitScript`); and an update whose accept callback invalidates it + * (as a refresh runtime does when it cannot apply one) has had the reload + * that the page's `invalidate()` asked the server for, also when what the + * page sends reaches the server late. */ import path from 'node:path' import { fileURLToPath } from 'node:url' @@ -93,3 +96,58 @@ test.for([ }) }, ) + +test( + 'once settled, an update whose accept callback invalidates it has reloaded the page, also when the page reaches the server late', + { timeout }, + async () => { + const server = await createDevServer({ + dir: testsDir, + prefix: '.hmr-sync-', + registerCleanup: onTestFinished, + browser: true, + files: { + 'index.html': `
`, + 'hmr-sync.ts': hmrSyncModule, + // A module that accepts its own update, then gives up on it (Vite + // propagates the update to its importer, which accepts nothing: a + // full reload) + 'main.js': `import './hmr-sync.ts' +import { text } from './text.js' +document.getElementById('app').textContent = text +`, + 'text.js': `export const text = 'text v1' +import.meta.hot.accept(() => import.meta.hot.invalidate('cannot apply')) +`, + }, + }) + const page = await openPage('about:blank', { + registerCleanup: onTestFinished, + }) + // What the page sends over its HMR WebSocket reaches the server 400 ms + // late (a busy server or a slow link); what the server sends is not held + await page.page.context().routeWebSocket(/./, (ws) => { + const upstream = ws.connectToServer() + ws.onMessage((message) => { + setTimeout(() => upstream.send(message), 400) + }) + upstream.onMessage((message) => ws.send(message)) + }) + await page.page.goto(server.url!) + const inFlight = trackRequests(page) + await page.waitForText('text v1') + await settlePage(server, page, inFlight) + const loads = page.loads() + + await server.edit({ + 'text.js': `export const text = 'text v2' +import.meta.hot.accept(() => import.meta.hot.invalidate('cannot apply')) +`, + }) + await settlePage(server, page, inFlight) + expect({ + text: await page.text('#app'), + reloads: page.loads() - loads, + }).toEqual({ text: 'text v2', reloads: 1 }) + }, +)