import { createError, hash, unique } from '@compiled/utils'; import autoprefixer from 'autoprefixer'; import postcss from 'postcss'; import nested from 'postcss-nested'; import whitespace from 'postcss-normalize-whitespace'; import { atomicifyRules } from './plugins/atomicify-rules'; import { danglingCombinators } from './plugins/dangling-combinators'; import { discardDuplicates } from './plugins/discard-duplicates'; import { discardEmptyRules } from './plugins/discard-empty-rules'; import { expandShorthands } from './plugins/expand-shorthands'; import { extractStyleSheets } from './plugins/extract-stylesheets'; import { flattenMultipleSelectors } from './plugins/flatten-multiple-selectors'; import { increaseSpecificity } from './plugins/increase-specificity'; import { nonAtomicifyRules } from './plugins/non-atomicify-rules'; import { normalizeCSS } from './plugins/normalize-css'; import { parentOrphanedPseudos } from './plugins/parent-orphaned-pseudos'; import { sortStyleSheet } from './plugins/sort-style-sheet'; export interface TransformOpts { optimizeCss?: boolean; increaseSpecificity?: boolean; sortAtRules?: boolean; sortShorthand?: boolean; classHashPrefix?: string; flattenMultipleSelectors?: boolean; /** * When `true`, atomic class names use the collision-resistant base-62 hash * (11-char classes) instead of the legacy base-36 `.slice(0, 4)` hash * (9-char classes). Migration flag — defaults to `false` (legacy output). * * @default false */ collisionResistantHash?: boolean; } /** * As opposed to TransformOpts which are babel plugin level options, * LocalTransformOptions control each individual transformation separately. */ export interface LocalTransformOptions { /** * When `true`, styles are emitted as a single non-atomic class per variant * (via `cssMapScoped`) rather than one atomic class per declaration. * The class name uses the `cc-` prefix so `ax()` treats it as a plain * opaque class rather than an atomic group. * * @default false * @experimental Not part of the public API. May change without notice. */ nonAtomic?: boolean; /** * Pre-computed class name for non-atomic mode (`cssMapScoped`). When provided, * avoids hashing the full CSS content string. The babel plugin computes this as * `NON_ATOMIC_CLASS_PREFIX + hash(relative(filename) + ':' + variableName + ':' + variantKey)`. * Falls back to hashing the full CSS content string if not provided. * * @experimental Not part of the public API. May change without notice. */ nonAtomicClassName?: string; } /** * Class name prefix used for non-atomic CSS classes generated by `cssMapScoped`. * Unlike atomic classes (prefixed with `_`), the `cc-` prefix signals to `ax()` that this * is an opaque plain class and should not be treated as an atomic group for deduplication. */ /** @internal — not part of public API, do not import from other packages */ export const NON_ATOMIC_CLASS_PREFIX = 'cc-'; /** * Will transform CSS into multiple CSS sheets. * * @param css CSS string * @param opts Transformation options */ export const transformCss = ( css: string, opts: TransformOpts, localOpts: LocalTransformOptions = {} ): { sheets: string[]; classNames: string[] } => { const sheets: string[] = []; const classNames: string[] = []; const flattenMultipleSelectorsOption = opts.flattenMultipleSelectors ?? true; try { // Shared PostCSS plugins used by both atomic and non-atomic pipelines. const sharedPlugins = [ discardDuplicates(), discardEmptyRules(), parentOrphanedPseudos(), danglingCombinators(), nested({ bubble: [ 'container', '-moz-document', 'layer', 'else', 'when', // postcss-nested bubbles `starting-style` by default in versions from 6.0.2 onwards: // https://github.com/postcss/postcss-nested?tab=readme-ov-file#bubble // When we upgrade to a version that includes this change, we can remove this from the list. 'starting-style', ], unwrap: ['color-profile', 'counter-style', 'font-palette-values', 'page', 'property'], }), ...normalizeCSS(opts), expandShorthands(), ]; // Shared tail plugins applied after the atomic/non-atomic transformation step. const tailPlugins = [ ...(process.env.AUTOPREFIXER === 'off' ? [] : [autoprefixer()]), whitespace(), extractStyleSheets({ callback: (sheet: string) => sheets.push(sheet) }), ]; // When used by `cssMapScoped`, all declarations for a variant are grouped under a single // `cc-` class instead of individual atomic `_xxx` classes. if (localOpts.nonAtomic) { // Non-atomic mode: wrap all declarations under a single generated class name. // Use the pre-computed class name (hash of filename + variantKey) when available — // this avoids hashing the full CSS content string for large cssMap variants. // Falls back to hashing the CSS content for standalone transformCss() callers. const className = localOpts.nonAtomicClassName ?? `${NON_ATOMIC_CLASS_PREFIX}${hash(css)}`; const nonAtomicResult = postcss([ ...sharedPlugins, nonAtomicifyRules({ className, callback: (name: string) => classNames.push(name), }), ...tailPlugins, ]).process(css, { from: undefined }); // We need to access something to make the transformation happen. nonAtomicResult.css; } else { const atomicResult = postcss([ ...sharedPlugins, atomicifyRules({ callback: (className: string) => classNames.push(className), classHashPrefix: opts.classHashPrefix, collisionResistantHash: opts.collisionResistantHash, }), ...(flattenMultipleSelectorsOption ? [flattenMultipleSelectors(), discardDuplicates()] : []), ...(opts.increaseSpecificity ? [increaseSpecificity()] : []), sortStyleSheet({ sortAtRulesEnabled: opts.sortAtRules, sortShorthandEnabled: opts.sortShorthand, }), ...tailPlugins, ]).process(css, { from: undefined }); // We need to access something to make the transformation happen. atomicResult.css; } return { sheets, classNames: unique(classNames), }; } catch (e: unknown) { const message = e instanceof Error ? e.message : e; throw createError( 'css', 'Unhandled exception' )( `An unhandled exception was raised when parsing your CSS, this is probably a bug! Raise an issue here: https://github.com/atlassian-labs/compiled/issues/new?assignees=&labels=&template=bug_report.md&title=CSS%20Parsing%20Exception:%20 Input CSS: { ${css} } Exception: ${message}` ); } };