From d53e9e63927d3de52419a3bed7e8ad828fa48aa2 Mon Sep 17 00:00:00 2001 From: cpojer Date: Fri, 15 May 2026 12:59:42 +0900 Subject: [PATCH] fix: FOUC in dev. --- packages/react/src/plugin-islands.ts | 49 +- packages/solid/src/plugin-islands.ts | 50 +- packages/svelte/src/plugin-islands.ts | 50 +- packages/void/package.json | 2 +- packages/void/src/index.ts | 3 + packages/void/src/pages/dev-css-assets.ts | 536 ++++++++++++++++++ packages/void/src/pages/islands-plugin.ts | 102 ---- packages/void/src/pages/protocol.ts | 181 +++++- packages/void/src/pages/types.ts | 9 + packages/void/src/router/compile.ts | 113 +++- packages/void/test/unit/pages-compile.test.ts | 103 ++++ .../test/unit/pages-dev-css-assets.test.ts | 448 +++++++++++++++ .../void/test/unit/pages-protocol.test.ts | 177 ++++++ packages/vue/src/plugin-islands.ts | 69 +-- pnpm-lock.yaml | 6 +- 15 files changed, 1550 insertions(+), 348 deletions(-) create mode 100644 packages/void/src/pages/dev-css-assets.ts create mode 100644 packages/void/test/unit/pages-dev-css-assets.test.ts diff --git a/packages/react/src/plugin-islands.ts b/packages/react/src/plugin-islands.ts index 1b2cc45d8..4d1e9dc83 100644 --- a/packages/react/src/plugin-islands.ts +++ b/packages/react/src/plugin-islands.ts @@ -6,11 +6,8 @@ import type { PageScanResult } from 'void/pages'; import { resolveSpecifier, needsIslandClientBundle, - fileHasCssImports, extractCssImports, - rebuildIslandCssMap, computePagesNeedingClientJS, - configureIslandCssServer, watchPagesForRescan, rewriteCssImportForVirtualModule, ISLANDS_RENDERER_ID, @@ -34,17 +31,8 @@ export function islandsPlugin(pagesDir: string): Array { const islandManifest = new Map(); const islandCssFiles = new Set(); let viteRoot = ''; - const islandCssMap = new Map>(); let resolvedConfig: ResolvedConfig | null = null; - /** Rebuild islandCssMap from current file contents (re-runs fileHasCssImports). */ - function rebuildCssMapLocal(): void { - if (!pageScan) { - return; - } - rebuildIslandCssMap(pageScan, pagesDir, islandCssMap, fileHasCssImports); - } - function computePagesNeedingClientJSLocal(): Set { if (!pageScan) { return new Set(); @@ -62,14 +50,9 @@ export function islandsPlugin(pagesDir: string): Array { isDev = config.command === 'serve'; }, - // Serve virtual island CSS as raw text/css in dev. The client transform - // produces a JS module with `__vite__css = "..."` for HMR — we extract - // the CSS string and serve it directly for render-blocking tags. configureServer(server) { - configureIslandCssServer(server, islandCssFiles, viteRoot, rebuildCssMapLocal); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; - rebuildCssMapLocal(); }); }, @@ -131,9 +114,6 @@ export function islandsPlugin(pagesDir: string): Array { islandCssFiles.add(normalizePath(resolve(pagesDir, layout.filePath))); } } - - // Build CSS map for dev FOUC prevention (only files with CSS imports) - rebuildCssMapLocal(); } }, @@ -175,15 +155,7 @@ export function islandsPlugin(pagesDir: string): Array { mdPlugin?.api?.getClientScripts?.()?.keys() ?? [], ); const needsJS = computePagesNeedingClientJSLocal(); - return generateIslandRenderer( - pageScan, - pagesDir, - isDev, - islandCssMap, - viteRoot, - mdScriptIds, - needsJS, - ); + return generateIslandRenderer(pageScan, pagesDir, isDev, mdScriptIds, needsJS); } if (id === '\0' + ISLANDS_CLIENT_ENTRY_ID) { if (!pageScan) { @@ -301,8 +273,6 @@ function generateIslandRenderer( scan: PageScanResult, pagesDir: string, isDev: boolean, - islandCssMap: Map>, - viteRoot: string, mdScriptIds: Set, pagesNeedingClientJS: Set, ): string { @@ -317,16 +287,6 @@ function generateIslandRenderer( ` : ''; - // Build CSS link map for dev FOUC prevention - let cssMapCode = ''; - if (isDev && islandCssMap.size > 0) { - const cssMapObj: Record> = {}; - for (const [compId, paths] of islandCssMap) { - cssMapObj[compId] = paths.map((p) => '/' + normalizePath(relative(viteRoot, p)) + '.css'); - } - cssMapCode = `const __cssPaths = ${JSON.stringify(cssMapObj)};`; - } - const mdScriptIdsCode = `const __mdClientScriptIds = new Set(${JSON.stringify([...mdScriptIds])});`; const needsJSCode = `const __pagesNeedingClientJS = new Set(${JSON.stringify([...pagesNeedingClientJS])});`; @@ -337,7 +297,6 @@ import { SharedContext, ErrorsContext, ParamsContext } from "@void/react"; import { renderHeadToString, renderHtmlAttrs, renderBodyAttrs } from "void/pages-head"; ${generateComponentManifest(scan, pagesDir)} -${cssMapCode} ${mdScriptIdsCode} ${needsJSCode} @@ -382,7 +341,7 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${typeof __cssPaths !== "undefined" ? (__cssPaths[pageObj.component] || []).map(url => '').join("\\n") : ""}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""} +\${headHtml}\${PREAMBLE_SCRIPT}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}
\${html}
\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} @@ -407,8 +366,8 @@ function generateIslandClientEntry( lines.push('import { initIslands } from "void/pages-client";'); - // In dev, page/layout CSS is served via render-blocking tags - // injected in the SSR HTML. Skip CSS imports here to avoid duplicate injection. + // In dev, first-paint CSS is provided by Void's shared dev CSS collector. + // Skip CSS imports here to avoid duplicate client injection. // In production, the tags aren't used — the imports below ensure // the CSS is included in the bundled output. if (!isDev) { diff --git a/packages/solid/src/plugin-islands.ts b/packages/solid/src/plugin-islands.ts index 17c74dfbc..cc7e0b7d0 100644 --- a/packages/solid/src/plugin-islands.ts +++ b/packages/solid/src/plugin-islands.ts @@ -7,11 +7,8 @@ import { resolveSpecifier, needsIslandClientBundle, rewriteCssImportForVirtualModule, - fileHasCssImports, extractCssImports, - rebuildIslandCssMap as rebuildIslandCssMapShared, computePagesNeedingClientJS as computePagesNeedingClientJSShared, - configureIslandCssServer, watchPagesForRescan, ISLANDS_RENDERER_ID, ISLANDS_CLIENT_ENTRY_ID, @@ -51,17 +48,8 @@ export function islandsPlugin(pagesDir: string): Array { const wrapperMeta = new Map(); let wrapperId = 0; let viteRoot = ''; - const islandCssMap = new Map>(); let resolvedConfig: ResolvedConfig | null = null; - /** Rebuild islandCssMap from current file contents (re-runs fileHasCssImports). */ - function rebuildIslandCssMap(): void { - if (!pageScan) { - return; - } - rebuildIslandCssMapShared(pageScan, pagesDir, islandCssMap, fileHasCssImports); - } - function computePagesNeedingClientJS(): Set { if (!pageScan) { return new Set(); @@ -80,14 +68,9 @@ export function islandsPlugin(pagesDir: string): Array { isDev = config.command === 'serve'; }, - // Serve virtual island CSS as raw text/css in dev. The client transform - // produces a JS module with `__vite__css = "..."` for HMR — we extract - // the CSS string and serve it directly for render-blocking tags. configureServer(server) { - configureIslandCssServer(server, islandCssFiles, viteRoot, rebuildIslandCssMap); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; - rebuildIslandCssMap(); }); }, @@ -149,9 +132,6 @@ export function islandsPlugin(pagesDir: string): Array { islandCssFiles.add(normalizePath(resolve(pagesDir, layout.filePath))); } } - - // Build CSS map for dev FOUC prevention (only files with CSS imports) - rebuildIslandCssMap(); } }, @@ -202,15 +182,7 @@ export function islandsPlugin(pagesDir: string): Array { mdPlugin?.api?.getClientScripts?.()?.keys() ?? [], ); const needsJS = computePagesNeedingClientJS(); - return generateIslandRenderer( - pageScan, - pagesDir, - isDev, - islandCssMap, - viteRoot, - mdScriptIds, - needsJS, - ); + return generateIslandRenderer(pageScan, pagesDir, mdScriptIds, needsJS); } if (id === '\0' + ISLANDS_CLIENT_ENTRY_ID) { if (!pageScan) { @@ -330,22 +302,9 @@ export default function _IslandWrap(props) { function generateIslandRenderer( scan: PageScanResult, pagesDir: string, - isDev: boolean, - islandCssMap: Map>, - viteRoot: string, mdScriptIds: Set, pagesNeedingClientJS: Set, ): string { - // Build CSS link map for dev FOUC prevention - let cssMapCode = ''; - if (isDev && islandCssMap.size > 0) { - const cssMapObj: Record> = {}; - for (const [compId, paths] of islandCssMap) { - cssMapObj[compId] = paths.map((p) => '/' + normalizePath(relative(viteRoot, p)) + '.css'); - } - cssMapCode = `const __cssPaths = ${JSON.stringify(cssMapObj)};`; - } - const mdScriptIdsCode = `const __mdClientScriptIds = new Set(${JSON.stringify([...mdScriptIds])});`; const needsJSCode = `const __pagesNeedingClientJS = new Set(${JSON.stringify([...pagesNeedingClientJS])});`; @@ -356,7 +315,6 @@ import { SharedContext, ErrorsContext, ParamsContext } from "@void/solid"; import { renderHeadToString, renderHtmlAttrs, renderBodyAttrs } from "void/pages-head"; ${generateComponentManifest(scan, pagesDir)} -${cssMapCode} ${mdScriptIdsCode} ${needsJSCode} @@ -407,7 +365,7 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${typeof __cssPaths !== "undefined" ? (__cssPaths[pageObj.component] || []).map(url => '').join("\\n") : ""}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}\${__pagesNeedingClientJS.has(pageObj.component) ? generateHydrationScript() : ""} +\${headHtml}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}\${__pagesNeedingClientJS.has(pageObj.component) ? generateHydrationScript() : ""}
\${html}
\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} @@ -431,8 +389,8 @@ function generateIslandClientEntry( const lines: Array = []; lines.push('import { initIslands } from "void/pages-client";'); - // In dev, page/layout CSS is served via render-blocking tags - // injected in the SSR HTML. Skip CSS imports here to avoid duplicate injection. + // In dev, first-paint CSS is provided by Void's shared dev CSS collector. + // Skip CSS imports here to avoid duplicate client injection. // In production, the tags aren't used — the imports below ensure // the CSS is included in the bundled output. if (!isDev) { diff --git a/packages/svelte/src/plugin-islands.ts b/packages/svelte/src/plugin-islands.ts index 504dd25da..ee0b89215 100644 --- a/packages/svelte/src/plugin-islands.ts +++ b/packages/svelte/src/plugin-islands.ts @@ -7,11 +7,8 @@ import { resolveSpecifier, needsIslandClientBundle, rewriteCssImportForVirtualModule, - fileHasCssImports, extractCssImports, - rebuildIslandCssMap as rebuildIslandCssMapShared, computePagesNeedingClientJS as computePagesNeedingClientJSShared, - configureIslandCssServer, watchPagesForRescan, ISLANDS_RENDERER_ID, ISLANDS_CLIENT_ENTRY_ID, @@ -41,17 +38,8 @@ export function islandsPlugin(pagesDir: string): Array { const islandCssFiles = new Set(); let isDev = false; let viteRoot = ''; - const islandCssMap = new Map>(); let resolvedConfig: ResolvedConfig | null = null; - /** Rebuild islandCssMap from current file contents (re-runs fileHasCssImports). */ - function rebuildIslandCssMap(): void { - if (!pageScan) { - return; - } - rebuildIslandCssMapShared(pageScan, pagesDir, islandCssMap, fileHasCssImports); - } - function computePagesNeedingClientJS(): Set { if (!pageScan) { return new Set(); @@ -70,14 +58,9 @@ export function islandsPlugin(pagesDir: string): Array { isDev = config.command === 'serve'; }, - // Serve virtual island CSS as raw text/css in dev. The client transform - // produces a JS module with `__vite__css = "..."` for HMR — we extract - // the CSS string and serve it directly for render-blocking tags. configureServer(server) { - configureIslandCssServer(server, islandCssFiles, viteRoot, rebuildIslandCssMap); watchPagesForRescan(server, pagesDir, root, (scan: PageScanResult) => { pageScan = scan; - rebuildIslandCssMap(); }); }, @@ -139,9 +122,6 @@ export function islandsPlugin(pagesDir: string): Array { islandCssFiles.add(normalizePath(resolve(pagesDir, layout.filePath))); } } - - // Build CSS map for dev FOUC prevention (only files with CSS imports) - rebuildIslandCssMap(); } }, @@ -192,15 +172,7 @@ export function islandsPlugin(pagesDir: string): Array { mdPlugin?.api?.getClientScripts?.()?.keys() ?? [], ); const needsJS = computePagesNeedingClientJS(); - return generateIslandRenderer( - pageScan, - pagesDir, - isDev, - islandCssMap, - viteRoot, - mdScriptIds, - needsJS, - ); + return generateIslandRenderer(pageScan, pagesDir, mdScriptIds, needsJS); } if (id === '\0' + ISLANDS_CLIENT_ENTRY_ID) { if (!pageScan) { @@ -365,22 +337,9 @@ function generateWrapperComponent(id: string): string { function generateIslandRenderer( scan: PageScanResult, pagesDir: string, - isDev: boolean, - islandCssMap: Map>, - viteRoot: string, mdScriptIds: Set, pagesNeedingClientJS: Set, ): string { - // Build CSS link map for dev FOUC prevention - let cssMapCode = ''; - if (isDev && islandCssMap.size > 0) { - const cssMapObj: Record> = {}; - for (const [compId, paths] of islandCssMap) { - cssMapObj[compId] = paths.map((p) => '/' + normalizePath(relative(viteRoot, p)) + '.css'); - } - cssMapCode = `const __cssPaths = ${JSON.stringify(cssMapObj)};`; - } - const mdScriptIdsCode = `const __mdClientScriptIds = new Set(${JSON.stringify([...mdScriptIds])});`; const needsJSCode = `const __pagesNeedingClientJS = new Set(${JSON.stringify([...pagesNeedingClientJS])});`; @@ -390,7 +349,6 @@ import App from "@void/svelte/App.svelte"; import { renderHeadToString, renderHtmlAttrs, renderBodyAttrs } from "void/pages-head"; ${generateComponentManifest(scan, pagesDir)} -${cssMapCode} ${mdScriptIdsCode} ${needsJSCode} @@ -425,7 +383,7 @@ export async function renderIslandPage(pageObj, assetTags) { return \` -\${headHtml}\${typeof __cssPaths !== "undefined" ? (__cssPaths[pageObj.component] || []).map(url => '').join("\\n") : ""}\${head}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""} +\${headHtml}\${head}\${assetTags.css}\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.preloads : ""}
\${html}
\${__pagesNeedingClientJS.has(pageObj.component) ? assetTags.body : ""} @@ -450,8 +408,8 @@ function generateIslandClientEntry( lines.push('import { initIslands } from "void/pages-client";'); - // In dev, page/layout CSS is served via render-blocking tags - // injected in the SSR HTML. Skip CSS imports here to avoid duplicate injection. + // In dev, first-paint CSS is provided by Void's shared dev CSS collector. + // Skip CSS imports here to avoid duplicate client injection. // In production, the tags aren't used — the imports below ensure // the CSS is included in the bundled output. if (!isDev) { diff --git a/packages/void/package.json b/packages/void/package.json index 97c1943bb..ab054e014 100644 --- a/packages/void/package.json +++ b/packages/void/package.json @@ -305,6 +305,7 @@ "drizzle-orm": "^0.45.2", "drizzle-valibot": "^0.4.2", "drizzle-zod": "^0.8.3", + "es-module-lexer": "^2.1.0", "hono": "^4.12.18", "ignore": "^7.0.5", "jsonc-parser": "3.3.1", @@ -319,7 +320,6 @@ "@types/pg": "^8.20.0", "@typescript/native-preview": "catalog:", "arktype": "^2.2.0", - "es-module-lexer": "^2.1.0", "estree-walker": "^3.0.3", "magic-string": "^0.30.21", "ofetch": "2.0.0-alpha.3", diff --git a/packages/void/src/index.ts b/packages/void/src/index.ts index 02df920a1..accb68dda 100644 --- a/packages/void/src/index.ts +++ b/packages/void/src/index.ts @@ -32,6 +32,7 @@ import { readConfig, resolveBindingNames, isNodeTarget, getDatabaseDialect } fro import { scanJobsSync } from './crons/scan.ts'; import { inferBindingsFromSource } from './inference/walk.ts'; import { voidLog, voidWarn, voidError } from './log.ts'; +import { pagesDevCssAssetsPlugin } from './pages/dev-css-assets.ts'; import { devTriggersHintPlugin } from './plugin-dev-triggers-hint.ts'; import { drizzlePlugin } from './plugin-drizzle.ts'; import { envClientFoldPlugin } from './plugin-env-client-fold.ts'; @@ -1407,6 +1408,7 @@ export function voidPlugin(options?: { restartPlugin(), envPlugin, envSchemaPlugin(root), + ...pagesDevCssAssetsPlugin(root, devTriggerToken), routingPlugin(root, { isAuthEnabled: () => false, devTriggerToken, @@ -1478,6 +1480,7 @@ export function voidPlugin(options?: { envClientFoldPlugin(), clientStubsPlugin, ...(bindings.needsSandbox ? [createSandboxSdkResolvePlugin()] : []), + ...pagesDevCssAssetsPlugin(root, devTriggerToken), routingPlugin(root, { isAuthEnabled: () => authEnabled, devTriggerToken, diff --git a/packages/void/src/pages/dev-css-assets.ts b/packages/void/src/pages/dev-css-assets.ts new file mode 100644 index 000000000..a56fa14a6 --- /dev/null +++ b/packages/void/src/pages/dev-css-assets.ts @@ -0,0 +1,536 @@ +import { init, parse } from 'es-module-lexer'; +import { normalizePath, type EnvironmentModuleNode, type Plugin, type ViteDevServer } from 'vite'; +import type { DevCssAsset } from './types.ts'; + +export const DEV_CSS_ASSET_MODULE_ID = 'virtual:void-pages-dev-assets'; +export const DEV_CSS_ASSET_ENDPOINT = '/__void/dev/pages-css'; +export const DEV_CSS_ASSET_GUARD_HEADER = 'X-Void-Dev-Asset-Request'; +export const DEV_CSS_ASSET_GUARD_VALUE = 'pages-css'; + +export type DevCssRootPhases = Array>; + +interface DevCssRequestBody { + componentId?: string; + kind?: 'pages' | 'islands'; + rootPhases?: DevCssRootPhases; +} + +interface OrderedEdgeStore { + version: number; + set(importer: string, edges: Array): void; + deleteForId(id: string): void; + getForNode(node: EnvironmentModuleNode): Array | undefined; +} + +const CSS_REQUEST_RE = /\.(?:css|scss|sass|less|styl|stylus|pcss|postcss)(?:$|[?#])/; +const STYLE_QUERY_RE = /[?&](?:vue|svelte|island-style)\b.*[?&]type=style\b|[?&]type=style\b/; +const CSS_BYPASS_RE = /[?&](?:raw|url|worker|sharedworker)\b/; +const INLINE_CSS_EXPORT_RE = + /(?:export\s+default|__vite__css\s*=)\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|`(?:[^`\\]|\\.)*`)/; +const VITE_DEV_ID_RE = /const\s+__vite__id\s*=\s*("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*')/; +const SKIPPABLE_VIRTUAL_URL_RE = + /^(?:\/@id\/__x00__)?virtual:void-client-(?:browser|worker)(?:$|[?#])/; + +function splitQueryHash(value: string): { pathname: string; suffix: string } { + const index = value.search(/[?#]/); + if (index === -1) { + return { pathname: value, suffix: '' }; + } + return { pathname: value.slice(0, index), suffix: value.slice(index) }; +} + +export function normalizeDevCssUrl(id: string, root: string): string { + const normalized = normalizePath(id); + if (normalized.startsWith('/@id/')) { + return normalized; + } + if (normalized.startsWith('\0')) { + return '/@id/__x00__' + normalized.slice(1); + } + if (normalized.startsWith('virtual:')) { + return '/@id/__x00__' + normalized; + } + const { pathname, suffix } = splitQueryHash(normalized); + const normalizedRoot = normalizePath(root); + if (pathname === normalizedRoot || pathname.startsWith(normalizedRoot + '/')) { + return '/' + normalizePath(pathname.slice(normalizedRoot.length + 1)) + suffix; + } + if ( + pathname.startsWith('/@fs/') || + pathname.startsWith('/@vite/') || + pathname === '/@vite/client' || + pathname.startsWith('/@react-refresh') || + pathname.startsWith('/node_modules/.vite/') + ) { + return normalized; + } + if (pathname.startsWith('/')) { + const rootFirstSegment = normalizedRoot.split('/').filter(Boolean)[0]; + if (rootFirstSegment && !pathname.startsWith(`/${rootFirstSegment}/`)) { + return normalized; + } + return '/@fs' + pathname + suffix; + } + return normalized; +} + +function normalizeRequestUrl(url: string): string { + return normalizePath(url).replace(/^\/@id\/__x00__/, '\0'); +} + +function toTransformRequestUrl(url: string): string { + return normalizeRequestUrl(url); +} + +function isCssRequest(url: string): boolean { + return !CSS_BYPASS_RE.test(url) && (CSS_REQUEST_RE.test(url) || STYLE_QUERY_RE.test(url)); +} + +function isOptimizedDepUrl(url: string): boolean { + return normalizePath(url).startsWith('/node_modules/.vite/deps/'); +} + +function isSkippableVirtualUrl(url: string): boolean { + const normalized = normalizePath(url); + return ( + SKIPPABLE_VIRTUAL_URL_RE.test(normalized) || + (normalized.charCodeAt(0) === 0 && + /^virtual:void-client-(?:browser|worker)(?:$|[?#])/.test(normalized.slice(1))) + ); +} + +export function appendInlineQuery(url: string): string { + const parsed = new URL(url, 'http://void.local'); + if (!parsed.searchParams.has('inline')) { + parsed.searchParams.append('inline', ''); + } + return parsed.pathname + parsed.search + parsed.hash; +} + +export function extractInlineCss(code: string): string { + const match = code.match(INLINE_CSS_EXPORT_RE); + if (!match) { + throw new Error('Unable to extract inline CSS from Vite transform output.'); + } + const raw = match[1]; + if (raw.startsWith('`')) { + throw new Error('Unexpected template literal inline CSS output.'); + } + return JSON.parse(raw); +} + +export function extractViteDevId(code: string): string | undefined { + const match = code.match(VITE_DEV_ID_RE); + if (!match) { + return; + } + return JSON.parse(match[1]); +} + +function createOrderedEdgeStore(root: string): OrderedEdgeStore { + let version = 0; + const byKey = new Map>(); + + const aliasesForId = (id: string): Array => { + const normalized = normalizePath(id); + const aliases = new Set([normalized, normalizeDevCssUrl(normalized, root)]); + if (normalized.startsWith('/@id/__x00__')) { + aliases.add(normalized.replace('/@id/__x00__', '\0')); + } + return [...aliases]; + }; + + return { + get version() { + return version; + }, + set(importer, edges) { + version++; + for (const key of aliasesForId(importer)) { + byKey.set(key, edges); + } + }, + deleteForId(id) { + let deleted = false; + for (const key of aliasesForId(id)) { + deleted = byKey.delete(key) || deleted; + } + if (deleted) { + version++; + } + }, + getForNode(node) { + const keys = [node.url, node.id].filter( + (value): value is string => typeof value === 'string', + ); + for (const key of keys) { + const direct = byKey.get(normalizePath(key)); + if (direct) { + return direct; + } + const url = normalizeDevCssUrl(key, root); + const byUrl = byKey.get(url) ?? byKey.get(normalizeRequestUrl(url)); + if (byUrl) { + return byUrl; + } + } + + const staticUrls = (node as EnvironmentModuleNode & { staticImportedUrls?: Set }) + .staticImportedUrls; + return staticUrls ? [...staticUrls] : undefined; + }, + }; +} + +class DevCssProvider { + private cache = new Map>(); + private graphVersion = 0; + + constructor( + private server: ViteDevServer, + private root: string, + private edgeStore: OrderedEdgeStore, + ) {} + + invalidate(): void { + this.graphVersion++; + this.cache.clear(); + } + + async collect(rootPhases: DevCssRootPhases): Promise> { + const normalizedPhases = rootPhases.map((phase) => + phase.map((root) => normalizeDevCssUrl(root, this.root)), + ); + const cacheKey = JSON.stringify({ + roots: normalizedPhases, + graphVersion: this.graphVersion, + edgeVersion: this.edgeStore.version, + }); + const cached = this.cache.get(cacheKey); + if (cached) { + return cached; + } + + const environment = this.server.environments.client; + const graph = environment.moduleGraph; + const seen = new Set(); + const seenCssUrls = new Set(); + const cssUrls: Array = []; + const cssViteDevIds = new Map(); + + const addByUrl = async (rawUrl: string): Promise => { + const url = normalizeDevCssUrl(rawUrl, this.root); + if (isOptimizedDepUrl(url)) { + return; + } + const requestUrl = toTransformRequestUrl(url); + let result: { code: string } | null | undefined; + try { + result = await environment.transformRequest(requestUrl); + } catch (error) { + if (!isSkippableVirtualUrl(url)) { + this.server.config.logger.warnOnce( + `[void] Skipping dev CSS traversal for ${url}: ${error instanceof Error ? error.message : String(error)}`, + ); + } + return; + } + const node = + (await graph.getModuleByUrl(url)) ?? + (requestUrl !== url ? await graph.getModuleByUrl(requestUrl) : undefined); + if (node) { + await visit(node, result?.code); + } + }; + + const visit = async (node: EnvironmentModuleNode, transformedCode?: string): Promise => { + if (seen.has(node)) { + return; + } + seen.add(node); + + if (isCssRequest(node.url)) { + if (!seenCssUrls.has(node.url)) { + seenCssUrls.add(node.url); + cssUrls.push(node.url); + } + const viteDevId = transformedCode ? extractViteDevId(transformedCode) : undefined; + cssViteDevIds.set(node.url, viteDevId ?? node.id ?? node.url); + return; + } + + if (isOptimizedDepUrl(node.url)) { + return; + } + + const staticUrls = this.edgeStore.getForNode(node); + if (!staticUrls) { + this.server.config.logger.warnOnce( + `[void] Missing ordered static import metadata for ${node.url}; skipping broad dev CSS traversal.`, + ); + return; + } + + for (const dep of staticUrls) { + await addByUrl(dep); + } + }; + + for (const roots of normalizedPhases) { + for (const root of roots) { + await addByUrl(root); + } + } + + const assets: Array = []; + for (const url of cssUrls) { + const inlineUrl = appendInlineQuery(url); + const result = await environment.transformRequest(inlineUrl); + if (!result) { + continue; + } + assets.push({ url, id: cssViteDevIds.get(url) ?? url, css: extractInlineCss(result.code) }); + } + + this.cache.set(cacheKey, assets); + if (this.cache.size > 100) { + const oldest = this.cache.keys().next().value as string | undefined; + if (oldest) { + this.cache.delete(oldest); + } + } + return assets; + } +} + +async function readJsonBody(req: import('node:http').IncomingMessage): Promise { + const chunks: Array = []; + for await (const chunk of req) { + chunks.push(Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk)); + } + if (chunks.length === 0) { + return {}; + } + return JSON.parse(Buffer.concat(chunks).toString('utf-8')); +} + +function getInternalDevOrigin(server: ViteDevServer): string { + const address = server.httpServer?.address(); + if (address && typeof address === 'object') { + const protocol = server.config.server.https ? 'https' : 'http'; + const rawHost = + address.address === '::' || address.address === '0.0.0.0' ? '127.0.0.1' : address.address; + const host = rawHost.includes(':') ? `[${rawHost}]` : rawHost; + return `${protocol}://${host}:${address.port}`; + } + + const localUrl = server.resolvedUrls?.local[0]; + if (localUrl) { + return new URL(localUrl).origin; + } + + const protocol = server.config.server.https ? 'https' : 'http'; + return `${protocol}://127.0.0.1:${server.config.server.port ?? 5173}`; +} + +export function pagesDevCssAssetsPlugin(root: string, token: string): Array { + const edgeStore = createOrderedEdgeStore(root); + let provider: DevCssProvider | null = null; + let viteServer: ViteDevServer | null = null; + + return [ + { + name: 'void:pages-dev-css-assets', + apply: 'serve', + + resolveId(id) { + if (id !== DEV_CSS_ASSET_MODULE_ID) { + return; + } + if (this.environment?.name === 'client') { + throw new Error( + `${DEV_CSS_ASSET_MODULE_ID} is server-only and cannot be imported by client code.`, + ); + } + return '\0' + DEV_CSS_ASSET_MODULE_ID; + }, + + load(id) { + if (id !== '\0' + DEV_CSS_ASSET_MODULE_ID) { + return; + } + if (this.environment?.name === 'client') { + throw new Error( + `${DEV_CSS_ASSET_MODULE_ID} is server-only and cannot be loaded by client code.`, + ); + } + const internalOrigin = viteServer + ? getInternalDevOrigin(viteServer) + : 'http://127.0.0.1:5173'; + return ` +const TOKEN = ${JSON.stringify(token)}; +const INTERNAL_ORIGIN = ${JSON.stringify(internalOrigin)}; +const ENDPOINT = ${JSON.stringify(DEV_CSS_ASSET_ENDPOINT)}; +const GUARD_HEADER = ${JSON.stringify(DEV_CSS_ASSET_GUARD_HEADER)}; +const GUARD_VALUE = ${JSON.stringify(DEV_CSS_ASSET_GUARD_VALUE)}; + +function createDevCssRequest(url, payload, signal) { + return new Request(url, { + method: "POST", + headers: { + "Authorization": "Bearer " + TOKEN, + "Content-Type": "application/json", + [GUARD_HEADER]: GUARD_VALUE, + }, + body: JSON.stringify(payload), + signal, + }); +} + +async function readDevCssResponse(response) { + if (!response.ok) { + throw new Error("HTTP " + response.status); + } + const body = await response.json(); + return Array.isArray(body.assets) ? body.assets : []; +} + +export async function getVoidPagesDevCss(request, env, payload) { + const controller = new AbortController(); + const timeout = setTimeout(() => controller.abort(), 1500); + const attempts = []; + if (env?.ASSETS && typeof env.ASSETS.fetch === "function") { + attempts.push({ + fetcher: env.ASSETS, + label: "ASSETS", + url: new URL(ENDPOINT, request.url).toString(), + }); + } else { + attempts.push({ + fetcher: "global", + label: INTERNAL_ORIGIN, + url: new URL(ENDPOINT, INTERNAL_ORIGIN).toString(), + }); + } + try { + let lastError; + let lastLabel = "unknown"; + for (const attempt of attempts) { + try { + const request = createDevCssRequest(attempt.url, payload, controller.signal); + const response = + attempt.fetcher === "global" + ? await fetch(request) + : await attempt.fetcher.fetch(request); + return await readDevCssResponse(response); + } catch (error) { + lastError = error; + lastLabel = attempt.label; + } + } + throw new Error( + lastLabel + ": " + (lastError instanceof Error ? lastError.message : String(lastError)), + ); + } catch (error) { + console.warn("[void] dev CSS collection failed:", error instanceof Error ? error.message : String(error)); + return []; + } finally { + clearTimeout(timeout); + } +} +`; + }, + + configureServer(server) { + viteServer = server; + provider = new DevCssProvider(server, root, edgeStore); + const invalidate = () => provider?.invalidate(); + server.watcher.on('add', invalidate); + server.watcher.on('change', invalidate); + server.watcher.on('unlink', invalidate); + + server.middlewares.use(async (req, res, next) => { + if (!req.url) { + return next(); + } + const url = new URL(req.url, 'http://void.local'); + if ( + url.pathname === '/@id/' + DEV_CSS_ASSET_MODULE_ID || + url.pathname === '/@id/__x00__' + DEV_CSS_ASSET_MODULE_ID + ) { + res.statusCode = 404; + res.end('Not Found'); + return; + } + if (url.pathname !== DEV_CSS_ASSET_ENDPOINT) { + return next(); + } + if (req.method !== 'POST') { + res.statusCode = 405; + res.end('Method Not Allowed'); + return; + } + if (req.headers[DEV_CSS_ASSET_GUARD_HEADER.toLowerCase()] !== DEV_CSS_ASSET_GUARD_VALUE) { + res.statusCode = 403; + res.end('Forbidden'); + return; + } + const auth = req.headers.authorization; + if (auth !== `Bearer ${token}`) { + res.statusCode = 401; + res.end('Unauthorized'); + return; + } + try { + const body = (await readJsonBody(req)) as DevCssRequestBody; + const rootPhases = Array.isArray(body.rootPhases) ? body.rootPhases : []; + const assets = await provider!.collect(rootPhases); + res.statusCode = 200; + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ assets })); + } catch (error) { + server.config.logger.warn( + `[void] dev CSS collection failed: ${error instanceof Error ? error.message : String(error)}`, + ); + res.statusCode = 200; + res.setHeader('Content-Type', 'application/json'); + res.end(JSON.stringify({ assets: [] })); + } + }); + }, + }, + { + name: 'void:pages-dev-css-static-edges', + apply: 'serve', + enforce: 'post', + + async transform(code, id) { + if (this.environment?.name !== 'client') { + return; + } + if (id.includes('/node_modules/.vite/')) { + return; + } + await init; + let imports: ReturnType[0]; + try { + [imports] = parse(code); + } catch { + return; + } + const edges: Array = []; + for (const item of imports) { + if (item.d !== -1 || !item.n) { + continue; + } + const resolved = await this.resolve(item.n, id, { skipSelf: true }); + if (resolved?.id) { + edges.push(normalizeDevCssUrl(resolved.id, root)); + } + } + edgeStore.set(id, edges); + return; + }, + }, + ]; +} diff --git a/packages/void/src/pages/islands-plugin.ts b/packages/void/src/pages/islands-plugin.ts index ace19e4ae..72c6eaf68 100644 --- a/packages/void/src/pages/islands-plugin.ts +++ b/packages/void/src/pages/islands-plugin.ts @@ -86,18 +86,6 @@ export function needsIslandClientBundle( return false; } -/** Check if a file has CSS import statements (JS-style imports). */ -export function fileHasCssImports(filePath: string): boolean { - try { - const code = readFileSync(filePath, 'utf-8'); - return /import\b[^"']*["'][^"']+\.(?:css|scss|sass|less|styl|stylus|pcss|postcss)["']/.test( - code, - ); - } catch { - return false; - } -} - /** * Rewrite a matched CSS import line so relative specifiers resolve from the * virtual module. Absolute and bare specifiers are kept as-is. @@ -127,36 +115,6 @@ export function extractCssImports(filePath: string): string { return imports.join('\n'); } -/** Rebuild islandCssMap from current file contents. */ -export function rebuildIslandCssMap( - pageScan: PageScanResult, - pagesDir: string, - islandCssMap: Map>, - fileHasCssFn: (filePath: string) => boolean, -): void { - islandCssMap.clear(); - for (const page of pageScan.pages) { - if (!page.island) { - continue; - } - const cssPaths: Array = []; - const layoutChain = resolveEffectiveLayoutChain(page, pageScan.layouts, pageScan.namedLayouts); - for (const layout of layoutChain) { - const layoutPath = resolve(pagesDir, layout.filePath); - if (fileHasCssFn(layoutPath)) { - cssPaths.push(layoutPath); - } - } - const pagePath = resolve(pagesDir, page.componentPath); - if (fileHasCssFn(pagePath)) { - cssPaths.push(pagePath); - } - if (cssPaths.length > 0) { - islandCssMap.set(page.componentId, cssPaths); - } - } -} - /** Compute which island pages need client-side JavaScript. */ export function computePagesNeedingClientJS( pageScan: PageScanResult, @@ -215,66 +173,6 @@ export function computePagesNeedingClientJS( return result; } -/** - * Configure the Vite dev server for island CSS serving. - * Sets up file watching and a middleware for serving virtual CSS modules. - */ -export function configureIslandCssServer( - server: ViteDevServer, - islandCssFiles: Set, - viteRoot: string, - rebuildCssMap: () => void, -): void { - server.watcher.on('change', (path) => { - const normalizedPath = normalizePath(path); - if (!islandCssFiles.has(normalizedPath)) { - return; - } - rebuildCssMap(); - for (const env of Object.values(server.environments)) { - const mod = env.moduleGraph.getModuleById('\0' + ISLANDS_RENDERER_ID); - if (mod) { - env.moduleGraph.invalidateModule(mod); - } - } - const cssMod = server.environments.client?.moduleGraph.getModuleById(normalizedPath + '.css'); - if (cssMod) { - server.environments.client.moduleGraph.invalidateModule(cssMod); - } - }); - - server.middlewares.use(async (req, res, next) => { - if (!req.url) { - return next(); - } - const url = req.url.split('?')[0]; - if (!url.endsWith('.css')) { - return next(); - } - const srcPath = normalizePath(resolve(viteRoot, url.slice(1, -4))); - if (!islandCssFiles.has(srcPath)) { - return next(); - } - try { - const result = await server.environments.client.transformRequest(url); - if (result) { - const m = - result.code.match(/\b__vite__css\s*=\s*("(?:[^"\\]|\\.)*")/) || - result.code.match(/export\s+default\s+("(?:[^"\\]|\\.)*")/); - if (m) { - res.setHeader('Content-Type', 'text/css'); - res.statusCode = 200; - res.end(JSON.parse(m[1])); - return; - } - } - } catch { - // fall through - } - next(); - }); -} - /** * Watch the pages directory for structural changes (add/remove) and .md content * changes (frontmatter layout field) so that new layouts and named layouts are diff --git a/packages/void/src/pages/protocol.ts b/packages/void/src/pages/protocol.ts index 0ee7f0a3a..51300d31f 100644 --- a/packages/void/src/pages/protocol.ts +++ b/packages/void/src/pages/protocol.ts @@ -2,11 +2,13 @@ import type { CloudBindings, CloudContext } from '../runtime/handler.ts'; import { isConvertedResponse } from '../runtime/response.ts'; import { DEFERRED, separateDeferred, type ResolvedDeferredGroup } from './defer.ts'; import { resolveHead, type HeadDescriptor, type HeadConfig } from './head.ts'; +import type { DevCssAsset } from './types.ts'; import { ValidationError } from './validation-error.ts'; export { ValidationError }; const POWERED_BY = { 'X-Powered-By': 'Void' } as const; +const RENDER_ERROR_ASSET_TAGS_KEY = '__voidPageAssetTags'; /** Escape characters that are unsafe inside inline `, (group, error) => `\n`, + assetTags, ); } @@ -377,8 +513,13 @@ export async function handlePageMutation( if (isPagesRequest(c)) { return pageJsonResponse(c, pageObj); } - const assetTags = await getAssetTags(c.req.raw, c.env, componentId); - return renderedResponse(c, await renderFn(pageObj, assetTags), 'text/html; charset=utf-8'); + const assetTags = prepareAssetTags(await getAssetTags(c.req.raw, c.env, componentId)); + return renderedResponse( + c, + await renderWithAssetTags(renderFn, pageObj, assetTags), + 'text/html; charset=utf-8', + assetTags, + ); } throw e; } @@ -403,8 +544,13 @@ export async function handlePageMutation( if (isPagesRequest(c)) { return pageJsonResponse(c, pageObj); } - const assetTags = await getAssetTags(c.req.raw, c.env, componentId); - return renderedResponse(c, await renderFn(pageObj, assetTags), 'text/html; charset=utf-8'); + const assetTags = prepareAssetTags(await getAssetTags(c.req.raw, c.env, componentId)); + return renderedResponse( + c, + await renderWithAssetTags(renderFn, pageObj, assetTags), + 'text/html; charset=utf-8', + assetTags, + ); } // 204 (void from withValidator) — fall through to re-run GET if (status !== 204) { @@ -422,6 +568,11 @@ export async function handlePageMutation( if (isPagesRequest(c)) { return pageJsonResponse(c, pageObj); } - const assetTags = await getAssetTags(c.req.raw, c.env, componentId); - return renderedResponse(c, await renderFn(pageObj, assetTags), 'text/html; charset=utf-8'); + const assetTags = prepareAssetTags(await getAssetTags(c.req.raw, c.env, componentId)); + return renderedResponse( + c, + await renderWithAssetTags(renderFn, pageObj, assetTags), + 'text/html; charset=utf-8', + assetTags, + ); } diff --git a/packages/void/src/pages/types.ts b/packages/void/src/pages/types.ts index 6141f0ac5..26e5a5ccc 100644 --- a/packages/void/src/pages/types.ts +++ b/packages/void/src/pages/types.ts @@ -52,3 +52,12 @@ export interface PageScanResult { layouts: Array; namedLayouts: Array; } + +export interface DevCssAsset { + /** Vite client URL used to request the CSS module. */ + url: string; + /** Vite dev style id used by the client to adopt/update SSR-inlined styles. */ + id?: string; + /** CSS bytes returned by Vite's client environment transform with ?inline. */ + css: string; +} diff --git a/packages/void/src/router/compile.ts b/packages/void/src/router/compile.ts index baf057ea9..8c84767de 100644 --- a/packages/void/src/router/compile.ts +++ b/packages/void/src/router/compile.ts @@ -521,6 +521,20 @@ function pushDefaultErrorPageHelpers(lines: Array, options: CompileOptio ); lines.push(`}`); lines.push(''); + lines.push(`function __voidGetErrorAssetCss(error) {`); + lines.push( + ` const tags = error && (typeof error === "object" || typeof error === "function") ? error.__voidPageAssetTags : null;`, + ); + lines.push(` return tags && typeof tags.css === "string" ? tags.css : "";`); + lines.push(`}`); + lines.push(''); + lines.push(`function __voidInjectErrorAssetCss(html, css) {`); + lines.push(` if (!css) return html;`); + lines.push( + ` return /<\\/head\\s*>/i.test(html) ? html.replace(/<\\/head\\s*>/i, css + "") : css + html;`, + ); + lines.push(`}`); + lines.push(''); lines.push(`function __voidRenderErrorPage(request, status, title, error) {`); lines.push(` const heading = status + ": " + title;`); lines.push(` const prefix = status + ": ";`); @@ -533,6 +547,7 @@ function pushDefaultErrorPageHelpers(lines: Array, options: CompileOptio lines.push(` `); lines.push(` `); lines.push(` \${__voidEscapeHtml(heading)}`); + lines.push(` \${__voidGetErrorAssetCss(error)}`); lines.push(` "}' }], + })); + + const html = await response.text(); + expect(html).toContain('data-vite-dev-id="/pages/styled.tsx?x=1"'); + expect(html).toContain('nonce="'); + expect(html).toContain('<\\/style>'); + expect(html).not.toContain(''); + }); + + it('adds a quoted dev CSS nonce source to strict style CSP responses', async () => { + const c = await createTestContext('GET', '/styled'); + const response = await handlePageGet( + (ctx: Context) => { + ctx.header('Content-Security-Policy', "default-src 'self'; style-src 'self'"); + return {}; + }, + undefined, + c, + 'styled', + vi.fn(async (_pageObj: RenderPage, assetTags) => `${assetTags.css}`), + async () => ({ + css: '', + preloads: '', + body: '', + devCss: [{ url: '/pages/styled.css', css: '.x{color:red}' }], + }), + ); + + const csp = response.headers.get('content-security-policy') ?? ''; + expect(csp).toContain("style-src 'self' 'nonce-"); + expect(csp).not.toContain("style-src 'self' nonce-"); + }); + + it('adds style-src with a quoted nonce when only default-src is present', async () => { + const c = await createTestContext('GET', '/styled'); + const response = await handlePageGet( + (ctx: Context) => { + ctx.header('Content-Security-Policy', "default-src 'self'"); + return {}; + }, + undefined, + c, + 'styled', + vi.fn(async (_pageObj: RenderPage, assetTags) => `${assetTags.css}`), + async () => ({ + css: '', + preloads: '', + body: '', + devCss: [{ url: '/pages/styled.css', css: '.x{color:red}' }], + }), + ); + + const csp = response.headers.get('content-security-policy') ?? ''; + expect(csp).toContain("default-src 'self'"); + expect(csp).toContain("style-src 'self' 'nonce-"); + }); + + it('adds the generated dev CSS nonce when CSP already has another nonce', async () => { + const c = await createTestContext('GET', '/styled'); + const response = await handlePageGet( + (ctx: Context) => { + ctx.header('Content-Security-Policy', "style-src 'self' 'nonce-existing'"); + return {}; + }, + undefined, + c, + 'styled', + vi.fn(async (_pageObj: RenderPage, assetTags) => `${assetTags.css}`), + async () => ({ + css: '', + preloads: '', + body: '', + devCss: [{ url: '/pages/styled.css', css: '.x{color:red}' }], + }), + ); + + const html = await response.text(); + const nonce = html.match(/nonce="([^"]+)"/)?.[1]; + expect(nonce).toBeTruthy(); + const csp = response.headers.get('content-security-policy') ?? ''; + expect(csp).toContain("'nonce-existing'"); + expect(csp).toContain(`'nonce-${nonce}'`); + }); + + it('attaches prepared asset tags to render errors for styled 500 pages', async () => { + const c = await createTestContext('GET', '/styled'); + const error = new Error('render failed'); + + await expect( + handlePageGet( + undefined, + undefined, + c, + 'styled', + vi.fn(async () => { + throw error; + }), + async () => ({ + css: '', + preloads: '', + body: '', + devCss: [{ url: '/pages/styled.css', id: '/root/pages/styled.css', css: '.x{}' }], + }), + ), + ).rejects.toThrow(error); + + expect( + (error as Error & { __voidPageAssetTags?: { css: string } }).__voidPageAssetTags?.css, + ).toContain('data-vite-dev-id="/root/pages/styled.css"'); + }); + it('includes shared data from context', async () => { const c = await createTestContext('GET', '/', { headers: { 'x-voidpages': 'true' }, @@ -432,6 +553,36 @@ describe('handlePageMutation', () => { expect(body.props).toEqual({ users: [] }); }); + it('ValidationError HTML responses include collected dev CSS', async () => { + const c = await createTestContext('POST', '/users'); + const mutationHandler = vi.fn(() => { + throw new ValidationError({ name: 'required' }); + }); + const getHandler = vi.fn(() => ({ users: [] })); + const renderFn = vi.fn( + async (_pageObj: RenderPage, assetTags) => `${assetTags.css}`, + ); + + const response = await handlePageMutation( + mutationHandler, + getHandler, + undefined, + c, + 'users', + renderFn, + async () => ({ + css: '', + preloads: '', + body: '', + devCss: [{ url: '/pages/users.css', css: '.error{color:red}' }], + }), + ); + + const html = await response.text(); + expect(html).toContain('data-vite-dev-id="/pages/users.css"'); + expect(html).toContain('.error{color:red}'); + }); + it('Response 400 (withValidator) — extracts errors, re-runs GET', async () => { const c = await createTestContext('POST', '/users', { headers: { 'x-voidpages': 'true' }, @@ -489,6 +640,32 @@ describe('handlePageMutation', () => { expect(body.errors).toBeNull(); }); + it('post-mutation HTML rerenders include collected dev CSS', async () => { + const c = await createTestContext('POST', '/users'); + const renderFn = vi.fn( + async (_pageObj: RenderPage, assetTags) => `${assetTags.css}`, + ); + + const response = await handlePageMutation( + () => undefined, + () => ({ users: ['created'] }), + undefined, + c, + 'users', + renderFn, + async () => ({ + css: '', + preloads: '', + body: '', + devCss: [{ url: '/pages/users.css', css: '.created{color:green}' }], + }), + ); + + const html = await response.text(); + expect(html).toContain('data-vite-dev-id="/pages/users.css"'); + expect(html).toContain('.created{color:green}'); + }); + it('re-throws non-ValidationError errors', async () => { const c = await createTestContext('POST', '/users', { headers: { 'x-voidpages': 'true' }, diff --git a/packages/vue/src/plugin-islands.ts b/packages/vue/src/plugin-islands.ts index f98a94ee7..bc096b86c 100644 --- a/packages/vue/src/plugin-islands.ts +++ b/packages/vue/src/plugin-islands.ts @@ -7,9 +7,7 @@ import { resolveSpecifier, needsIslandClientBundle, rewriteCssImportForVirtualModule, - rebuildIslandCssMap as rebuildIslandCssMapShared, computePagesNeedingClientJS as computePagesNeedingClientJSShared, - configureIslandCssServer, watchPagesForRescan, ISLANDS_RENDERER_ID, ISLANDS_CLIENT_ENTRY_ID, @@ -25,25 +23,6 @@ type MdPluginWithApi = Plugin & { }; type ScannableEntry = { filePath: string; island: boolean | undefined }; -function fileHasCss(filePath: string): boolean { - try { - const code = readFileSync(filePath, 'utf-8'); - // JS-style CSS imports - if ( - /import\b[^"']*["'][^"']+\.(?:css|scss|sass|less|styl|stylus|pcss|postcss)["']/.test(code) - ) { - return true; - } - // Vue