import { parseAsync, transformFromAstAsync } from '@babel/core'; import type { PluginOptions as BabelPluginOptions } from '@compiled/babel-plugin'; import type { PluginOptions as BabelStripRuntimePluginOptions, BabelFileMetadata, } from '@compiled/babel-plugin-strip-runtime'; import { sort } from '@compiled/css'; import { DEFAULT_IMPORT_SOURCES, DEFAULT_PARSER_BABEL_PLUGINS, toBoolean } from '@compiled/utils'; import type { OutputAsset, OutputBundle } from 'rollup'; import { createDevCssHooks, isCompiledCssRequest } from './dev-css.js'; import type { PluginOptions } from './types'; import { createDefaultResolver } from './utils.js'; /** * Partition style rules so that cssMapScoped (non-atomic, `.cc-`) rules come * first in source order, followed by atomic rules sorted lexically. This * ensures: * - Non-atomic rules win the cascade over atomic rules (they appear later in * the cascade order WITHIN their bucket — but since they come earlier in * the output we rely on Compiled's sort() to handle final positioning). * Actually the key invariant here is: same source → same output (no churn). * - Atomic rules are deterministic across builds, regardless of the order in * which assets were processed. * * The `.cc-` detection uses `includes` so it matches both bare class selectors * (`.cc-xxx{...}`) AND at-rule-wrapped ones (`@media{.cc-xxx{...}}`). */ const sortStyleRulesForDeterministicOutput = (styleRules: string[]): string[] => { const nonAtomicRules: string[] = []; const atomicRules: string[] = []; for (const rule of styleRules) { if (rule.includes('.cc-')) { nonAtomicRules.push(rule); } else { atomicRules.push(rule); } } atomicRules.sort(); return [...nonAtomicRules, ...atomicRules]; }; /** * Name of the chunk that all `.compiled.css` modules are grouped into when * `sortOnlyCompiledCss` is enabled, so their CSS is emitted as its own asset. */ const COMPILED_CSS_CHUNK_NAME = 'compiled-css'; type ManualChunks = ((id: string, meta: unknown) => string | null | undefined | void) | undefined; /** * Wraps `manualChunks` so every `.compiled.css` module goes into the `compiled-css` * chunk and everything else keeps the chunking the user configured. */ const withCompiledCssChunk = (manualChunks: unknown): ManualChunks => { if (manualChunks && typeof manualChunks !== 'function') { throw new Error( '[@compiled/vite-plugin] `sortOnlyCompiledCss` cannot be combined with an object-form `build.rollupOptions.output.manualChunks`. Use the function form instead.' ); } const existing = manualChunks as ManualChunks; return (id, meta) => (isCompiledCssRequest(id) ? COMPILED_CSS_CHUNK_NAME : existing?.(id, meta)); }; /** * Adds the `compiled-css` group to Rolldown's `codeSplitting` option (Vite 8+), which * makes Rolldown ignore `manualChunks` whenever it is set. Groups are matched by * priority, so ours wins over the user's own groups for `.compiled.css` modules. */ const withCompiledCssGroup = (codeSplitting: unknown): unknown => { if (codeSplitting === false) { throw new Error( '[@compiled/vite-plugin] `sortOnlyCompiledCss` cannot be combined with `codeSplitting: false`.' ); } const group = { name: COMPILED_CSS_CHUNK_NAME, test: /\.compiled\.css(?:$|\?)/, priority: Number.MAX_SAFE_INTEGER, }; const existing = typeof codeSplitting === 'object' && codeSplitting ? codeSplitting : {}; return { ...existing, groups: [group, ...((existing as any).groups ?? [])] }; }; /** * Mutates the user's Vite config in place. Returning an object instead would let Vite * concatenate an `output` array with ours rather than replace it. Vite 8 (Rolldown) accepts * `rolldownOptions` as well as `rollupOptions`, so whichever the user set is edited. */ const groupCompiledCssIntoChunk = (userConfig: any): void => { userConfig.build ??= {}; // Vite merges all CSS into one asset without CSS code splitting (its default in // library mode), leaving no separate Compiled CSS asset to sort. const { cssCodeSplit, lib } = userConfig.build; if (cssCodeSplit === false || (lib && cssCodeSplit === undefined)) { throw new Error( '[@compiled/vite-plugin] `sortOnlyCompiledCss` requires `build.cssCodeSplit` to be enabled. Remove `cssCodeSplit: false`, or set `cssCodeSplit: true` in library mode.' ); } const containers = ['rollupOptions', 'rolldownOptions'] .map((key) => userConfig.build[key]) .filter(Boolean); if (containers.length === 0) { containers.push((userConfig.build.rollupOptions = {})); } for (const container of containers) { const outputs = Array.isArray(container.output) ? container.output : [(container.output ??= {})]; for (const output of outputs) { const key = ['codeSplitting', 'advancedChunks'].find((name) => output[name] !== undefined); if (key) { output[key] = withCompiledCssGroup(output[key]); } else { output.manualChunks = withCompiledCssChunk(output.manualChunks); } } } }; /** * Compiled Vite plugin. * * Transforms CSS-in-JS to atomic CSS at build time using Babel. * * @param userOptions - Plugin configuration options * @returns Vite plugin object */ function compiled(userOptions: PluginOptions = {}): any { const options: PluginOptions = { // Vite-specific bake: true, extract: false, transformerBabelPlugins: undefined, ssr: false, extractStylesToDirectory: undefined, sortShorthand: true, sortOnlyCompiledCss: false, // Babel-inherited importReact: true, nonce: undefined, importSources: undefined, optimizeCss: true, resolver: undefined, extensions: undefined, parserBabelPlugins: undefined, addComponentName: false, processXcss: undefined, increaseSpecificity: undefined, sortAtRules: true, classHashPrefix: undefined, collisionResistantHash: undefined, flattenMultipleSelectors: undefined, ...userOptions, }; const sortCompiledCss = (css: string): string => sort(css, { sortAtRulesEnabled: options.sortAtRules, sortShorthandEnabled: options.sortShorthand, }); // Storage for collected style rules during transformation // Map of filePath → array of style rules (in source order from the babel // transform). We sort by filePath at extraction time for cross-file // determinism, then partition + sort atomic rules for stable output. const collectedStyleRulesByFile = new Map(); // Store the emitted CSS filename for HTML injection // This gets set in generateBundle after the file is emitted let extractedCssFileName: string | undefined; // Name used for the extracted CSS asset const EXTRACTED_CSS_NAME = 'compiled-extracted.css'; // Local source normally relies on the Compiled runtime in development. Keep // those atomic rules in the same stylesheet as imported `.compiled.css` // modules so the cascade is deterministic across both sources. const localDevCssByFile = new Map(); let isDevServer = false; const devCssHooks = createDevCssHooks(sortCompiledCss, (id) => localDevCssByFile.get(id)); return { ...devCssHooks, name: '@compiled/vite-plugin', enforce: 'pre', // Run before other plugins config(userConfig: any, env: { command: string }) { if (options.sortOnlyCompiledCss && env.command === 'build') { groupCompiledCssIntoChunk(userConfig); } }, configResolved(config: { base: string; command: string }) { isDevServer = config.command === 'serve'; devCssHooks.configResolved(config); }, async transform(code: string, id: string, transformOptions?: { ssr?: boolean }): Promise { const isClientDevTransform = isDevServer && !transformOptions?.ssr; if (isClientDevTransform && isCompiledCssRequest(id) && code.includes('._')) { try { return { code: sortCompiledCss(code), map: null, }; } catch (error) { const err = error as Error; this.warn({ message: `[@compiled/vite-plugin] Failed to sort CSS in ${id}: ${err.message}`, }); return null; } } // Filter out node_modules (except for specific includes if needed) if (id.includes('/node_modules/@compiled/react')) { return null; } // Only process JS/TS/JSX/TSX files if (!/\.[jt]sx?$/.test(id)) { return null; } const importSources = [...DEFAULT_IMPORT_SOURCES, ...(options.importSources || [])]; // Bail early if Compiled (via an importSource) isn't in the module if (!importSources.some((name) => code.includes(name))) { return null; } try { const includedFiles: string[] = []; // Parse to AST using Babel const ast = await parseAsync(code, { filename: id, babelrc: false, configFile: false, caller: { name: 'compiled' }, rootMode: 'upward-optional', parserOpts: { plugins: options.parserBabelPlugins ?? DEFAULT_PARSER_BABEL_PLUGINS, }, plugins: options.transformerBabelPlugins ?? undefined, }); if (!ast) { return null; } // Build extraction follows the explicit option regardless of NODE_ENV. // Client-side dev transforms force extraction so local rules can join // the virtual stylesheet; dev SSR keeps its existing runtime behavior. const extract = isClientDevTransform || (options.extract && !isDevServer); // First compile the source. Runtime stripping must be a separate // transform so it can observe the JSX calls emitted by Compiled. const compiledResult = await transformFromAstAsync(ast, code, { babelrc: false, configFile: false, sourceMaps: true, filename: id, parserOpts: { plugins: options.parserBabelPlugins ?? DEFAULT_PARSER_BABEL_PLUGINS, }, plugins: [ ...(options.transformerBabelPlugins ?? []), options.bake && [ '@compiled/babel-plugin', { ...options, onIncludedFiles: (files: string[]) => includedFiles.push(...files), resolver: options.resolver ? options.resolver : createDefaultResolver(options), cache: false, } as BabelPluginOptions, ], ].filter(toBoolean), caller: { name: 'compiled', }, }); let result = compiledResult; if (extract && compiledResult?.code) { const compiledAst = await parseAsync(compiledResult.code, { filename: id, babelrc: false, configFile: false, caller: { name: 'compiled' }, rootMode: 'upward-optional', parserOpts: { plugins: options.parserBabelPlugins ?? DEFAULT_PARSER_BABEL_PLUGINS, }, }); result = compiledAst ? await transformFromAstAsync(compiledAst, compiledResult.code, { babelrc: false, configFile: false, sourceMaps: true, inputSourceMap: compiledResult.map ?? undefined, filename: id, plugins: [ [ '@compiled/babel-plugin-strip-runtime', { compiledRequireExclude: true, extractStylesToDirectory: options.extractStylesToDirectory, processJsxDev: isClientDevTransform, } as BabelStripRuntimePluginOptions, ], ], caller: { name: 'compiled' }, }) : compiledResult; } // Store metadata for CSS extraction if enabled. Clear the previous // local value first so HMR updates that remove all styles do not keep // registering stale CSS. if (isClientDevTransform) { localDevCssByFile.delete(id); } if (extract && result?.metadata) { const metadata = result.metadata as BabelFileMetadata; // Collect style rules from this file, keyed by filePath for // cross-file deterministic ordering at extraction time. if (metadata.styleRules && metadata.styleRules.length > 0) { collectedStyleRulesByFile.set(id, metadata.styleRules.slice()); if (isClientDevTransform) { localDevCssByFile.set(id, metadata.styleRules.join('\n')); } } } // Return transformed code and source map if (result?.code) { const localCssImport = isClientDevTransform && localDevCssByFile.has(id) ? `import ${JSON.stringify( `virtual:@compiled/vite-plugin/local-css:${encodeURIComponent(id)}` )};\n` : ''; return { code: `${localCssImport}${result.code}`, map: localCssImport && result.map ? { ...result.map, mappings: `;${result.map.mappings}`, } : result.map ?? null, }; } return null; } catch (e: unknown) { // Throw error to be displayed by Vite const error = e as Error; this.error({ message: `[@compiled/vite-plugin] Failed to transform: ${error.message}`, stack: error.stack, }); } }, generateBundle(_outputOptions: any, bundle: OutputBundle) { // Post-process CSS assets to apply Compiled's sorting and deduplication const extract = options.extract; // With `sortOnlyCompiledCss`, only CSS emitted from the `compiled-css` chunk (the // `.compiled.css` modules) is sorted; other CSS keeps its order. const compiledCssAssets = new Set(); if (options.sortOnlyCompiledCss) { for (const output of Object.values(bundle)) { if (output.type === 'chunk' && output.name === COMPILED_CSS_CHUNK_NAME) { (output as any).viteMetadata?.importedCss?.forEach((name: string) => compiledCssAssets.add(name) ); } } } // Process each CSS asset in the bundle for (const [fileName, output] of Object.entries(bundle)) { // Only process CSS assets if (!fileName.endsWith('.css') || output.type !== 'asset') { continue; } const asset = output as OutputAsset; const cssContent = asset.source as string; // By default, any CSS containing Compiled atomic classes (starting with an // underscore) is sorted. This is a heuristic to identify CSS that came from // .compiled.css files. const shouldSort = options.sortOnlyCompiledCss ? compiledCssAssets.has(fileName) : cssContent.includes('._'); if (shouldSort) { try { // Update the asset with sorted CSS asset.source = sortCompiledCss(cssContent); } catch (error) { const err = error as Error; this.warn({ message: `[@compiled/vite-plugin] Failed to sort CSS in ${fileName}: ${err.message}`, }); } } } // Also emit extracted styles if we collected any from local code if (extract && collectedStyleRulesByFile.size > 0) { try { // Sort entries by filePath for stable cross-file ordering, then // collect all rules. Deduplication happens downstream in `sort()` // via `postcss-discard-duplicates`. const sortedEntries = [...collectedStyleRulesByFile.entries()].sort(([keyA], [keyB]) => keyA > keyB ? 1 : -1 ); const collectedRules: string[] = []; for (const [, rules] of sortedEntries) { collectedRules.push(...rules); } const allRules = sortStyleRulesForDeterministicOutput(collectedRules); // Join all rules and apply CSS sorting const combinedCss = allRules.join('\n'); // Emit the CSS file with content-based naming // Vite will add a content hash to the filename automatically this.emitFile({ type: 'asset', name: EXTRACTED_CSS_NAME, source: sortCompiledCss(combinedCss), }); // Mark that we've emitted the file so transformIndexHtml can inject it // The actual filename will be determined in transformIndexHtml from the bundle extractedCssFileName = EXTRACTED_CSS_NAME; } catch (error) { const err = error as Error; this.warn({ message: `[@compiled/vite-plugin] Failed to generate CSS bundle: ${err.message}`, }); } } }, transformIndexHtml( _html: string, ctx: { bundle?: OutputBundle; [key: string]: any } ): { tag: string; attrs: Record; injectTo: string }[] { // Inject the extracted CSS file into HTML if it was emitted if (!extractedCssFileName || !ctx.bundle) { return []; } // Find the emitted CSS asset in the bundle by its name // The actual fileName will have a content hash added by Vite const cssAsset = Object.values(ctx.bundle).find( (asset): asset is OutputAsset => asset.type === 'asset' && asset.name === EXTRACTED_CSS_NAME ); if (!cssAsset) { return []; } return [ { tag: 'link', attrs: { rel: 'stylesheet', href: `/${cssAsset.fileName}`, }, injectTo: 'head', }, ]; }, }; } export { compiled }; export type { PluginOptions as VitePluginOptions }; export default compiled;