diff --git a/packages/react/src/plugin-islands.ts b/packages/react/src/plugin-islands.ts index 1b924c0ad..074d37d82 100644 --- a/packages/react/src/plugin-islands.ts +++ b/packages/react/src/plugin-islands.ts @@ -64,6 +64,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server, pagesDir); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); diff --git a/packages/solid/src/plugin-islands.ts b/packages/solid/src/plugin-islands.ts index 2ad7597ab..ab1ce002c 100644 --- a/packages/solid/src/plugin-islands.ts +++ b/packages/solid/src/plugin-islands.ts @@ -85,6 +85,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server, pagesDir); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); diff --git a/packages/svelte/src/plugin-islands.ts b/packages/svelte/src/plugin-islands.ts index 4e31c054a..a65803b18 100644 --- a/packages/svelte/src/plugin-islands.ts +++ b/packages/svelte/src/plugin-islands.ts @@ -81,6 +81,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server, pagesDir); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); diff --git a/packages/void/src/pages/islands-plugin.ts b/packages/void/src/pages/islands-plugin.ts index 232737428..226a0034e 100644 --- a/packages/void/src/pages/islands-plugin.ts +++ b/packages/void/src/pages/islands-plugin.ts @@ -81,6 +81,13 @@ export type IslandManifest = { * build may load the islands client entry before their transforms run. */ registerPages(pageScan: PageScanResult, pagesDir: string): void; + /** + * Regenerate the dev islands client entry when an island is recorded, or an + * island file is added or deleted, so the next page load hydrates the + * current islands without a server restart. Markdown pages in `pagesDir` + * are recorded when they are saved. + */ + configureServer(server: ViteDevServer, pagesDir: string): void; }; /** `extensions` are tried, in order, for an island import without one. */ @@ -89,6 +96,7 @@ export function createIslandManifest( extensions: ReadonlyArray, ): IslandManifest { const entries = new Map(); + let server: ViteDevServer | null = null; type RegisteredIsland = { absPath: string | null; islandId: string }; @@ -98,10 +106,27 @@ export function createIslandManifest( return { absPath, islandId: specifier }; } const islandId = normalizePath(relative(root, absPath)).replace(/\.[^.]+$/, ''); + const isNew = entries.get(islandId)?.componentPath !== absPath; entries.set(islandId, { componentPath: absPath, islandId, hydrate }); + if (isNew && server) { + invalidateVirtualModule(server, ISLANDS_CLIENT_ENTRY_ID); + } return { absPath, islandId }; } + function registerFile(filePath: string): void { + let code: string; + try { + code = readFileSync(filePath, 'utf8'); + } catch { + // Deleted since the scan or watcher event. Its unlink event follows. + return; + } + for (const islandImport of findIslandImports(code, filePath)) { + register(islandImport.specifier, dirname(filePath), islandImport.hydrate); + } + } + return { entries, register, @@ -115,13 +140,37 @@ export function createIslandManifest( if (!entry.island) { continue; } - const filePath = resolve(pagesDir, entry.filePath); - const code = readFileSync(filePath, 'utf8'); - for (const islandImport of findIslandImports(code, filePath)) { - register(islandImport.specifier, dirname(filePath), islandImport.hydrate); - } + registerFile(resolve(pagesDir, entry.filePath)); } }, + configureServer(devServer, pagesDir) { + server = devServer; + const pagesPrefix = normalizePath(pagesDir) + '/'; + // The entry skips islands whose file is missing. Regenerate it when a + // recorded island file is deleted or comes back. + const onIslandFile = (path: string) => { + for (const entry of entries.values()) { + if (entry.componentPath === path) { + invalidateVirtualModule(devServer, ISLANDS_CLIENT_ENTRY_ID); + return; + } + } + }; + // Markdown pages emit their own island wrappers, so no page transform + // records their islands. Record them before the page reloads. + const onSave = (file: string) => { + const path = normalizePath(file); + if (path.startsWith(pagesPrefix) && path.endsWith('.md')) { + registerFile(path); + } + }; + devServer.watcher.on('add', (file: string) => { + onIslandFile(normalizePath(file)); + onSave(file); + }); + devServer.watcher.on('change', onSave); + devServer.watcher.on('unlink', (file: string) => onIslandFile(normalizePath(file))); + }, }; } @@ -388,6 +437,12 @@ export type IslandClientEntryOptions = { export function generateIslandClientEntry(options: IslandClientEntryOptions): string { const uniqueIslands = new Map(); for (const entry of options.manifest.entries.values()) { + // A dev edit can delete an island the manifest recorded. Importing its + // path would fail the whole entry and stop every other island hydrating. + // Keep the entry: the file may come back. + if (!existsSync(entry.componentPath)) { + continue; + } uniqueIslands.set(entry.islandId, entry.componentPath); } @@ -414,8 +469,7 @@ export function generateIslandClientEntry(options: IslandClientEntryOptions): st // Without islands, no built page gets this script (see // computePagesNeedingClientJS), so the entry only gives the styles a chunk to - // link. Dev keeps the runtime: it does not reload this module when a page - // gains an island. + // link. Dev keeps the runtime so a page that gains its first island hydrates. if (!options.needsRuntime && !options.isDev) { return lines.join('\n'); } @@ -516,10 +570,21 @@ export function computePagesNeedingClientJS( type PagesRescan = { flush: () => Promise }; +/** Make the dev server load a virtual module again on its next request. */ +function invalidateVirtualModule(server: ViteDevServer, id: string): void { + for (const env of Object.values(server.environments)) { + const mod = env.moduleGraph.getModuleById('\0' + id); + if (mod) { + env.moduleGraph.invalidateModule(mod); + } + } +} + /** * Watch the pages directory for structural changes (add/remove) and .md content * changes (frontmatter layout field) so that new layouts and named layouts are - * picked up without a dev server restart. + * picked up without a dev server restart. Any other page or layout edit + * regenerates the islands renderer, which reads their island imports. * * Returns a `flush()` function that resolves when any pending rescan completes * (useful for tests). @@ -552,12 +617,7 @@ export function watchPagesForRescan( .then( (pageScan) => { onRescan(pageScan); - for (const env of Object.values(server.environments)) { - const mod = env.moduleGraph.getModuleById('\0' + ISLANDS_RENDERER_ID); - if (mod) { - env.moduleGraph.invalidateModule(mod); - } - } + invalidateVirtualModule(server, ISLANDS_RENDERER_ID); }, () => { // The adapter pages plugin runs the same scan on the same events and @@ -573,8 +633,13 @@ export function watchPagesForRescan( server.watcher.on('add', scheduleRescan); server.watcher.on('unlink', scheduleRescan); server.watcher.on('change', (path) => { - if (normalizePath(path).endsWith('.md')) { + const normalizedPath = normalizePath(path); + if (normalizedPath.endsWith('.md')) { scheduleRescan(path); + } else if (normalizedPath.startsWith(normalizedPagesDir + '/')) { + // The renderer decides from the page and layout sources which pages + // need client JavaScript. An edit can add a page's first island. + invalidateVirtualModule(server, ISLANDS_RENDERER_ID); } }); diff --git a/packages/void/test/unit/pages-islands-rescan.test.ts b/packages/void/test/unit/pages-islands-rescan.test.ts index b50c5c02c..a81978ffc 100644 --- a/packages/void/test/unit/pages-islands-rescan.test.ts +++ b/packages/void/test/unit/pages-islands-rescan.test.ts @@ -4,7 +4,15 @@ import { join } from 'node:path'; import type { ViteDevServer } from 'vite'; import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'; import { packageFixturePath } from '../../../../test/fixture-dir.ts'; -import { hasIslandPages, watchPagesForRescan } from '../../src/pages/islands-plugin.ts'; +import { + createIslandManifest, + generateIslandClientEntry, + hasIslandPages, + ISLANDS_CLIENT_ENTRY_ID, + ISLANDS_RENDERER_ID, + watchPagesForRescan, +} from '../../src/pages/islands-plugin.ts'; +import { scanPages } from '../../src/pages/scan.ts'; import type { PageScanResult } from '../../src/pages/types.ts'; const TMP = packageFixturePath(import.meta.dirname, '__tmp_pages_islands_rescan__'); @@ -17,11 +25,24 @@ function writePage(relativePath: string, source: string): string { return full; } -function setup(onRescan: (scan: PageScanResult) => void) { +/** A dev server with file events and the virtual modules it has loaded. */ +function fakeServer() { const watcher = new EventEmitter(); - const server = { watcher, environments: {} } as unknown as ViteDevServer; + const invalidated: Array = []; + const moduleGraph = { + getModuleById: (id: string) => ({ id }), + invalidateModule: (mod: { id: string }) => invalidated.push(mod.id), + }; + const server = { watcher, environments: { client: { moduleGraph } } } as unknown as ViteDevServer; + return { server, watcher, invalidated }; +} + +function setup(onRescan: (scan: PageScanResult) => void) { + const { server, watcher, invalidated } = fakeServer(); const { flush } = watchPagesForRescan(server, PAGES_DIR, TMP, onRescan); return { + watcher, + invalidated, /** Emit a watcher event, run the debounce timer, and return the scan promise. */ emitAdd(path: string): Promise { watcher.emit('add', path); @@ -73,6 +94,95 @@ describe('watchPagesForRescan', () => { const scan = onRescan.mock.calls[0][0] as PageScanResult; expect(scan.pages.map((page) => page.componentPath)).toEqual(['x.dev.island.tsx']); }); + + it('regenerates the renderer when a page or layout changes', () => { + const page = writePage('index.island.tsx', 'export default () => null;'); + const { watcher, invalidated } = setup(vi.fn()); + + watcher.emit('change', join(TMP, 'components/Counter.tsx')); + expect(invalidated).toEqual([]); + + // The renderer reads the page sources to decide which pages need client JS. + watcher.emit('change', page); + expect(invalidated).toEqual(['\0' + ISLANDS_RENDERER_ID]); + }); +}); + +describe('createIslandManifest in dev', () => { + afterEach(() => { + rmSync(TMP, { recursive: true, force: true }); + }); + + function setupManifest() { + const counter = writePage('../components/Counter.tsx', 'export default () => null;'); + const { server, watcher, invalidated } = fakeServer(); + const manifest = createIslandManifest(TMP, ['.tsx']); + manifest.configureServer(server, PAGES_DIR); + const entry = () => + generateIslandClientEntry({ + manifest, + cssFiles: new Set(), + styles: null, + needsRuntime: true, + isDev: true, + hydrateIsland: '', + }); + return { manifest, watcher, invalidated, counter, entry }; + } + + it('regenerates the client entry only when an island is new', () => { + const { manifest, invalidated } = setupManifest(); + + manifest.register('../components/Counter', PAGES_DIR, 'load'); + expect(invalidated).toEqual(['\0' + ISLANDS_CLIENT_ENTRY_ID]); + + manifest.register('../components/Counter', PAGES_DIR, 'idle'); + expect(invalidated).toHaveLength(1); + }); + + it('skips a deleted island and brings it back with its file', () => { + const { manifest, watcher, invalidated, counter, entry } = setupManifest(); + manifest.register('../components/Counter', PAGES_DIR, 'load'); + invalidated.length = 0; + + watcher.emit('unlink', join(TMP, 'components/Other.tsx')); + expect(invalidated).toEqual([]); + + rmSync(counter); + watcher.emit('unlink', counter); + expect(invalidated).toEqual(['\0' + ISLANDS_CLIENT_ENTRY_ID]); + expect(entry()).not.toContain('components/Counter'); + + writeFileSync(counter, 'export default () => null;'); + watcher.emit('add', counter); + expect(invalidated).toHaveLength(2); + expect(entry()).toContain('components/Counter'); + }); + + it('records the islands of a Markdown page when it is saved', () => { + const { watcher, invalidated, entry } = setupManifest(); + const page = writePage('index.md', '# Home\n'); + watcher.emit('add', page); + expect(invalidated).toEqual([]); + + writePage( + 'index.md', + '\n\n\n', + ); + watcher.emit('change', page); + expect(invalidated).toEqual(['\0' + ISLANDS_CLIENT_ENTRY_ID]); + expect(entry()).toContain('components/Counter'); + }); + + it('skips a page deleted before its islands are read', async () => { + const { manifest, watcher } = setupManifest(); + const page = writePage('index.md', '# Home\n'); + const scan = await scanPages(TMP, { pagesDir: PAGES_DIR, environment: 'dev' }); + rmSync(page); + + expect(() => manifest.registerPages(scan, PAGES_DIR)).not.toThrow(); + expect(() => watcher.emit('change', page)).not.toThrow(); + }); }); describe('hasIslandPages', () => { diff --git a/packages/vue/src/plugin-islands.ts b/packages/vue/src/plugin-islands.ts index d210a9877..7a54d402d 100644 --- a/packages/vue/src/plugin-islands.ts +++ b/packages/vue/src/plugin-islands.ts @@ -72,6 +72,7 @@ export function islandsPlugin( }, configureServer(server) { + islandManifest.configureServer(server, pagesDir); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; }); diff --git a/packages/vue/test/integration/island-dev-client-entry.test.ts b/packages/vue/test/integration/island-dev-client-entry.test.ts new file mode 100644 index 000000000..4942fe1c2 --- /dev/null +++ b/packages/vue/test/integration/island-dev-client-entry.test.ts @@ -0,0 +1,133 @@ +import { mkdirSync, rmSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; +import vue from '@vitejs/plugin-vue'; +import { createServer } from 'vite'; +import type { ViteDevServer } from 'vite'; +import { afterEach, expect, it } from 'vite-plus/test'; +import { createPackageFixtureDir } from '../../../../test/fixture-dir.ts'; +import { islandsPlugin } from '../../src/plugin-islands.ts'; + +const COUNTER = ` + +`; + +function islandPage(names: ReadonlyArray): string { + const imports = names.map( + (name) => `import ${name} from "../components/${name}.vue" with { island: "load" };`, + ); + return `\n\n`; +} + +let root = ''; +let server: ViteDevServer | null = null; + +afterEach(async () => { + await server?.close(); + server = null; + rmSync(root, { recursive: true, force: true, maxRetries: 20, retryDelay: 50 }); +}); + +/** Writes `pages/index.island.vue` and the given components, then starts a dev server without file watching. */ +async function startServer(page: string, components: ReadonlyArray) { + root = createPackageFixtureDir(join(import.meta.dirname, '../..'), '__tmp_island_dev_'); + const pages = join(root, 'pages'); + mkdirSync(pages); + mkdirSync(join(root, 'components')); + for (const name of components) { + writeFileSync(join(root, `components/${name}.vue`), COUNTER); + } + writeFileSync(join(pages, 'index.island.vue'), page); + server = await createServer({ + root, + configFile: false, + cacheDir: join(root, '.vite'), + logLevel: 'silent', + optimizeDeps: { noDiscovery: true, include: [] }, + plugins: [vue(), ...islandsPlugin(pages)], + server: { ws: false, watch: null }, + }); + return { server, page: join(pages, 'index.island.vue') }; +} + +async function clientEntry(devServer: ViteDevServer): Promise { + return (await devServer.environments.client.transformRequest('virtual:void-islands-client'))! + .code; +} + +it('adds an island imported after the dev server loaded the islands client entry', async () => { + const { server, page } = await startServer(islandPage(['Counter']), ['Counter', 'Second']); + const before = await clientEntry(server); + expect(before).toContain('components/Counter'); + expect(before).not.toContain('components/Second'); + + writeFileSync(page, islandPage(['Counter', 'Second'])); + // Rendering the edited page records the new island. + await server.environments.ssr.transformRequest('/pages/index.island.vue'); + + expect(await clientEntry(server)).toContain('components/Second'); +}); + +it('adds an island imported by a Markdown page after the dev server started', async () => { + const { server, page } = await startServer(islandPage(['Counter']), ['Counter', 'Note']); + const md = join(page, '../about.md'); + writeFileSync(md, '# About\n'); + server.watcher.emit('add', md); + expect(await clientEntry(server)).not.toContain('components/Note'); + + writeFileSync( + md, + '\n\n# About\n\n\n', + ); + server.watcher.emit('change', md); + expect(await clientEntry(server)).toContain('components/Note'); +}); + +it('drops a deleted island from the client entry and restores it when the file comes back', async () => { + const { server } = await startServer(islandPage(['Counter', 'Removed']), ['Counter', 'Removed']); + await server.environments.ssr.transformRequest('/pages/index.island.vue'); + expect(await clientEntry(server)).toContain('components/Removed'); + + // A missing import would fail the whole entry, so other islands would not hydrate. + const removed = join(root, 'components/Removed.vue'); + rmSync(removed); + server.watcher.emit('unlink', removed); + const withoutFile = await clientEntry(server); + expect(withoutFile).toContain('components/Counter'); + expect(withoutFile).not.toContain('components/Removed'); + + writeFileSync(removed, COUNTER); + server.watcher.emit('add', removed); + expect(await clientEntry(server)).toContain('components/Removed'); +}); + +it('loads the islands client on a static island page that gains its first island', async () => { + const { server, page } = await startServer('\n', ['Counter']); + const render = async () => { + const renderer = (await server.ssrLoadModule('virtual:void-islands-renderer')) as { + renderIslandPage( + page: { component: string; props: Record }, + assetTags: { css: string; preloads: string; body: string }, + ): Promise; + }; + return renderer.renderIslandPage( + { component: 'index', props: {} }, + { css: '', preloads: '', body: '' }, + ); + }; + // `server.listen()` runs the pages scan, but also starts the dependency optimizer. + await server.environments.client.pluginContainer.buildStart({}); + expect(await render()).not.toContain('/islands.js'); + + writeFileSync(page, islandPage(['Counter'])); + // What the dev server's watcher reports when the page is saved. Vite's own + // listener invalidates the page asynchronously, so invalidate it here too. + server.watcher.emit('change', page); + server.environments.ssr.moduleGraph.onFileChange(page); + + const html = await render(); + expect(html).toContain('data-island="components/Counter"'); + expect(html).toContain('/islands.js'); +});