@tenphi/tasty 3.7.0 → 3.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/{babel-DWCsafYw.d.ts → babel-Zs1Q03qt.d.ts} +2 -2
- package/dist/chunks/async-storage-CG5HnUT5.js +20 -0
- package/dist/chunks/async-storage-CG5HnUT5.js.map +1 -0
- package/dist/chunks/build-config-CUQVwdWF.js +42 -0
- package/dist/chunks/build-config-CUQVwdWF.js.map +1 -0
- package/dist/{collector-B3OsM252.js → chunks/collector-B0LTHw6Z.js} +6 -125
- package/dist/chunks/collector-B0LTHw6Z.js.map +1 -0
- package/dist/chunks/config-engine-C3pF9EK9.js +267 -0
- package/dist/chunks/config-engine-C3pF9EK9.js.map +1 -0
- package/dist/chunks/css-definitions-D_it4XZH.js +875 -0
- package/dist/chunks/css-definitions-D_it4XZH.js.map +1 -0
- package/dist/{css-resources-Cyl_axbI.js → chunks/css-resources-BN8apgxt.js} +1 -8
- package/dist/chunks/css-resources-BN8apgxt.js.map +1 -0
- package/dist/chunks/debug-C9LeNVoJ.js +501 -0
- package/dist/chunks/debug-C9LeNVoJ.js.map +1 -0
- package/dist/chunks/dsl-C5yuAn41.js +1373 -0
- package/dist/chunks/dsl-C5yuAn41.js.map +1 -0
- package/dist/chunks/hydration-TRcz5vnk.js +41 -0
- package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
- package/dist/chunks/react-runtime-O-OUrKLH.js +557 -0
- package/dist/chunks/react-runtime-O-OUrKLH.js.map +1 -0
- package/dist/chunks/runtime-engine-DvnE2g-E.js +2437 -0
- package/dist/chunks/runtime-engine-DvnE2g-E.js.map +1 -0
- package/dist/chunks/runtime-state-BTDqSYBk.js +127 -0
- package/dist/chunks/runtime-state-BTDqSYBk.js.map +1 -0
- package/dist/{merge-styles-DuoZEsm9.js → chunks/shared-utils-DWA4LjIa.js} +55 -54
- package/dist/chunks/shared-utils-DWA4LjIa.js.map +1 -0
- package/dist/chunks/style-engine-C1ECBZxR.js +5131 -0
- package/dist/chunks/style-engine-C1ECBZxR.js.map +1 -0
- package/dist/{css-writer-Bgowobbx.js → chunks/zero-engine-B6EnYcXY.js} +3 -120
- package/dist/chunks/zero-engine-B6EnYcXY.js.map +1 -0
- package/dist/{collector-BTVXj2hS.d.ts → collector-hl5KNH7k.d.ts} +6 -4
- package/dist/{config-LfIDmVHx.d.ts → config-DWL1ZYue.d.ts} +20 -25
- package/dist/core/index.d.ts +5 -5
- package/dist/core/index.js +9 -6
- package/dist/{index-Bm9ltvdH.d.ts → index-D9N9GV24.d.ts} +96 -82
- package/dist/index.d.ts +5 -5
- package/dist/index.js +11 -922
- package/dist/{merge-styles-BcLl1u_d.d.ts → merge-styles-C_oMoJVd.d.ts} +2 -2
- package/dist/ssr/astro-client.js +1 -14
- package/dist/ssr/astro-client.js.map +1 -1
- package/dist/ssr/astro-middleware-extract-static.js +1 -1
- package/dist/ssr/astro-middleware-extract.js +1 -1
- package/dist/ssr/astro-middleware-static.js +1 -12
- package/dist/ssr/astro-middleware-static.js.map +1 -1
- package/dist/ssr/astro-middleware.js +1 -13
- package/dist/ssr/astro-middleware.js.map +1 -1
- package/dist/ssr/astro.js +219 -1
- package/dist/ssr/astro.js.map +1 -0
- package/dist/ssr/index.d.ts +6 -6
- package/dist/ssr/index.js +4 -4
- package/dist/ssr/next-config.d.ts +1 -1
- package/dist/ssr/next-config.js +29 -20
- package/dist/ssr/next-config.js.map +1 -1
- package/dist/ssr/next.d.ts +1 -1
- package/dist/ssr/next.js +5 -37
- package/dist/ssr/next.js.map +1 -1
- package/dist/static/index.d.ts +2 -2
- package/dist/static/index.js +1 -19
- package/dist/static/index.js.map +1 -1
- package/dist/{index-BmogEzTo.d.ts → types-jKZNpias.d.ts} +845 -804
- package/dist/zero/babel.d.ts +1 -1
- package/dist/zero/babel.js +25 -96
- package/dist/zero/babel.js.map +1 -1
- package/dist/zero/index.d.ts +1 -1
- package/dist/zero/index.js +1 -1
- package/dist/zero/next.d.ts +1 -1
- package/dist/zero/next.js +0 -31
- package/dist/zero/next.js.map +1 -1
- package/docs/ai-agents.md +8 -3
- package/docs/debug.md +2 -5
- package/docs/methodology.md +3 -3
- package/docs/pipeline.md +3 -0
- package/docs/runtime-benchmarks.md +105 -68
- package/docs/styles.md +43 -11
- package/package.json +48 -5
- package/dist/astro-CeYENy2x.js +0 -301
- package/dist/astro-CeYENy2x.js.map +0 -1
- package/dist/async-storage-DKK-wTD4.js +0 -44
- package/dist/async-storage-DKK-wTD4.js.map +0 -1
- package/dist/collector-B3OsM252.js.map +0 -1
- package/dist/config-B3gPdCqd.js +0 -12421
- package/dist/config-B3gPdCqd.js.map +0 -1
- package/dist/context-CA8YKeMn.js +0 -24
- package/dist/context-CA8YKeMn.js.map +0 -1
- package/dist/core-DGm0CFHP.js +0 -1732
- package/dist/core-DGm0CFHP.js.map +0 -1
- package/dist/css-resources-Cyl_axbI.js.map +0 -1
- package/dist/css-writer-Bgowobbx.js.map +0 -1
- package/dist/format-global-rules-DklyaXv-.js +0 -22
- package/dist/format-global-rules-DklyaXv-.js.map +0 -1
- package/dist/format-rules-XRw9u7d4.js +0 -104
- package/dist/format-rules-XRw9u7d4.js.map +0 -1
- package/dist/hydrate-CNOmZprz.js +0 -37
- package/dist/hydrate-CNOmZprz.js.map +0 -1
- package/dist/index.js.map +0 -1
- package/dist/keyframes-DE-OE76F.js +0 -535
- package/dist/keyframes-DE-OE76F.js.map +0 -1
- package/dist/merge-styles-DuoZEsm9.js.map +0 -1
- package/dist/resolve-recipes-H9NqOQuP.js +0 -144
- package/dist/resolve-recipes-H9NqOQuP.js.map +0 -1
- package/dist/ssr-collector-ref-COs_ioWl.js +0 -29
- package/dist/ssr-collector-ref-COs_ioWl.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"style-engine-C1ECBZxR.js","names":["devMode","processGroup","dimension","dimension","dimension","STYLE_HANDLER_MAP"],"sources":["../../src/config-state.ts","../../src/states/index.ts","../../src/styles/logical-list.ts","../../src/chunks/style-chunk-map.ts","../../src/styles/const.ts","../../src/styles/shared.ts","../../src/styles/border.ts","../../src/styles/dimension.ts","../../src/styles/blockSize.ts","../../src/styles/color.ts","../../src/styles/createStyle.ts","../../src/styles/display.ts","../../src/styles/fade.ts","../../src/styles/fill.ts","../../src/styles/flow.ts","../../src/styles/gap.ts","../../src/styles/height.ts","../../src/styles/directional.ts","../../src/styles/inset.ts","../../src/styles/inlineSize.ts","../../src/styles/logical.ts","../../src/styles/margin.ts","../../src/styles/outline.ts","../../src/styles/padding.ts","../../src/styles/placement.ts","../../src/styles/preset.ts","../../src/styles/radius.ts","../../src/styles/scrollMargin.ts","../../src/styles/scrollPadding.ts","../../src/styles/scrollbar.ts","../../src/styles/shadow.ts","../../src/styles/transition.ts","../../src/styles/width.ts","../../src/styles/predefined.ts","../../src/styles/define-handler.ts","../../src/styles/index.ts","../../src/pipeline/conditions.ts","../../src/pipeline/simplify.ts","../../src/pipeline/materialize-contradictions.ts","../../src/pipeline/materialize.ts","../../src/pipeline/warnings.ts","../../src/pipeline/exclusive.ts","../../src/utils/case-converter.ts","../../src/utils/selector-transform.ts","../../src/pipeline/parseStateKey.ts","../../src/pipeline/index.ts","../../src/styles/list.ts","../../src/styles/base-props.ts","../../src/chunks/definitions.ts","../../src/chunks/cacheKey.ts","../../src/chunks/renderChunk.ts"],"sourcesContent":["/**\n * Minimal configuration state shared by the style engine, zero-runtime\n * extractor, and runtime configuration module. Keeping it independent\n * prevents pure rendering code from importing the full injector graph.\n */\n\nlet stylesGenerated = false;\nlet globalPolyfills: { functions?: boolean } | null = null;\n\nconst GTKEY_POLYFILLS = '__tasty_cfg_polyfills__';\n\nexport function hasStylesGenerated(): boolean {\n return stylesGenerated;\n}\n\n/** Mark the lock and report whether this call changed it. */\nexport function markStylesGeneratedState(): boolean {\n if (stylesGenerated) return false;\n stylesGenerated = true;\n return true;\n}\n\nexport function resetStylesGeneratedState(): void {\n stylesGenerated = false;\n}\n\n/** Whether the CSS `@function` inline-expansion polyfill is enabled. */\nexport function isFunctionsPolyfillEnabled(): boolean {\n const shared = (globalThis as Record<string, unknown>)[GTKEY_POLYFILLS] as\n { functions?: boolean } | undefined;\n return (globalPolyfills ?? shared)?.functions === true;\n}\n\nexport function setGlobalPolyfillsState(polyfills: {\n functions?: boolean;\n}): void {\n globalPolyfills = { ...(globalPolyfills ?? {}), ...polyfills };\n (globalThis as Record<string, unknown>)[GTKEY_POLYFILLS] = globalPolyfills;\n}\n\nexport function resetGlobalPolyfillsState(): void {\n globalPolyfills = null;\n delete (globalThis as Record<string, unknown>)[GTKEY_POLYFILLS];\n}\n","/**\n * Advanced State Mapping - Predefined States Management\n *\n * This module handles global and local predefined states for the Tasty styling system.\n * See ADVANCED_STATE_MAPPING.md for full specification.\n */\n\nimport { hasStylesGenerated } from '../config-state';\nimport type { Styles } from '../styles/types';\nimport { isDevEnv } from '../utils/is-dev-env';\n\n/**\n * Parsed advanced state information\n */\nexport interface ParsedAdvancedState {\n type:\n | 'media'\n | 'container'\n | 'root'\n | 'parent'\n | 'own'\n | 'starting'\n | 'predefined'\n | 'modifier';\n condition: string; // e.g., 'width <= 920px' or 'hovered'\n containerName?: string; // for container queries\n raw: string; // original state key\n mediaType?: string; // for @media:screen, @media:print, etc.\n}\n\n/**\n * Context for state parsing operations\n */\nexport interface StateParserContext {\n localPredefinedStates: Record<string, string>;\n globalPredefinedStates: Record<string, string>;\n isSubElement?: boolean; // true when processing sub-element styles (for @own() validation)\n}\n\n/**\n * At-rule context for CSS generation\n */\nexport interface AtRuleContext {\n media?: string[]; // @media conditions to wrap rule in (merged with 'and')\n container?: { name?: string; condition: string }[]; // @container conditions (nested)\n startingStyle?: boolean;\n rootStates?: string[]; // :root state selectors (e.g., '[data-theme=\"dark\"]')\n negatedRootStates?: string[]; // Negated :root state selectors for non-overlapping rules (e.g., ':not([data-theme=\"dark\"])')\n}\n\n// Built-in state names that cannot be overridden\nconst BUILTIN_STATES = new Set([\n '@starting',\n '@keyframes',\n '@property',\n '@font-face',\n '@counter-style',\n '@function',\n '@supports',\n // @inherit is a value (not a key), but reserved here to prevent\n // users from accidentally defining a state named '@inherit'.\n '@inherit',\n]);\n\nconst PREDEFINED_STATE_NAME_PATTERN = /^@[A-Za-z][A-Za-z0-9-]*$/;\n\nfunction isReservedStateName(name: string): boolean {\n return (\n name === '@media' ||\n name === '@root' ||\n name === '@parent' ||\n name === '@own'\n );\n}\n\n// Global predefined states storage\nlet globalPredefinedStates: Record<string, string> = {};\n\n// Warnings tracking to avoid duplicates\nconst emittedWarnings = new Set<string>();\n\nconst devMode = isDevEnv();\n\n/**\n * Emit a warning only once\n */\nfunction warnOnce(key: string, message: string): void {\n if (devMode && !emittedWarnings.has(key)) {\n emittedWarnings.add(key);\n console.warn(message);\n }\n}\n\n/**\n * Configure global predefined states\n */\nexport function setGlobalPredefinedStates(\n states: Record<string, string>,\n): void {\n if (hasStylesGenerated()) {\n const newStateNames = Object.keys(states).join(', ');\n warnOnce(\n `dynamic-states:${newStateNames}`,\n `[Tasty] Cannot update predefined states after styles have been generated.\\n` +\n `The new definition(s) for ${newStateNames} will be ignored.`,\n );\n return;\n }\n\n // Validate state names\n for (const name of Object.keys(states)) {\n const value = states[name];\n\n // Check for valid name format\n if (!PREDEFINED_STATE_NAME_PATTERN.test(name)) {\n warnOnce(\n `invalid-state-name:${name}`,\n `[Tasty] Invalid predefined state name '${name}'. Must start with '@' followed by a letter.`,\n );\n continue;\n }\n\n // Check for reserved names\n if (BUILTIN_STATES.has(name)) {\n warnOnce(\n `reserved-state:${name}`,\n `[Tasty] Cannot define predefined state '${name}'. This name is reserved for built-in functionality.`,\n );\n continue;\n }\n\n // Reserve bare built-in function names without blocking user-defined names\n // that merely share their prefixes (for example, @media-query).\n if (isReservedStateName(name)) {\n warnOnce(\n `reserved-prefix:${name}`,\n `[Tasty] Cannot define predefined state '${name}'. This prefix is reserved for built-in functionality.`,\n );\n continue;\n }\n\n // Check for cross-references\n const crossRefs = extractPredefinedStateRefs(value);\n if (crossRefs.length > 0) {\n warnOnce(\n `cross-ref:${name}`,\n `[Tasty] Predefined state '${name}' references another predefined state '${crossRefs[0]}'.\\n` +\n `Predefined states cannot reference each other. Use the full definition instead.`,\n );\n continue;\n }\n\n // Check for duplicates\n if (\n globalPredefinedStates[name] &&\n globalPredefinedStates[name] !== value\n ) {\n warnOnce(\n `duplicate-state:${name}`,\n `[Tasty] Duplicate predefined state '${name}' in configure(). The last definition will be used.`,\n );\n }\n\n globalPredefinedStates[name] = value;\n }\n}\n\n/**\n * Get global predefined states\n */\nexport function getGlobalPredefinedStates(): Record<string, string> {\n return globalPredefinedStates;\n}\n\n/**\n * Clear global predefined states (for testing only)\n */\nexport function clearGlobalPredefinedStates(): void {\n globalPredefinedStates = {};\n emittedWarnings.clear();\n}\n\n/**\n * Regex to match predefined state references in a string\n * Matches @name that is NOT followed by ( or : and is a complete word\n * Uses word boundary and negative lookahead\n */\nconst PREDEFINED_STATE_PATTERN = /@[A-Za-z][A-Za-z0-9-]*(?![A-Za-z0-9-:(])/g;\n\n/**\n * Extract predefined state references from a string\n */\nexport function extractPredefinedStateRefs(value: string): string[] {\n const matches = value.match(PREDEFINED_STATE_PATTERN);\n if (!matches) return [];\n\n const refs: string[] = [];\n\n for (const stateName of matches) {\n // Skip built-in states (@starting) and duplicates\n // Note: @media, @root, @own are always followed by '(' so the regex\n // negative lookahead (?![A-Za-z0-9-:(]) already excludes them\n if (!BUILTIN_STATES.has(stateName) && !refs.includes(stateName)) {\n refs.push(stateName);\n }\n }\n\n return refs;\n}\n\n/**\n * Check if a state key is a predefined state reference\n */\nexport function isPredefinedStateRef(stateKey: string): boolean {\n return (\n PREDEFINED_STATE_NAME_PATTERN.test(stateKey) &&\n !BUILTIN_STATES.has(stateKey) &&\n !isReservedStateName(stateKey)\n );\n}\n\nconst _localStatesCache = new WeakMap<object, Record<string, string>>();\n\n/**\n * Extract local predefined states from a styles object\n * Local predefined states are top-level keys starting with @ that have string values\n * and are valid predefined state names (not built-in like @media, @root, etc.)\n *\n * Results are cached by object identity via WeakMap since the same styles object\n * is passed to this function multiple times per pipeline run (once per chunk\n * in renderStylesForChunk and generateChunkCacheKey).\n */\nexport function extractLocalPredefinedStates(\n styles: Styles,\n): Record<string, string> {\n if (!styles || typeof styles !== 'object') {\n return {};\n }\n\n const cached = _localStatesCache.get(styles as object);\n if (cached !== undefined) return cached;\n\n const localStates: Record<string, string> = {};\n\n for (const key of Object.keys(styles)) {\n const value = styles[key];\n\n if (\n typeof value !== 'string' ||\n key[0] !== '@' ||\n !PREDEFINED_STATE_NAME_PATTERN.test(key) ||\n BUILTIN_STATES.has(key) ||\n isReservedStateName(key)\n ) {\n continue;\n }\n\n // Check for cross-references (predefined states cannot reference each other)\n const crossRefs = extractPredefinedStateRefs(value);\n if (crossRefs.length > 0) {\n warnOnce(\n `local-cross-ref:${key}`,\n `[Tasty] Predefined state '${key}' references another predefined state '${crossRefs[0]}'.\\n` +\n `Predefined states cannot reference each other. Use the full definition instead.`,\n );\n continue;\n }\n\n localStates[key] = value;\n }\n\n _localStatesCache.set(styles as object, localStates);\n\n return localStates;\n}\n\n/**\n * Create a state parser context from styles\n */\nexport function createStateParserContext(\n styles?: Styles,\n isSubElement?: boolean,\n): StateParserContext {\n const localStates = styles ? extractLocalPredefinedStates(styles) : {};\n\n return {\n localPredefinedStates: localStates,\n globalPredefinedStates,\n isSubElement,\n };\n}\n\n/**\n * Resolve a predefined state reference to its value\n * Returns the resolved value or null if not found\n */\nexport function resolvePredefinedState(\n stateKey: string,\n ctx: StateParserContext,\n): string | null {\n // Check local first (higher priority), then global.\n const resolved =\n ctx.localPredefinedStates[stateKey] || ctx.globalPredefinedStates[stateKey];\n if (resolved) return resolved;\n\n // Not found - emit warning\n warnOnce(\n `undefined-state:${stateKey}`,\n `[Tasty] Undefined predefined state '${stateKey}'.\\n` +\n `Define it in configure({ states: { '${stateKey}': '...' } }) or in the component's styles.`,\n );\n\n return null;\n}\n\n/**\n * Normalize state key by trimming whitespace and removing trailing/leading operators\n */\nexport function normalizeStateKey(stateKey: string): {\n key: string;\n warnings: string[];\n} {\n const warnings: string[] = [];\n let key = stateKey;\n\n // Check for whitespace-only\n if (key.trim() === '') {\n if (key !== '') {\n warnings.push(\n `[Tasty] Whitespace-only state key normalized to default state ''.`,\n );\n }\n return { key: '', warnings };\n }\n\n // Trim whitespace\n key = key.trim();\n\n // Remove trailing operators\n const trailingOpMatch = key.match(/\\s*[&|^]\\s*$/);\n if (trailingOpMatch) {\n const originalKey = key;\n key = key.slice(0, -trailingOpMatch[0].length).trim();\n warnings.push(\n `[Tasty] State key '${originalKey}' has trailing operator. Normalized to '${key}'.`,\n );\n }\n\n // Remove leading operators (except !)\n const leadingOpMatch = key.match(/^\\s*[&|^]\\s*/);\n if (leadingOpMatch) {\n const originalKey = key;\n key = key.slice(leadingOpMatch[0].length).trim();\n warnings.push(\n `[Tasty] State key '${originalKey}' has leading operator. Normalized to '${key}'.`,\n );\n }\n\n return { key, warnings };\n}\n\n/**\n * Expand dimension shorthands in a condition string\n * w -> width, h -> height, is -> inline-size, bs -> block-size\n */\nexport function expandDimensionShorthands(condition: string): string {\n return condition.replace(/\\b(?:w|h|is|bs)\\b/g, (dimension) =>\n dimension === 'w'\n ? 'width'\n : dimension === 'h'\n ? 'height'\n : dimension === 'is'\n ? 'inline-size'\n : 'block-size',\n );\n}\n\n/**\n * Convert tasty units in a string (e.g., 40x -> calc(var(--gap) * 40))\n */\nexport function expandTastyUnits(value: string): string {\n // Match number followed by 'x' unit (tasty gap unit)\n return value.replace(\n /(\\d+(?:\\.\\d+)?)\\s*x\\b/g,\n (_, num) => `calc(var(--gap) * ${num})`,\n );\n}\n\n/**\n * Parse an advanced state key and return its type and components\n */\nexport function parseAdvancedState(\n stateKey: string,\n ctx: StateParserContext,\n): ParsedAdvancedState {\n const raw = stateKey;\n\n // Check for @starting (exact match)\n if (stateKey === '@starting') {\n return {\n type: 'starting',\n condition: '',\n raw,\n };\n }\n\n // Check for @media:type (e.g., @media:print)\n if (stateKey.startsWith('@media:')) {\n const mediaType = stateKey.slice(7); // Remove '@media:'\n if (!['all', 'screen', 'print', 'speech'].includes(mediaType)) {\n warnOnce(\n `unknown-media-type:${mediaType}`,\n `[Tasty] Unknown media type '${mediaType}'. Valid types: all, screen, print, speech.`,\n );\n }\n return {\n type: 'media',\n condition: '',\n mediaType,\n raw,\n };\n }\n\n // Check for @media(...) - media query with condition\n if (stateKey.startsWith('@media(')) {\n const endParen = findMatchingParen(stateKey, 6);\n if (endParen === -1) {\n warnOnce(\n `unclosed-media:${stateKey}`,\n `[Tasty] Unclosed media query '${stateKey}'. Missing closing parenthesis.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n let condition = stateKey.slice(7, endParen);\n\n // Check for empty condition\n if (!condition.trim()) {\n warnOnce(\n `empty-media:${stateKey}`,\n `[Tasty] Empty media query condition '${stateKey}'.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n // Expand shorthands and units\n condition = expandDimensionShorthands(condition);\n condition = expandTastyUnits(condition);\n\n return {\n type: 'media',\n condition,\n raw,\n };\n }\n\n // Check for @root(...) - root state\n if (stateKey.startsWith('@root(')) {\n const endParen = findMatchingParen(stateKey, 5);\n if (endParen === -1) {\n warnOnce(\n `unclosed-root:${stateKey}`,\n `[Tasty] Unclosed root state '${stateKey}'. Missing closing parenthesis.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n const condition = stateKey.slice(6, endParen);\n\n if (!condition.trim()) {\n warnOnce(\n `empty-root:${stateKey}`,\n `[Tasty] Empty root state condition '${stateKey}'.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n return {\n type: 'root',\n condition,\n raw,\n };\n }\n\n // Check for @parent(...) - parent element state\n if (stateKey.startsWith('@parent(')) {\n const endParen = findMatchingParen(stateKey, 7);\n if (endParen === -1) {\n warnOnce(\n `unclosed-parent:${stateKey}`,\n `[Tasty] Unclosed parent state '${stateKey}'. Missing closing parenthesis.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n const condition = stateKey.slice(8, endParen);\n\n if (!condition.trim()) {\n warnOnce(\n `empty-parent:${stateKey}`,\n `[Tasty] Empty parent state condition '${stateKey}'.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n return {\n type: 'parent',\n condition,\n raw,\n };\n }\n\n // Check for @own(...) - sub-element own state\n if (stateKey.startsWith('@own(')) {\n const endParen = findMatchingParen(stateKey, 4);\n if (endParen === -1) {\n warnOnce(\n `unclosed-own:${stateKey}`,\n `[Tasty] Unclosed own state '${stateKey}'. Missing closing parenthesis.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n const condition = stateKey.slice(5, endParen);\n\n if (!condition.trim()) {\n warnOnce(\n `empty-own:${stateKey}`,\n `[Tasty] Empty own state condition '${stateKey}'.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n // Check if used outside sub-element context\n if (!ctx.isSubElement) {\n warnOnce(\n `own-outside-subelement:${stateKey}`,\n `[Tasty] @own(${condition}) used outside sub-element context.\\n` +\n `@own() is equivalent to '${condition}' at the root level. ` +\n `Did you mean to use it inside a sub-element?`,\n );\n // Treat as regular modifier\n return {\n type: 'modifier',\n condition,\n raw,\n };\n }\n\n return {\n type: 'own',\n condition,\n raw,\n };\n }\n\n // Check for @(...) - container query (unnamed or named)\n if (stateKey.startsWith('@(')) {\n const endParen = findMatchingParen(stateKey, 1);\n if (endParen === -1) {\n warnOnce(\n `unclosed-container:${stateKey}`,\n `[Tasty] Unclosed container query '${stateKey}'. Missing closing parenthesis.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n const content = stateKey.slice(2, endParen);\n\n if (!content.trim()) {\n warnOnce(\n `empty-container:${stateKey}`,\n `[Tasty] Empty container query '${stateKey}'.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n\n // Check if named container (first token is name, followed by comma)\n // Use parentheses-aware comma search so inner commas (e.g., scroll-state(a, b)) are skipped\n const commaIndex = findTopLevelComma(content);\n let containerName: string | undefined;\n let condition: string;\n\n if (commaIndex !== -1) {\n // Named container: @(layout, w < 600px)\n containerName = content.slice(0, commaIndex).trim();\n condition = content.slice(commaIndex + 1).trim();\n } else {\n // Unnamed container: @(w < 600px)\n condition = content.trim();\n }\n\n // Check for style query shorthand (starts with $)\n if (condition.startsWith('$')) {\n // Style query: @(layout, $compact) or @(layout, $variant=compact)\n const styleCondition = parseStyleQuery(condition);\n if (!styleCondition) {\n warnOnce(\n `invalid-style-query:${stateKey}`,\n `[Tasty] Invalid style query '${condition}' in container query.`,\n );\n return { type: 'modifier', condition: stateKey, raw };\n }\n condition = styleCondition;\n } else if (/^[a-zA-Z][\\w-]*\\s*\\(/.test(condition)) {\n // Function-like syntax: scroll-state(...), style(...), etc.\n // Pass through verbatim — no dimension expansion needed\n } else {\n // Dimension query - expand shorthands and units\n condition = expandDimensionShorthands(condition);\n condition = expandTastyUnits(condition);\n }\n\n return {\n type: 'container',\n condition,\n containerName,\n raw,\n };\n }\n\n // Check for predefined state reference\n if (isPredefinedStateRef(stateKey)) {\n const resolved = resolvePredefinedState(stateKey, ctx);\n if (resolved) {\n // Recursively parse the resolved value to extract the actual state type\n // (e.g., @mobile -> @media(w < 768px) should become a media state)\n const parsedResolved = parseAdvancedState(resolved, ctx);\n return {\n ...parsedResolved,\n raw, // Keep original raw for traceability\n };\n }\n // If not resolved, treat as modifier (will likely produce invalid CSS)\n return {\n type: 'modifier',\n condition: stateKey,\n raw,\n };\n }\n\n // Regular modifier (boolean mod, pseudo-class, class, attribute)\n return {\n type: 'modifier',\n condition: stateKey,\n raw,\n };\n}\n\n/**\n * Parse a style query condition (e.g., $compact, $variant=compact, $variant=\"very compact\")\n */\nfunction parseStyleQuery(condition: string): string | null {\n // Remove $ prefix\n const query = condition.slice(1);\n\n // Check for comparison operators (not supported)\n if (/[<>]/.test(query)) {\n warnOnce(\n `style-query-comparison:${condition}`,\n `[Tasty] Style queries only support equality. '${condition}' is invalid. Use '${condition.split(/[<>]/)[0]}=...' instead.`,\n );\n return null;\n }\n\n // Check for equality\n const eqIndex = query.indexOf('=');\n if (eqIndex === -1) {\n // Just existence check: style(--compact)\n return `style(--${query})`;\n }\n\n const propName = query.slice(0, eqIndex).trim();\n let value = query.slice(eqIndex + 1).trim();\n\n // Handle quoted values\n if (\n (value.startsWith('\"') && value.endsWith('\"')) ||\n (value.startsWith(\"'\") && value.endsWith(\"'\"))\n ) {\n // Keep quotes for CSS\n } else {\n // Add quotes if needed\n value = `\"${value}\"`;\n }\n\n // Expand tasty units in value\n value = expandTastyUnits(value);\n\n return `style(--${propName}: ${value})`;\n}\n\n/**\n * Find the index of the first comma at parentheses depth 0.\n * Returns -1 if no top-level comma is found.\n * This prevents splitting on commas inside function calls like scroll-state(a, b).\n */\nexport function findTopLevelComma(s: string): number {\n let depth = 0;\n\n for (let i = 0; i < s.length; i++) {\n if (s[i] === '(') depth++;\n else if (s[i] === ')') depth--;\n else if (s[i] === ',' && depth === 0) return i;\n }\n\n return -1;\n}\n\nfunction findMatchingParen(str: string, startIndex: number): number {\n let depth = 1;\n let i = startIndex + 1;\n\n while (i < str.length && depth > 0) {\n if (str[i] === '(') depth++;\n else if (str[i] === ')') depth--;\n i++;\n }\n\n return depth === 0 ? i - 1 : -1;\n}\n\n/**\n * Check if a state key is an advanced state (starts with @)\n */\nexport function isAdvancedState(stateKey: string): boolean {\n return stateKey.startsWith('@') || stateKey.startsWith('!@');\n}\n","/** Data-only logical style families shared by handlers, public lists, and chunks. */\n\nexport const BLOCK_SIZE_STYLES = [\n 'blockSize',\n 'minBlockSize',\n 'maxBlockSize',\n] as const;\n\nexport const INLINE_SIZE_STYLES = [\n 'inlineSize',\n 'minInlineSize',\n 'maxInlineSize',\n] as const;\n\n/** Enhanced logical size categories exposed by Tasty's public style lists. */\nexport const LOGICAL_SIZE_STYLES = ['blockSize', 'inlineSize'] as const;\n\n/** Every input consumed by the two logical size handlers. */\nexport const LOGICAL_SIZE_HANDLER_STYLES = [\n ...BLOCK_SIZE_STYLES,\n ...INLINE_SIZE_STYLES,\n] as const;\n\nexport const LOGICAL_PADDING_STYLES = [\n 'blockPadding',\n 'inlinePadding',\n] as const;\n\nexport const LOGICAL_MARGIN_STYLES = ['blockMargin', 'inlineMargin'] as const;\n\nexport const LOGICAL_INSET_STYLES = ['blockInset', 'inlineInset'] as const;\n\nexport const LOGICAL_SCROLL_MARGIN_STYLES = [\n 'blockScrollMargin',\n 'inlineScrollMargin',\n] as const;\n\nexport const LOGICAL_SCROLL_PADDING_STYLES = [\n 'blockScrollPadding',\n 'inlineScrollPadding',\n] as const;\n\nexport const LOGICAL_BORDER_STYLES = ['blockBorder', 'inlineBorder'] as const;\n","import {\n LOGICAL_BORDER_STYLES,\n LOGICAL_INSET_STYLES,\n LOGICAL_MARGIN_STYLES,\n LOGICAL_PADDING_STYLES,\n LOGICAL_SCROLL_MARGIN_STYLES,\n LOGICAL_SCROLL_PADDING_STYLES,\n LOGICAL_SIZE_HANDLER_STYLES,\n} from '../styles/logical-list';\n\n/**\n * Chunk names, the built-in chunk style lists, and the style→chunk lookup.\n *\n * This module only imports data-only style-name lists. It exists separately\n * from `definitions.ts` for two reasons:\n *\n * 1. The style handler registry (`styles/predefined.ts`) needs to assign chunk\n * membership for custom handlers. Reaching for `definitions.ts` would create an\n * import cycle (`definitions` -> `pipeline` -> `styles` -> `predefined`).\n * 2. `STYLE_TO_CHUNK` is populated as a side effect of module load, so it must be\n * populated by the module that *owns* it. Otherwise an importer that only pulls\n * in this module would see an empty map and misclassify every style as `misc`.\n *\n * `definitions.ts` re-exports everything here, so existing import paths and the\n * public API surface are unchanged.\n */\n\nexport const CHUNK_NAMES = {\n /** Special chunk for styles that cannot be split */\n COMBINED: 'combined',\n SUBCOMPONENTS: 'subcomponents',\n APPEARANCE: 'appearance',\n FONT: 'font',\n DIMENSION: 'dimension',\n DISPLAY: 'display',\n LAYOUT: 'layout',\n POSITION: 'position',\n MISC: 'misc',\n} as const;\n\nexport type ChunkName = (typeof CHUNK_NAMES)[keyof typeof CHUNK_NAMES];\n\n// ============================================================================\n// Built-in Chunk Style Lists\n// ============================================================================\n\n/**\n * Appearance chunk - visual styling with independent handlers\n *\n * @public\n */\nexport const APPEARANCE_CHUNK_STYLES = [\n 'fill', // fillStyle (independent)\n 'color', // colorStyle (independent)\n 'opacity', // independent\n 'border', // borderStyle (independent)\n ...LOGICAL_BORDER_STYLES,\n 'radius', // radiusStyle (independent)\n 'outline', // outlineStyle: outline ↔ outlineOffset\n 'outlineOffset', // outlineStyle: outline ↔ outlineOffset\n 'shadow', // shadowStyle (independent)\n 'fade', // fadeStyle (independent)\n] as const;\n\n/**\n * Font chunk - typography styles\n *\n * Handler dependencies (all styles in each handler MUST stay in this chunk):\n * ⚠️ presetStyle: preset, fontSize, lineHeight, letterSpacing, textTransform,\n * fontWeight, fontStyle, font\n */\n/** @public */\nexport const FONT_CHUNK_STYLES = [\n // All from presetStyle handler - MUST stay together\n 'preset',\n 'font',\n 'fontWeight',\n 'fontStyle',\n 'fontSize',\n 'lineHeight',\n 'letterSpacing',\n 'textTransform',\n // Independent text styles grouped for cohesion\n 'fontFamily', // independent alias (logical grouping with font styles)\n 'textAlign',\n 'textDecoration',\n 'wordBreak',\n 'wordWrap',\n 'boldFontWeight',\n] as const;\n\n/**\n * Dimension chunk - sizing and spacing\n *\n * Handler dependencies (all styles in each handler MUST stay in this chunk):\n * ⚠️ paddingStyle: padding, paddingTop/Right/Bottom/Left\n * ⚠️ marginStyle: margin, marginTop/Right/Bottom/Left\n * ⚠️ widthStyle: width, minWidth, maxWidth\n * ⚠️ heightStyle: height, minHeight, maxHeight\n * ⚠️ blockSizeStyle: blockSize, minBlockSize, maxBlockSize\n * ⚠️ inlineSizeStyle: inlineSize, minInlineSize, maxInlineSize\n */\n/** @public */\nexport const DIMENSION_CHUNK_STYLES = [\n // Physical and logical padding handlers\n 'padding',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n ...LOGICAL_PADDING_STYLES,\n // Physical and logical margin handlers\n 'margin',\n 'marginTop',\n 'marginRight',\n 'marginBottom',\n 'marginLeft',\n ...LOGICAL_MARGIN_STYLES,\n // widthStyle handler - MUST stay together\n 'width',\n 'minWidth',\n 'maxWidth',\n // heightStyle handler - MUST stay together\n 'height',\n 'minHeight',\n 'maxHeight',\n ...LOGICAL_SIZE_HANDLER_STYLES,\n 'flexBasis',\n 'flexGrow',\n 'flexShrink',\n 'flex',\n] as const;\n\n/**\n * Display chunk - display mode, layout flow, text overflow, and scrollbar\n *\n * Handler dependencies (all styles in each handler MUST stay in this chunk):\n * ⚠️ displayStyle: display, hide, textOverflow, overflow, whiteSpace\n * ⚠️ flowStyle: display, flow\n * ⚠️ gapStyle: display, flow, gap\n * ⚠️ scrollbarStyle: scrollbar, overflow\n */\n/** @public */\nexport const DISPLAY_CHUNK_STYLES = [\n // displayStyle handler\n 'display',\n 'hide',\n 'textOverflow',\n 'overflow', // also used by scrollbarStyle\n 'whiteSpace',\n // flowStyle handler (requires display)\n 'flow',\n // gapStyle handler (requires display, flow)\n 'gap',\n // scrollbarStyle handler (requires overflow)\n 'scrollbar',\n] as const;\n\n/**\n * Layout chunk - flex/grid alignment and grid templates\n *\n * Note: flow and gap are in DISPLAY chunk due to handler dependencies\n * (flowStyle and gapStyle both require 'display' prop).\n */\n/** @public */\nexport const LAYOUT_CHUNK_STYLES = [\n // Alignment styles (all independent handlers)\n 'placeItems',\n 'placeContent',\n 'alignItems',\n 'alignContent',\n 'justifyItems',\n 'justifyContent',\n 'align', // placementStyle\n 'justify', // placementStyle\n 'place', // placementStyle\n 'columnGap',\n 'rowGap',\n // Grid template styles\n 'gridColumns',\n 'gridRows',\n 'gridTemplate',\n 'gridAreas',\n 'gridAutoFlow',\n 'gridAutoColumns',\n 'gridAutoRows',\n] as const;\n\n/**\n * Position chunk - element positioning\n *\n * Handler dependencies (all styles in each handler MUST stay in this chunk):\n * ⚠️ insetStyle: inset, top, right, bottom, left\n */\n/** @public */\nexport const POSITION_CHUNK_STYLES = [\n 'position',\n // Physical and logical inset handlers\n 'inset',\n ...LOGICAL_INSET_STYLES,\n 'top',\n 'right',\n 'bottom',\n 'left',\n // Logical scroll offsets stay separate from the physical handlers\n ...LOGICAL_SCROLL_MARGIN_STYLES,\n ...LOGICAL_SCROLL_PADDING_STYLES,\n 'zIndex',\n 'gridArea',\n 'gridColumn',\n 'gridRow',\n 'order',\n 'placeSelf',\n 'alignSelf',\n 'justifySelf',\n 'transform',\n 'transition',\n 'animation',\n] as const;\n\n// ============================================================================\n// Style-to-Chunk Lookup Map (O(1) categorization)\n// ============================================================================\n\n/**\n * Map for O(1) style-to-chunk lookup. Seeded with the built-in lists above and\n * extended by {@link assignStyleChunk} when a custom handler declares style names\n * the built-in lists don't know.\n */\nexport const STYLE_TO_CHUNK = new Map<string, ChunkName>();\n\n/** Built-in assignments, captured so `resetStyleChunks()` can restore them. */\nlet builtinSnapshot: Map<string, ChunkName> | null = null;\n\nfunction populateStyleToChunkMap(): void {\n for (const style of APPEARANCE_CHUNK_STYLES) {\n STYLE_TO_CHUNK.set(style, CHUNK_NAMES.APPEARANCE);\n }\n for (const style of FONT_CHUNK_STYLES) {\n STYLE_TO_CHUNK.set(style, CHUNK_NAMES.FONT);\n }\n for (const style of DIMENSION_CHUNK_STYLES) {\n STYLE_TO_CHUNK.set(style, CHUNK_NAMES.DIMENSION);\n }\n for (const style of DISPLAY_CHUNK_STYLES) {\n STYLE_TO_CHUNK.set(style, CHUNK_NAMES.DISPLAY);\n }\n for (const style of LAYOUT_CHUNK_STYLES) {\n STYLE_TO_CHUNK.set(style, CHUNK_NAMES.LAYOUT);\n }\n for (const style of POSITION_CHUNK_STYLES) {\n STYLE_TO_CHUNK.set(style, CHUNK_NAMES.POSITION);\n }\n}\n\n// Populate at module load and record the result as the baseline that\n// resetStyleChunks() restores.\npopulateStyleToChunkMap();\nbuiltinSnapshot = new Map(STYLE_TO_CHUNK);\n\n/**\n * Assign a style name to a chunk.\n *\n * Used to keep a custom handler's dependencies in one chunk: chunks are rendered\n * and cached independently, and a chunk's cache key covers only its own style\n * values, so a handler whose `__lookupStyles` straddle two chunks is invoked once\n * per chunk with a subset of its inputs and can emit stale CSS.\n */\nexport function assignStyleChunk(styleName: string, chunk: ChunkName): void {\n STYLE_TO_CHUNK.set(styleName, chunk);\n}\n\n/**\n * Drop custom chunk assignments and restore the built-in baseline.\n *\n * Called by `resetConfig()`. Without this, a custom handler's chunk assignments\n * would leak across tests the same way custom handlers themselves did before\n * `resetHandlers()` existed.\n *\n * @internal\n */\nexport function resetStyleChunks(): void {\n if (!builtinSnapshot) return;\n\n STYLE_TO_CHUNK.clear();\n\n for (const [style, chunk] of builtinSnapshot) {\n STYLE_TO_CHUNK.set(style, chunk);\n }\n}\n","export const BORDER_STYLES = [\n 'none',\n 'hidden',\n 'dotted',\n 'dashed',\n 'solid',\n 'double',\n 'groove',\n 'ridge',\n 'inset',\n 'outset',\n] as const;\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport type { StyleDetails } from '../parser/types';\nimport { warnOnceDev } from '../utils/warnings';\n\n/**\n * If the group contains exactly one value that is a CSS-wide keyword\n * and no colors, return the keyword. Otherwise null.\n *\n * Direction mods (top/right/bottom/left) may coexist with the keyword\n * for directional application like `padding=\"inherit top\"`.\n */\nexport function extractCSSWideKeyword(group: StyleDetails): string | null {\n if (group.values.length !== 1 || group.colors.length > 0) return null;\n return CSS_WIDE_KEYWORDS.has(group.values[0]) ? group.values[0] : null;\n}\n\n/** A resolved custom-property reference, i.e. `var(--name)` or `var(--name, …)`. */\nconst RE_VAR_REFERENCE = /^var\\(/;\n\n/**\n * Assign custom-property references to the style and color slots of a\n * `<line-width> <line-style> <line-color>` shorthand (`border`, `outline`).\n *\n * The parser cannot type a reference, so it buckets `$name` as a plain value and\n * the handler has to place it. A reference fills the first slot still free, in\n * shorthand order: the width takes `values[0]`, then the style, then the color.\n * The style would otherwise arrive as a keyword (`solid`, `dashed`, …) that a\n * reference has no way to match, and the color as `#name` — the `$name-color`\n * form the parser buckets as a color exists to reference a raw CSS custom\n * property, not as the way colors are written, so a reference should not reach\n * for the color slot until the style slot is taken.\n *\n * Lengths are left alone: a second length is not valid in these shorthands, and\n * promoting one would emit an invalid declaration instead of ignoring an extra\n * value. Callers supply their own slot defaults.\n */\nexport function assignLineSlots(\n values: string[],\n styleKeyword: string | undefined,\n colorToken: string | undefined,\n): { style: string | undefined; color: string | undefined } {\n if (styleKeyword && colorToken) {\n return { style: styleKeyword, color: colorToken };\n }\n\n // A `$name-color` reference is filed under both buckets (`Bucket.ColorValue`),\n // so skip the one the color slot already claimed rather than placing it twice.\n const spare = values\n .slice(1)\n .filter((value) => RE_VAR_REFERENCE.test(value) && value !== colorToken);\n\n return {\n style: styleKeyword || spare.shift(),\n color: colorToken || spare.shift(),\n };\n}\n\n/** A resolved custom-property reference anywhere in a token. */\nconst RE_HAS_VAR_REFERENCE = /var\\(/;\n\n/**\n * Reject a custom-property reference used where a *token name* is expected.\n *\n * `preset` and `transition` take the name of a design token (`t3`, `fill`) and\n * interpolate it into a CSS custom property — `var(--t3-font-size)`. A reference\n * substituted into that position builds `var(--var(--x)-font-size)`, which is not\n * a valid custom-property name, so the browser drops the declaration and the\n * style silently does nothing. The DSL has no way to indirect a token name\n * through a custom property: the name is needed at build time, and a reference\n * only resolves in the browser.\n *\n * Returns true (warning once per value in dev) so the caller can fall back\n * instead of emitting a declaration that cannot work.\n */\nexport function isTokenNameReference(property: string, name: string): boolean {\n if (!RE_HAS_VAR_REFERENCE.test(name)) return false;\n\n warnOnceDev(\n `token-name-reference:${property}:${name}`,\n `${property}=\"${name}\": a custom property cannot name a token. The name is ` +\n `interpolated into a CSS custom property at build time, so a reference ` +\n `would build an unusable name. It is ignored.`,\n );\n\n return true;\n}\n\n/**\n * Report a comma group that names direction modifiers together with more values\n * than the group can use.\n *\n * The parser buckets values and modifiers into separate arrays per comma group,\n * so `padding: '2x 4x top right'`, `padding: '2x top 4x right'` and\n * `padding: 'top 2x right 4x'` all reach a handler identically — the pairing a\n * reader infers from source order does not survive parsing. Such a group\n * therefore carries a single value, applied to every direction it names.\n *\n * `maxValues` is 2 only for a span modifier (`inset: '2x 4x bottom dock'`),\n * where the second value insets the sides the dock spans.\n *\n * Callers must guard on the count themselves so the valid path costs one integer\n * comparison; everything expensive happens here, on the misuse path only.\n */\nexport function warnExtraGroupValues(\n property: string,\n input: string,\n maxValues: 1 | 2,\n directionExamples: readonly [string, string] = ['top', 'right'],\n): void {\n const message =\n maxValues === 2\n ? `${property}=\"${input}\": with a span modifier a group takes at most two ` +\n `values — one for the named edge and one for the spanned sides. ` +\n `The extra values are ignored.`\n : `${property}=\"${input}\": a group that names directions takes a single ` +\n `value, applied to every direction it names. The extra values are ` +\n `ignored — use comma-separated groups instead, ` +\n `e.g. ${property}=\"2x ${directionExamples[0]}, 4x ${directionExamples[1]}\".`;\n\n warnOnceDev(`extra-values:${property}:${input}`, message);\n}\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport { DIRECTIONS, parseStyle } from '../utils/styles';\nimport { BORDER_STYLES } from './const';\nimport { assignLineSlots, extractCSSWideKeyword } from './shared';\n\ntype Direction = (typeof DIRECTIONS)[number];\n\ninterface GroupData {\n values: string[];\n mods: string[];\n colors: string[];\n}\n\ninterface BorderValue {\n width: string;\n style: string;\n color: string;\n}\n\ninterface ProcessedBorderGroup extends BorderValue {\n modFlags: number;\n}\n\n/**\n * Process a single group and return its directional flags and border value.\n */\nfunction processGroup(group: GroupData): ProcessedBorderGroup {\n const { values, mods, colors } = group;\n let modFlags = 0;\n let lineStyle: string | undefined;\n\n for (const mod of mods) {\n if (mod === 'top') modFlags |= 1;\n else if (mod === 'right') modFlags |= 2;\n else if (mod === 'bottom') modFlags |= 4;\n else if (mod === 'left') modFlags |= 8;\n else if (mod === 'longhand') modFlags |= 16;\n else if (\n lineStyle === undefined &&\n (BORDER_STYLES as readonly string[]).includes(mod)\n ) {\n lineStyle = mod;\n }\n }\n\n const slots = assignLineSlots(values, lineStyle, colors[0]);\n\n const width = values[0] || 'var(--border-width)';\n const style = slots.style || 'solid';\n const color = slots.color || 'var(--border-color, currentColor)';\n\n return { modFlags, width, style, color };\n}\n\n/**\n * Format a border value to CSS string.\n */\nfunction formatBorderValue(value: BorderValue): string {\n return `${value.width} ${value.style} ${value.color}`;\n}\n\nfunction expandBorder(value: string): Record<string, string> {\n const styles: Record<string, string> = {};\n\n for (const dir of DIRECTIONS) {\n styles[`border-${dir}`] = value;\n }\n\n return styles;\n}\n\n/** Parse one native border declaration without Tasty's physical-side modifiers. */\nexport function parseBorderValue(\n value: string | number | boolean,\n): string | null {\n if (value === false) return null;\n if (value === true) value = '1bw';\n\n const stringValue =\n typeof value === 'number' ? `${value}px` : String(value).trim();\n\n if (!stringValue) return null;\n if (CSS_WIDE_KEYWORDS.has(stringValue)) return stringValue;\n\n const group = parseStyle(stringValue).groups[0];\n if (!group) return null;\n\n const keyword = extractCSSWideKeyword(group);\n if (keyword) return keyword;\n\n return formatBorderValue(processGroup(group));\n}\n\n/**\n * Border style handler with multi-group support.\n *\n * Single group (backward compatible):\n * - `border=\"1bw solid #red\"` - all sides\n * - `border=\"1bw solid #red top left\"` - only top and left\n *\n * Multi-group (new):\n * - `border=\"1bw #red, 2bw #blue top\"` - all sides red 1bw, then top overridden to blue 2bw\n * - `border=\"1bw, dashed top bottom, #purple left right\"` - base 1bw, dashed on top/bottom, purple on left/right\n *\n * Later groups override earlier groups for conflicting directions.\n */\nexport function borderStyle({\n border,\n}: {\n border?: string | number | boolean;\n}) {\n if (!border && border !== 0) return null;\n\n if (border === true) border = '1bw';\n\n const strBorder = String(border);\n\n if (CSS_WIDE_KEYWORDS.has(strBorder)) {\n return { border: strBorder };\n }\n\n const processed = parseStyle(strBorder);\n const groups = processed.groups;\n\n if (!groups.length) return null;\n\n // Single group - use original logic for backward compatibility\n if (groups.length === 1) {\n const group = groups[0];\n const keyword = extractCSSWideKeyword(group);\n\n if (keyword) {\n if (group.mods.includes('longhand')) {\n return expandBorder(keyword);\n }\n\n return { border: keyword };\n }\n\n const borderValue = processGroup(group);\n const { modFlags } = borderValue;\n const directionFlags = modFlags & 15;\n const useLonghand = modFlags & 16;\n\n const styleValue = formatBorderValue(borderValue);\n\n if (!directionFlags) {\n if (useLonghand) {\n return expandBorder(styleValue);\n }\n\n return { border: styleValue };\n }\n\n const zeroValue = `0 ${borderValue.style} ${borderValue.color}`;\n const styles: Record<string, string> = {};\n\n for (let i = 0; i < DIRECTIONS.length; i++) {\n const dir = DIRECTIONS[i];\n styles[`border-${dir}`] =\n directionFlags & (1 << i) ? styleValue : zeroValue;\n }\n\n return styles;\n }\n\n // Multi-group - process groups in order, later groups override earlier\n // Track whether any group specifies directions\n let hasAnyDirections = false;\n let useLonghand = false;\n\n // Build a map of direction -> border value. Missing entries have no border.\n const directionMap: Partial<Record<Direction, BorderValue>> = {};\n\n // Track the last \"all directions\" value for fallback\n let allDirectionsValue: BorderValue | null = null;\n\n // Process groups in order (first to last)\n for (const group of groups) {\n const borderValue = processGroup(group);\n const { modFlags } = borderValue;\n const directionFlags = modFlags & 15;\n if (modFlags & 16) useLonghand = true;\n\n if (!directionFlags) {\n // No specific directions - applies to all\n allDirectionsValue = borderValue;\n // Set all directions\n for (const dir of DIRECTIONS) {\n directionMap[dir] = borderValue;\n }\n } else {\n // Specific directions - override only those\n hasAnyDirections = true;\n for (let i = 0; i < DIRECTIONS.length; i++) {\n if (directionFlags & (1 << i)) {\n directionMap[DIRECTIONS[i]] = borderValue;\n }\n }\n }\n }\n\n // If no group specified any directions and we have an all-directions value,\n // return the simple `border` shorthand (or longhands if requested)\n if (!hasAnyDirections && allDirectionsValue) {\n const formatted = formatBorderValue(allDirectionsValue);\n\n if (useLonghand) {\n return expandBorder(formatted);\n }\n\n return { border: formatted };\n }\n\n // Otherwise, output individual border-* properties\n const result: Record<string, string> = {};\n const fallbackStyle = allDirectionsValue?.style || 'solid';\n const fallbackColor =\n allDirectionsValue?.color || 'var(--border-color, currentColor)';\n\n for (const dir of DIRECTIONS) {\n const value = directionMap[dir];\n if (value) {\n result[`border-${dir}`] = formatBorderValue(value);\n } else {\n // No border for this direction - set to 0\n // Use the last all-directions value for style/color consistency, or defaults\n result[`border-${dir}`] = `0 ${fallbackStyle} ${fallbackColor}`;\n }\n }\n\n return result;\n}\n\nborderStyle.__lookupStyles = ['border'];\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport { makeEmptyDetails } from '../parser/types';\nimport { parseStyle } from '../utils/styles';\n\nconst DEFAULT_MIN_SIZE = 'var(--gap)';\nconst DEFAULT_MAX_SIZE = '100%';\n\n/**\n * Parse a dimension value (string, number, or boolean) into a CSS value\n */\nfunction parseDimensionValue(\n val: string | number | boolean | undefined,\n): string | null {\n if (val == null) return null;\n if (typeof val === 'number') return `${val}px`;\n if (val === true) return 'initial';\n\n const processed = parseStyle(String(val));\n return processed.groups[0]?.values[0] || null;\n}\n\ninterface DimensionProps {\n value?: string | number | boolean;\n min?: string | number | boolean;\n max?: string | number | boolean;\n}\n\n/**\n * Creates a dimension style handler for a physical or logical size.\n *\n * Supports:\n * - Main dimension prop (width/height) with syntax for min/max\n * - Separate min/max props (minWidth/maxWidth or minHeight/maxHeight)\n *\n * Priority: Individual min/max props override values from main prop syntax\n */\nexport function dimensionStyle(\n name: 'width' | 'height' | 'block-size' | 'inline-size',\n) {\n const minStyle = `min-${name}`;\n const maxStyle = `max-${name}`;\n\n return ({ value, min, max }: DimensionProps) => {\n if (value == null && min == null && max == null) return null;\n\n if (\n value != null &&\n typeof value === 'string' &&\n CSS_WIDE_KEYWORDS.has(value)\n ) {\n const styles: Record<string, string> = {\n [name]: value,\n [minStyle]: value,\n [maxStyle]: value,\n };\n\n const minVal = parseDimensionValue(min);\n const maxVal = parseDimensionValue(max);\n if (minVal) styles[minStyle] = minVal;\n if (maxVal) styles[maxStyle] = maxVal;\n\n return styles;\n }\n\n if (value === true) {\n const styles: Record<string, string | string[]> = {\n [name]: 'auto',\n [minStyle]: 'initial',\n [maxStyle]: 'initial',\n };\n\n // Apply individual min/max overrides\n const minVal = parseDimensionValue(min);\n const maxVal = parseDimensionValue(max);\n if (minVal) styles[minStyle] = minVal;\n if (maxVal) styles[maxStyle] = maxVal;\n\n return styles;\n }\n\n const styles: Record<string, string | string[]> = {\n [name]: 'auto',\n [minStyle]: 'initial',\n [maxStyle]: 'initial',\n };\n\n // Process main dimension value\n if (value != null) {\n let val = value;\n if (typeof val === 'number') {\n val = `${val}px`;\n }\n\n val = String(val);\n\n const processed = parseStyle(val);\n const { mods, values } = processed.groups[0] ?? makeEmptyDetails();\n\n let flag = false;\n\n for (const mod of mods) {\n switch (mod) {\n case 'min':\n styles[minStyle] = values[0] || DEFAULT_MIN_SIZE;\n flag = true;\n break;\n case 'max':\n styles[maxStyle] = values[0] || DEFAULT_MAX_SIZE;\n flag = true;\n break;\n case 'fixed': {\n // Fixed modifier: set all three dimensions to the same value\n const fixedValue = values[0] || 'max-content';\n styles[minStyle] = fixedValue;\n styles[name] = fixedValue;\n styles[maxStyle] = fixedValue;\n flag = true;\n break;\n }\n default:\n break;\n }\n }\n\n if (!flag || !mods.length) {\n if (values.length === 2) {\n styles[minStyle] = values[0];\n styles[maxStyle] = values[1];\n } else if (values.length === 3) {\n styles[minStyle] = values[0];\n styles[name] = values[1];\n styles[maxStyle] = values[2];\n } else {\n styles[name] = values[0] || 'auto';\n }\n }\n\n if (styles[name] === 'stretch') {\n if (name === 'width') {\n styles[name] = [\n 'stretch',\n '-webkit-fill-available',\n '-moz-available',\n ];\n } else {\n styles[name] = 'auto';\n }\n }\n }\n\n // Apply individual min/max props (higher priority, override main prop syntax)\n const minVal = parseDimensionValue(min);\n const maxVal = parseDimensionValue(max);\n if (minVal) styles[minStyle] = minVal;\n if (maxVal) styles[maxStyle] = maxVal;\n\n return styles;\n };\n}\n","import { dimensionStyle } from './dimension';\nimport { BLOCK_SIZE_STYLES } from './logical-list';\n\nconst dimension = dimensionStyle('block-size');\n\nexport function blockSizeStyle({\n blockSize,\n minBlockSize,\n maxBlockSize,\n}: {\n blockSize?: string | number | boolean;\n minBlockSize?: string | number | boolean;\n maxBlockSize?: string | number | boolean;\n}) {\n return dimension({\n value: blockSize,\n min: minBlockSize,\n max: maxBlockSize,\n });\n}\n\nblockSizeStyle.__lookupStyles = [...BLOCK_SIZE_STYLES];\n","import { parseColor, resolveCustomProperties } from '../utils/styles';\n\n/**\n * A color that already resolves against the color the element inherits, and so\n * must not be republished as `--current-color`: a descendant reading the\n * variable would resolve it a second time against its own color. Covers the\n * keyword and the variable alike — the latter would also be a self-reference.\n */\nconst RE_READS_CURRENT = /var\\(--current-color[,)]|currentcolor/i;\n\nexport function colorStyle({ color }: { color?: string | boolean }) {\n if (!color) return null;\n\n if (color === true) color = 'currentColor';\n\n // Resolve whatever the parser recognizes as a color — a `#token`, a fallback\n // chain, a color function with tokens inside it. Anything else (a keyword, a\n // bare `$name`) is emitted verbatim, so references still need substituting or\n // the raw DSL leaks into the declaration.\n color = parseColor(color, true).color || resolveCustomProperties(color);\n\n const styles: Record<string, string> = { color };\n\n // Republish the color as `--current-color`, the variable a consumer reads to\n // pick the inherited color up as a *color* rather than as `currentcolor` —\n // usable in hand-authored CSS and anywhere the keyword will not do. `#current`\n // itself does not go through it; the keyword composes and the variable cannot.\n //\n // Every color is published, not only a named token: `color: 'red'` has to\n // displace an ancestor's token color, or a reader below sees the ancestor's.\n //\n // A value that already reads the color it inherits is skipped, because\n // publishing it would resolve it a second time at the descendant — a\n // `color-mix()` over `currentcolor` would fade twice — and `var(--current-color)`\n // into itself is a self-reference that silently drops the declaration.\n if (!RE_READS_CURRENT.test(color)) {\n styles['--current-color'] = color;\n }\n\n return styles;\n}\n\ncolorStyle.__lookupStyles = ['color'];\n","import { normalizeDslName, toSnakeCase } from '../utils/string';\nimport {\n normalizeColorTokenValue,\n parseColor,\n parseStyle,\n} from '../utils/styles';\nimport type {\n CSSMap,\n StyleHandler,\n StyleValue,\n StyleValueStateMap,\n} from '../utils/styles';\n\nconst CACHE: Record<string, StyleHandler> = {};\n\nexport function createStyle(\n styleName: string,\n cssStyle?: string,\n converter?: (styleValue: string | number | true) => string | undefined,\n) {\n const key = `${styleName}.${cssStyle ?? ''}`;\n\n if (!CACHE[key]) {\n const styleHandler = (styleMap: StyleValueStateMap): CSSMap | null => {\n let styleValue = styleMap[styleName];\n\n if (styleValue == null || styleValue === false) return null;\n\n let finalCssStyle: string;\n const isColorToken =\n !cssStyle && typeof styleName === 'string' && styleName.startsWith('#');\n\n if (isColorToken) {\n finalCssStyle = `--${normalizeDslName(styleName.slice(1))}-color`;\n } else if (!cssStyle && styleName[0] === '$') {\n // A `$name` key names a custom property, so it keeps its case rather than\n // being kebab-cased — `$myVar` has to reach the same `--myVar` that\n // `$myVar` in a value references.\n finalCssStyle = `--${normalizeDslName(styleName.slice(1))}`;\n } else {\n finalCssStyle = cssStyle || toSnakeCase(styleName);\n }\n\n if (isColorToken) {\n const normalized = normalizeColorTokenValue(styleValue);\n if (normalized === null) return null;\n styleValue = normalized;\n }\n\n if (converter) {\n const converted = converter(styleValue as string | number | true);\n\n if (converted) {\n styleValue = converted;\n } else if (typeof styleValue !== 'string') {\n // A converter declining a non-string value leaves nothing to emit —\n // `true` and numbers have no meaningful CSS serialization on their\n // own. Strings are already valid CSS, so they pass through untouched.\n return null;\n }\n }\n\n if (\n typeof styleValue === 'string' &&\n finalCssStyle.startsWith('--') &&\n finalCssStyle.endsWith('-color')\n ) {\n styleValue = styleValue.trim();\n\n // The color is emitted as the parser resolved it: a `#token` or fallback\n // chain becomes its `var()` chain, a color function keeps its expanded\n // tokens, a literal or keyword passes through as authored. Nothing needs\n // rewriting into a particular color space — opacity is applied with\n // relative color syntax, which reads the channels off whatever the\n // browser resolves the value to.\n return {\n [finalCssStyle]: parseColor(styleValue as string).color ?? '',\n };\n }\n\n const processed = parseStyle(styleValue as StyleValue);\n return { [finalCssStyle]: processed.output };\n };\n\n styleHandler.__lookupStyles = [styleName];\n\n CACHE[key] = styleHandler;\n }\n\n return CACHE[key];\n}\n","import { parseStyle, resolveCustomProperties } from '../utils/styles';\n\ninterface DisplayStyleProps {\n display?: string;\n hide?: boolean;\n textOverflow?: string | boolean;\n overflow?: string;\n whiteSpace?: string;\n}\n\n/**\n * Process textOverflow into CSS properties for truncation/clamping.\n *\n * - `ellipsis` — single-line truncation with ellipsis\n * - `ellipsis / 3` — multi-line clamping (3 lines) with ellipsis\n * - `clip` — single-line truncation with clip\n * - `clip / 2` — multi-line clip (2 lines)\n * - `true` or `initial` — reset to initial\n */\nfunction applyTextOverflow(\n result: Record<string, string | number>,\n textOverflow: string | boolean,\n whiteSpace?: string,\n): void {\n if (textOverflow === true || textOverflow === 'initial') {\n result['text-overflow'] = 'initial';\n\n return;\n }\n\n const processed = parseStyle(String(textOverflow));\n const group = processed.groups[0];\n\n if (!group) return;\n\n const { parts } = group;\n const modePart = parts[0];\n const clampPart = parts[1];\n\n const hasEllipsis = modePart?.mods.includes('ellipsis');\n const hasClip = modePart?.mods.includes('clip');\n\n if (!hasEllipsis && !hasClip) return;\n\n let clamp = 1;\n\n if (clampPart?.values[0]) {\n const parsed = parseInt(clampPart.values[0], 10);\n\n if (!isNaN(parsed) && parsed > 0) {\n clamp = parsed;\n }\n }\n\n result['overflow'] = 'hidden';\n result['text-overflow'] = hasEllipsis ? 'ellipsis' : 'clip';\n\n if (clamp === 1) {\n result['white-space'] = whiteSpace || 'nowrap';\n } else {\n result['display'] = '-webkit-box';\n result['-webkit-box-orient'] = 'vertical';\n result['-webkit-line-clamp'] = clamp;\n result['line-clamp'] = clamp;\n result['white-space'] = whiteSpace || 'initial';\n }\n}\n\n/**\n * Handles display, hide, textOverflow, overflow, and whiteSpace styles.\n *\n * Priority:\n * 1. `hide` takes precedence (display: none)\n * 2. Multi-line `textOverflow` forces display: -webkit-box\n * 3. Single-line `textOverflow` defaults white-space to nowrap\n * 4. Explicit `whiteSpace` overrides the default from `textOverflow`\n */\nexport function displayStyle({\n display,\n hide,\n textOverflow,\n overflow,\n whiteSpace,\n}: DisplayStyleProps) {\n const result: Record<string, string | number> = {};\n\n // Resolved once up front: `applyTextOverflow` emits `whiteSpace` as the\n // clamp's `white-space` too, so substituting only at the branch below would\n // still leak the raw reference through the truncation path.\n const whiteSpaceValue = whiteSpace\n ? resolveCustomProperties(whiteSpace)\n : whiteSpace;\n\n if (textOverflow != null && textOverflow !== false) {\n applyTextOverflow(result, textOverflow, whiteSpaceValue);\n }\n\n if (overflow && !result['overflow']) {\n result['overflow'] = resolveCustomProperties(overflow);\n }\n if (whiteSpaceValue && !result['white-space']) {\n result['white-space'] = whiteSpaceValue;\n }\n\n if (hide) {\n result['display'] = 'none';\n } else if (!result['display'] && display) {\n result['display'] = resolveCustomProperties(display);\n }\n\n return result['text-overflow'] ||\n result['overflow'] ||\n result['white-space'] ||\n result['display']\n ? result\n : null;\n}\n\ndisplayStyle.__lookupStyles = [\n 'display',\n 'hide',\n 'textOverflow',\n 'overflow',\n 'whiteSpace',\n];\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport type { StyleDetails } from '../parser/types';\nimport { DIRECTIONS, parseStyle } from '../utils/styles';\n\nimport { warnExtraGroupValues } from './shared';\n\n// Positional counterparts to DIRECTIONS: top, right, bottom, left.\nconst GRADIENT_DIRECTIONS = ['to bottom', 'to left', 'to top', 'to right'];\n\n// Default mask colors (standard black with alpha for gradient masks)\nconst DEFAULT_TRANSPARENT_COLOR = 'rgb(0 0 0 / 0)';\nconst DEFAULT_OPAQUE_COLOR = 'rgb(0 0 0 / 1)';\n\n/**\n * Process a single group and append gradient strings for its directions.\n */\nfunction processGroup(\n group: StyleDetails,\n isOnlyGroup: boolean,\n gradients: string[],\n): void {\n const { input, values, mods, colors } = group;\n\n // Extract colors: first = transparent mask color, second = opaque mask color\n const transparentColor = colors[0] || DEFAULT_TRANSPARENT_COLOR;\n const opaqueColor = colors[1] || DEFAULT_OPAQUE_COLOR;\n const firstSize = values.length ? values[0] : 'calc(2 * var(--gap))';\n let namedCount = 0;\n\n // A group that names edges takes a single width, applied to every edge it\n // names — different widths per edge come from comma groups\n // (`fade: '3x top, 1x bottom'`). A group that names none covers all four\n // edges and keeps plain CSS shorthand order, so `fade: '3x 1x'` fades block\n // edges at 3x and inline edges at 1x, matching `padding`.\n for (const mod of mods) {\n const directionIndex = DIRECTIONS.indexOf(mod);\n if (directionIndex === -1) continue;\n\n if (namedCount++ === 0 && values.length > 1) {\n warnExtraGroupValues('fade', input, 1);\n }\n\n gradients.push(\n `linear-gradient(${GRADIENT_DIRECTIONS[directionIndex]}, ${transparentColor} 0%, ${opaqueColor} ${firstSize})`,\n );\n }\n\n if (namedCount || !isOnlyGroup) return;\n\n // If this is the only group and no directions are specified, apply it to\n // every edge in CSS shorthand order.\n for (let i = 0; i < DIRECTIONS.length; i++) {\n const size = values.length\n ? values[i] || values[i % 2] || values[0]\n : firstSize;\n\n gradients.push(\n `linear-gradient(${GRADIENT_DIRECTIONS[i]}, ${transparentColor} 0%, ${opaqueColor} ${size})`,\n );\n }\n}\n\nexport function fadeStyle({ fade }: { fade?: string }) {\n if (!fade) return null;\n\n if (CSS_WIDE_KEYWORDS.has(fade)) {\n return { mask: fade, 'mask-composite': fade };\n }\n\n const groups = parseStyle(fade).groups;\n\n if (!groups.length) return null;\n\n const isOnlyGroup = groups.length === 1;\n\n // Process all groups and collect gradients\n const gradients: string[] = [];\n\n for (const group of groups) {\n processGroup(group, isOnlyGroup, gradients);\n }\n\n if (!gradients.length) return null;\n\n return {\n mask: gradients.join(', '),\n 'mask-composite': 'intersect',\n };\n}\n\nfadeStyle.__lookupStyles = ['fade'];\n","import { parseStyle, resolveCustomProperties } from '../utils/styles';\n\nexport function fillStyle({\n fill,\n backgroundColor,\n image,\n backgroundImage,\n backgroundPosition,\n backgroundSize,\n backgroundRepeat,\n backgroundAttachment,\n backgroundOrigin,\n backgroundClip,\n background,\n}: {\n fill?: string;\n backgroundColor?: string;\n image?: string;\n backgroundImage?: string;\n backgroundPosition?: string;\n backgroundSize?: string;\n backgroundRepeat?: string;\n backgroundAttachment?: string;\n backgroundOrigin?: string;\n backgroundClip?: string;\n background?: string;\n}) {\n // If background is set, it overrides everything\n if (background) {\n const processed = parseStyle(background);\n return { background: processed.output || background };\n }\n\n const result: Record<string, string> = {};\n\n // Priority: backgroundColor > fill\n const colorValue = backgroundColor ?? fill;\n if (colorValue) {\n const parsed = parseStyle(colorValue);\n const firstColor = parsed.groups[0]?.colors[0];\n const secondColor = parsed.groups[0]?.colors[1];\n\n // No color found: the value may still be a custom-property reference the\n // parser classified as a plain value (`$name` is a color only when the name\n // ends with `-color`), so substitute before falling back to the raw input.\n result['background-color'] =\n firstColor || resolveCustomProperties(colorValue);\n\n if (secondColor) {\n result['--tasty-second-fill-color'] = secondColor;\n }\n }\n\n const gradientLayer = result['--tasty-second-fill-color']\n ? 'linear-gradient(var(--tasty-second-fill-color), var(--tasty-second-fill-color))'\n : null;\n\n // Priority: backgroundImage > image\n const imageValue = backgroundImage ?? image;\n if (imageValue) {\n const parsed = parseStyle(imageValue);\n const imgCss = parsed.output || imageValue;\n\n result['background-image'] = gradientLayer\n ? `${imgCss}, ${gradientLayer}`\n : imgCss;\n } else if (gradientLayer) {\n result['background-image'] = gradientLayer;\n }\n\n // Other background properties (pass through with parseStyle for token support)\n if (backgroundPosition) {\n result['background-position'] =\n parseStyle(backgroundPosition).output || backgroundPosition;\n }\n if (backgroundSize) {\n result['background-size'] =\n parseStyle(backgroundSize).output || backgroundSize;\n }\n if (backgroundRepeat) {\n result['background-repeat'] = resolveCustomProperties(backgroundRepeat);\n }\n if (backgroundAttachment) {\n result['background-attachment'] =\n resolveCustomProperties(backgroundAttachment);\n }\n if (backgroundOrigin) {\n result['background-origin'] = resolveCustomProperties(backgroundOrigin);\n }\n if (backgroundClip) {\n result['background-clip'] = resolveCustomProperties(backgroundClip);\n }\n\n if (Object.keys(result).length === 0) return null;\n return result;\n}\n\nfillStyle.__lookupStyles = [\n 'fill',\n 'backgroundColor',\n 'image',\n 'backgroundImage',\n 'backgroundPosition',\n 'backgroundSize',\n 'backgroundRepeat',\n 'backgroundAttachment',\n 'backgroundOrigin',\n 'backgroundClip',\n 'background',\n];\n\nexport function svgFillStyle({ svgFill }: { svgFill?: string }) {\n if (!svgFill) return null;\n\n const processed = parseStyle(svgFill);\n svgFill = processed.groups[0]?.colors[0] || resolveCustomProperties(svgFill);\n\n return { fill: svgFill };\n}\n\nsvgFillStyle.__lookupStyles = ['svgFill'];\n","import { resolveCustomProperties } from '../utils/styles';\n\nexport function flowStyle({\n display = 'block',\n flow,\n}: {\n display?: string;\n flow?: string;\n}) {\n let style;\n\n if (display.includes('grid')) {\n style = 'grid-auto-flow';\n } else if (display.includes('flex')) {\n style = 'flex-flow';\n }\n\n return style && flow ? { [style]: resolveCustomProperties(flow) } : null;\n}\n\nflowStyle.__lookupStyles = ['display', 'flow'];\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport { makeEmptyDetails } from '../parser/types';\nimport { parseStyle } from '../utils/styles';\n\nexport function gapStyle({\n display = 'block',\n flow,\n gap,\n}: {\n display?: string;\n flow?: string;\n gap?: string | number | boolean;\n}) {\n if (typeof gap === 'number') {\n gap = `${gap}px`;\n }\n\n if (!gap) {\n return null;\n }\n\n if (gap === true) {\n gap = '1x';\n }\n\n if (CSS_WIDE_KEYWORDS.has(String(gap))) {\n return { gap: String(gap) };\n }\n\n const isGrid = display.includes('grid');\n const isFlex = display.includes('flex');\n const isWrap = flow\n ? flow.includes('wrap') && !flow.includes('nowrap')\n : false;\n\n if (!isGrid && flow == null) {\n flow = isFlex ? 'row' : 'column';\n }\n\n const processed = parseStyle(gap);\n const { values } = processed.groups[0] ?? makeEmptyDetails();\n\n gap = values.join(' ');\n\n if (isGrid || isFlex) {\n return { gap };\n }\n\n const gapDir = flow?.includes('row') ? 'right' : 'bottom';\n\n return isWrap\n ? [\n {\n 'margin-right': `calc(-1 * ${values[1] || values[0]})`,\n 'margin-bottom': `calc(-1 * ${values[0]})`,\n },\n {\n $: '& > *',\n 'margin-right': values[1] || values[0],\n 'margin-bottom': values[0],\n },\n ]\n : {\n $: '& > *:not(:last-child)',\n [`margin-${gapDir}`]: gap,\n };\n}\n\ngapStyle.__lookupStyles = ['display', 'flow', 'gap'];\n","import { dimensionStyle } from './dimension';\n\nconst dimension = dimensionStyle('height');\n\ninterface HeightStyleProps {\n height?: string | number | boolean;\n minHeight?: string | number | boolean;\n maxHeight?: string | number | boolean;\n}\n\nexport function heightStyle({\n height,\n minHeight,\n maxHeight,\n}: HeightStyleProps) {\n return dimension({ value: height, min: minHeight, max: maxHeight });\n}\n\nheightStyle.__lookupStyles = ['height', 'minHeight', 'maxHeight'];\n","import type { StyleDetails } from '../parser/types';\nimport { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport { parseStyle } from '../utils/styles';\nimport { extractCSSWideKeyword, warnExtraGroupValues } from './shared';\n\ntype Direction = 'top' | 'right' | 'bottom' | 'left';\n\nconst DIRECTION_TOP = 1;\nconst DIRECTION_RIGHT = 2;\nconst DIRECTION_BOTTOM = 4;\nconst DIRECTION_LEFT = 8;\nconst DIRECTION_MASK = 15;\nconst DIRECTION_LONGHAND = 16;\nconst DIRECTION_SPAN = 32;\n\nexport interface DirectionalConfig {\n /** CSS property name (e.g. 'padding', 'margin', 'inset', 'scroll-margin') */\n property: string;\n /** Default value when parsing yields empty (e.g. 'var(--gap)', '0') */\n defaultValue: string;\n /** Value used when the prop is `true` (e.g. '1x', '0') */\n trueValue: string;\n /** Default per-direction init value (e.g. '0', 'auto') */\n defaultInit: string;\n /**\n * When true, if only individual direction props are set (no shorthand),\n * output individual CSS properties instead of the shorthand. Needed by\n * inset for correct CSS cascade with modifiers.\n */\n individualOnly?: boolean;\n /**\n * Maps individual direction CSS property names. Defaults to\n * `${property}-top`, `${property}-right`, etc. For inset this is\n * `top`, `right`, `bottom`, `left`.\n */\n directionProperty?: (dir: Direction) => string;\n /**\n * Modifiers that expand the named side(s) to also cover the perpendicular\n * pair, so `inset: 'bottom dock'` pins the bottom edge and spans the full\n * width (`inset: auto 0 0 0`).\n *\n * Opt-in per property: only `inset` docks to an edge, so `padding`, `margin`\n * and `scrollMargin` ignore the modifier and treat it as an unknown mod.\n */\n spanModifiers?: readonly string[];\n}\n\nfunction parseSingleValue(\n val: string | number | boolean,\n defaultValue: string,\n trueValue: string,\n): string | null {\n if (typeof val === 'number') return `${val}px`;\n if (!val) return null;\n if (val === true) val = trueValue;\n\n const strVal = String(val);\n\n if (CSS_WIDE_KEYWORDS.has(strVal)) return strVal;\n\n const { values } = parseStyle(strVal).groups[0] ?? { values: [] };\n\n return values[0] || defaultValue;\n}\n\nfunction directionModFlags(\n mods: string[],\n spanModifiers?: readonly string[],\n): number {\n let flags = 0;\n\n for (const mod of mods) {\n if (mod === 'top') flags |= DIRECTION_TOP;\n else if (mod === 'right') flags |= DIRECTION_RIGHT;\n else if (mod === 'bottom') flags |= DIRECTION_BOTTOM;\n else if (mod === 'left') flags |= DIRECTION_LEFT;\n else if (mod === 'longhand') flags |= DIRECTION_LONGHAND;\n }\n\n if (spanModifiers) {\n for (const spanModifier of spanModifiers) {\n if (mods.includes(spanModifier)) {\n flags |= DIRECTION_SPAN;\n break;\n }\n }\n }\n\n return flags;\n}\n\nfunction applyGroup(\n dirs: Record<Direction, string>,\n group: StyleDetails,\n modFlags: number,\n property: string,\n defaultValue: string,\n): void {\n const values = group.values.length ? group.values : [defaultValue];\n const directions = modFlags & DIRECTION_MASK;\n const span = modFlags & DIRECTION_SPAN;\n\n // A group that names directions carries one value — two with a span modifier.\n // Guarded inline so the valid path costs a single comparison.\n if (directions && values.length > (span ? 2 : 1)) {\n warnExtraGroupValues(property, group.input, span ? 2 : 1);\n }\n\n if (!directions) {\n // No direction named — plain CSS shorthand order (1-4 values). Unambiguous,\n // so it keeps working: `padding: '1x 2x'` is block 1x / inline 2x.\n dirs.top = values[0];\n dirs.right = values[1] || values[0];\n dirs.bottom = values[2] || values[0];\n dirs.left = values[3] || values[1] || values[0];\n\n return;\n }\n\n // A group that names directions has one meaningful value, applied to every\n // named direction: `padding: '2x top, 4x right'`, not `'2x 4x top right'`.\n // Extra values were reported above and are ignored here.\n const value = values[0];\n\n // Span first so an explicitly named direction always wins over the value it\n // would otherwise inherit as a perpendicular side.\n if (span) {\n // `inset: '2x 4x bottom dock'` pins the bottom at 2x and insets the spanned\n // sides by 4x. Without a second value the span reuses the edge's own value.\n const spanValue = values[1] ?? value;\n\n if (directions & DIRECTION_TOP) dirs.right = dirs.left = spanValue;\n if (directions & DIRECTION_RIGHT) dirs.top = dirs.bottom = spanValue;\n if (directions & DIRECTION_BOTTOM) dirs.right = dirs.left = spanValue;\n if (directions & DIRECTION_LEFT) dirs.top = dirs.bottom = spanValue;\n }\n\n if (directions & DIRECTION_TOP) dirs.top = value;\n if (directions & DIRECTION_RIGHT) dirs.right = value;\n if (directions & DIRECTION_BOTTOM) dirs.bottom = value;\n if (directions & DIRECTION_LEFT) dirs.left = value;\n}\n\nfunction optimizeShorthand(\n property: string,\n dirs: Record<Direction, string>,\n): Record<string, string> {\n const { top, right, bottom, left } = dirs;\n\n if (top === right && right === bottom && bottom === left) {\n return { [property]: top };\n }\n if (top === bottom && left === right) {\n return { [property]: `${top} ${left}` };\n }\n\n return { [property]: `${top} ${right} ${bottom} ${left}` };\n}\n\ninterface DirectionalProps {\n main?: string | number | boolean;\n top?: string | number | boolean;\n right?: string | number | boolean;\n bottom?: string | number | boolean;\n left?: string | number | boolean;\n}\n\n/**\n * Core directional style logic shared by padding, margin, inset, scrollMargin.\n */\nexport function processDirectionalStyle(\n config: DirectionalConfig,\n props: DirectionalProps,\n): Record<string, string> | null {\n const { main, top, right, bottom, left } = props;\n\n if (\n main == null &&\n top == null &&\n right == null &&\n bottom == null &&\n left == null\n ) {\n return null;\n }\n\n const {\n property,\n defaultValue,\n trueValue,\n defaultInit,\n individualOnly,\n directionProperty,\n spanModifiers,\n } = config;\n const dirProp =\n directionProperty ?? ((dir: Direction) => `${property}-${dir}`);\n\n if (individualOnly) {\n const onlyIndividualProps = main == null;\n\n if (onlyIndividualProps) {\n const result: Record<string, string> = {};\n\n if (top != null) {\n const val = parseSingleValue(top, defaultValue, trueValue);\n if (val) result[dirProp('top')] = val;\n }\n if (right != null) {\n const val = parseSingleValue(right, defaultValue, trueValue);\n if (val) result[dirProp('right')] = val;\n }\n if (bottom != null) {\n const val = parseSingleValue(bottom, defaultValue, trueValue);\n if (val) result[dirProp('bottom')] = val;\n }\n if (left != null) {\n const val = parseSingleValue(left, defaultValue, trueValue);\n if (val) result[dirProp('left')] = val;\n }\n\n return Object.keys(result).length > 0 ? result : null;\n }\n }\n\n const dirs: Record<Direction, string> = {\n top: defaultInit,\n right: defaultInit,\n bottom: defaultInit,\n left: defaultInit,\n };\n\n let useLonghand = false;\n\n if (main != null) {\n if (typeof main === 'number') {\n const v = `${main}px`;\n dirs.top = dirs.right = dirs.bottom = dirs.left = v;\n } else {\n const strMain = main === true ? trueValue : String(main);\n\n if (strMain) {\n const keyword = CSS_WIDE_KEYWORDS.has(strMain) ? strMain : null;\n\n if (keyword) {\n dirs.top = dirs.right = dirs.bottom = dirs.left = keyword;\n } else {\n const processed = parseStyle(strMain);\n const groups = processed.groups ?? [];\n\n for (const group of groups) {\n const modFlags = directionModFlags(group.mods, spanModifiers);\n if (modFlags & DIRECTION_LONGHAND) useLonghand = true;\n\n const kw = extractCSSWideKeyword(group);\n\n if (kw) {\n const directions = modFlags & DIRECTION_MASK;\n\n if (!directions) {\n dirs.top = dirs.right = dirs.bottom = dirs.left = kw;\n } else {\n if (directions & DIRECTION_TOP) dirs.top = kw;\n if (directions & DIRECTION_RIGHT) dirs.right = kw;\n if (directions & DIRECTION_BOTTOM) dirs.bottom = kw;\n if (directions & DIRECTION_LEFT) dirs.left = kw;\n }\n } else {\n applyGroup(dirs, group, modFlags, property, defaultValue);\n }\n }\n }\n }\n }\n }\n\n if (top != null) {\n const val = parseSingleValue(top, defaultValue, trueValue);\n if (val) dirs.top = val;\n }\n if (right != null) {\n const val = parseSingleValue(right, defaultValue, trueValue);\n if (val) dirs.right = val;\n }\n if (bottom != null) {\n const val = parseSingleValue(bottom, defaultValue, trueValue);\n if (val) dirs.bottom = val;\n }\n if (left != null) {\n const val = parseSingleValue(left, defaultValue, trueValue);\n if (val) dirs.left = val;\n }\n\n if (useLonghand) {\n return {\n [dirProp('top')]: dirs.top,\n [dirProp('right')]: dirs.right,\n [dirProp('bottom')]: dirs.bottom,\n [dirProp('left')]: dirs.left,\n };\n }\n\n return optimizeShorthand(property, dirs);\n}\n","import { type DirectionalConfig, processDirectionalStyle } from './directional';\n\nconst INSET_CONFIG: DirectionalConfig = {\n property: 'inset',\n defaultValue: '0',\n trueValue: '0',\n defaultInit: 'auto',\n individualOnly: true,\n spanModifiers: ['dock'],\n directionProperty: (dir) => dir,\n};\n\nexport function insetStyle({\n inset,\n top,\n right,\n bottom,\n left,\n}: {\n inset?: string | number | boolean;\n top?: string | number | boolean;\n right?: string | number | boolean;\n bottom?: string | number | boolean;\n left?: string | number | boolean;\n}) {\n return processDirectionalStyle(INSET_CONFIG, {\n main: inset,\n top,\n right,\n bottom,\n left,\n });\n}\n\ninsetStyle.__lookupStyles = ['inset', 'top', 'right', 'bottom', 'left'];\n","import { dimensionStyle } from './dimension';\nimport { INLINE_SIZE_STYLES } from './logical-list';\n\nconst dimension = dimensionStyle('inline-size');\n\nexport function inlineSizeStyle({\n inlineSize,\n minInlineSize,\n maxInlineSize,\n}: {\n inlineSize?: string | number | boolean;\n minInlineSize?: string | number | boolean;\n maxInlineSize?: string | number | boolean;\n}) {\n return dimension({\n value: inlineSize,\n min: minInlineSize,\n max: maxInlineSize,\n });\n}\n\ninlineSizeStyle.__lookupStyles = [...INLINE_SIZE_STYLES];\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport { parseStyle } from '../utils/styles';\nimport type { StyleHandler, StyleValue } from '../utils/styles';\nimport { warnOnceDev } from '../utils/warnings';\nimport { parseBorderValue } from './border';\nimport {\n LOGICAL_BORDER_STYLES,\n LOGICAL_INSET_STYLES,\n LOGICAL_MARGIN_STYLES,\n LOGICAL_PADDING_STYLES,\n LOGICAL_SCROLL_MARGIN_STYLES,\n LOGICAL_SCROLL_PADDING_STYLES,\n} from './logical-list';\nimport { extractCSSWideKeyword, warnExtraGroupValues } from './shared';\n\ntype LogicalValue = string | number | boolean | undefined;\n\nconst LOGICAL_DIRECTIONS = ['start', 'end'] as const;\ntype LogicalDirection = (typeof LOGICAL_DIRECTIONS)[number];\n\nconst LOGICAL_START = 1;\nconst LOGICAL_END = 2;\nconst LOGICAL_LONGHAND = 4;\n\nfunction logicalModFlags(mods: string[]): number {\n let flags = 0;\n\n for (const mod of mods) {\n if (mod === 'start') flags |= LOGICAL_START;\n else if (mod === 'end') flags |= LOGICAL_END;\n else if (mod === 'longhand') flags |= LOGICAL_LONGHAND;\n }\n\n return flags;\n}\n\ninterface LogicalAxisConfig<Name extends string> {\n styleName: Name;\n cssProperty: string;\n defaultValue: string;\n trueValue: string;\n defaultInit: string;\n}\n\ntype LogicalHandlerMap<Names extends readonly string[]> = {\n [Name in Names[number]]: StyleHandler<Partial<Record<Name, LogicalValue>>>;\n};\n\n/**\n * Create one enhanced handler for one logical axis/category pair.\n *\n * The handler owns the native axis shorthand and its start/end declarations,\n * but never reads or converts a physical property. The browser remains\n * responsible for resolving logical edges from writing mode and direction.\n */\nfunction logicalAxisStyle<const Name extends string>({\n styleName,\n cssProperty,\n defaultValue,\n trueValue,\n defaultInit,\n}: LogicalAxisConfig<Name>): StyleHandler<Partial<Record<Name, LogicalValue>>> {\n const handler = ((styles: Partial<Record<Name, LogicalValue>>) => {\n let value = styles[styleName];\n\n if (value == null || value === false || value === '') return null;\n if (value === true) value = trueValue;\n if (typeof value === 'number') value = `${value}px`;\n\n const strValue = String(value);\n\n if (CSS_WIDE_KEYWORDS.has(strValue)) {\n return { [cssProperty]: strValue };\n }\n\n const groups = parseStyle(strValue as StyleValue).groups ?? [];\n if (!groups.length) return null;\n\n const edges: Record<LogicalDirection, string> = {\n start: defaultInit,\n end: defaultInit,\n };\n let useLonghand = false;\n\n for (const group of groups) {\n const modFlags = logicalModFlags(group.mods);\n const hasDirection = modFlags & (LOGICAL_START | LOGICAL_END);\n const keyword = extractCSSWideKeyword(group);\n const values = keyword\n ? [keyword]\n : group.values.length\n ? group.values\n : [defaultValue];\n if (hasDirection && values.length > 1) {\n warnExtraGroupValues(styleName, group.input, 1, LOGICAL_DIRECTIONS);\n } else if (!hasDirection && values.length > 2) {\n warnOnceDev(\n `extra-logical-axis-values:${styleName}:${group.input}`,\n `${styleName}=\"${group.input}\": a logical axis takes at most two ` +\n 'values in start/end order. The extra values are ignored.',\n );\n }\n\n if (modFlags & LOGICAL_LONGHAND) useLonghand = true;\n\n if (!hasDirection) {\n edges.start = values[0];\n edges.end = values[1] ?? values[0];\n } else {\n if (modFlags & LOGICAL_START) edges.start = values[0];\n if (modFlags & LOGICAL_END) edges.end = values[0];\n }\n }\n\n if (useLonghand) {\n return {\n [`${cssProperty}-start`]: edges.start,\n [`${cssProperty}-end`]: edges.end,\n };\n }\n\n return {\n [cssProperty]:\n edges.start === edges.end ? edges.start : `${edges.start} ${edges.end}`,\n };\n }) as StyleHandler<Partial<Record<Name, LogicalValue>>>;\n\n handler.__lookupStyles = [styleName];\n return handler;\n}\n\nfunction zeroBorderValue(value: string): string {\n const firstSpace = value.indexOf(' ');\n\n return firstSpace === -1\n ? '0 solid var(--border-color, currentColor)'\n : `0${value.slice(firstSpace)}`;\n}\n\n/** Create one enhanced border handler for one logical axis. */\nfunction logicalBorderStyle<const Name extends string>(\n styleName: Name,\n cssProperty: string,\n): StyleHandler<Partial<Record<Name, LogicalValue>>> {\n const handler = ((styles: Partial<Record<Name, LogicalValue>>) => {\n let value = styles[styleName];\n\n if (value == null || value === false || value === '') return null;\n if (value === true) value = '1bw';\n if (typeof value === 'number') value = `${value}px`;\n\n const groups = parseStyle(String(value)).groups ?? [];\n if (!groups.length) return null;\n\n const edges: Record<LogicalDirection, string | null> = {\n start: null,\n end: null,\n };\n let fallback = '0 solid var(--border-color, currentColor)';\n let useLonghand = false;\n\n for (const group of groups) {\n const borderValue = parseBorderValue(group.input);\n if (borderValue == null) continue;\n\n const modFlags = logicalModFlags(group.mods);\n const hasDirection = modFlags & (LOGICAL_START | LOGICAL_END);\n\n if (modFlags & LOGICAL_LONGHAND) useLonghand = true;\n\n if (!hasDirection) {\n edges.start = borderValue;\n edges.end = borderValue;\n } else {\n fallback = zeroBorderValue(borderValue);\n if (modFlags & LOGICAL_START) edges.start = borderValue;\n if (modFlags & LOGICAL_END) edges.end = borderValue;\n }\n }\n\n const start = edges.start ?? fallback;\n const end = edges.end ?? fallback;\n\n if (!useLonghand && start === end) {\n return { [cssProperty]: start };\n }\n\n return {\n [`${cssProperty}-start`]: start,\n [`${cssProperty}-end`]: end,\n };\n }) as StyleHandler<Partial<Record<Name, LogicalValue>>>;\n\n handler.__lookupStyles = [styleName];\n return handler;\n}\n\nfunction logicalAxisStyles<const Names extends readonly [string, string]>(\n styleNames: Names,\n cssProperty: string,\n defaultValue: string,\n trueValue: string,\n defaultInit: string,\n): LogicalHandlerMap<Names> {\n return Object.fromEntries(\n styleNames.map((styleName, index) => [\n styleName,\n logicalAxisStyle({\n styleName,\n cssProperty: `${cssProperty}-${index ? 'inline' : 'block'}`,\n defaultValue,\n trueValue,\n defaultInit,\n }),\n ]),\n ) as LogicalHandlerMap<Names>;\n}\n\nfunction logicalBorderStyles<const Names extends readonly [string, string]>(\n styleNames: Names,\n): LogicalHandlerMap<Names> {\n return Object.fromEntries(\n styleNames.map((styleName, index) => [\n styleName,\n logicalBorderStyle(styleName, `border-${index ? 'inline' : 'block'}`),\n ]),\n ) as LogicalHandlerMap<Names>;\n}\n\n/** One handler per logical axis/category; native CSS longhands stay ordinary. */\nexport const logicalStyleHandlers = {\n ...logicalAxisStyles(\n LOGICAL_PADDING_STYLES,\n 'padding',\n 'var(--gap)',\n '1x',\n '0',\n ),\n ...logicalAxisStyles(\n LOGICAL_MARGIN_STYLES,\n 'margin',\n 'var(--gap)',\n '1x',\n '0',\n ),\n ...logicalAxisStyles(LOGICAL_INSET_STYLES, 'inset', '0', '0', 'auto'),\n ...logicalAxisStyles(\n LOGICAL_SCROLL_MARGIN_STYLES,\n 'scroll-margin',\n '0',\n '1x',\n '0',\n ),\n ...logicalAxisStyles(\n LOGICAL_SCROLL_PADDING_STYLES,\n 'scroll-padding',\n '0',\n '1x',\n '0',\n ),\n ...logicalBorderStyles(LOGICAL_BORDER_STYLES),\n} as const;\n","import { processDirectionalStyle } from './directional';\n\nconst MARGIN_CONFIG = {\n property: 'margin',\n defaultValue: 'var(--gap)',\n trueValue: '1x',\n defaultInit: '0',\n} as const;\n\nexport function marginStyle({\n margin,\n marginTop,\n marginRight,\n marginBottom,\n marginLeft,\n}: {\n margin?: string | number | boolean;\n marginTop?: string | number | boolean;\n marginRight?: string | number | boolean;\n marginBottom?: string | number | boolean;\n marginLeft?: string | number | boolean;\n}) {\n return processDirectionalStyle(MARGIN_CONFIG, {\n main: margin,\n top: marginTop,\n right: marginRight,\n bottom: marginBottom,\n left: marginLeft,\n });\n}\n\nmarginStyle.__lookupStyles = [\n 'margin',\n 'marginTop',\n 'marginRight',\n 'marginBottom',\n 'marginLeft',\n];\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport { parseStyle, resolveCustomProperties } from '../utils/styles';\nimport { BORDER_STYLES } from './const';\nimport { assignLineSlots } from './shared';\n\ninterface OutlineStyleProps {\n outline?: string | boolean | number;\n outlineOffset?: string | number;\n}\n\n/**\n * Generates CSS for outline property with optional offset.\n *\n * Syntax:\n * - `outline=\"2px solid #red\"` - outline only\n * - `outline=\"2px solid #red / 4px\"` - outline with offset (slash separator)\n * - `outline=\"2px / 4px\"` - width with offset (simpler form)\n * - `outline={true}` - default 1ow solid outline\n * - `outlineOffset=\"4px\"` - offset as separate prop (can be combined with outline)\n *\n * Priority: slash syntax in outline takes precedence over outlineOffset prop\n *\n * @return CSS properties for outline and optionally outline-offset\n */\nexport function outlineStyle({ outline, outlineOffset }: OutlineStyleProps) {\n const result: Record<string, string> = {};\n\n // Handle outline (0 is valid - means no outline)\n if (outline != null && outline !== false) {\n if (typeof outline === 'string' && CSS_WIDE_KEYWORDS.has(outline)) {\n result.outline = outline;\n } else {\n let outlineValue: string | boolean | number = outline;\n if (outline === true) outlineValue = '1ow';\n if (outline === 0) outlineValue = '0';\n\n const processed = parseStyle(String(outlineValue));\n const group = processed.groups[0];\n\n if (group) {\n const { parts } = group;\n const outlinePart = parts[0] ?? { values: [], mods: [], colors: [] };\n const offsetPart = parts[1];\n let lineStyle: string | undefined;\n\n for (const mod of outlinePart.mods) {\n if ((BORDER_STYLES as readonly string[]).includes(mod)) {\n lineStyle = mod;\n break;\n }\n }\n\n const slots = assignLineSlots(\n outlinePart.values,\n lineStyle,\n outlinePart.colors[0],\n );\n\n const value = outlinePart.values[0] || 'var(--outline-width)';\n const type = slots.style || 'solid';\n const outlineColor = slots.color || 'var(--outline-color)';\n\n result.outline = `${value} ${type} ${outlineColor}`;\n\n if (offsetPart?.values[0]) {\n result['outline-offset'] = offsetPart.values[0];\n }\n }\n }\n }\n\n // Handle outlineOffset prop (only if not already set by slash syntax)\n if (outlineOffset != null && result['outline-offset'] === undefined) {\n const offsetValue =\n typeof outlineOffset === 'number' ? `${outlineOffset}px` : outlineOffset;\n const processed = parseStyle(offsetValue);\n result['outline-offset'] =\n processed.groups[0]?.values[0] || resolveCustomProperties(offsetValue);\n }\n\n return result.outline === undefined && result['outline-offset'] === undefined\n ? null\n : result;\n}\n\noutlineStyle.__lookupStyles = ['outline', 'outlineOffset'];\n","import { processDirectionalStyle } from './directional';\n\nconst PADDING_CONFIG = {\n property: 'padding',\n defaultValue: 'var(--gap)',\n trueValue: '1x',\n defaultInit: '0',\n} as const;\n\nexport function paddingStyle({\n padding,\n paddingTop,\n paddingRight,\n paddingBottom,\n paddingLeft,\n}: {\n padding?: string | number | boolean;\n paddingTop?: string | number | boolean;\n paddingRight?: string | number | boolean;\n paddingBottom?: string | number | boolean;\n paddingLeft?: string | number | boolean;\n}) {\n return processDirectionalStyle(PADDING_CONFIG, {\n main: padding,\n top: paddingTop,\n right: paddingRight,\n bottom: paddingBottom,\n left: paddingLeft,\n });\n}\n\npaddingStyle.__lookupStyles = [\n 'padding',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n];\n","import { resolveCustomProperties } from '../utils/styles';\n\ninterface PlacementStyleProps {\n place?: string | boolean;\n placeItems?: string | boolean;\n placeContent?: string | boolean;\n align?: string | boolean;\n justify?: string | boolean;\n alignItems?: string | boolean;\n alignContent?: string | boolean;\n justifyItems?: string | boolean;\n justifyContent?: string | boolean;\n}\n\nfunction str(val: string | boolean | undefined): string | null {\n if (val == null || val === false || val === '') return null;\n if (val === true) return 'center';\n\n return resolveCustomProperties(String(val));\n}\n\n/**\n * Unified placement handler replacing align, justify, and place.\n *\n * Priority (later overrides earlier):\n * 1. place (lowest) — sets all 4 longhands\n * 2. placeItems, placeContent, align, justify (medium) — each sets 2 longhands\n * 3. alignItems, alignContent, justifyItems, justifyContent (highest) — each sets 1 longhand\n */\nexport function placementStyle({\n place,\n placeItems,\n placeContent,\n align,\n justify,\n alignItems,\n alignContent,\n justifyItems,\n justifyContent,\n}: PlacementStyleProps) {\n const result: Record<string, string> = {};\n\n const placeVal = str(place);\n\n if (placeVal) {\n const parts = placeVal.split(/\\s+/);\n const first = parts[0];\n const second = parts[1] || first;\n\n result['align-items'] = first;\n result['justify-items'] = second;\n result['align-content'] = first;\n result['justify-content'] = second;\n }\n\n const placeItemsVal = str(placeItems);\n\n if (placeItemsVal) {\n const parts = placeItemsVal.split(/\\s+/);\n\n result['align-items'] = parts[0];\n result['justify-items'] = parts[1] || parts[0];\n }\n\n const placeContentVal = str(placeContent);\n\n if (placeContentVal) {\n const parts = placeContentVal.split(/\\s+/);\n\n result['align-content'] = parts[0];\n result['justify-content'] = parts[1] || parts[0];\n }\n\n const alignVal = str(align);\n\n if (alignVal) {\n result['align-items'] = alignVal;\n result['align-content'] = alignVal;\n }\n\n const justifyVal = str(justify);\n\n if (justifyVal) {\n result['justify-items'] = justifyVal;\n result['justify-content'] = justifyVal;\n }\n\n const alignItemsVal = str(alignItems);\n\n if (alignItemsVal) result['align-items'] = alignItemsVal;\n\n const alignContentVal = str(alignContent);\n\n if (alignContentVal) result['align-content'] = alignContentVal;\n\n const justifyItemsVal = str(justifyItems);\n\n if (justifyItemsVal) result['justify-items'] = justifyItemsVal;\n\n const justifyContentVal = str(justifyContent);\n\n if (justifyContentVal) result['justify-content'] = justifyContentVal;\n\n if (Object.keys(result).length === 0) return null;\n\n return result;\n}\n\nplacementStyle.__lookupStyles = [\n 'place',\n 'placeItems',\n 'placeContent',\n 'align',\n 'justify',\n 'alignItems',\n 'alignContent',\n 'justifyItems',\n 'justifyContent',\n];\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport { parseStyle, resolveCustomProperties } from '../utils/styles';\nimport { isTokenNameReference } from './shared';\nimport type { CSSMap } from '../utils/styles';\n\nconst PRESET_MODIFIERS = new Set([\n 'strong',\n 'bold',\n 'italic',\n 'icon',\n 'tight',\n 'normal',\n]);\n\nconst SANS_FONT = 'var(--font-sans, var(--font-sans-fallback))';\n\n/**\n * Convert a value to CSS, handling numbers as pixels for numeric properties\n */\nfunction toCSS(\n value: string | number | undefined,\n isNumeric: boolean,\n): string | null {\n if (value == null) return null;\n if (typeof value === 'number') {\n return isNumeric ? `${value}px` : String(value);\n }\n // Parse through style parser to handle custom units like 1x, 2r, etc.\n const processed = parseStyle(value);\n // A `$name-color` reference lands in the color bucket, not `values`, so the\n // fallback still has to substitute custom properties rather than emit the\n // raw DSL.\n return processed.groups[0]?.values[0] || resolveCustomProperties(value);\n}\n\nfunction setCSSValue(\n styles: CSSMap,\n styleName: string,\n presetName: string,\n mode?: 'var' | 'css',\n) {\n let value = presetName;\n\n if (!CSS_WIDE_KEYWORDS.has(presetName)) {\n const fontSuffix = styleName === 'font-family' ? `, ${SANS_FONT}` : '';\n\n const defaultValue = `var(--default-${styleName}${fontSuffix})`;\n\n if (presetName === 'default') {\n value = `${defaultValue}${fontSuffix}`;\n } else {\n value = `var(--${presetName}-${styleName}, ${defaultValue})${fontSuffix}`;\n }\n }\n\n if (mode !== 'css') {\n styles[`--${styleName}`] = value;\n }\n\n if (mode !== 'var') {\n styles[styleName] = value;\n }\n}\n\ninterface PresetStyleProps {\n preset?: string | boolean;\n fontSize?: string | number;\n lineHeight?: string | number;\n textTransform?: string;\n letterSpacing?: string | number;\n fontWeight?: string | number;\n fontStyle?: string | boolean;\n fontFamily?: string;\n /** Alias for fontFamily with special handling for 'monospace' and boolean */\n font?: string | boolean;\n}\n\n/**\n * Resolve font/fontFamily value to CSS font-family string.\n *\n * - `font=\"monospace\"` → var(--font-mono, var(--font-mono-fallback))\n * - `font={true}` → var(--font-sans, var(--font-sans-fallback))\n * - `font=\"CustomFont\"` → CustomFont, var(--font-sans, var(--font-sans-fallback))\n * - `fontFamily=\"Arial\"` → Arial (direct, no fallback)\n */\nfunction resolveFontFamily(\n font: string | boolean | undefined,\n fontFamily: string | undefined,\n): string | null {\n // fontFamily takes precedence as a direct value\n if (fontFamily) {\n return resolveCustomProperties(fontFamily);\n }\n\n if (font == null || font === false) {\n return null;\n }\n\n if (font === 'monospace') {\n return 'var(--font-mono, var(--font-mono-fallback))';\n }\n\n if (font === true) {\n return SANS_FONT;\n }\n\n return `${resolveCustomProperties(font)}, ${SANS_FONT}`;\n}\n\n/**\n * Handles typography preset and individual font properties.\n *\n * Preset syntax uses `/` to separate the name from one or more\n * space-separated modifiers:\n * - `preset=\"h1\"` — name only\n * - `preset=\"h2 / strong\"` — name + modifier\n * - `preset=\"h2 / strong italic\"` — name + multiple modifiers\n * - `preset=\"bold\"` — modifier-only shorthand (name defaults to `inherit`)\n * - `preset=\"bold italic\"` — modifier-only shorthand with multiple modifiers\n *\n * When `preset` is defined, it sets up CSS custom properties for typography.\n * Individual font props can be used with or without `preset`:\n * - With `preset`: overrides the preset value for that property\n * - Without `preset`: outputs the CSS directly\n *\n * Number values are converted to pixels for fontSize, lineHeight, letterSpacing.\n * fontWeight accepts numbers directly (e.g., 400, 700).\n *\n * font vs fontFamily:\n * - `font` is the recommended prop with special handling (monospace, boolean, fallback)\n * - `fontFamily` is a direct value without special handling\n */\nexport function presetStyle({\n preset,\n fontSize,\n lineHeight,\n textTransform,\n letterSpacing,\n fontWeight,\n fontStyle,\n fontFamily,\n font,\n}: PresetStyleProps) {\n // A handler result, not an authoring styles object: every key written below is\n // a kebab-case CSS property or a `--custom-property`.\n const styles: CSSMap = {};\n const hasPreset = preset != null && preset !== false;\n\n // Handle preset if defined\n if (hasPreset) {\n const presetValue = preset === true ? '' : String(preset);\n\n const processed = parseStyle(presetValue);\n const group = processed.groups[0];\n const { parts } = group ?? { parts: [] };\n\n // parts[0] = preset name (or modifiers for shorthand like preset=\"bold italic\")\n // parts[1] = optional space-separated modifiers after slash (e.g. \"t3 / strong italic\")\n const namePart = parts[0];\n const modPart = parts[1];\n\n const nameTokens = namePart?.all ?? [];\n // Mod-only shorthand: all tokens in parts[0] are recognized modifiers.\n const isModOnly =\n nameTokens.length > 0 && nameTokens.every((t) => PRESET_MODIFIERS.has(t));\n\n const nameToken = namePart?.mods[0] ?? namePart?.values[0] ?? '';\n // A reference cannot name a preset; fall back to `inherit`, the same name an\n // absent preset resolves to, rather than emitting `var(--var(--x)-font-size)`.\n const name =\n isModOnly || isTokenNameReference('preset', nameToken)\n ? 'inherit'\n : nameToken || 'inherit';\n\n const modTokens = isModOnly ? nameTokens : (modPart?.all ?? []);\n const isStrong = modTokens.includes('strong') || modTokens.includes('bold');\n const isItalic = modTokens.includes('italic');\n const isIcon = modTokens.includes('icon');\n const isTight = modTokens.includes('tight');\n const isNormal = modTokens.includes('normal');\n\n // Set preset values for properties not explicitly overridden\n if (fontSize == null) {\n setCSSValue(styles, 'font-size', name, 'css');\n }\n if (lineHeight == null) {\n setCSSValue(styles, 'line-height', name, 'css');\n }\n if (letterSpacing == null) {\n setCSSValue(styles, 'letter-spacing', name, 'css');\n }\n if (fontWeight == null) {\n setCSSValue(styles, 'font-weight', name, 'css');\n }\n if (fontStyle == null) {\n setCSSValue(styles, 'font-style', name, 'css');\n }\n if (textTransform == null) {\n setCSSValue(styles, 'text-transform', name, 'css');\n }\n if (fontFamily == null && font == null) {\n setCSSValue(styles, 'font-family', name, 'css');\n }\n\n setCSSValue(styles, 'bold-font-weight', name, 'var');\n setCSSValue(styles, 'icon-size', name, 'var');\n\n if (isStrong) {\n styles['font-weight'] = 'var(--bold-font-weight)';\n }\n if (isItalic) {\n styles['font-style'] = 'italic';\n }\n if (isIcon) {\n styles['font-size'] = 'var(--icon-size)';\n styles['line-height'] = 'var(--icon-size)';\n }\n if (isTight) {\n styles['line-height'] = '1em';\n }\n if (isNormal) {\n styles['line-height'] = 'normal';\n }\n }\n\n // Handle individual font properties (work with or without preset)\n const fontSizeVal = toCSS(fontSize, true);\n if (fontSizeVal) {\n styles['font-size'] = fontSizeVal;\n }\n\n const lineHeightVal = toCSS(lineHeight, true);\n if (lineHeightVal) {\n styles['line-height'] = lineHeightVal;\n }\n\n const letterSpacingVal = toCSS(letterSpacing, true);\n if (letterSpacingVal) {\n styles['letter-spacing'] = letterSpacingVal;\n }\n\n // fontWeight: numbers should NOT get 'px' suffix\n const fontWeightVal = toCSS(fontWeight, false);\n if (fontWeightVal) {\n styles['font-weight'] = fontWeightVal;\n }\n\n if (fontStyle != null) {\n if (fontStyle === true) {\n styles['font-style'] = 'italic';\n } else if (\n typeof fontStyle === 'string' &&\n CSS_WIDE_KEYWORDS.has(fontStyle)\n ) {\n styles['font-style'] = fontStyle;\n } else {\n styles['font-style'] = fontStyle ? 'italic' : 'normal';\n }\n }\n\n if (textTransform) {\n styles['text-transform'] = resolveCustomProperties(textTransform);\n }\n\n // Handle font/fontFamily (font has special handling, fontFamily is direct)\n const fontFamily_ = resolveFontFamily(font, fontFamily);\n if (fontFamily_) {\n styles['font-family'] = fontFamily_;\n }\n\n if (Object.keys(styles).length === 0) {\n return null;\n }\n\n return styles;\n}\n\npresetStyle.__lookupStyles = [\n 'preset',\n 'fontSize',\n 'lineHeight',\n 'letterSpacing',\n 'textTransform',\n 'fontWeight',\n 'fontStyle',\n 'fontFamily',\n 'font',\n];\n","import { makeEmptyDetails } from '../parser/types';\nimport { DIRECTIONS, parseStyle } from '../utils/styles';\nimport { extractCSSWideKeyword } from './shared';\n\nconst PROP = 'var(--radius)';\nconst SHARP = 'var(--sharp-radius)';\n\nconst RADIUS_LONGHANDS = [\n 'border-top-left-radius',\n 'border-top-right-radius',\n 'border-bottom-right-radius',\n 'border-bottom-left-radius',\n];\n\n/**\n * Single-corner modifiers, indexed to match `RADIUS_LONGHANDS`.\n *\n * A directional modifier (`top`, `right`, …) addresses the corner *pair* along\n * that edge, so it cannot express one corner on its own. These name a corner\n * directly: `radius: 'top-right'` rounds only the top-right corner.\n */\nconst CORNERS = [\n 'top-left',\n 'top-right',\n 'bottom-right',\n 'bottom-left',\n] as const;\n\n/**\n * Corner indices (into `RADIUS_LONGHANDS`) addressed by the given modifiers.\n * Empty when no corner was named, so callers fall back to all corners.\n */\nfunction cornerIndices(mods: string[]): number[] {\n const out = new Set<number>();\n\n DIRECTIONS.forEach((dir, i) => {\n if (!mods.includes(dir)) return;\n\n out.add(i);\n out.add((i + 1) % 4);\n });\n\n CORNERS.forEach((corner, i) => {\n if (mods.includes(corner)) out.add(i);\n });\n\n return [...out];\n}\n\nexport function radiusStyle({\n radius,\n}: {\n radius?: string | number | boolean;\n}) {\n if (typeof radius === 'number') {\n radius = `${radius}px`;\n }\n\n if (!radius) return null;\n\n if (radius === true) radius = '1r';\n\n const processed = parseStyle(radius);\n const group = processed.groups[0] ?? makeEmptyDetails();\n const { mods } = group;\n let { values } = group;\n\n const keyword = extractCSSWideKeyword(group);\n\n const useLonghand = mods.includes('longhand');\n\n if (keyword) {\n const corners = cornerIndices(mods);\n\n if (!corners.length) {\n if (useLonghand) {\n return Object.fromEntries(\n RADIUS_LONGHANDS.map((prop) => [prop, keyword]),\n );\n }\n\n return { 'border-radius': keyword };\n }\n\n const result: Record<string, string> = {};\n\n for (const i of corners) {\n result[RADIUS_LONGHANDS[i]] = keyword;\n }\n\n return result;\n }\n\n if (mods.includes('round')) {\n values = ['9999rem'];\n } else if (mods.includes('ellipse')) {\n values = ['50%'];\n } else if (!values.length) {\n values = [PROP];\n }\n\n if (mods.includes('leaf')) {\n values = [\n values[1] || SHARP,\n values[0] || PROP,\n values[1] || SHARP,\n values[0] || PROP,\n ];\n } else if (mods.includes('backleaf')) {\n values = [\n values[0] || PROP,\n values[1] || SHARP,\n values[0] || PROP,\n values[1] || SHARP,\n ];\n } else if (mods.length) {\n const corners = cornerIndices(mods);\n\n if (corners.length) {\n const arr = ['0', '0', '0', '0'];\n\n for (const i of corners) {\n arr[i] = values[0] || PROP;\n }\n\n values = arr;\n }\n }\n\n if (useLonghand) {\n return {\n [RADIUS_LONGHANDS[0]]: values[0],\n [RADIUS_LONGHANDS[1]]: values[1] || values[0],\n [RADIUS_LONGHANDS[2]]: values[2] || values[0],\n [RADIUS_LONGHANDS[3]]: values[3] || values[1] || values[0],\n };\n }\n\n return {\n 'border-radius': values.join(' '),\n };\n}\n\nradiusStyle.__lookupStyles = ['radius'];\n","import { processDirectionalStyle } from './directional';\n\nconst SCROLL_MARGIN_CONFIG = {\n property: 'scroll-margin',\n defaultValue: '0',\n trueValue: '1x',\n defaultInit: '0',\n} as const;\n\nexport function scrollMarginStyle({\n scrollMargin,\n scrollMarginTop,\n scrollMarginRight,\n scrollMarginBottom,\n scrollMarginLeft,\n}: {\n scrollMargin?: string | number | boolean;\n scrollMarginTop?: string | number | boolean;\n scrollMarginRight?: string | number | boolean;\n scrollMarginBottom?: string | number | boolean;\n scrollMarginLeft?: string | number | boolean;\n}) {\n return processDirectionalStyle(SCROLL_MARGIN_CONFIG, {\n main: scrollMargin,\n top: scrollMarginTop,\n right: scrollMarginRight,\n bottom: scrollMarginBottom,\n left: scrollMarginLeft,\n });\n}\n\nscrollMarginStyle.__lookupStyles = [\n 'scrollMargin',\n 'scrollMarginTop',\n 'scrollMarginRight',\n 'scrollMarginBottom',\n 'scrollMarginLeft',\n];\n","import { processDirectionalStyle } from './directional';\n\nconst SCROLL_PADDING_CONFIG = {\n property: 'scroll-padding',\n defaultValue: '0',\n trueValue: '1x',\n defaultInit: '0',\n} as const;\n\nexport function scrollPaddingStyle({\n scrollPadding,\n scrollPaddingTop,\n scrollPaddingRight,\n scrollPaddingBottom,\n scrollPaddingLeft,\n}: {\n scrollPadding?: string | number | boolean;\n scrollPaddingTop?: string | number | boolean;\n scrollPaddingRight?: string | number | boolean;\n scrollPaddingBottom?: string | number | boolean;\n scrollPaddingLeft?: string | number | boolean;\n}) {\n return processDirectionalStyle(SCROLL_PADDING_CONFIG, {\n main: scrollPadding,\n top: scrollPaddingTop,\n right: scrollPaddingRight,\n bottom: scrollPaddingBottom,\n left: scrollPaddingLeft,\n });\n}\n\nscrollPaddingStyle.__lookupStyles = [\n 'scrollPadding',\n 'scrollPaddingTop',\n 'scrollPaddingRight',\n 'scrollPaddingBottom',\n 'scrollPaddingLeft',\n];\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport { makeEmptyDetails } from '../parser/types';\nimport { parseStyle } from '../utils/styles';\nimport { warn } from '../utils/warnings';\n\ninterface ScrollbarStyleProps {\n scrollbar?: string | boolean;\n overflow?: string;\n}\n\n/**\n * Standard CSS scrollbar styling via `scrollbar-width`, `scrollbar-color`,\n * and `scrollbar-gutter`.\n *\n * Width values: `thin` (default), `auto`, `none`\n * Modifiers: `stable`, `both-edges`, `always`\n *\n * Note: `auto` is classified as a VALUE_KEYWORD by the parser, so it lands\n * in `values` rather than `mods`. Both locations are checked for robustness.\n */\nexport function scrollbarStyle({\n scrollbar,\n overflow,\n}: ScrollbarStyleProps): Record<string, string> | null {\n if (!scrollbar) return null;\n\n if (typeof scrollbar === 'string' && CSS_WIDE_KEYWORDS.has(scrollbar)) {\n return {\n 'scrollbar-width': scrollbar,\n 'scrollbar-color': scrollbar,\n };\n }\n\n // `true` is treated as `thin` (empty string is falsy, caught by the guard above)\n const value = scrollbar === true ? 'thin' : scrollbar;\n const processed = parseStyle(String(value));\n const { mods, colors, values } = processed.groups[0] ?? makeEmptyDetails();\n\n const defaultThumbColor = 'var(--scrollbar-thumb-color)';\n const defaultTrackColor = 'var(--scrollbar-track-color, transparent)';\n\n const style: Record<string, string> = {};\n\n if (mods.includes('none')) {\n const ignored = [...mods.filter((m) => m !== 'none'), ...values, ...colors];\n\n if (ignored.length && process.env.NODE_ENV !== 'production') {\n warn(\n `scrollbar=\"none\" hides the scrollbar; other tokens are ignored: ${ignored.join(', ')}`,\n );\n }\n\n style['scrollbar-width'] = 'none';\n\n return style;\n }\n\n // `thin` is the default — accepted as a value for readability but always\n // the fallback when neither `auto` nor `none` is specified.\n // `auto` is a VALUE_KEYWORD in the parser, so it may land in `values`.\n if (mods.includes('auto') || values.includes('auto')) {\n style['scrollbar-width'] = 'auto';\n } else {\n style['scrollbar-width'] = 'thin';\n }\n\n const thumbColor = colors?.[0] || defaultThumbColor;\n const trackColor = colors?.[1] || defaultTrackColor;\n style['scrollbar-color'] = `${thumbColor} ${trackColor}`;\n\n if (mods.includes('stable') || mods.includes('both-edges')) {\n style['scrollbar-gutter'] = mods.includes('both-edges')\n ? 'stable both-edges'\n : 'stable';\n }\n\n if (mods.includes('always')) {\n const effectiveOverflow = overflow || 'scroll';\n style['overflow'] = effectiveOverflow;\n\n // scrollbar-gutter only applies with scroll/auto overflow\n if (\n !style['scrollbar-gutter'] &&\n (effectiveOverflow === 'scroll' || effectiveOverflow === 'auto')\n ) {\n style['scrollbar-gutter'] = 'stable';\n }\n }\n\n return style;\n}\n\nscrollbarStyle.__lookupStyles = ['scrollbar', 'overflow'];\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport type { StyleDetails } from '../parser/types';\nimport { parseStyle } from '../utils/styles';\n\nfunction toBoxShadow(group: StyleDetails): string {\n const { values, mods, colors } = group;\n const mod = mods[0] || '';\n const shadowColor = colors[0] ?? '';\n\n return [mod, ...values, shadowColor].join(' ');\n}\n\nexport function shadowStyle({ shadow }: { shadow?: string | boolean }) {\n if (!shadow) return null;\n\n if (shadow === true) shadow = 'var(--shadow)';\n\n if (CSS_WIDE_KEYWORDS.has(shadow)) {\n return { 'box-shadow': shadow };\n }\n\n // Shadow layers are split by the parser, not by a plain `split(',')` — a\n // color function brings commas of its own, so `color-mix(in oklab, …)` would\n // otherwise be torn into pieces that are neither a layer nor a color.\n const { groups } = parseStyle(shadow);\n\n return {\n 'box-shadow': groups.map(toBoxShadow).join(','),\n };\n}\n\nshadowStyle.__lookupStyles = ['shadow'];\n","import { CSS_WIDE_KEYWORDS } from '../parser/const';\nimport { parseStyle } from '../utils/styles';\nimport { isTokenNameReference } from './shared';\n\nconst SECOND_FILL_COLOR_PROPERTY = '--tasty-second-fill-color';\n\nconst MAP: Record<string, string[]> = {\n fade: ['mask', 'mask-composite'],\n translate: ['transform', 'translate'],\n rotate: ['transform', 'rotate'],\n scale: ['transform', 'scale'],\n fill: ['background-color', 'background-image', SECOND_FILL_COLOR_PROPERTY],\n image: [\n 'background-image',\n 'background-position',\n 'background-size',\n 'background-repeat',\n 'background-attachment',\n 'background-origin',\n 'background-clip',\n SECOND_FILL_COLOR_PROPERTY,\n ],\n background: [\n 'background-color',\n 'background-image',\n 'background-position',\n 'background-size',\n 'background-repeat',\n 'background-attachment',\n 'background-origin',\n 'background-clip',\n SECOND_FILL_COLOR_PROPERTY,\n ],\n border: [\n 'border',\n 'border-top',\n 'border-right',\n 'border-bottom',\n 'border-left',\n ],\n filter: ['filter', 'backdrop-filter'],\n radius: ['border-radius'],\n shadow: ['box-shadow'],\n outline: ['outline', 'outline-offset'],\n preset: [\n 'font-size',\n 'line-height',\n 'letter-spacing',\n 'font-weight',\n 'font-style',\n ],\n text: ['font-weight', 'text-decoration-color'],\n color: ['color'],\n opacity: ['opacity'],\n theme: [\n 'color',\n 'background-color',\n 'background-image',\n 'box-shadow',\n 'border',\n 'border-radius',\n 'outline',\n 'opacity',\n SECOND_FILL_COLOR_PROPERTY,\n ],\n width: ['max-width', 'min-width', 'width'],\n height: ['max-height', 'min-height', 'height'],\n gap: ['gap', 'margin'],\n zIndex: ['z-index'],\n inset: ['inset', 'top', 'right', 'bottom', 'left'],\n};\n\nconst DEFAULT_EASING = 'linear';\n\nconst EASING_KEYWORDS = new Set(\n 'ease ease-in ease-out ease-in-out linear step-start step-end'.split(' '),\n);\n\nfunction isEasing(token: string): boolean {\n return (\n EASING_KEYWORDS.has(token) ||\n token.startsWith('cubic-bezier(') ||\n token.startsWith('steps(') ||\n token.startsWith('linear(')\n );\n}\n\nfunction getTiming(name: string): string {\n const varName = name.startsWith('--')\n ? `${name}-transition`\n : `--${name}-transition`;\n return `var(${varName}, var(--transition))`;\n}\n\nexport function transitionStyle({ transition }: { transition?: string }) {\n if (!transition) return null;\n\n if (CSS_WIDE_KEYWORDS.has(transition)) {\n return { transition };\n }\n\n const processed = parseStyle(transition);\n const map: Record<string, string> = {};\n\n for (const group of processed.groups) {\n const tokens = group.all;\n const name = tokens[0];\n\n // The name doubles as the property to transition and as the timing token, so\n // a reference cannot stand in for it.\n if (!name || isTokenNameReference('transition', name)) continue;\n\n let timing: string | undefined;\n let easing: string | undefined;\n let delay: string | undefined;\n\n if (tokens[1] && isEasing(tokens[1])) {\n easing = tokens[1];\n delay = tokens[2];\n } else {\n timing = tokens[1];\n easing = tokens[2];\n delay = tokens[3];\n }\n\n let value = timing || getTiming(name);\n if (easing || delay) {\n value += ` ${easing || DEFAULT_EASING}`;\n }\n if (delay) {\n value += ` ${delay}`;\n }\n\n const styles = MAP[name];\n if (styles) {\n for (const style of styles) map[style] = value;\n } else {\n map[name] = value;\n }\n }\n\n // Every entry may have been rejected as a reference-named transition.\n const result = Object.keys(map)\n .map((style) => `${style} ${map[style]}`)\n .join(', ');\n if (!result) return null;\n\n return { transition: result };\n}\n\ntransitionStyle.__lookupStyles = ['transition'];\n","import { dimensionStyle } from './dimension';\n\nconst dimension = dimensionStyle('width');\n\ninterface WidthStyleProps {\n width?: string | number | boolean;\n minWidth?: string | number | boolean;\n maxWidth?: string | number | boolean;\n}\n\nexport function widthStyle({ width, minWidth, maxWidth }: WidthStyleProps) {\n return dimension({ value: width, min: minWidth, max: maxWidth });\n}\n\nwidthStyle.__lookupStyles = ['width', 'minWidth', 'maxWidth'];\n","import {\n assignStyleChunk,\n CHUNK_NAMES,\n STYLE_TO_CHUNK,\n} from '../chunks/style-chunk-map';\nimport type { ChunkName } from '../chunks/style-chunk-map';\nimport { isDevEnv } from '../utils/is-dev-env';\nimport type {\n AnyStyleHandler,\n RawStyleHandler,\n StyleHandler,\n StyleHandlerDefinition,\n} from '../utils/styles';\n\nimport { borderStyle } from './border';\nimport { blockSizeStyle } from './blockSize';\nimport { colorStyle } from './color';\nimport { createStyle } from './createStyle';\nimport { displayStyle } from './display';\nimport { fadeStyle } from './fade';\nimport { fillStyle, svgFillStyle } from './fill';\nimport { flowStyle } from './flow';\nimport { gapStyle } from './gap';\nimport { heightStyle } from './height';\nimport { insetStyle } from './inset';\nimport { inlineSizeStyle } from './inlineSize';\nimport { logicalStyleHandlers } from './logical';\nimport { marginStyle } from './margin';\nimport { outlineStyle } from './outline';\nimport { paddingStyle } from './padding';\nimport { placementStyle } from './placement';\nimport { presetStyle } from './preset';\nimport { radiusStyle } from './radius';\nimport { scrollMarginStyle } from './scrollMargin';\nimport { scrollPaddingStyle } from './scrollPadding';\nimport { scrollbarStyle } from './scrollbar';\nimport { shadowStyle } from './shadow';\nimport { transitionStyle } from './transition';\nimport { widthStyle } from './width';\n\nconst devMode = isDevEnv();\n\n/**\n * Dev-mode check evaluated per call rather than at module load.\n *\n * `isDevEnv()` reports `false` for `NODE_ENV=test`, so a module-load capture makes\n * a warning impossible to assert in a test. Only used on paths that already know\n * something is wrong, so the extra call is never on the hot path.\n */\nfunction inDevMode(): boolean {\n return isDevEnv();\n}\n\nconst _numberConverter = (val: string | number | boolean | undefined) => {\n if (typeof val === 'number') {\n return `${val}px`;\n }\n\n return val;\n};\n/**\n * Read a grid track count, or `undefined` when the value isn't one.\n *\n * Plain digit strings count: every value inside a state map arrives as a\n * string, so `gridColumns: { '': '2', '@media(w < 600px)': '1' }` would\n * otherwise emit `grid-template-columns: 2` — invalid CSS that browsers drop\n * silently.\n *\n * Zero and negatives yield `undefined`. Zero already produced an empty value,\n * and a negative number used to throw inside `String.repeat`.\n */\nfunction trackCount(\n val: string | number | boolean | undefined,\n): number | undefined {\n const count =\n typeof val === 'number'\n ? val\n : typeof val === 'string' && /^\\d+$/.test(val.trim())\n ? Number(val.trim())\n : NaN;\n\n return Number.isFinite(count) && count >= 1 ? Math.floor(count) : undefined;\n}\n\nconst columnsConverter = (val: string | number | boolean | undefined) => {\n const count = trackCount(val);\n\n return count === undefined\n ? undefined\n : 'minmax(1px, 1fr) '.repeat(count).trim();\n};\nconst rowsConverter = (val: string | number | boolean | undefined) => {\n const count = trackCount(val);\n\n return count === undefined ? undefined : 'auto '.repeat(count).trim();\n};\n\ntype StyleHandlerMap = Record<string, AnyStyleHandler[]>;\n\nconst STYLE_HANDLER_MAP: StyleHandlerMap = {};\n\nfunction addStyleHandler(name: string, handler: AnyStyleHandler): void {\n (STYLE_HANDLER_MAP[name] ??= []).push(handler);\n}\n\n/**\n * Reset STYLE_HANDLER_MAP to the initial built-in state.\n * Called by resetConfig() to restore handlers after tests.\n */\nexport function resetHandlers(): void {\n for (const key of Object.keys(STYLE_HANDLER_MAP)) {\n delete STYLE_HANDLER_MAP[key];\n }\n\n // Replay the canonical registration list instead of retaining a duplicate\n // snapshot of every handler array for the lifetime of the module.\n predefine();\n}\n\nfunction defineCustomStyle(handler: AnyStyleHandler): void {\n for (const name of handler.__lookupStyles) {\n addStyleHandler(name, handler);\n }\n}\n\ntype ConverterHandler = (\n s: string | boolean | number | undefined,\n) => string | undefined;\n\nfunction defineStyleAlias(\n styleName: string,\n cssStyleName?: string,\n converter?: ConverterHandler,\n) {\n addStyleHandler(styleName, createStyle(styleName, cssStyleName, converter));\n}\n\nexport function predefine() {\n // Style aliases\n defineStyleAlias('gridAreas', 'grid-template-areas');\n defineStyleAlias('gridColumns', 'grid-template-columns', columnsConverter);\n defineStyleAlias('gridRows', 'grid-template-rows', rowsConverter);\n defineStyleAlias(\n 'gridTemplate',\n 'grid-template',\n (val: string | boolean | number | undefined) => {\n if (typeof val !== 'string') return;\n\n // Each side converts independently, and a side that isn't a track count\n // (`auto`, `1fr`, an areas string) is kept verbatim.\n return val\n .split('/')\n .map((s, i) => (i ? columnsConverter : rowsConverter)(s) ?? s)\n .join('/');\n },\n );\n // Note: outlineOffset is now handled by outlineStyle\n\n [\n displayStyle,\n transitionStyle,\n fillStyle,\n svgFillStyle,\n widthStyle,\n marginStyle,\n gapStyle,\n flowStyle,\n colorStyle,\n heightStyle,\n radiusStyle,\n borderStyle,\n shadowStyle,\n paddingStyle,\n placementStyle,\n presetStyle,\n scrollMarginStyle,\n outlineStyle,\n scrollbarStyle,\n fadeStyle,\n insetStyle,\n blockSizeStyle,\n inlineSizeStyle,\n scrollPaddingStyle,\n ...Object.values(logicalStyleHandlers),\n ].forEach((handler) => defineCustomStyle(handler));\n\n return STYLE_HANDLER_MAP;\n}\n\n// ============================================================================\n// Handler Registration API (for configure())\n// ============================================================================\n\n/**\n * Normalize a handler definition to a StyleHandler with __lookupStyles.\n * - Function only: lookup styles inferred from key name\n * - [string, fn]: single lookup style\n * - [string[], fn]: multiple lookup styles\n */\nexport function normalizeHandlerDefinition(\n keyName: string,\n definition: StyleHandlerDefinition,\n): StyleHandler {\n let handler: RawStyleHandler;\n let lookupStyles: string[];\n\n if (typeof definition === 'function') {\n // Function only - lookup styles inferred from key name\n handler = definition;\n lookupStyles = [keyName];\n } else if (Array.isArray(definition)) {\n const [first, fn] = definition;\n\n if (typeof fn !== 'function') {\n throw new Error(\n `[Tasty] Invalid handler definition for \"${keyName}\". ` +\n 'Tuple must have a function as the second element: [string, function] or [string[], function].',\n );\n }\n\n handler = fn;\n\n if (typeof first === 'string') {\n // [string, fn] - single lookup style\n lookupStyles = [first];\n } else if (Array.isArray(first)) {\n // [string[], fn] - multiple lookup styles\n lookupStyles = first;\n } else {\n throw new Error(\n `[Tasty] Invalid handler definition for \"${keyName}\". ` +\n 'First element must be a string or string array.',\n );\n }\n } else {\n throw new Error(\n `[Tasty] Invalid handler definition for \"${keyName}\". ` +\n 'Expected function, [string, function], or [string[], function].',\n );\n }\n\n // Validate lookup styles in dev mode\n validateLookupStyles(keyName, lookupStyles);\n\n // Wrap the handler to avoid mutation issues when the same function\n // is reused for multiple handler definitions. Each registration\n // gets its own function identity with its own __lookupStyles.\n const wrappedHandler = ((props) => handler(props)) as StyleHandler;\n wrappedHandler.__lookupStyles = lookupStyles;\n\n return wrappedHandler;\n}\n\n/**\n * Validate a handler's lookup styles in development mode.\n */\nfunction validateLookupStyles(name: string, lookupStyles: string[]): void {\n if (!devMode) return;\n\n if (\n !lookupStyles ||\n !Array.isArray(lookupStyles) ||\n lookupStyles.length === 0\n ) {\n console.warn(\n `[Tasty] Handler \"${name}\" has invalid lookupStyles. ` +\n 'Expected non-empty array of style names.',\n );\n }\n}\n\nexport interface RegisterHandlerOptions {\n /** The `handlers` key this handler was registered under, for diagnostics. */\n key?: string;\n /** Where it came from — a plugin name, or `'configure()'`. */\n source?: string;\n}\n\n/** Describe a handler in a warning message. */\nfunction describeHandler(\n lookupStyles: string[],\n options?: RegisterHandlerOptions,\n): string {\n const name = options?.key ?? lookupStyles.join(', ');\n\n return options?.source ? `\"${name}\" (from ${options.source})` : `\"${name}\"`;\n}\n\n/**\n * Keep a handler's dependencies inside one chunk.\n *\n * Chunks are rendered and cached independently and a chunk's cache key covers\n * only its own style values, so a handler whose `__lookupStyles` straddle two\n * chunks gets invoked once per chunk with a *subset* of its inputs — and can emit\n * stale CSS. Custom style names are unknown to the built-in chunk lists and would\n * otherwise fall into `misc`, splitting any handler that mixes them with built-in\n * styles. Pull them into the built-in chunk instead.\n *\n * Runs in production too: this is a correctness fix, not a diagnostic. It only\n * ever moves names the built-in lists don't know, so no existing class name can\n * change.\n */\nfunction alignHandlerChunks(\n lookupStyles: string[],\n options?: RegisterHandlerOptions,\n): void {\n const known = new Set<ChunkName>();\n const unknown: string[] = [];\n\n for (const styleName of lookupStyles) {\n const chunk = STYLE_TO_CHUNK.get(styleName);\n\n if (chunk) {\n known.add(chunk);\n } else {\n unknown.push(styleName);\n }\n }\n\n if (known.size > 1) {\n // The handler bridges two built-in chunks. Resolving this correctly would\n // mean re-deriving chunk membership across the whole handler graph, which can\n // move built-in styles between chunks and change class names — so warn only.\n if (inDevMode()) {\n console.warn(\n `[Tasty] Handler ${describeHandler(lookupStyles, options)} depends on ` +\n `styles from different chunks (${[...known].sort().join(', ')}). ` +\n `Chunks are cached independently, so this handler will be invoked once ` +\n `per chunk with only part of its dependencies and can emit stale CSS. ` +\n `Split it into per-chunk handlers, or have one property expand into the ` +\n `others before chunking.`,\n );\n }\n\n return;\n }\n\n if (unknown.length === 0) return;\n\n // Exactly one known chunk → custom names join it. No known chunk → pin them\n // together in `misc`, where they would land anyway, so they stay together even\n // if one of them later becomes known.\n const target = known.size === 1 ? [...known][0] : CHUNK_NAMES.MISC;\n\n for (const styleName of unknown) {\n assignStyleChunk(styleName, target);\n }\n}\n\n/**\n * Warn when replacing a handler takes unrelated style properties down with it.\n *\n * Built-in handlers are shared across several style names (`displayStyle` also\n * emits `hide`, `overflow`, `whiteSpace`, `textOverflow`), so registering a\n * handler for one of them unregisters the built-in from *all* of its names. The\n * displaced names don't go dark — the pipeline falls back to an auto-generated\n * CSS alias and writes it back into the map — so `hide: true` starts emitting a\n * literal `hide: true` declaration. Silent wrongness, which is worth a warning.\n *\n * Must run before the handlers are actually removed.\n */\nfunction warnAboutOrphanedStyles(\n lookupStyles: string[],\n handlersToRemove: Set<StyleHandler>,\n options?: RegisterHandlerOptions,\n): void {\n const incoming = new Set(lookupStyles);\n const orphaned = new Set<string>();\n\n for (const oldHandler of handlersToRemove) {\n for (const oldStyleName of oldHandler.__lookupStyles ?? []) {\n if (incoming.has(oldStyleName)) continue;\n\n const survivors = (STYLE_HANDLER_MAP[oldStyleName] ?? []).filter(\n (h) => !handlersToRemove.has(h),\n );\n\n if (survivors.length === 0) orphaned.add(oldStyleName);\n }\n }\n\n if (orphaned.size === 0) return;\n\n console.warn(\n `[Tasty] Custom handler ${describeHandler(lookupStyles, options)} displaced ` +\n `built-in handlers that also handle: ${[...orphaned].sort().join(', ')}. ` +\n `Those properties now fall back to auto-generated CSS aliases, which is ` +\n `usually wrong (e.g. \\`hide: true\\` would emit a literal \\`hide: true\\` ` +\n `declaration). Either declare them in this handler's lookup styles and ` +\n `delegate via \\`styleHandlers.*\\`, or pick a narrower style name.`,\n );\n}\n\n/**\n * Register a custom handler, replacing any existing handlers for the same lookup styles.\n * This is called by configure() to process user-defined handlers.\n *\n * When registering a handler for style X, any existing handler that processes X\n * is removed from ALL its lookup styles to prevent double-processing.\n * For example, if gapStyle handles ['display', 'flow', 'gap'] and a new handler\n * is registered for just ['gap'], gapStyle is removed from display and flow too.\n *\n * Note: this bypasses the `configure()` lock, so calling it after styles have\n * been generated changes the handlers for already-emitted class names. Prefer\n * `configure({ handlers })`, which is rejected after first render.\n */\nexport function registerHandler(\n handler: StyleHandler,\n options?: RegisterHandlerOptions,\n): void {\n const lookupStyles = handler.__lookupStyles;\n\n if (!lookupStyles || lookupStyles.length === 0) {\n if (devMode) {\n console.warn(\n '[Tasty] Cannot register handler without __lookupStyles property.',\n );\n }\n return;\n }\n\n alignHandlerChunks(lookupStyles, options);\n\n // Find and remove existing handlers that would conflict\n // A handler conflicts if it handles any of the same styles as the new handler\n const handlersToRemove = new Set<StyleHandler>();\n\n for (const styleName of lookupStyles) {\n const existing = STYLE_HANDLER_MAP[styleName];\n if (existing) {\n for (const existingHandler of existing) {\n handlersToRemove.add(existingHandler);\n }\n }\n }\n\n if (handlersToRemove.size > 0 && inDevMode()) {\n warnAboutOrphanedStyles(lookupStyles, handlersToRemove, options);\n }\n\n // Remove conflicting handlers from ALL their lookup styles\n for (const oldHandler of handlersToRemove) {\n const oldLookupStyles = oldHandler.__lookupStyles;\n if (oldLookupStyles) {\n for (const oldStyleName of oldLookupStyles) {\n const handlers = STYLE_HANDLER_MAP[oldStyleName];\n if (handlers) {\n const filtered = handlers.filter((h) => h !== oldHandler);\n if (filtered.length === 0) {\n delete STYLE_HANDLER_MAP[oldStyleName];\n } else {\n STYLE_HANDLER_MAP[oldStyleName] = filtered;\n }\n }\n }\n }\n }\n\n // Register the new handler under its lookup styles\n for (const styleName of lookupStyles) {\n addStyleHandler(styleName, handler);\n }\n}\n\n// ============================================================================\n// Wrapped Style Handlers Export\n// ============================================================================\n\n/**\n * Create a wrapped handler that can be safely called by users.\n * The wrapper preserves __lookupStyles for proper registration.\n */\nfunction wrapHandler<T extends { __lookupStyles: string[] }>(handler: T): T {\n const fn = handler as unknown as (props: unknown) => unknown;\n const wrapped = ((props: unknown) => fn(props)) as unknown as T;\n wrapped.__lookupStyles = handler.__lookupStyles;\n return wrapped;\n}\n\nfunction wrapHandlerRecord<\n T extends Record<string, { __lookupStyles: string[] }>,\n>(handlers: T): T {\n return Object.fromEntries(\n Object.entries(handlers).map(([name, handler]) => [\n name,\n wrapHandler(handler),\n ]),\n ) as T;\n}\n\nconst wrappedLogicalStyleHandlers = wrapHandlerRecord(logicalStyleHandlers);\n\n/**\n * Exported object containing wrapped predefined style handlers.\n * Users can import and call these to extend or delegate to built-in behavior.\n *\n * Internal handlers use *Style suffix for searchability.\n * External API uses short names for convenience.\n *\n * @example\n * ```ts\n * import { styleHandlers, configure } from '@tenphi/tasty';\n *\n * configure({\n * handlers: {\n * fill: ({ fill }) => {\n * if (fill?.startsWith('gradient:')) {\n * return { background: fill.slice(9) };\n * }\n * return styleHandlers.fill({ fill });\n * },\n * },\n * });\n * ```\n */\nexport const styleHandlers = {\n blockSize: wrapHandler(blockSizeStyle),\n border: wrapHandler(borderStyle),\n color: wrapHandler(colorStyle),\n display: wrapHandler(displayStyle),\n fade: wrapHandler(fadeStyle),\n fill: wrapHandler(fillStyle),\n svgFill: wrapHandler(svgFillStyle),\n flow: wrapHandler(flowStyle),\n gap: wrapHandler(gapStyle),\n height: wrapHandler(heightStyle),\n inset: wrapHandler(insetStyle),\n inlineSize: wrapHandler(inlineSizeStyle),\n ...wrappedLogicalStyleHandlers,\n margin: wrapHandler(marginStyle),\n outline: wrapHandler(outlineStyle),\n padding: wrapHandler(paddingStyle),\n placement: wrapHandler(placementStyle),\n preset: wrapHandler(presetStyle),\n radius: wrapHandler(radiusStyle),\n scrollMargin: wrapHandler(scrollMarginStyle),\n scrollPadding: wrapHandler(scrollPaddingStyle),\n scrollbar: wrapHandler(scrollbarStyle),\n shadow: wrapHandler(shadowStyle),\n transition: wrapHandler(transitionStyle),\n width: wrapHandler(widthStyle),\n} as const;\n","import type {\n RawStyleHandler,\n ResolvedStyleValue,\n StyleHandlerResult,\n} from '../utils/styles';\n\n/**\n * Declare a multi-dependency style handler with its dependency names inferred\n * into the handler's parameter type.\n *\n * Without it, the multi-dependency tuple form needs a hand-written parameter\n * annotation that can silently drift from the dependency list:\n *\n * ```ts\n * // Annotation and dependency list are maintained separately.\n * handlers: {\n * spacing: [['gap', 'padding'], ({ gap, padding }: { gap?: string; padding?: string }) => …],\n * }\n *\n * // Both come from the same array; a typo in the destructure is a type error.\n * handlers: {\n * spacing: defineHandler(['gap', 'padding'], ({ gap, padding }) => …),\n * }\n * ```\n *\n * Values arrive **state-resolved but unparsed** — the raw authored DSL string\n * (`'2x'`, `'#purple.5'`), so call `parseStyle()` / `parseColor()` as needed. The\n * result is a kebab-case CSS declaration map (or an array of them); the reserved\n * `$` key applies the declarations to a nested selector.\n *\n * All names must belong to the same chunk. Names the built-in chunk lists don't\n * know are pulled into their handler's chunk automatically at registration.\n */\nexport function defineHandler<const TDeps extends readonly string[]>(\n deps: TDeps,\n handler: (\n props: Partial<Record<TDeps[number], ResolvedStyleValue>>,\n ) => StyleHandlerResult,\n): [readonly string[], RawStyleHandler] {\n return [deps, handler as RawStyleHandler];\n}\n","import { predefine, styleHandlers } from './predefined';\n\nconst STYLE_HANDLER_MAP = predefine();\n\nexport { STYLE_HANDLER_MAP, styleHandlers };\nexport * from './createStyle';\nexport { defineHandler } from './define-handler';\nexport {\n normalizeHandlerDefinition,\n registerHandler,\n resetHandlers,\n} from './predefined';\n","/**\n * ConditionNode Types and Helpers\n *\n * Core data structures for representing style conditions as an abstract syntax tree.\n * Used throughout the pipeline for parsing, simplification, and CSS generation.\n */\n\n// ============================================================================\n// Core ConditionNode Types\n// ============================================================================\n\n/**\n * Base interface for all state conditions (leaf nodes)\n */\ninterface BaseStateCondition {\n kind: 'state';\n negated: boolean;\n raw: string; // Original string for debugging/caching\n uniqueId: string; // Normalized ID for comparison (built from props)\n}\n\n/**\n * Modifier condition: [data-attr] or [data-attr=\"value\"]\n */\nexport interface ModifierCondition extends BaseStateCondition {\n type: 'modifier';\n attribute: string; // e.g., 'data-theme', 'data-size'\n value?: string; // e.g., 'danger', 'large' (undefined = boolean attr)\n operator?: '=' | '^=' | '$=' | '*='; // Attribute match operator\n}\n\n/**\n * Pseudo-class condition: :hover, :focus-visible\n */\nexport interface PseudoCondition extends BaseStateCondition {\n type: 'pseudo';\n pseudo: string; // e.g., ':hover', ':focus-visible', ':nth-child(2n)'\n}\n\n/**\n * Numeric bound for dimension queries\n */\nexport interface NumericBound {\n value: string; // e.g., '768px', 'calc(var(--gap) * 40)'\n valueNumeric: number | null; // Parsed numeric value for comparison\n inclusive: boolean; // true for >=/<= , false for >/<\n}\n\n/**\n * Media query condition\n */\nexport interface MediaCondition extends BaseStateCondition {\n type: 'media';\n subtype: 'dimension' | 'feature' | 'type';\n\n // For dimension queries: @media(w < 768px), @media(600px <= w < 1200px)\n dimension?: 'width' | 'height' | 'inline-size' | 'block-size';\n lowerBound?: NumericBound; // >= or >\n upperBound?: NumericBound; // <= or <\n\n // For feature queries: @media(prefers-contrast: high)\n feature?: string; // e.g., 'prefers-contrast', 'prefers-color-scheme'\n featureValue?: string; // e.g., 'high', 'dark' (undefined = boolean feature)\n\n // For type queries: @media:print\n mediaType?: 'print' | 'screen' | 'all' | 'speech';\n}\n\n/**\n * Container query condition\n */\nexport interface ContainerCondition extends BaseStateCondition {\n type: 'container';\n subtype: 'dimension' | 'style' | 'raw';\n containerName?: string; // e.g., 'layout', 'sidebar' (undefined = nearest)\n\n // For dimension queries: @(w < 600px), @(layout, w < 600px)\n dimension?: 'width' | 'height' | 'inline-size' | 'block-size';\n lowerBound?: NumericBound;\n upperBound?: NumericBound;\n\n // For style queries: @(layout, $variant=danger), @($theme)\n property?: string; // CSS custom property name (without --)\n propertyValue?: string; // e.g., 'danger' (undefined = existence check)\n\n // For raw function queries: @(scroll-state(stuck: top)), @(style(display: flex))\n rawCondition?: string; // Verbatim CSS condition string\n}\n\n/**\n * Root state condition: @root(theme=dark)\n */\nexport interface RootCondition extends BaseStateCondition {\n type: 'root';\n innerCondition: ConditionNode;\n}\n\n/**\n * Parent state condition: @parent(hovered), @parent(theme=dark, >)\n */\nexport interface ParentCondition extends BaseStateCondition {\n type: 'parent';\n innerCondition: ConditionNode;\n direct: boolean; // true for @parent(..., >) — direct parent only\n}\n\n/**\n * Own state condition: @own(hovered)\n */\nexport interface OwnCondition extends BaseStateCondition {\n type: 'own';\n innerCondition: ConditionNode; // The parsed inner condition\n}\n\n/**\n * Starting style condition: @starting\n */\nexport interface StartingCondition extends BaseStateCondition {\n type: 'starting';\n}\n\n/**\n * Supports query condition: @supports(display: grid), @supports($, :has(*))\n */\nexport interface SupportsCondition extends BaseStateCondition {\n type: 'supports';\n subtype: 'feature' | 'selector';\n // The raw condition string (e.g., \"display: grid\" or \":has(*)\")\n condition: string;\n}\n\n/**\n * Union of all state condition types\n */\nexport type StateCondition =\n | ModifierCondition\n | PseudoCondition\n | MediaCondition\n | ContainerCondition\n | RootCondition\n | ParentCondition\n | OwnCondition\n | StartingCondition\n | SupportsCondition;\n\n/**\n * Compound node: combines conditions with AND/OR\n */\nexport interface CompoundCondition {\n kind: 'compound';\n operator: 'AND' | 'OR';\n children: ConditionNode[];\n}\n\n/**\n * True condition (matches everything)\n */\nexport interface TrueCondition {\n kind: 'true';\n}\n\n/**\n * False condition (matches nothing - skip this rule)\n */\nexport interface FalseCondition {\n kind: 'false';\n}\n\n/**\n * Union of all condition node types\n */\nexport type ConditionNode =\n StateCondition | CompoundCondition | TrueCondition | FalseCondition;\n\n/** Serialize numeric bounds using CSS range syntax. */\nexport function buildDimensionCondition(\n dimension: string,\n lowerBound?: Pick<NumericBound, 'value' | 'inclusive'>,\n upperBound?: Pick<NumericBound, 'value' | 'inclusive'>,\n emptyDimension = dimension,\n): string {\n if (lowerBound && upperBound) {\n const lowerOp = lowerBound.inclusive ? '<=' : '<';\n const upperOp = upperBound.inclusive ? '<=' : '<';\n return `(${lowerBound.value} ${lowerOp} ${dimension} ${upperOp} ${upperBound.value})`;\n }\n if (upperBound) {\n return `(${dimension} ${upperBound.inclusive ? '<=' : '<'} ${upperBound.value})`;\n }\n if (lowerBound) {\n return `(${dimension} ${lowerBound.inclusive ? '>=' : '>'} ${lowerBound.value})`;\n }\n return `(${emptyDimension})`;\n}\n\n// ============================================================================\n// Constructor Functions\n// ============================================================================\n\n/**\n * Create a TRUE condition (matches everything)\n */\nexport function trueCondition(): TrueCondition {\n return { kind: 'true' };\n}\n\n/**\n * Create a FALSE condition (matches nothing)\n */\nexport function falseCondition(): FalseCondition {\n return { kind: 'false' };\n}\n\n/**\n * Create an AND compound condition\n */\nexport function and(...children: ConditionNode[]): ConditionNode {\n const filtered: ConditionNode[] = [];\n\n for (const child of children) {\n // Short-circuit on FALSE\n if (child.kind === 'false') {\n return falseCondition();\n }\n // Skip TRUE (identity for AND)\n if (child.kind === 'true') {\n continue;\n }\n // Flatten nested ANDs\n if (child.kind === 'compound' && child.operator === 'AND') {\n filtered.push(...child.children);\n } else {\n filtered.push(child);\n }\n }\n\n if (filtered.length === 0) {\n return trueCondition();\n }\n if (filtered.length === 1) {\n return filtered[0];\n }\n\n return {\n kind: 'compound',\n operator: 'AND',\n children: filtered,\n };\n}\n\n/**\n * Create an OR compound condition\n */\nexport function or(...children: ConditionNode[]): ConditionNode {\n const filtered: ConditionNode[] = [];\n\n for (const child of children) {\n // Short-circuit on TRUE\n if (child.kind === 'true') {\n return trueCondition();\n }\n // Skip FALSE (identity for OR)\n if (child.kind === 'false') {\n continue;\n }\n // Flatten nested ORs\n if (child.kind === 'compound' && child.operator === 'OR') {\n filtered.push(...child.children);\n } else {\n filtered.push(child);\n }\n }\n\n if (filtered.length === 0) {\n return falseCondition();\n }\n if (filtered.length === 1) {\n return filtered[0];\n }\n\n return {\n kind: 'compound',\n operator: 'OR',\n children: filtered,\n };\n}\n\n/**\n * Negate a condition\n */\nexport function not(node: ConditionNode): ConditionNode {\n // NOT(TRUE) = FALSE\n if (node.kind === 'true') {\n return falseCondition();\n }\n\n // NOT(FALSE) = TRUE\n if (node.kind === 'false') {\n return trueCondition();\n }\n\n // NOT(state) = toggle negated flag\n if (node.kind === 'state') {\n return {\n ...node,\n negated: !node.negated,\n uniqueId: node.negated\n ? node.uniqueId.replace(/^!/, '')\n : `!${node.uniqueId}`,\n };\n }\n\n // NOT(AND(a, b, ...)) = OR(NOT(a), NOT(b), ...) - De Morgan's law\n if (node.kind === 'compound' && node.operator === 'AND') {\n return or(...node.children.map((c) => not(c)));\n }\n\n // NOT(OR(a, b, ...)) = AND(NOT(a), NOT(b), ...) - De Morgan's law\n if (node.kind === 'compound' && node.operator === 'OR') {\n return and(...node.children.map((c) => not(c)));\n }\n\n // Fallback - should not reach here\n return node;\n}\n\n// ============================================================================\n// Condition Type Checking\n// ============================================================================\n\n/**\n * Check if a condition is a compound condition\n */\nexport function isCompoundCondition(\n node: ConditionNode,\n): node is CompoundCondition {\n return node.kind === 'compound';\n}\n\n// ============================================================================\n// UniqueId Generation\n// ============================================================================\n\n/**\n * Generate a normalized unique ID for a modifier condition\n */\nfunction modifierUniqueId(\n attribute: string,\n value?: string,\n operator = '=',\n negated = false,\n): string {\n const base = value\n ? `mod:${attribute}${operator}${value}`\n : `mod:${attribute}`;\n return negated ? `!${base}` : base;\n}\n\n/**\n * Generate a normalized unique ID for a pseudo condition\n */\nfunction pseudoUniqueId(pseudo: string, negated = false): string {\n const base = `pseudo:${pseudo}`;\n return negated ? `!${base}` : base;\n}\n\n/**\n * Generate a normalized unique ID for a media condition\n */\nfunction mediaUniqueId(\n subtype: 'dimension' | 'feature' | 'type',\n props: {\n dimension?: string;\n lowerBound?: NumericBound;\n upperBound?: NumericBound;\n feature?: string;\n featureValue?: string;\n mediaType?: string;\n },\n negated = false,\n): string {\n let base: string;\n\n if (subtype === 'dimension') {\n const parts = ['media', 'dim', props.dimension];\n if (props.lowerBound) {\n parts.push(props.lowerBound.inclusive ? '>=' : '>');\n parts.push(props.lowerBound.value);\n }\n if (props.upperBound) {\n parts.push(props.upperBound.inclusive ? '<=' : '<');\n parts.push(props.upperBound.value);\n }\n base = parts.join(':');\n } else if (subtype === 'feature') {\n base = props.featureValue\n ? `media:feat:${props.feature}:${props.featureValue}`\n : `media:feat:${props.feature}`;\n } else {\n base = `media:type:${props.mediaType}`;\n }\n\n return negated ? `!${base}` : base;\n}\n\n/**\n * Generate a normalized unique ID for a container condition\n */\nfunction containerUniqueId(\n subtype: 'dimension' | 'style' | 'raw',\n props: {\n containerName?: string;\n dimension?: string;\n lowerBound?: NumericBound;\n upperBound?: NumericBound;\n property?: string;\n propertyValue?: string;\n rawCondition?: string;\n },\n negated = false,\n): string {\n let base: string;\n const name = props.containerName || '_';\n\n if (subtype === 'dimension') {\n const parts = ['container', 'dim', name, props.dimension];\n if (props.lowerBound) {\n parts.push(props.lowerBound.inclusive ? '>=' : '>');\n parts.push(props.lowerBound.value);\n }\n if (props.upperBound) {\n parts.push(props.upperBound.inclusive ? '<=' : '<');\n parts.push(props.upperBound.value);\n }\n base = parts.join(':');\n } else if (subtype === 'raw') {\n base = `container:raw:${name}:${props.rawCondition}`;\n } else {\n base = props.propertyValue\n ? `container:style:${name}:--${props.property}:${props.propertyValue}`\n : `container:style:${name}:--${props.property}`;\n }\n\n return negated ? `!${base}` : base;\n}\n\n/**\n * Generate a normalized unique ID for a root condition\n */\nfunction rootUniqueId(innerUniqueId: string, negated = false): string {\n const base = `root:${innerUniqueId}`;\n return negated ? `!${base}` : base;\n}\n\n/**\n * Generate a normalized unique ID for a parent condition\n */\nfunction parentUniqueId(\n innerUniqueId: string,\n direct: boolean,\n negated = false,\n): string {\n const base = `parent:${direct ? '>' : ''}${innerUniqueId}`;\n return negated ? `!${base}` : base;\n}\n\n/**\n * Generate a normalized unique ID for an own condition\n */\nfunction ownUniqueId(innerUniqueId: string, negated = false): string {\n const base = `own:${innerUniqueId}`;\n return negated ? `!${base}` : base;\n}\n\n/**\n * Generate a normalized unique ID for a starting condition\n */\nfunction startingUniqueId(negated = false): string {\n return negated ? '!starting' : 'starting';\n}\n\n/**\n * Generate a normalized unique ID for a supports condition\n */\nfunction supportsUniqueId(\n subtype: 'feature' | 'selector',\n condition: string,\n negated = false,\n): string {\n const base = `supports:${subtype}:${condition}`;\n return negated ? `!${base}` : base;\n}\n\n// ============================================================================\n// Condition Creation Helpers\n// ============================================================================\n\n/**\n * Create a modifier condition\n */\nexport function createModifierCondition(\n attribute: string,\n value?: string,\n operator: '=' | '^=' | '$=' | '*=' = '=',\n negated = false,\n raw?: string,\n): ModifierCondition {\n return {\n kind: 'state',\n type: 'modifier',\n negated,\n raw: raw || (value ? `${attribute}${operator}${value}` : attribute),\n uniqueId: modifierUniqueId(attribute, value, operator, negated),\n attribute,\n value,\n operator: value ? operator : undefined,\n };\n}\n\n/**\n * Create a pseudo condition\n */\nexport function createPseudoCondition(\n pseudo: string,\n negated = false,\n raw?: string,\n): PseudoCondition {\n return {\n kind: 'state',\n type: 'pseudo',\n negated,\n raw: raw || pseudo,\n uniqueId: pseudoUniqueId(pseudo, negated),\n pseudo,\n };\n}\n\n/**\n * Create a media dimension condition\n */\nexport function createMediaDimensionCondition(\n dimension: 'width' | 'height' | 'inline-size' | 'block-size',\n lowerBound?: NumericBound,\n upperBound?: NumericBound,\n negated = false,\n raw?: string,\n): MediaCondition {\n return {\n kind: 'state',\n type: 'media',\n subtype: 'dimension',\n negated,\n raw: raw || `@media(${dimension})`,\n uniqueId: mediaUniqueId(\n 'dimension',\n { dimension, lowerBound, upperBound },\n negated,\n ),\n dimension,\n lowerBound,\n upperBound,\n };\n}\n\n/**\n * Create a media feature condition\n */\nexport function createMediaFeatureCondition(\n feature: string,\n featureValue?: string,\n negated = false,\n raw?: string,\n): MediaCondition {\n return {\n kind: 'state',\n type: 'media',\n subtype: 'feature',\n negated,\n raw: raw || `@media(${feature}${featureValue ? `: ${featureValue}` : ''})`,\n uniqueId: mediaUniqueId('feature', { feature, featureValue }, negated),\n feature,\n featureValue,\n };\n}\n\n/**\n * Create a media type condition\n */\nexport function createMediaTypeCondition(\n mediaType: 'print' | 'screen' | 'all' | 'speech',\n negated = false,\n raw?: string,\n): MediaCondition {\n return {\n kind: 'state',\n type: 'media',\n subtype: 'type',\n negated,\n raw: raw || `@media:${mediaType}`,\n uniqueId: mediaUniqueId('type', { mediaType }, negated),\n mediaType,\n };\n}\n\n/**\n * Create a container dimension condition\n */\nexport function createContainerDimensionCondition(\n dimension: 'width' | 'height' | 'inline-size' | 'block-size',\n lowerBound?: NumericBound,\n upperBound?: NumericBound,\n containerName?: string,\n negated = false,\n raw?: string,\n): ContainerCondition {\n return {\n kind: 'state',\n type: 'container',\n subtype: 'dimension',\n negated,\n raw: raw || `@(${containerName ? containerName + ', ' : ''}${dimension})`,\n uniqueId: containerUniqueId(\n 'dimension',\n { containerName, dimension, lowerBound, upperBound },\n negated,\n ),\n containerName,\n dimension,\n lowerBound,\n upperBound,\n };\n}\n\n/**\n * Create a container style condition\n */\nexport function createContainerStyleCondition(\n property: string,\n propertyValue?: string,\n containerName?: string,\n negated = false,\n raw?: string,\n): ContainerCondition {\n return {\n kind: 'state',\n type: 'container',\n subtype: 'style',\n negated,\n raw:\n raw ||\n `@(${containerName ? containerName + ', ' : ''}$${property}${propertyValue ? '=' + propertyValue : ''})`,\n uniqueId: containerUniqueId(\n 'style',\n { containerName, property, propertyValue },\n negated,\n ),\n containerName,\n property,\n propertyValue,\n };\n}\n\n/**\n * Create a container raw function condition (e.g., scroll-state(), style(), etc.)\n * The condition string is passed through to CSS verbatim.\n */\nexport function createContainerRawCondition(\n rawCondition: string,\n containerName?: string,\n negated = false,\n raw?: string,\n): ContainerCondition {\n return {\n kind: 'state',\n type: 'container',\n subtype: 'raw',\n negated,\n raw:\n raw || `@(${containerName ? containerName + ', ' : ''}${rawCondition})`,\n uniqueId: containerUniqueId(\n 'raw',\n { containerName, rawCondition },\n negated,\n ),\n containerName,\n rawCondition,\n };\n}\n\n/**\n * Create a root condition\n */\nexport function createRootCondition(\n innerCondition: ConditionNode,\n negated = false,\n raw?: string,\n): RootCondition {\n const innerUniqueId = getConditionUniqueId(innerCondition);\n return {\n kind: 'state',\n type: 'root',\n negated,\n raw: raw || `@root(${innerUniqueId})`,\n uniqueId: rootUniqueId(innerUniqueId, negated),\n innerCondition,\n };\n}\n\n/**\n * Create a parent condition\n */\nexport function createParentCondition(\n innerCondition: ConditionNode,\n direct: boolean,\n negated = false,\n raw?: string,\n): ParentCondition {\n const innerUniqueId = getConditionUniqueId(innerCondition);\n return {\n kind: 'state',\n type: 'parent',\n negated,\n raw: raw || `@parent(${innerUniqueId})`,\n uniqueId: parentUniqueId(innerUniqueId, direct, negated),\n innerCondition,\n direct,\n };\n}\n\n/**\n * Create an own condition\n */\nexport function createOwnCondition(\n innerCondition: ConditionNode,\n negated = false,\n raw?: string,\n): OwnCondition {\n const innerUniqueId = getConditionUniqueId(innerCondition);\n return {\n kind: 'state',\n type: 'own',\n negated,\n raw: raw || `@own(...)`,\n uniqueId: ownUniqueId(innerUniqueId, negated),\n innerCondition,\n };\n}\n\n/**\n * Create a starting condition\n */\nexport function createStartingCondition(\n negated = false,\n raw?: string,\n): StartingCondition {\n return {\n kind: 'state',\n type: 'starting',\n negated,\n raw: raw || '@starting',\n uniqueId: startingUniqueId(negated),\n };\n}\n\n/**\n * Create a supports condition\n *\n * @param subtype 'feature' for @supports(display: grid), 'selector' for @supports($, :has(*))\n * @param condition The condition string (e.g., \"display: grid\" or \":has(*)\")\n */\nexport function createSupportsCondition(\n subtype: 'feature' | 'selector',\n condition: string,\n negated = false,\n raw?: string,\n): SupportsCondition {\n return {\n kind: 'state',\n type: 'supports',\n subtype,\n negated,\n raw: raw || `@supports(${condition})`,\n uniqueId: supportsUniqueId(subtype, condition, negated),\n condition,\n };\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\nconst uniqueIdCache = new WeakMap<ConditionNode, string>();\n\n/**\n * Get the unique ID for any condition node.\n * Results are memoized via WeakMap since condition nodes are immutable.\n */\nexport function getConditionUniqueId(node: ConditionNode): string {\n const cached = uniqueIdCache.get(node);\n if (cached !== undefined) return cached;\n\n let id: string;\n if (node.kind === 'true') {\n id = 'TRUE';\n } else if (node.kind === 'false') {\n id = 'FALSE';\n } else if (node.kind === 'state') {\n id = node.uniqueId;\n } else if (node.kind === 'compound') {\n const childIds = node.children.map(getConditionUniqueId).sort();\n id = `${node.operator}(${childIds.join(',')})`;\n } else {\n id = 'UNKNOWN';\n }\n\n uniqueIdCache.set(node, id);\n return id;\n}\n","/**\n * Condition Simplification Engine\n *\n * Simplifies condition trees by applying boolean algebra rules,\n * detecting contradictions, merging ranges, and deduplicating terms.\n *\n * This is critical for:\n * 1. Detecting invalid combinations (A & !A → FALSE)\n * 2. Reducing CSS output size\n * 3. Producing cleaner selectors\n */\n\nimport { Lru } from '../parser/lru';\n\nimport type {\n ConditionNode,\n ContainerCondition,\n MediaCondition,\n ModifierCondition,\n NumericBound,\n OwnCondition,\n RootCondition,\n} from './conditions';\nimport {\n and,\n buildDimensionCondition,\n createOwnCondition,\n createParentCondition,\n createRootCondition,\n falseCondition,\n getConditionUniqueId,\n not,\n or,\n trueCondition,\n} from './conditions';\n\n// ============================================================================\n// Caching\n// ============================================================================\n\nconst simplifyCache = new Lru<string, ConditionNode>(5000);\n\n// ============================================================================\n// Main Simplify Function\n// ============================================================================\n\n/**\n * Simplify a condition tree aggressively.\n *\n * This applies all possible simplification rules:\n * - Boolean algebra (identity, annihilator, idempotent, absorption)\n * - Contradiction detection (A & !A → FALSE)\n * - Tautology detection (A | !A → TRUE)\n * - Range intersection for numeric queries\n * - Attribute value conflict detection\n * - Deduplication and sorting\n */\nexport function simplifyCondition(node: ConditionNode): ConditionNode {\n // Check cache\n const key = getConditionUniqueId(node);\n const cached = simplifyCache.get(key);\n if (cached) {\n return cached;\n }\n\n const result = simplifyInner(node);\n\n // Cache result\n simplifyCache.set(key, result);\n\n return result;\n}\n\n/**\n * Clear the simplify cache (for testing)\n */\nexport function clearSimplifyCache(): void {\n simplifyCache.clear();\n}\n\n// ============================================================================\n// Inner Simplification\n// ============================================================================\n\nfunction simplifyInner(node: ConditionNode): ConditionNode {\n // Base cases\n if (node.kind === 'true' || node.kind === 'false') {\n return node;\n }\n\n // State conditions: most are leaves, but @root / @own / @parent wrap a\n // nested condition that benefits from the same simplification (e.g.\n // `@root(schema=dark & schema=light)` → inner is FALSE → wrapper is FALSE).\n // Only descend on non-negated wrappers; negated wrappers would need\n // additional reasoning (`!@root(FALSE)` = TRUE) that isn't worth the\n // surface area for the current bug.\n if (node.kind === 'state') {\n if (\n (node.type === 'root' || node.type === 'own' || node.type === 'parent') &&\n !node.negated\n ) {\n const simplifiedInner = simplifyInner(node.innerCondition);\n if (simplifiedInner.kind === 'false') return falseCondition();\n if (simplifiedInner === node.innerCondition) return node;\n if (node.type === 'root') {\n return createRootCondition(simplifiedInner, false, node.raw);\n }\n if (node.type === 'own') {\n return createOwnCondition(simplifiedInner, false, node.raw);\n }\n return createParentCondition(\n simplifiedInner,\n node.direct,\n false,\n node.raw,\n );\n }\n return node;\n }\n\n // Compound conditions - recursively simplify.\n // Memoize compound results: the cross-level pruning pass\n // (`pruneContradictedOrBranches`) re-simplifies many overlapping\n // `AND(branch, ...siblings)` combinations, so caching by structural id\n // turns repeated work into O(1) lookups and tames otherwise exponential\n // blowup on wide exclusive conditions (large state maps).\n if (node.kind === 'compound') {\n const key = getConditionUniqueId(node);\n const cached = simplifyCache.get(key);\n if (cached) {\n return cached;\n }\n\n // First, recursively simplify all children\n const simplifiedChildren = node.children.map((c) => simplifyInner(c));\n\n // Then apply compound-specific simplifications\n const result =\n node.operator === 'AND'\n ? simplifyAnd(simplifiedChildren)\n : simplifyOr(simplifiedChildren);\n\n simplifyCache.set(key, result);\n return result;\n }\n\n return node;\n}\n\n// ============================================================================\n// AND Simplification\n// ============================================================================\n\nfunction simplifyAnd(children: ConditionNode[]): ConditionNode {\n let terms: ConditionNode[] = [];\n\n // ─── Pass 1: flatten + identity/annihilator ────────────────────────────\n // Flatten nested ANDs, drop TRUE children, short-circuit on any FALSE.\n for (const child of children) {\n if (child.kind === 'false') {\n // AND with FALSE → FALSE\n return falseCondition();\n }\n if (child.kind === 'true') {\n // AND with TRUE → skip (identity)\n continue;\n }\n if (child.kind === 'compound' && child.operator === 'AND') {\n // Flatten nested AND\n terms.push(...child.children);\n } else {\n terms.push(child);\n }\n }\n\n // Empty → TRUE\n if (terms.length === 0) {\n return trueCondition();\n }\n\n // Single term → return it\n if (terms.length === 1) {\n return terms[0];\n }\n\n // ─── Pass 2: filter contradictions ─────────────────────────────────────\n // Any of these indicates the conjunction can never be satisfied.\n\n // Check for contradictions\n if (hasContradiction(terms)) {\n return falseCondition();\n }\n\n // Check for range contradictions in media/container queries\n if (hasRangeContradiction(terms)) {\n return falseCondition();\n }\n\n // Check for attribute value conflicts\n if (hasAttributeConflict(terms)) {\n return falseCondition();\n }\n\n // Check for container style query conflicts\n if (hasContainerStyleConflict(terms)) {\n return falseCondition();\n }\n\n // ─── Passes 3-5: redundancy elimination + boolean reductions ───────────\n // Run to a fixpoint: Pass 5 (`pruneContradictedOrBranches`) can collapse\n // single-branch ORs into flat AND siblings, which then expose fresh\n // implied negations for Pass 3 (`removeImpliedNegations`) and absorption\n // targets for Pass 4. Without re-running, an exclusive condition like\n // `[theme=gray] & OR(!proc, !theme=rose)` keeps a redundant\n // `:not([theme=rose])` term even though `[theme=gray]` already implies it.\n const MAX_SIMPLIFY_PASSES = 4;\n for (let pass = 0; pass < MAX_SIMPLIFY_PASSES; pass++) {\n const lengthBefore = terms.length;\n const keyBefore = simplifyTermsKey(terms);\n\n // Pass 3: redundancy elimination + canonicalization\n // Remove redundant negations implied by positive terms\n // e.g., style(--variant: danger) implies NOT style(--variant: success)\n // and style(--variant: danger) implies style(--variant) (existence)\n terms = removeImpliedNegations(terms);\n terms = deduplicateTerms(terms);\n terms = mergeRanges(terms);\n terms = sortTerms(terms);\n\n // Pass 4: boolean-algebra reductions\n terms = applyAbsorption(terms, 'OR'); // A & (A | B) → A\n terms = applyPairReduction(terms, 'OR'); // (A | B) & (A | !B) → A\n\n // Pass 5: cross-level contradiction pruning\n // A & OR(!A & X, Y) → A & Y\n // For each OR child, prune branches that are impossible given the other\n // AND siblings. This catches dead branches left by exclusive negation.\n terms = pruneContradictedOrBranches(terms);\n\n // Re-check contradictions exposed by pruning before continuing.\n if (terms.length === 0) break;\n if (terms.length === 1) break;\n if (hasContradiction(terms)) {\n return falseCondition();\n }\n if (hasAttributeConflict(terms)) {\n return falseCondition();\n }\n\n // Stop once a full pass made no structural change.\n if (\n terms.length === lengthBefore &&\n simplifyTermsKey(terms) === keyBefore\n ) {\n break;\n }\n }\n\n if (terms.length === 0) {\n return trueCondition();\n }\n if (terms.length === 1) {\n return terms[0];\n }\n\n return {\n kind: 'compound',\n operator: 'AND',\n children: terms,\n };\n}\n\n// ============================================================================\n// OR Simplification\n// ============================================================================\n\nfunction simplifyOr(children: ConditionNode[]): ConditionNode {\n let terms: ConditionNode[] = [];\n\n // ─── Pass 1: flatten + identity/annihilator ────────────────────────────\n // Flatten nested ORs, drop FALSE children, short-circuit on any TRUE.\n for (const child of children) {\n if (child.kind === 'true') {\n // OR with TRUE → TRUE\n return trueCondition();\n }\n if (child.kind === 'false') {\n // OR with FALSE → skip (identity)\n continue;\n }\n if (child.kind === 'compound' && child.operator === 'OR') {\n // Flatten nested OR\n terms.push(...child.children);\n } else {\n terms.push(child);\n }\n }\n\n // Empty → FALSE\n if (terms.length === 0) {\n return falseCondition();\n }\n\n // Single term → return it\n if (terms.length === 1) {\n return terms[0];\n }\n\n // ─── Pass 2: filter tautologies ────────────────────────────────────────\n // A | !A means the disjunction is always satisfied.\n if (hasTautology(terms)) {\n return trueCondition();\n }\n\n // ─── Pass 3: redundancy elimination + canonicalization ─────────────────\n\n // Deduplicate\n terms = deduplicateTerms(terms);\n\n // Sort for canonical form\n terms = sortTerms(terms);\n\n // ─── Pass 4: boolean-algebra reductions ────────────────────────────────\n\n // Apply absorption: A | (A & B) → A\n terms = applyAbsorption(terms, 'AND');\n\n // Apply complementary factoring: (A & B) | (A & !B) → A\n terms = applyPairReduction(terms, 'AND');\n\n if (terms.length === 0) {\n return falseCondition();\n }\n if (terms.length === 1) {\n return terms[0];\n }\n\n return {\n kind: 'compound',\n operator: 'OR',\n children: terms,\n };\n}\n\n// ============================================================================\n// Contradiction Detection\n// ============================================================================\n\n/**\n * Check if any pair of terms has complementary negation (A and !A).\n * Used for both contradiction detection (in AND) and tautology detection (in OR),\n * since the underlying check is identical: the context determines the semantics.\n */\nfunction hasComplementaryPair(terms: ConditionNode[]): boolean {\n const uniqueIds = new Set<string>();\n\n for (const term of terms) {\n if (term.kind !== 'state') continue;\n\n const id = term.uniqueId;\n const negatedId = term.negated ? id.slice(1) : `!${id}`;\n\n if (uniqueIds.has(negatedId)) {\n return true;\n }\n uniqueIds.add(id);\n }\n\n return false;\n}\n\nconst hasContradiction = hasComplementaryPair;\nconst hasTautology = hasComplementaryPair;\n\n// ============================================================================\n// Range Contradiction Detection\n// ============================================================================\n\n/**\n * Effective bounds computed from conditions (including negated single-bound conditions)\n */\ninterface EffectiveBounds {\n lowerBound: number | null;\n lowerInclusive: boolean;\n upperBound: number | null;\n upperInclusive: boolean;\n}\n\n/**\n * Excluded range from a negated range condition\n */\ninterface ExcludedRange {\n lower: number;\n lowerInclusive: boolean;\n upper: number;\n upperInclusive: boolean;\n}\n\n/**\n * Check for range contradictions in media/container queries\n * e.g., @media(w < 400px) & @media(w > 800px) → FALSE\n *\n * Also handles negated conditions:\n * - Single-bound negations are inverted (not (w < 600px) → w >= 600px)\n * - Range negations create excluded ranges that are checked against positive bounds\n */\nfunction hasRangeContradiction(terms: ConditionNode[]): boolean {\n // Group by dimension, separating positive and negated conditions\n const mediaByDim = new Map<\n string,\n { positive: MediaCondition[]; negated: MediaCondition[] }\n >();\n const containerByDim = new Map<\n string,\n { positive: ContainerCondition[]; negated: ContainerCondition[] }\n >();\n\n for (const term of terms) {\n if (term.kind !== 'state') continue;\n\n if (term.type === 'media' && term.subtype === 'dimension') {\n const key = term.dimension || 'width';\n let group = mediaByDim.get(key);\n if (!group) {\n group = { positive: [], negated: [] };\n mediaByDim.set(key, group);\n }\n if (term.negated) {\n group.negated.push(term);\n } else {\n group.positive.push(term);\n }\n }\n\n if (term.type === 'container' && term.subtype === 'dimension') {\n const key = `${term.containerName || '_'}:${term.dimension || 'width'}`;\n let group = containerByDim.get(key);\n if (!group) {\n group = { positive: [], negated: [] };\n containerByDim.set(key, group);\n }\n if (term.negated) {\n group.negated.push(term);\n } else {\n group.positive.push(term);\n }\n }\n }\n\n // Check each dimension group for impossible ranges\n for (const group of mediaByDim.values()) {\n if (rangesAreImpossibleWithNegations(group.positive, group.negated)) {\n return true;\n }\n }\n\n for (const group of containerByDim.values()) {\n if (rangesAreImpossibleWithNegations(group.positive, group.negated)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Check if conditions are impossible, including negated conditions.\n *\n * For negated single-bound conditions:\n * not (w < 600px) → w >= 600px (inverted to lower bound)\n * not (w >= 800px) → w < 800px (inverted to upper bound)\n *\n * For negated range conditions:\n * not (400px <= w < 800px) → excludes [400, 800)\n * If the effective bounds fall entirely within an excluded range, it's impossible.\n */\nfunction rangesAreImpossibleWithNegations(\n positive: (MediaCondition | ContainerCondition)[],\n negated: (MediaCondition | ContainerCondition)[],\n): boolean {\n // Start with bounds from positive conditions\n const bounds = computeEffectiveBounds(positive);\n\n // Apply inverted bounds from single-bound negated conditions\n // and collect excluded ranges from range negated conditions\n const excludedRanges: ExcludedRange[] = [];\n\n for (const cond of negated) {\n const hasLower = cond.lowerBound?.valueNumeric != null;\n const hasUpper = cond.upperBound?.valueNumeric != null;\n\n if (hasLower && hasUpper) {\n // Range negation: not (lower <= w < upper) excludes [lower, upper)\n excludedRanges.push({\n lower: cond.lowerBound!.valueNumeric!,\n lowerInclusive: cond.lowerBound!.inclusive,\n upper: cond.upperBound!.valueNumeric!,\n upperInclusive: cond.upperBound!.inclusive,\n });\n } else if (hasUpper) {\n // not (w < upper) → w >= upper (becomes lower bound)\n // not (w <= upper) → w > upper (becomes lower bound, exclusive)\n const value = cond.upperBound!.valueNumeric!;\n const inclusive = !cond.upperBound!.inclusive; // flip inclusivity\n\n if (bounds.lowerBound === null || value > bounds.lowerBound) {\n bounds.lowerBound = value;\n bounds.lowerInclusive = inclusive;\n } else if (value === bounds.lowerBound && !inclusive) {\n bounds.lowerInclusive = false;\n }\n } else if (hasLower) {\n // not (w >= lower) → w < lower (becomes upper bound)\n // not (w > lower) → w <= lower (becomes upper bound, inclusive)\n const value = cond.lowerBound!.valueNumeric!;\n const inclusive = !cond.lowerBound!.inclusive; // flip inclusivity\n\n if (bounds.upperBound === null || value < bounds.upperBound) {\n bounds.upperBound = value;\n bounds.upperInclusive = inclusive;\n } else if (value === bounds.upperBound && !inclusive) {\n bounds.upperInclusive = false;\n }\n }\n }\n\n // Check if effective bounds are impossible on their own\n if (bounds.lowerBound !== null && bounds.upperBound !== null) {\n if (bounds.lowerBound > bounds.upperBound) {\n return true;\n }\n if (\n bounds.lowerBound === bounds.upperBound &&\n (!bounds.lowerInclusive || !bounds.upperInclusive)\n ) {\n return true;\n }\n }\n\n // Check if effective bounds fall entirely within any excluded range\n if (\n bounds.lowerBound !== null &&\n bounds.upperBound !== null &&\n excludedRanges.length > 0\n ) {\n for (const excluded of excludedRanges) {\n if (boundsWithinExcludedRange(bounds, excluded)) {\n return true;\n }\n }\n }\n\n return false;\n}\n\n/**\n * Compute effective bounds from positive (non-negated) conditions\n */\nfunction computeEffectiveBounds(\n conditions: (MediaCondition | ContainerCondition)[],\n): EffectiveBounds {\n let lowerBound: number | null = null;\n let lowerInclusive = false;\n let upperBound: number | null = null;\n let upperInclusive = false;\n\n for (const cond of conditions) {\n if (cond.lowerBound?.valueNumeric != null) {\n const value = cond.lowerBound.valueNumeric;\n const inclusive = cond.lowerBound.inclusive;\n\n if (lowerBound === null || value > lowerBound) {\n lowerBound = value;\n lowerInclusive = inclusive;\n } else if (value === lowerBound && !inclusive) {\n lowerInclusive = false;\n }\n }\n\n if (cond.upperBound?.valueNumeric != null) {\n const value = cond.upperBound.valueNumeric;\n const inclusive = cond.upperBound.inclusive;\n\n if (upperBound === null || value < upperBound) {\n upperBound = value;\n upperInclusive = inclusive;\n } else if (value === upperBound && !inclusive) {\n upperInclusive = false;\n }\n }\n }\n\n return { lowerBound, lowerInclusive, upperBound, upperInclusive };\n}\n\n/**\n * Check if effective bounds fall entirely within an excluded range.\n *\n * For example:\n * Effective: [400, 800)\n * Excluded: [400, 800)\n * → bounds fall entirely within excluded range → impossible\n */\nfunction boundsWithinExcludedRange(\n bounds: EffectiveBounds,\n excluded: ExcludedRange,\n): boolean {\n if (bounds.lowerBound === null || bounds.upperBound === null) {\n return false;\n }\n\n // Check if bounds.lower >= excluded.lower\n let lowerOk = false;\n if (bounds.lowerBound > excluded.lower) {\n lowerOk = true;\n } else if (bounds.lowerBound === excluded.lower) {\n // If excluded includes lower, and bounds includes or excludes lower, it's within\n // If excluded excludes lower, bounds must also exclude it to be within\n lowerOk = excluded.lowerInclusive || !bounds.lowerInclusive;\n }\n\n // Check if bounds.upper <= excluded.upper\n let upperOk = false;\n if (bounds.upperBound < excluded.upper) {\n upperOk = true;\n } else if (bounds.upperBound === excluded.upper) {\n // If excluded includes upper, and bounds includes or excludes upper, it's within\n // If excluded excludes upper, bounds must also exclude it to be within\n upperOk = excluded.upperInclusive || !bounds.upperInclusive;\n }\n\n return lowerOk && upperOk;\n}\n\n// ============================================================================\n// Attribute Conflict Detection\n// ============================================================================\n\n/**\n * Check for attribute value conflicts\n * e.g., [data-theme=\"dark\"] & [data-theme=\"light\"] → FALSE\n * e.g., [data-theme=\"dark\"] & ![data-theme] → FALSE\n */\n/**\n * Generic value-conflict checker for grouped conditions.\n *\n * Groups terms by a key, splits into positive/negated, then checks:\n * 1. Multiple distinct positive values → conflict\n * 2. Positive value + negated existence (value === undefined) → conflict\n * 3. Positive value + negated same value → conflict\n */\nfunction hasGroupedValueConflict<T extends { negated: boolean }>(\n terms: ConditionNode[],\n match: (term: ConditionNode) => T | null,\n groupKey: (term: T) => string,\n getValue: (term: T) => string | undefined,\n): boolean {\n const groups = new Map<string, { positive: T[]; negated: T[] }>();\n\n for (const term of terms) {\n const matched = match(term);\n if (!matched) continue;\n\n const key = groupKey(matched);\n let group = groups.get(key);\n if (!group) {\n group = { positive: [], negated: [] };\n groups.set(key, group);\n }\n\n if (matched.negated) {\n group.negated.push(matched);\n } else {\n group.positive.push(matched);\n }\n }\n\n for (const [, group] of groups) {\n const positiveValues = group.positive\n .map(getValue)\n .filter((v) => v !== undefined);\n if (new Set(positiveValues).size > 1) return true;\n\n const hasPositiveValue = positiveValues.length > 0;\n const hasNegatedExistence = group.negated.some(\n (t) => getValue(t) === undefined,\n );\n if (hasPositiveValue && hasNegatedExistence) return true;\n\n for (const pos of group.positive) {\n const posVal = getValue(pos);\n if (posVal !== undefined) {\n for (const neg of group.negated) {\n if (getValue(neg) === posVal) return true;\n }\n }\n }\n }\n\n return false;\n}\n\nfunction hasAttributeConflict(terms: ConditionNode[]): boolean {\n // Top-level modifiers: `schema=dark & schema=light`.\n if (\n hasGroupedValueConflict<ModifierCondition>(\n terms,\n (t) => (t.kind === 'state' && t.type === 'modifier' ? t : null),\n (t) => t.attribute,\n (t) => t.value,\n )\n ) {\n return true;\n }\n\n // @root scope (single :root element):\n // `@root(schema=dark) & @root(schema=light)` cannot match anything because\n // there is only one document root.\n if (hasNestedModifierConflict(terms, 'root')) return true;\n\n // @own scope (single sub-element / styled element under `&`):\n // `@own(schema=dark) & @own(schema=light)` is impossible for the same\n // reason — both refer to the same element.\n if (hasNestedModifierConflict(terms, 'own')) return true;\n\n // NOTE: @parent is intentionally NOT checked. Different ancestor elements\n // can hold different attribute values, so two `@parent(schema=...)` calls\n // can both match (different ancestors), even when the values differ.\n\n return false;\n}\n\n/**\n * Collect modifier conditions inside non-negated state wrappers of `kind`\n * and check for the same value-conflict pattern as the top-level pass.\n *\n * Modifiers from multiple sibling wrappers are combined — both wrappers\n * scope to the same element (one :root, one own scope), so an attribute\n * conflict across wrappers is still impossible.\n */\nfunction hasNestedModifierConflict(\n terms: ConditionNode[],\n wrapperType: 'root' | 'own',\n): boolean {\n const innerTerms: ConditionNode[] = [];\n for (const term of terms) {\n if (term.kind === 'state' && term.type === wrapperType && !term.negated) {\n flattenAndIntoArray(\n (term as RootCondition | OwnCondition).innerCondition,\n innerTerms,\n );\n }\n }\n if (innerTerms.length < 2) return false;\n return hasGroupedValueConflict<ModifierCondition>(\n innerTerms,\n (t) => (t.kind === 'state' && t.type === 'modifier' ? t : null),\n (t) => t.attribute,\n (t) => t.value,\n );\n}\n\n/**\n * Flatten a top-level AND tree into a flat list of conjuncts. Non-AND nodes\n * are pushed as-is.\n */\nfunction flattenAndIntoArray(node: ConditionNode, into: ConditionNode[]): void {\n if (node.kind === 'compound' && node.operator === 'AND') {\n for (const child of node.children) flattenAndIntoArray(child, into);\n } else {\n into.push(node);\n }\n}\n\nfunction hasContainerStyleConflict(terms: ConditionNode[]): boolean {\n return hasGroupedValueConflict<ContainerCondition>(\n terms,\n (t) =>\n t.kind === 'state' && t.type === 'container' && t.subtype === 'style'\n ? t\n : null,\n (t) => `${t.containerName || '_'}:${t.property}`,\n (t) => t.propertyValue,\n );\n}\n\n// ============================================================================\n// Implied Negation Removal\n// ============================================================================\n\n/**\n * Remove negations that are implied by positive terms.\n *\n * Key optimizations:\n * 1. style(--variant: danger) implies NOT style(--variant: success)\n * → If we have style(--variant: danger) & not style(--variant: success),\n * the negation is redundant and can be removed.\n *\n * 2. [data-theme=\"dark\"] implies NOT [data-theme=\"light\"]\n * → Same logic for attribute selectors.\n *\n * This produces cleaner CSS:\n * Before: @container style(--variant: danger) and (not style(--variant: success))\n * After: @container style(--variant: danger)\n */\n/**\n * Collect positive values from terms and build a \"is this negation implied?\" check.\n *\n * A negation is implied (redundant) when a positive term for the same group\n * already pins a specific value, making \"NOT other-value\" obvious.\n * e.g. style(--variant: danger) implies NOT style(--variant: success).\n */\nfunction buildImpliedNegationCheck(\n terms: ConditionNode[],\n): (term: ConditionNode) => boolean {\n const positiveValues = new Map<string, string>();\n const negatedBooleanAttrs = new Set<string>();\n\n for (const term of terms) {\n if (term.kind !== 'state') continue;\n\n if (!term.negated) {\n if (term.type === 'container' && term.subtype === 'style') {\n if (term.propertyValue !== undefined) {\n positiveValues.set(\n `c:${term.containerName || '_'}:${term.property}`,\n term.propertyValue,\n );\n }\n } else if (term.type === 'modifier' && term.value !== undefined) {\n positiveValues.set(`m:${term.attribute}`, term.value);\n }\n } else {\n // NOT [data-attr] (boolean negation) implies NOT [data-attr=\"val\"]\n if (term.type === 'modifier' && term.value === undefined) {\n negatedBooleanAttrs.add(term.attribute);\n }\n }\n }\n\n return (term: ConditionNode): boolean => {\n if (term.kind !== 'state' || !term.negated) return false;\n\n if (term.type === 'container' && term.subtype === 'style') {\n if (term.propertyValue === undefined) return false;\n const pos = positiveValues.get(\n `c:${term.containerName || '_'}:${term.property}`,\n );\n return pos !== undefined && term.propertyValue !== pos;\n }\n\n if (term.type === 'modifier' && term.value !== undefined) {\n // :not([data-attr]) already present → :not([data-attr=\"val\"]) is redundant\n if (negatedBooleanAttrs.has(term.attribute)) return true;\n const pos = positiveValues.get(`m:${term.attribute}`);\n return pos !== undefined && term.value !== pos;\n }\n\n return false;\n };\n}\n\nfunction removeImpliedNegations(terms: ConditionNode[]): ConditionNode[] {\n const isImplied = buildImpliedNegationCheck(terms);\n return terms.filter((t) => !isImplied(t));\n}\n\n// ============================================================================\n// Deduplication\n// ============================================================================\n\n/**\n * Build a stable, order-insensitive key for a list of AND terms.\n * Used to detect fixpoint convergence in `simplifyAnd`.\n */\nfunction simplifyTermsKey(terms: ConditionNode[]): string {\n return terms\n .map((t) => getConditionUniqueId(t))\n .sort()\n .join('&');\n}\n\nfunction deduplicateTerms(terms: ConditionNode[]): ConditionNode[] {\n const seen = new Set<string>();\n const result: ConditionNode[] = [];\n\n for (const term of terms) {\n const id = getConditionUniqueId(term);\n if (!seen.has(id)) {\n seen.add(id);\n result.push(term);\n }\n }\n\n return result;\n}\n\n// ============================================================================\n// Range Merging\n// ============================================================================\n\n/**\n * Merge compatible range conditions\n * e.g., @media(w >= 400px) & @media(w <= 800px) → @media(400px <= w <= 800px)\n */\nfunction mergeRanges(terms: ConditionNode[]): ConditionNode[] {\n // Group media conditions by dimension\n const mediaByDim = new Map<\n string,\n { conditions: MediaCondition[]; indices: number[] }\n >();\n const containerByDim = new Map<\n string,\n { conditions: ContainerCondition[]; indices: number[] }\n >();\n\n terms.forEach((term, index) => {\n if (term.kind !== 'state') return;\n\n if (\n term.type === 'media' &&\n term.subtype === 'dimension' &&\n !term.negated\n ) {\n const key = term.dimension || 'width';\n let group = mediaByDim.get(key);\n if (!group) {\n group = { conditions: [], indices: [] };\n mediaByDim.set(key, group);\n }\n group.conditions.push(term);\n group.indices.push(index);\n }\n\n if (\n term.type === 'container' &&\n term.subtype === 'dimension' &&\n !term.negated\n ) {\n const key = `${term.containerName || '_'}:${term.dimension || 'width'}`;\n let group = containerByDim.get(key);\n if (!group) {\n group = { conditions: [], indices: [] };\n containerByDim.set(key, group);\n }\n group.conditions.push(term);\n group.indices.push(index);\n }\n });\n\n // Track indices to remove\n const indicesToRemove = new Set<number>();\n const mergedTerms: ConditionNode[] = [];\n\n // Merge media conditions\n for (const [, group] of mediaByDim) {\n if (group.conditions.length > 1) {\n const merged = mergeMediaRanges(group.conditions);\n if (merged) {\n group.indices.forEach((i) => indicesToRemove.add(i));\n mergedTerms.push(merged);\n }\n }\n }\n\n // Merge container conditions\n for (const [, group] of containerByDim) {\n if (group.conditions.length > 1) {\n const merged = mergeContainerRanges(group.conditions);\n if (merged) {\n group.indices.forEach((i) => indicesToRemove.add(i));\n mergedTerms.push(merged);\n }\n }\n }\n\n // Build result\n const result: ConditionNode[] = [];\n terms.forEach((term, index) => {\n if (!indicesToRemove.has(index)) {\n result.push(term);\n }\n });\n result.push(...mergedTerms);\n\n return result;\n}\n\n/**\n * Tighten bounds by picking the most restrictive lower and upper bounds\n * from a set of conditions that have lowerBound/upperBound fields.\n */\nfunction tightenBounds(\n conditions: { lowerBound?: NumericBound; upperBound?: NumericBound }[],\n): { lowerBound?: NumericBound; upperBound?: NumericBound } {\n let lowerBound: NumericBound | undefined;\n let upperBound: NumericBound | undefined;\n\n for (const cond of conditions) {\n if (cond.lowerBound) {\n if (\n !lowerBound ||\n (cond.lowerBound.valueNumeric ?? -Infinity) >\n (lowerBound.valueNumeric ?? -Infinity)\n ) {\n lowerBound = cond.lowerBound;\n }\n }\n if (cond.upperBound) {\n if (\n !upperBound ||\n (cond.upperBound.valueNumeric ?? Infinity) <\n (upperBound.valueNumeric ?? Infinity)\n ) {\n upperBound = cond.upperBound;\n }\n }\n }\n\n return { lowerBound, upperBound };\n}\n\nfunction appendBoundsToUniqueId(\n parts: string[],\n lowerBound?: NumericBound,\n upperBound?: NumericBound,\n): void {\n if (lowerBound) {\n parts.push(lowerBound.inclusive ? '>=' : '>');\n parts.push(lowerBound.value);\n }\n if (upperBound) {\n parts.push(upperBound.inclusive ? '<=' : '<');\n parts.push(upperBound.value);\n }\n}\n\nfunction mergeDimensionRanges<T extends MediaCondition | ContainerCondition>(\n conditions: T[],\n idPrefix: string[],\n): T | null {\n if (conditions.length === 0) return null;\n\n const { lowerBound, upperBound } = tightenBounds(conditions);\n const base = conditions[0];\n\n const parts = [...idPrefix];\n appendBoundsToUniqueId(parts, lowerBound, upperBound);\n\n return {\n ...base,\n negated: false,\n raw: buildMergedRaw(base.dimension || 'width', lowerBound, upperBound),\n uniqueId: parts.join(':'),\n lowerBound,\n upperBound,\n };\n}\n\nfunction mergeMediaRanges(conditions: MediaCondition[]): MediaCondition | null {\n const dim = conditions[0]?.dimension ?? 'width';\n return mergeDimensionRanges(conditions, ['media', 'dim', dim]);\n}\n\nfunction mergeContainerRanges(\n conditions: ContainerCondition[],\n): ContainerCondition | null {\n const base = conditions[0];\n if (!base) return null;\n const name = base.containerName || '_';\n const dim = base.dimension ?? 'width';\n return mergeDimensionRanges(conditions, ['container', 'dim', name, dim]);\n}\n\nfunction buildMergedRaw(\n dimension: string,\n lowerBound?: NumericBound,\n upperBound?: NumericBound,\n): string {\n return lowerBound || upperBound\n ? `@media${buildDimensionCondition(dimension, lowerBound, upperBound)}`\n : '@media()';\n}\n\n// ============================================================================\n// Complementary Factoring / Consensus Resolution\n// ============================================================================\n\n/**\n * Apply either side of the same Boolean reduction:\n *\n * - Complementary factoring: (A & B) | (A & !B) → A\n * - Consensus/resolution: (A | B) & (A | !B) → A\n *\n * This is applied iteratively until no more reductions are possible,\n * since one reduction can expose another.\n */\nfunction applyPairReduction(\n terms: ConditionNode[],\n childOperator: 'AND' | 'OR',\n): ConditionNode[] {\n let changed = true;\n\n while (changed) {\n changed = false;\n\n for (let i = 0; i < terms.length; i++) {\n const a = terms[i];\n if (a.kind !== 'compound' || a.operator !== childOperator) continue;\n\n for (let j = i + 1; j < terms.length; j++) {\n const b = terms[j];\n if (b.kind !== 'compound' || b.operator !== childOperator) continue;\n\n const reduced = tryReducePair(a.children, b.children, childOperator);\n if (reduced) {\n const replacement = simplifyInner(reduced);\n terms = [\n ...terms.slice(0, i),\n ...terms.slice(i + 1, j),\n ...terms.slice(j + 1),\n replacement,\n ];\n changed = true;\n break;\n }\n }\n\n if (changed) break;\n }\n }\n\n return terms;\n}\n\n/**\n * Reduce a pair of compound child lists using complementary terms.\n *\n * `childOperator` is the operator inside each term. The remaining parts\n * must collapse under the opposite operator, leaving only their shared\n * children.\n */\nfunction tryReducePair(\n aChildren: ConditionNode[],\n bChildren: ConditionNode[],\n childOperator: 'AND' | 'OR',\n): ConditionNode | null {\n const aIds = aChildren.map((c) => getConditionUniqueId(c));\n const bIds = bChildren.map((c) => getConditionUniqueId(c));\n const aIdSet = new Set(aIds);\n const bIdSet = new Set(bIds);\n\n // Extract common children (present in both by uniqueId)\n const common: ConditionNode[] = [];\n const restAChildren: ConditionNode[] = [];\n for (let i = 0; i < aIds.length; i++) {\n if (bIdSet.has(aIds[i])) {\n common.push(aChildren[i]);\n } else {\n restAChildren.push(aChildren[i]);\n }\n }\n\n const restBChildren: ConditionNode[] = [];\n for (let i = 0; i < bIds.length; i++) {\n if (!aIdSet.has(bIds[i])) {\n restBChildren.push(bChildren[i]);\n }\n }\n\n // Must have at least one common child and differing parts on both sides\n if (common.length === 0) return null;\n if (restAChildren.length === 0 && restBChildren.length === 0) return null;\n\n const combine = childOperator === 'AND' ? and : or;\n const identity = childOperator === 'AND' ? trueCondition() : falseCondition();\n const restA =\n restAChildren.length === 0\n ? identity\n : restAChildren.length === 1\n ? restAChildren[0]\n : combine(...restAChildren);\n const restB =\n restBChildren.length === 0\n ? identity\n : restBChildren.length === 1\n ? restBChildren[0]\n : combine(...restBChildren);\n const expectedKind = childOperator === 'AND' ? 'true' : 'false';\n\n // Factoring checks restA | restB → TRUE; resolution checks\n // restA & restB → FALSE.\n const combined = simplifyInner({\n kind: 'compound',\n operator: childOperator === 'AND' ? 'OR' : 'AND',\n children: [restA, restB],\n });\n\n if (combined.kind !== expectedKind) {\n // Direct complement check for compound conditions.\n // Leaf-level contradiction/tautology checks can miss complements that\n // expand via De Morgan into structurally different trees.\n const simplifiedRestB = simplifyInner(restB);\n const negRestA = simplifyInner(not(restA));\n\n if (\n getConditionUniqueId(negRestA) !== getConditionUniqueId(simplifiedRestB)\n ) {\n return null;\n }\n }\n\n return common.length === 1 ? common[0] : combine(...common);\n}\n\n// ============================================================================\n// Sorting\n// ============================================================================\n\nfunction sortTerms(terms: ConditionNode[]): ConditionNode[] {\n const withIds = terms.map((t) => [getConditionUniqueId(t), t] as const);\n withIds.sort((a, b) => a[0].localeCompare(b[0]));\n return withIds.map(([, t]) => t);\n}\n\n// ============================================================================\n// Absorption\n// ============================================================================\n\n/**\n * Apply the absorption law: removes compound terms that are absorbed by\n * another term already present (simple or compound).\n *\n * For AND context: A & (A | B) → A (absorbs OR compounds)\n * For OR context: A | (A & B) → A (absorbs AND compounds)\n *\n * After flattening, a compound A = OR(X, Y) becomes [X, Y, ...] in the\n * outer OR. A child AND(A, B) = AND(OR(X, Y), B) still references the\n * original un-flattened compound. We reconstruct possible compound\n * absorbers from the flattened terms so absorption works across nesting.\n */\nfunction applyAbsorption(\n terms: ConditionNode[],\n absorbedOperator: 'OR' | 'AND',\n): ConditionNode[] {\n // Collect IDs of ALL top-level terms as potential absorbers.\n const absorberIds = new Set<string>();\n for (const term of terms) {\n absorberIds.add(getConditionUniqueId(term));\n }\n\n // Reconstruct compound absorbers: if all children of a compound node\n // (found inside an absorbable term) are themselves absorbers, then\n // that compound is also an absorber. This handles the case where\n // A = OR(X, Y) was flattened into [X, Y, ...] at the top level,\n // but appears un-flattened as a child of AND(A, B).\n let changed = true;\n while (changed) {\n changed = false;\n for (const term of terms) {\n if (term.kind !== 'compound' || term.operator !== absorbedOperator) {\n continue;\n }\n for (const child of term.children) {\n if (child.kind !== 'compound') continue;\n const childId = getConditionUniqueId(child);\n if (absorberIds.has(childId)) continue;\n if (\n child.children.every((c) => absorberIds.has(getConditionUniqueId(c)))\n ) {\n absorberIds.add(childId);\n changed = true;\n }\n }\n }\n }\n\n return terms.filter((term) => {\n if (term.kind === 'compound' && term.operator === absorbedOperator) {\n for (const child of term.children) {\n if (absorberIds.has(getConditionUniqueId(child))) {\n return false;\n }\n }\n }\n return true;\n });\n}\n\n// ============================================================================\n// Cross-level Contradiction Pruning\n// ============================================================================\n\n/**\n * For each OR child of an AND, prune branches that are impossible\n * given the other AND siblings.\n *\n * Example: A & OR(!A & X, Y) → A & Y\n *\n * This catches dead OR branches left by exclusive negation (Stage 2b)\n * where `NOT(combined)` introduces branches contradicting flat siblings.\n */\nfunction pruneContradictedOrBranches(terms: ConditionNode[]): ConditionNode[] {\n const hasOr = terms.some((t) => t.kind === 'compound' && t.operator === 'OR');\n if (!hasOr) return terms;\n\n let changed = false;\n const result: ConditionNode[] = [];\n\n for (let i = 0; i < terms.length; i++) {\n const term = terms[i];\n if (term.kind !== 'compound' || term.operator !== 'OR') {\n result.push(term);\n continue;\n }\n\n // Gather all siblings (everything except this OR)\n const siblings = [...terms.slice(0, i), ...terms.slice(i + 1)];\n\n const surviving: ConditionNode[] = [];\n for (const branch of term.children) {\n const test: ConditionNode = {\n kind: 'compound',\n operator: 'AND',\n children: [branch, ...siblings],\n };\n const simplified = simplifyInner(test);\n if (simplified.kind !== 'false') {\n surviving.push(branch);\n }\n }\n\n if (surviving.length === term.children.length) {\n result.push(term);\n } else if (surviving.length === 0) {\n return [falseCondition()];\n } else {\n changed = true;\n if (surviving.length === 1) {\n result.push(surviving[0]);\n } else {\n result.push({\n kind: 'compound',\n operator: 'OR',\n children: surviving,\n });\n }\n }\n }\n\n if (!changed) return terms;\n\n // Re-flatten after pruning may have unwrapped single-branch ORs\n const flattened: ConditionNode[] = [];\n for (const term of result) {\n if (term.kind === 'compound' && term.operator === 'AND') {\n flattened.push(...term.children);\n } else {\n flattened.push(term);\n }\n }\n\n return flattened;\n}\n","/**\n * Contradiction Detection for Parsed CSS Conditions\n *\n * After conditions are converted into their parsed CSS shapes\n * (`ParsedMediaCondition`, `ParsedContainerCondition`,\n * `ParsedSupportsCondition`), variant merging in `materialize.ts` needs to\n * detect impossible combinations a second time at this lower level — the\n * tree-level simplifier in `simplify.ts` operates on `ConditionNode`s,\n * which can't see post-parse details like dimension bounds collapsing or\n * style-query property conflicts.\n *\n * Functions in this module are pure and self-contained; they take parsed\n * conditions and return booleans. They share no state with each other or\n * with the rest of the materialization pipeline.\n */\n\nimport type {\n ParsedContainerCondition,\n ParsedMediaCondition,\n ParsedSupportsCondition,\n} from './materialize-types';\n\n/**\n * Generic deduplication by a key extraction function.\n * Preserves insertion order, keeping the first occurrence of each key.\n */\nfunction dedupeByKey<T>(items: T[], getKey: (item: T) => string): T[] {\n const seen = new Set<string>();\n const result: T[] = [];\n for (const item of items) {\n const key = getKey(item);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(item);\n }\n }\n return result;\n}\n\nexport function dedupeMediaConditions(\n conditions: ParsedMediaCondition[],\n): ParsedMediaCondition[] {\n return dedupeByKey(\n conditions,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\nexport function dedupeContainerConditions(\n conditions: ParsedContainerCondition[],\n): ParsedContainerCondition[] {\n return dedupeByKey(\n conditions,\n (c) => `${c.name ?? ''}|${c.condition}|${c.negated}`,\n );\n}\n\nexport function dedupeSupportsConditions(\n conditions: ParsedSupportsCondition[],\n): ParsedSupportsCondition[] {\n return dedupeByKey(\n conditions,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\n/**\n * Check if supports conditions contain contradictions\n * e.g., @supports(display: grid) AND NOT @supports(display: grid)\n */\nexport function hasSupportsContradiction(\n conditions: ParsedSupportsCondition[],\n): boolean {\n const conditionMap = new Map<string, boolean>(); // key -> isPositive\n\n for (const cond of conditions) {\n const key = `${cond.subtype}|${cond.condition}`;\n const existing = conditionMap.get(key);\n if (existing !== undefined && existing !== !cond.negated) {\n return true; // Contradiction: positive AND negated\n }\n conditionMap.set(key, !cond.negated);\n }\n\n return false;\n}\n\n/**\n * Check if a set of media conditions contains contradictions\n * e.g., (prefers-color-scheme: light) AND NOT (prefers-color-scheme: light)\n * or (width >= 900px) AND (width < 600px)\n *\n * Uses parsed media conditions for efficient analysis without regex parsing.\n */\nexport function hasMediaContradiction(\n conditions: ParsedMediaCondition[],\n): boolean {\n // Track conditions by subtype and value to detect A and NOT A.\n const polarities = new Map<string, boolean>(); // key -> isPositive\n\n // Track dimension conditions for range contradiction detection (non-negated only)\n const dimensionsByDim = new Map<\n string,\n { lowerBound: number | null; upperBound: number | null }\n >();\n\n for (const cond of conditions) {\n const key = `${cond.subtype}|${\n cond.subtype === 'type' ? cond.mediaType || 'all' : cond.condition\n }`;\n const existing = polarities.get(key);\n if (existing !== undefined && existing !== !cond.negated) {\n return true;\n }\n polarities.set(key, !cond.negated);\n\n // Negated dimensions are handled by the direct contradiction check.\n if (cond.subtype !== 'dimension' || cond.negated) continue;\n\n const dim = cond.dimension || 'width';\n let bounds = dimensionsByDim.get(dim);\n if (!bounds) {\n bounds = { lowerBound: null, upperBound: null };\n dimensionsByDim.set(dim, bounds);\n }\n\n if (cond.lowerBound?.valueNumeric != null) {\n const value = cond.lowerBound.valueNumeric;\n if (bounds.lowerBound === null || value > bounds.lowerBound) {\n bounds.lowerBound = value;\n }\n }\n if (cond.upperBound?.valueNumeric != null) {\n const value = cond.upperBound.valueNumeric;\n if (bounds.upperBound === null || value < bounds.upperBound) {\n bounds.upperBound = value;\n }\n }\n\n if (\n bounds.lowerBound !== null &&\n bounds.upperBound !== null &&\n bounds.lowerBound >= bounds.upperBound\n ) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Check if container conditions contain contradictions in style queries\n * e.g., style(--variant: danger) and style(--variant: success) together\n * Same property with different values = always false\n *\n * Uses parsed container conditions for efficient analysis without regex parsing.\n */\nexport function hasContainerStyleContradiction(\n conditions: ParsedContainerCondition[],\n): boolean {\n // Track style queries by property name\n // key: property name, value: { hasExistence: boolean, values: Set<string>, hasNegatedExistence: boolean }\n const styleQueries = new Map<\n string,\n { hasExistence: boolean; values: Set<string>; hasNegatedExistence: boolean }\n >();\n\n for (const cond of conditions) {\n // Only analyze style queries\n if (cond.subtype !== 'style' || !cond.property) {\n continue;\n }\n\n const property = cond.property;\n const value = cond.propertyValue;\n\n let entry = styleQueries.get(property);\n if (!entry) {\n entry = {\n hasExistence: false,\n values: new Set(),\n hasNegatedExistence: false,\n };\n styleQueries.set(property, entry);\n }\n\n if (cond.negated) {\n if (value === undefined) {\n // not style(--prop) - negated existence check\n entry.hasNegatedExistence = true;\n }\n // Negated value checks don't contradict positive value checks directly\n // They just mean \"not this value\"\n } else {\n if (value === undefined) {\n // style(--prop) - existence check\n entry.hasExistence = true;\n } else {\n // style(--prop: value) - value check\n entry.values.add(value);\n }\n }\n }\n\n // Check for contradictions\n for (const [, entry] of styleQueries) {\n // Contradiction: existence check + negated existence check\n if (entry.hasExistence && entry.hasNegatedExistence) {\n return true;\n }\n\n // Contradiction: multiple different values for same property\n // style(--variant: danger) AND style(--variant: success) is impossible\n if (entry.values.size > 1) {\n return true;\n }\n\n // Contradiction: negated existence + value check\n // not style(--variant) AND style(--variant: danger) is impossible\n if (entry.hasNegatedExistence && entry.values.size > 0) {\n return true;\n }\n }\n\n return false;\n}\n","/**\n * CSS Materialization\n *\n * Converts condition trees into CSS selectors and at-rules.\n * This is the final stage that produces actual CSS output.\n */\n\nimport { Lru } from '../parser/lru';\n\nimport type {\n ConditionNode,\n ContainerCondition,\n MediaCondition,\n ModifierCondition,\n PseudoCondition,\n StateCondition,\n SupportsCondition,\n} from './conditions';\nimport {\n and,\n buildDimensionCondition,\n getConditionUniqueId,\n isCompoundCondition,\n not,\n} from './conditions';\nimport { simplifyCondition } from './simplify';\nimport {\n dedupeContainerConditions,\n dedupeMediaConditions,\n dedupeSupportsConditions,\n hasContainerStyleContradiction,\n hasMediaContradiction,\n hasSupportsContradiction,\n} from './materialize-contradictions';\nimport type {\n CSSComponents,\n ParentGroup,\n ParsedContainerCondition,\n ParsedMediaCondition,\n ParsedModifierCondition,\n ParsedPseudoCondition,\n ParsedSelectorCondition,\n ParsedSupportsCondition,\n SelectorGroup,\n SelectorVariant,\n} from './materialize-types';\n\n// ============================================================================\n// Caching\n// ============================================================================\n\nconst conditionCache = new Lru<string, CSSComponents>(3000);\n\n// ============================================================================\n// Main Functions\n// ============================================================================\n\n/**\n * Convert a condition tree to CSS components\n */\nexport function conditionToCSS(node: ConditionNode): CSSComponents {\n // Check cache\n const key = getConditionUniqueId(node);\n const cached = conditionCache.get(key);\n if (cached) {\n return cached;\n }\n\n const result = conditionToCSSInner(node);\n\n // Cache result\n conditionCache.set(key, result);\n\n return result;\n}\n\n/**\n * Clear the condition cache (for testing)\n */\nexport function clearConditionCache(): void {\n conditionCache.clear();\n}\n\n// ============================================================================\n// Inner Implementation\n// ============================================================================\n\nfunction emptyVariant(): SelectorVariant {\n return {\n modifierConditions: [],\n pseudoConditions: [],\n selectorGroups: [],\n ownGroups: [],\n mediaConditions: [],\n containerConditions: [],\n supportsConditions: [],\n rootGroups: [],\n parentGroups: [],\n startingStyle: false,\n };\n}\n\nfunction conditionToCSSInner(node: ConditionNode): CSSComponents {\n // Base case: TRUE condition - single empty variant (matches everything)\n if (node.kind === 'true') {\n return {\n variants: [emptyVariant()],\n isImpossible: false,\n };\n }\n\n // Base case: FALSE condition - no variants (matches nothing)\n if (node.kind === 'false') {\n return {\n variants: [],\n isImpossible: true,\n };\n }\n\n // State condition\n if (node.kind === 'state') {\n return stateToCSS(node);\n }\n\n // Compound condition\n if (node.kind === 'compound') {\n if (node.operator === 'AND') {\n return andToCSS(node.children);\n } else {\n return orToCSS(node.children);\n }\n }\n\n // Fallback - single empty variant\n return {\n variants: [emptyVariant()],\n isImpossible: false,\n };\n}\n\n/**\n * Convert a state condition to CSS\n */\nfunction stateToCSS(state: StateCondition): CSSComponents {\n switch (state.type) {\n case 'media': {\n const mediaResults = mediaToParsed(state);\n const variants = mediaResults.map((mediaCond) => {\n const v = emptyVariant();\n v.mediaConditions.push(mediaCond);\n return v;\n });\n return { variants, isImpossible: false };\n }\n\n case 'root':\n return innerConditionToVariants(\n state.innerCondition,\n state.negated ?? false,\n 'rootGroups',\n );\n\n case 'parent':\n return innerConditionToVariants(\n state.innerCondition,\n state.negated ?? false,\n 'parentGroups',\n state.direct,\n );\n\n case 'own':\n return innerConditionToVariants(\n state.innerCondition,\n state.negated ?? false,\n 'ownGroups',\n );\n\n case 'modifier': {\n const v = emptyVariant();\n v.modifierConditions.push(modifierToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'pseudo': {\n const v = emptyVariant();\n v.pseudoConditions.push(pseudoToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'container': {\n const v = emptyVariant();\n v.containerConditions.push(containerToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'supports': {\n const v = emptyVariant();\n v.supportsConditions.push(supportsToParsed(state));\n return { variants: [v], isImpossible: false };\n }\n\n case 'starting': {\n const v = emptyVariant();\n v.startingStyle = !state.negated;\n return { variants: [v], isImpossible: false };\n }\n }\n}\n\n/**\n * Convert modifier condition to parsed structure\n */\nfunction modifierToParsed(state: ModifierCondition): ParsedModifierCondition {\n return {\n attribute: state.attribute,\n value: state.value,\n operator: state.operator,\n negated: state.negated ?? false,\n };\n}\n\n/**\n * Convert parsed modifier to CSS selector string (for final output)\n */\nfunction modifierToCSS(mod: ParsedModifierCondition): string {\n let selector: string;\n\n if (mod.value !== undefined) {\n // Value attribute: [data-attr=\"value\"]\n const op = mod.operator || '=';\n selector = `[${mod.attribute}${op}\"${mod.value}\"]`;\n } else {\n // Boolean attribute: [data-attr]\n selector = `[${mod.attribute}]`;\n }\n\n if (mod.negated) {\n return `:not(${selector})`;\n }\n return selector;\n}\n\n/**\n * Convert pseudo condition to parsed structure\n */\nfunction pseudoToParsed(state: PseudoCondition): ParsedPseudoCondition {\n return {\n pseudo: state.pseudo,\n negated: state.negated ?? false,\n };\n}\n\n/**\n * Convert parsed pseudo to CSS selector string (for final output).\n *\n * :not() is normalized to negated :is() at parse time, so pseudo.pseudo\n * never starts with ':not(' here. When negated:\n * - :is(X) → :not(X) (unwrap :is)\n * - :where(X) → :not(X) (unwrap :where)\n * - :has(X) → :not(:has(X))\n * - other → :not(other)\n *\n * When not negated, single-argument :is()/:where() is unwrapped when the\n * inner content is a simple compound selector that can safely append to\n * the base selector (this happens after double-negation of :not()).\n */\nexport function pseudoToCSS(pseudo: ParsedPseudoCondition): string {\n const p = pseudo.pseudo;\n\n if (pseudo.negated) {\n if (p.startsWith(':is(') || p.startsWith(':where(')) {\n return `:not(${p.slice(p.indexOf('(') + 1, -1)})`;\n }\n return `:not(${p})`;\n }\n\n if ((p.startsWith(':is(') || p.startsWith(':where(')) && !p.includes(',')) {\n const inner = p.slice(p.indexOf('(') + 1, -1);\n const ch = inner[0];\n\n // Only unwrap when the inner content is a simple compound selector:\n // must start with a compoundable character and contain no whitespace\n // (whitespace implies combinators like `>`, `+`, `~`, or descendant).\n if (\n (ch === ':' || ch === '.' || ch === '[' || ch === '#') &&\n !/\\s/.test(inner)\n ) {\n return inner;\n }\n }\n\n return p;\n}\n\n/**\n * Convert media condition to parsed structure(s)\n * Returns an array because negated ranges produce OR branches (two separate conditions)\n */\nfunction mediaToParsed(state: MediaCondition): ParsedMediaCondition[] {\n if (state.subtype === 'type') {\n // @media:print → @media print (or @media not print)\n const mediaType = state.mediaType || 'all';\n return [\n {\n subtype: 'type',\n negated: state.negated ?? false,\n condition: mediaType,\n mediaType: state.mediaType,\n },\n ];\n } else if (state.subtype === 'feature') {\n // @media(prefers-contrast: high) → @media (prefers-contrast: high)\n let condition: string;\n if (state.featureValue) {\n condition = `(${state.feature}: ${state.featureValue})`;\n } else {\n condition = `(${state.feature})`;\n }\n return [\n {\n subtype: 'feature',\n negated: state.negated ?? false,\n condition,\n feature: state.feature,\n featureValue: state.featureValue,\n },\n ];\n } else {\n // Dimension query - negation is handled by inverting the condition\n // because \"not (width < x)\" doesn't work reliably in browsers\n return dimensionToMediaParsed(\n state.dimension || 'width',\n state.lowerBound,\n state.upperBound,\n state.negated ?? false,\n );\n }\n}\n\n/**\n * Convert dimension bounds to parsed media condition(s)\n * Uses CSS Media Queries Level 4 `not (condition)` syntax for negation.\n */\nfunction dimensionToMediaParsed(\n dimension: 'width' | 'height' | 'inline-size' | 'block-size',\n lowerBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n },\n upperBound?: {\n value: string;\n valueNumeric: number | null;\n inclusive: boolean;\n },\n negated?: boolean,\n): ParsedMediaCondition[] {\n // For negation, we use CSS `not (condition)` syntax in buildAtRulesFromVariant\n return [\n {\n subtype: 'dimension',\n negated: negated ?? false,\n condition: buildDimensionCondition(dimension, lowerBound, upperBound),\n dimension,\n lowerBound,\n upperBound,\n },\n ];\n}\n\n/**\n * Convert container condition to parsed structure\n * This enables structured analysis for contradiction detection and condition combining\n */\nfunction containerToParsed(\n state: ContainerCondition,\n): ParsedContainerCondition {\n let condition: string;\n\n if (state.subtype === 'style') {\n // Style query: style(--prop: value)\n if (state.propertyValue) {\n condition = `style(--${state.property}: ${state.propertyValue})`;\n } else {\n condition = `style(--${state.property})`;\n }\n } else if (state.subtype === 'raw') {\n // Raw function query: passed through verbatim (e.g., scroll-state(stuck: top))\n condition = state.rawCondition!;\n } else {\n // Dimension query\n condition = buildDimensionCondition(\n state.dimension || 'width',\n state.lowerBound,\n state.upperBound,\n 'width',\n );\n }\n\n return {\n name: state.containerName,\n condition,\n negated: state.negated ?? false,\n subtype: state.subtype,\n property: state.property,\n propertyValue: state.propertyValue,\n };\n}\n\n/**\n * Convert supports condition to parsed structure\n */\nfunction supportsToParsed(state: SupportsCondition): ParsedSupportsCondition {\n return {\n subtype: state.subtype,\n condition: state.condition,\n negated: state.negated ?? false,\n };\n}\n\n/**\n * Collect all modifier and pseudo conditions from a variant as a flat array.\n */\nfunction collectSelectorConditions(\n variant: SelectorVariant,\n): ParsedSelectorCondition[] {\n return [...variant.modifierConditions, ...variant.pseudoConditions];\n}\n\n/**\n * Convert an inner condition tree into a single SelectorVariant with\n * one SelectorGroup whose branches represent the inner OR alternatives.\n * Shared by @root(), @own(), and @parent().\n *\n * Both positive and negated cases produce one variant with one group.\n * Negation simply sets the `negated` flag, which swaps :is() for :not()\n * in the final CSS output — no De Morgan transformation is needed.\n *\n * OR branches are kept inside a single group and rendered as\n * comma-separated arguments in :is()/:not(), e.g. :root:is([a], [b]) or\n * [el]:not([a], [b]). Parent groups additionally retain their combinator.\n */\nfunction innerConditionToVariants(\n innerCondition: ConditionNode,\n negated: boolean,\n target: 'rootGroups' | 'ownGroups' | 'parentGroups',\n direct = false,\n): CSSComponents {\n const innerCSS = conditionToCSS(innerCondition);\n\n if (innerCSS.isImpossible || innerCSS.variants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n const branches: ParsedSelectorCondition[][] = [];\n\n for (const innerVariant of innerCSS.variants) {\n const conditions = collectSelectorConditions(innerVariant);\n\n if (conditions.length > 0) {\n branches.push(conditions);\n }\n }\n\n if (branches.length === 0) {\n return { variants: [emptyVariant()], isImpossible: false };\n }\n\n const v = emptyVariant();\n if (target === 'parentGroups') {\n v.parentGroups.push({ branches, direct, negated });\n } else {\n v[target].push({ branches, negated });\n }\n\n return { variants: [v], isImpossible: false };\n}\n\n/**\n * Sort key for canonical condition output within selectors.\n *\n * Priority order:\n * 0: Boolean attribute selectors ([data-hovered])\n * 1: Value attribute selectors ([data-size=\"small\"])\n * 2: Negated boolean attributes (:not([data-disabled]))\n * 3: Negated value attributes (:not([data-size=\"small\"]))\n * 4: Pseudo-classes (:hover, :focus)\n * 5: Negated pseudo-classes (:not(:disabled))\n *\n * Secondary sort: alphabetical by attribute name / pseudo string.\n */\nfunction conditionSortKey(cond: ParsedSelectorCondition): string {\n if ('attribute' in cond) {\n const hasValue = cond.value !== undefined ? 1 : 0;\n const neg = cond.negated ? 2 : 0;\n return `${neg + hasValue}|${cond.attribute}|${cond.value ?? ''}`;\n }\n const priority = cond.negated ? 5 : 4;\n return `${priority}|${cond.pseudo}`;\n}\n\nfunction sortConditions(\n conditions: ParsedSelectorCondition[],\n): ParsedSelectorCondition[] {\n return conditions.toSorted((a, b) =>\n conditionSortKey(a).localeCompare(conditionSortKey(b)),\n );\n}\n\nexport function branchToCSS(branch: ParsedSelectorCondition[]): string {\n let parts = '';\n for (const cond of sortConditions(branch)) {\n parts += selectorConditionToCSS(cond);\n }\n return parts;\n}\n\n/**\n * Wrap serialized selector arguments in :is() or :not().\n * Arguments are sorted for canonical output.\n */\nfunction wrapInIsOrNot(args: string[], negated: boolean): string {\n const wrapper = negated ? ':not' : ':is';\n return `${wrapper}(${args.sort().join(', ')})`;\n}\n\n/**\n * Wrap a non-empty selector fragment in `:where(...)` to zero its\n * specificity. Tasty anchors specificity solely on the doubled class\n * (`.tXX.tXX`) and `data-element` attributes; every stateful selector\n * (modifiers, pseudos, :is()/:not() groups, root/parent context) is wrapped\n * so it contributes nothing to specificity and the cascade is decided by\n * source order alone. Empty input passes through unchanged.\n */\nexport function wrapWhere(inner: string): string {\n if (!inner) return '';\n return `:where(${inner})`;\n}\n\n/**\n * Convert a selector group to a CSS selector fragment.\n *\n * Single-branch groups are unwrapped (no :is() wrapper).\n * Multi-branch groups use :is() or :not().\n * Negation swaps :is() for :not().\n */\nexport function selectorGroupToCSS(group: SelectorGroup): string {\n if (group.branches.length === 0) return '';\n\n // Single branch: emit directly without :is() wrapper\n if (group.branches.length === 1) {\n const parts = branchToCSS(group.branches[0]);\n if (group.negated) {\n return `:not(${parts})`;\n }\n return parts;\n }\n\n return wrapInIsOrNot(group.branches.map(branchToCSS), group.negated);\n}\n\n// ============================================================================\n// Modifier Subsumption (shared by optimizeGroups and dedupeSelectorConditions)\n// ============================================================================\n\ninterface SubsumptionFacts {\n negatedBooleanAttrs: Set<string>;\n positiveExactValuesByAttr: Map<string, Set<string>>;\n}\n\n/**\n * Collect facts about modifier conditions for subsumption analysis.\n * Tracks negated boolean attrs (:not([attr])) and positive exact values ([attr=\"X\"]).\n */\nfunction collectSubsumptionFacts(\n modifiers: Iterable<ParsedModifierCondition>,\n): SubsumptionFacts {\n const negatedBooleanAttrs = new Set<string>();\n const positiveExactValuesByAttr = new Map<string, Set<string>>();\n\n for (const mod of modifiers) {\n if (mod.negated && mod.value === undefined) {\n negatedBooleanAttrs.add(mod.attribute);\n }\n if (\n !mod.negated &&\n mod.value !== undefined &&\n (mod.operator ?? '=') === '='\n ) {\n let vals = positiveExactValuesByAttr.get(mod.attribute);\n if (!vals) {\n vals = new Set();\n positiveExactValuesByAttr.set(mod.attribute, vals);\n }\n vals.add(mod.value);\n }\n }\n\n return { negatedBooleanAttrs, positiveExactValuesByAttr };\n}\n\n/**\n * Check if a negated-value modifier is subsumed by stronger facts:\n * - :not([attr]) subsumes :not([attr=\"val\"])\n * - [attr=\"X\"] implies :not([attr=\"Y\"]) is redundant (single exact value)\n *\n * Only applies to exact-match (=) operators; substring operators don't\n * imply exclusivity between values.\n */\nfunction isSubsumedNegatedModifier(\n mod: ParsedModifierCondition,\n facts: SubsumptionFacts,\n): boolean {\n if (!mod.negated || mod.value === undefined) return false;\n\n if (facts.negatedBooleanAttrs.has(mod.attribute)) return true;\n\n if ((mod.operator ?? '=') === '=') {\n const posVals = facts.positiveExactValuesByAttr.get(mod.attribute);\n if (posVals && posVals.size === 1 && !posVals.has(mod.value)) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Remove redundant single-condition groups that are subsumed by stronger\n * groups on the same attribute. O(n) — only inspects single-branch,\n * single-condition groups.\n */\nexport function optimizeGroups(groups: SelectorGroup[]): SelectorGroup[] {\n if (groups.length <= 1) return groups;\n\n // Exact dedup by key\n const seen = new Set<string>();\n const result: SelectorGroup[] = [];\n for (const g of groups) {\n const key = getSelectorGroupKey(g);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(g);\n }\n }\n\n if (result.length <= 1) return result;\n\n // Extract modifier conditions from simple groups for subsumption analysis\n const effectiveModifiers: ParsedModifierCondition[] = [];\n for (const g of result) {\n if (g.branches.length !== 1 || g.branches[0].length !== 1) continue;\n const cond = g.branches[0][0];\n if (!('attribute' in cond)) continue;\n // Map group-level negation onto the condition for fact collection\n effectiveModifiers.push({\n ...cond,\n negated: g.negated !== cond.negated,\n });\n }\n\n const facts = collectSubsumptionFacts(effectiveModifiers);\n if (\n facts.negatedBooleanAttrs.size === 0 &&\n facts.positiveExactValuesByAttr.size === 0\n ) {\n return result;\n }\n\n return result.filter((g) => {\n if (g.branches.length !== 1 || g.branches[0].length !== 1) return true;\n const cond = g.branches[0][0];\n if (\n !('attribute' in cond) ||\n !g.negated ||\n cond.negated ||\n cond.value === undefined\n ) {\n return true;\n }\n return !isSubsumedNegatedModifier({ ...cond, negated: true }, facts);\n });\n}\n\n/**\n * Convert root groups to CSS selector prefix (for final output)\n */\nexport function rootGroupsToCSS(groups: SelectorGroup[]): string | undefined {\n if (groups.length === 0) return undefined;\n\n const optimized = optimizeGroups(groups);\n if (optimized.length === 0) return undefined;\n\n let prefix = ':root';\n for (const group of optimized) {\n prefix += selectorGroupToCSS(group);\n }\n // The root context prefix carries zero specificity: wrap the whole\n // `:root...` selector in :where() so neither the :root pseudo nor its\n // state groups contribute to specificity.\n return wrapWhere(prefix);\n}\n\n/**\n * Convert parent groups to CSS selector fragments (for final output).\n * Each group produces its own :is()/:not() wrapper with a combinator\n * suffix (` *` or ` > *`) appended to each branch.\n */\nexport function parentGroupsToCSS(groups: ParentGroup[]): string {\n let result = '';\n for (const group of groups) {\n const combinator = group.direct ? ' > *' : ' *';\n const args = group.branches.map(\n (branch) => branchToCSS(branch) + combinator,\n );\n // Ancestor context selectors carry zero specificity: wrap in :where().\n // Negation goes inside as :where(:not(...)) so the negated ancestor\n // adds nothing either.\n const inner = group.negated\n ? `:not(${args.sort().join(', ')})`\n : args.sort().join(', ');\n result += wrapWhere(inner);\n }\n return result;\n}\n\n/**\n * Convert a modifier or pseudo condition to a CSS selector fragment\n */\nfunction selectorConditionToCSS(cond: ParsedSelectorCondition): string {\n if ('attribute' in cond) {\n return modifierToCSS(cond);\n }\n return pseudoToCSS(cond);\n}\n\n/**\n * Get unique key for a modifier condition\n */\nfunction getModifierKey(mod: ParsedModifierCondition): string {\n const base = mod.value\n ? `${mod.attribute}${mod.operator || '='}${mod.value}`\n : mod.attribute;\n return mod.negated ? `!${base}` : base;\n}\n\n/**\n * Get unique key for a pseudo condition\n */\nfunction getPseudoKey(pseudo: ParsedPseudoCondition): string {\n return pseudo.negated ? `!${pseudo.pseudo}` : pseudo.pseudo;\n}\n\n/**\n * Get unique key for any selector condition (modifier or pseudo)\n */\nfunction getSelectorConditionKey(cond: ParsedSelectorCondition): string {\n return 'attribute' in cond\n ? `mod:${getModifierKey(cond)}`\n : `pseudo:${getPseudoKey(cond)}`;\n}\n\n/**\n * Deduplicate selector conditions (modifiers or pseudos).\n * Shared by root, parent, and own conditions.\n */\nfunction dedupeSelectorConditions(\n conditions: ParsedSelectorCondition[],\n): ParsedSelectorCondition[] {\n // Pass 1: exact-key dedup\n const seen = new Set<string>();\n const result: ParsedSelectorCondition[] = [];\n for (const c of conditions) {\n const key = getSelectorConditionKey(c);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(c);\n }\n }\n\n // Pass 2: remove negated value modifiers subsumed by other modifiers\n const modifiers = result.filter(\n (c): c is ParsedModifierCondition => 'attribute' in c,\n );\n const facts = collectSubsumptionFacts(modifiers);\n if (\n facts.negatedBooleanAttrs.size === 0 &&\n facts.positiveExactValuesByAttr.size === 0\n ) {\n return result;\n }\n\n return result.filter((c) => {\n if (!('attribute' in c)) return true;\n if (isSubsumedNegatedModifier(c, facts)) return false;\n // [data-attr] is redundant when [data-attr=\"val\"] already present\n if (\n !c.negated &&\n c.value === undefined &&\n facts.positiveExactValuesByAttr.has(c.attribute)\n ) {\n return false;\n }\n return true;\n });\n}\n\n/**\n * Check for selector condition contradiction (modifier or pseudo with opposite negation).\n * Shared by root, parent, and own conditions.\n */\nfunction hasSelectorConditionContradiction(\n conditions: ParsedSelectorCondition[],\n): boolean {\n const byKey = new Map<string, boolean>();\n\n for (const condition of conditions) {\n const key =\n 'attribute' in condition\n ? `mod:${\n condition.value\n ? `${condition.attribute}${condition.operator || '='}${condition.value}`\n : condition.attribute\n }`\n : `pseudo:${condition.pseudo}`;\n const existing = byKey.get(key);\n if (existing !== undefined && existing !== !condition.negated) {\n return true;\n }\n byKey.set(key, !condition.negated);\n }\n\n return false;\n}\n\n/**\n * Check for parent group contradiction: same target (direct + conditions)\n * with opposite negation. E.g. :not([data-hovered] *) and :is([data-hovered] *)\n * in the same variant is impossible.\n */\nfunction getBranchesKey(branches: ParsedSelectorCondition[][]): string {\n if (branches.length === 1) {\n const b = branches[0];\n if (b.length === 1) return getSelectorConditionKey(b[0]);\n return b.map(getSelectorConditionKey).sort().join('+');\n }\n return branches\n .map((b) => b.map(getSelectorConditionKey).sort().join('+'))\n .sort()\n .join(',');\n}\n\nfunction hasParentGroupContradiction(groups: ParentGroup[]): boolean {\n const byBaseKey = new Map<string, boolean>();\n\n for (const g of groups) {\n const baseKey = `${g.direct ? '>' : ''}(${getBranchesKey(g.branches)})`;\n const existing = byBaseKey.get(baseKey);\n if (existing !== undefined && existing !== !g.negated) {\n return true;\n }\n byBaseKey.set(baseKey, !g.negated);\n }\n return false;\n}\n\n/**\n * Check for selector group contradiction: same branches with opposite negation.\n * E.g. :is([data-a]) and :not([data-a]) in the same variant is impossible.\n */\nfunction hasSelectorGroupContradiction(groups: SelectorGroup[]): boolean {\n const byBaseKey = new Map<string, boolean>();\n\n for (const g of groups) {\n const baseKey = getBranchesKey(g.branches);\n const existing = byBaseKey.get(baseKey);\n if (existing !== undefined && existing !== !g.negated) {\n return true;\n }\n byBaseKey.set(baseKey, !g.negated);\n }\n return false;\n}\n\n/**\n * Merge two selector variants (AND operation)\n * Deduplicates conditions and checks for contradictions\n */\nfunction mergeVariants(\n a: SelectorVariant,\n b: SelectorVariant,\n): SelectorVariant | null {\n // Merge media conditions and check for contradictions\n const mergedMedia = dedupeMediaConditions([\n ...a.mediaConditions,\n ...b.mediaConditions,\n ]);\n if (hasMediaContradiction(mergedMedia)) {\n return null; // Impossible variant\n }\n\n // Concatenate root groups, optimize, and check for contradictions\n const mergedRootGroups = optimizeGroups([...a.rootGroups, ...b.rootGroups]);\n if (hasSelectorGroupContradiction(mergedRootGroups)) {\n return null; // Impossible variant\n }\n\n // Merge modifier and pseudo conditions separately, then cross-check\n const mergedModifiers = dedupeSelectorConditions([\n ...a.modifierConditions,\n ...b.modifierConditions,\n ]) as ParsedModifierCondition[];\n const mergedPseudos = dedupeSelectorConditions([\n ...a.pseudoConditions,\n ...b.pseudoConditions,\n ]) as ParsedPseudoCondition[];\n if (\n hasSelectorConditionContradiction([...mergedModifiers, ...mergedPseudos])\n ) {\n return null; // Impossible variant\n }\n\n // Concatenate selector groups, optimize, and check for contradictions\n const mergedSelectorGroups = optimizeGroups([\n ...a.selectorGroups,\n ...b.selectorGroups,\n ]);\n if (hasSelectorGroupContradiction(mergedSelectorGroups)) {\n return null; // Impossible variant\n }\n\n // Concatenate parent groups (each group is an independent :is() wrapper)\n const mergedParentGroups = [...a.parentGroups, ...b.parentGroups];\n if (hasParentGroupContradiction(mergedParentGroups)) {\n return null; // Impossible variant\n }\n\n // Concatenate own groups, optimize, and check for contradictions\n const mergedOwnGroups = optimizeGroups([...a.ownGroups, ...b.ownGroups]);\n if (hasSelectorGroupContradiction(mergedOwnGroups)) {\n return null; // Impossible variant\n }\n\n // Merge container conditions and check for contradictions\n const mergedContainers = dedupeContainerConditions([\n ...a.containerConditions,\n ...b.containerConditions,\n ]);\n if (hasContainerStyleContradiction(mergedContainers)) {\n return null; // Impossible variant\n }\n\n // Merge supports conditions and check for contradictions\n const mergedSupports = dedupeSupportsConditions([\n ...a.supportsConditions,\n ...b.supportsConditions,\n ]);\n if (hasSupportsContradiction(mergedSupports)) {\n return null; // Impossible variant\n }\n\n return {\n modifierConditions: mergedModifiers,\n pseudoConditions: mergedPseudos,\n selectorGroups: mergedSelectorGroups,\n ownGroups: mergedOwnGroups,\n mediaConditions: mergedMedia,\n containerConditions: mergedContainers,\n supportsConditions: mergedSupports,\n rootGroups: mergedRootGroups,\n parentGroups: mergedParentGroups,\n startingStyle: a.startingStyle || b.startingStyle,\n };\n}\n\n// Contradiction-detection helpers (`hasMediaContradiction`,\n// `hasContainerStyleContradiction`, `hasSupportsContradiction`) and the\n// matching `dedupe*Conditions` helpers live in `./materialize-contradictions`.\n// They're imported at the top of this file.\n\nconst variantKeyCache = new WeakMap<SelectorVariant, string>();\n\n/**\n * Get a unique key for a variant (for deduplication).\n * Cached via WeakMap since variants are compared multiple times during\n * deduplication and sorting.\n */\nfunction getSelectorGroupKey(g: SelectorGroup): string {\n return `${g.negated ? '!' : ''}(${getBranchesKey(g.branches)})`;\n}\n\n/**\n * Get a context key for a variant — everything except flat modifier/pseudo\n * conditions. Variants with the same context key can be merged into an\n * :is() group. Also used by getVariantKey as the shared non-selector portion.\n */\nfunction getVariantContextKey(v: SelectorVariant): string {\n const mediaKey = v.mediaConditions\n .map((c) => `${c.subtype}:${c.negated ? '!' : ''}${c.condition}`)\n .sort()\n .join('|');\n const containerKey = v.containerConditions\n .map((c) => `${c.name ?? ''}:${c.negated ? '!' : ''}${c.condition}`)\n .sort()\n .join('|');\n const supportsKey = v.supportsConditions\n .map((c) => `${c.subtype}:${c.negated ? '!' : ''}${c.condition}`)\n .sort()\n .join('|');\n const rootKey = v.rootGroups.map(getSelectorGroupKey).sort().join('|');\n const parentKey = v.parentGroups.map(getParentGroupKey).sort().join('|');\n const ownKey = v.ownGroups.map(getSelectorGroupKey).sort().join('|');\n const selectorGroupKey = v.selectorGroups\n .map(getSelectorGroupKey)\n .sort()\n .join('|');\n\n return [\n mediaKey,\n containerKey,\n supportsKey,\n rootKey,\n parentKey,\n ownKey,\n selectorGroupKey,\n v.startingStyle ? '1' : '0',\n ].join('###');\n}\n\nfunction getVariantKey(v: SelectorVariant): string {\n const cached = variantKeyCache.get(v);\n if (cached !== undefined) return cached;\n const modifierKey = v.modifierConditions.map(getModifierKey).sort().join('|');\n const pseudoKey = v.pseudoConditions.map(getPseudoKey).sort().join('|');\n const key = modifierKey + '###' + pseudoKey + '###' + getVariantContextKey(v);\n variantKeyCache.set(v, key);\n return key;\n}\n\n/**\n * Total number of leaf conditions in a variant (for superset / dedup comparisons).\n */\nfunction groupConditionCount(\n groups: readonly { branches: ParsedSelectorCondition[][] }[],\n): number {\n return groups.reduce(\n (sum, g) => sum + g.branches.reduce((s, b) => s + b.length, 0),\n 0,\n );\n}\n\nfunction variantConditionCount(v: SelectorVariant): number {\n return (\n v.modifierConditions.length +\n v.pseudoConditions.length +\n groupConditionCount(v.selectorGroups) +\n groupConditionCount(v.ownGroups) +\n v.mediaConditions.length +\n v.containerConditions.length +\n v.supportsConditions.length +\n groupConditionCount(v.rootGroups) +\n groupConditionCount(v.parentGroups)\n );\n}\n\n/**\n * Check if variant A is a superset of variant B (A is more restrictive)\n *\n * If A has all of B's conditions plus more, then A is redundant\n * because B already covers the same cases (and more).\n *\n * Example:\n * A: :not([size=large]):not([size=medium]):not([size=small])\n * B: :not([size=large])\n * A is a superset of B, so A is redundant when B exists.\n */\nfunction isVariantSuperset(a: SelectorVariant, b: SelectorVariant): boolean {\n // Must have same context\n if (a.startingStyle !== b.startingStyle) return false;\n\n // Check if a.rootGroups is superset of b.rootGroups\n if (!isSelectorGroupsSuperset(a.rootGroups, b.rootGroups)) return false;\n\n // Check if a.mediaConditions is superset of b.mediaConditions\n if (!isMediaConditionsSuperset(a.mediaConditions, b.mediaConditions))\n return false;\n\n // Check if a.containerConditions is superset of b.containerConditions\n if (\n !isContainerConditionsSuperset(a.containerConditions, b.containerConditions)\n )\n return false;\n\n // Check if a.supportsConditions is superset of b.supportsConditions\n if (!isSupportsConditionsSuperset(a.supportsConditions, b.supportsConditions))\n return false;\n\n // Check if a.modifierConditions is superset of b.modifierConditions\n if (!isModifierConditionsSuperset(a.modifierConditions, b.modifierConditions))\n return false;\n\n // Check if a.pseudoConditions is superset of b.pseudoConditions\n if (!isPseudoConditionsSuperset(a.pseudoConditions, b.pseudoConditions))\n return false;\n\n // Check if a.selectorGroups is superset of b.selectorGroups\n if (!isSelectorGroupsSuperset(a.selectorGroups, b.selectorGroups))\n return false;\n\n // Check if a.ownGroups is superset of b.ownGroups\n if (!isSelectorGroupsSuperset(a.ownGroups, b.ownGroups)) return false;\n\n // Check if a.parentGroups is superset of b.parentGroups\n if (!isParentGroupsSuperset(a.parentGroups, b.parentGroups)) return false;\n\n return variantConditionCount(a) > variantConditionCount(b);\n}\n\n/**\n * Generic superset check: true if every item in B has a matching key in A.\n */\nfunction isConditionsSuperset<T>(\n a: T[],\n b: T[],\n getKey: (item: T) => string,\n): boolean {\n const aKeys = new Set(a.map(getKey));\n return b.every((c) => aKeys.has(getKey(c)));\n}\n\nfunction isMediaConditionsSuperset(\n a: ParsedMediaCondition[],\n b: ParsedMediaCondition[],\n): boolean {\n return isConditionsSuperset(\n a,\n b,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction isContainerConditionsSuperset(\n a: ParsedContainerCondition[],\n b: ParsedContainerCondition[],\n): boolean {\n return isConditionsSuperset(\n a,\n b,\n (c) => `${c.name ?? ''}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction isSupportsConditionsSuperset(\n a: ParsedSupportsCondition[],\n b: ParsedSupportsCondition[],\n): boolean {\n return isConditionsSuperset(\n a,\n b,\n (c) => `${c.subtype}|${c.condition}|${c.negated}`,\n );\n}\n\nfunction isModifierConditionsSuperset(\n a: ParsedModifierCondition[],\n b: ParsedModifierCondition[],\n): boolean {\n return isConditionsSuperset(a, b, getModifierKey);\n}\n\nfunction isPseudoConditionsSuperset(\n a: ParsedPseudoCondition[],\n b: ParsedPseudoCondition[],\n): boolean {\n return isConditionsSuperset(a, b, getPseudoKey);\n}\n\nfunction isSelectorGroupsSuperset(\n a: SelectorGroup[],\n b: SelectorGroup[],\n): boolean {\n if (a.length < b.length) return false;\n return isConditionsSuperset(a, b, getSelectorGroupKey);\n}\n\n/**\n * Check if parent groups A is a superset of B.\n * Each group in B must have a matching group in A.\n */\nfunction isParentGroupsSuperset(a: ParentGroup[], b: ParentGroup[]): boolean {\n if (a.length < b.length) return false;\n return isConditionsSuperset(a, b, getParentGroupKey);\n}\n\nfunction getParentGroupKey(g: ParentGroup): string {\n return `${g.negated ? '!' : ''}${g.direct ? '>' : ''}(${getBranchesKey(g.branches)})`;\n}\n\n/**\n * Deduplicate variants\n *\n * Removes:\n * 1. Exact duplicates (same key)\n * 2. Superset variants (more restrictive selectors that are redundant)\n */\nfunction dedupeVariants(variants: SelectorVariant[]): SelectorVariant[] {\n if (variants.length <= 1) return variants;\n\n // First pass: exact deduplication\n const seen = new Set<string>();\n const result: SelectorVariant[] = [];\n\n for (const v of variants) {\n const key = getVariantKey(v);\n if (!seen.has(key)) {\n seen.add(key);\n result.push(v);\n }\n }\n\n if (result.length <= 1) return result;\n\n // Second pass: remove supersets (more restrictive variants)\n // Sort by total condition count (fewer conditions = less restrictive = keep)\n result.sort((a, b) => variantConditionCount(a) - variantConditionCount(b));\n\n // Remove variants that are supersets of earlier (less restrictive) variants\n const filtered: SelectorVariant[] = [];\n for (const candidate of result) {\n let isRedundant = false;\n for (const kept of filtered) {\n if (isVariantSuperset(candidate, kept)) {\n isRedundant = true;\n break;\n }\n }\n if (!isRedundant) {\n filtered.push(candidate);\n }\n }\n\n return filtered;\n}\n\n/**\n * Combine AND conditions into CSS\n *\n * AND of conditions means cartesian product of variants:\n * (A1 | A2) & (B1 | B2) = A1&B1 | A1&B2 | A2&B1 | A2&B2\n *\n * Variants that result in contradictions (e.g., conflicting media rules)\n * are filtered out.\n */\nfunction andToCSS(children: ConditionNode[]): CSSComponents {\n // Make inner OR branches exclusive before materializing so the\n // Cartesian product produces non-overlapping CSS variants.\n const exclusiveChildren = makeOrBranchesExclusive(children);\n\n // Start with a single empty variant\n let currentVariants: SelectorVariant[] = [emptyVariant()];\n\n for (const child of exclusiveChildren) {\n const childCSS = conditionToCSSInner(child);\n\n if (childCSS.isImpossible || childCSS.variants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n // Cartesian product: each current variant × each child variant\n const newVariants: SelectorVariant[] = [];\n for (const current of currentVariants) {\n for (const childVariant of childCSS.variants) {\n const merged = mergeVariants(current, childVariant);\n // Skip impossible variants (contradictions detected during merge)\n if (merged !== null) {\n newVariants.push(merged);\n }\n }\n }\n\n if (newVariants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n // Deduplicate after each step to prevent exponential blowup\n currentVariants = dedupeVariants(newVariants);\n }\n\n return {\n variants: currentVariants,\n isImpossible: false,\n };\n}\n\n/**\n * Check if a condition involves an `@supports` query (recursively).\n */\nfunction branchHasSupports(node: ConditionNode): boolean {\n if (node.kind === 'state') {\n return node.type === 'supports';\n }\n if (isCompoundCondition(node)) {\n return node.children.some(branchHasSupports);\n }\n return false;\n}\n\n/**\n * Make OR branches within AND children mutually exclusive.\n *\n * For an AND child that is OR(A, B), transforms it to OR(A, B & !A)\n * so that when andToCSS does a Cartesian product, the resulting\n * CSS variants don't overlap.\n *\n * Only transforms OR children whose branches actually produce\n * different at-rule contexts when materialized. This avoids\n * breaking cases where contradiction detection in the Cartesian\n * product naturally handles deduplication.\n */\nfunction makeOrBranchesExclusive(children: ConditionNode[]): ConditionNode[] {\n return children.map((child) => {\n if (!isCompoundCondition(child) || child.operator !== 'OR') return child;\n if (child.children.length <= 1) return child;\n\n // Only apply when branches produce different at-rule contexts.\n // Materialize each branch and compare context keys. If all branches\n // produce the same context key, the :is() merging handles it.\n if (!branchesProduceDifferentContexts(child.children)) return child;\n\n // Process `@supports` branches first so a negated feature guard becomes\n // the bare \"feature unsupported\" fallback and every dependent negation\n // (e.g. a `@container scroll-state(...)` query) nests inside the\n // supported scope. Without this, `simplify`'s alphabetical ordering can\n // emit a dependent query negation bare, where it is meaningless when the\n // feature is unsupported. Stable for ties.\n const sortedBranches = [...child.children].sort(\n (a, b) => (branchHasSupports(a) ? 0 : 1) - (branchHasSupports(b) ? 0 : 1),\n );\n\n const exclusiveBranches: ConditionNode[] = [];\n const priorBranches: ConditionNode[] = [];\n\n for (const branch of sortedBranches) {\n if (priorBranches.length === 0) {\n exclusiveBranches.push(branch);\n } else {\n let exclusive: ConditionNode = branch;\n for (const prior of priorBranches) {\n exclusive = and(exclusive, not(prior));\n }\n const simplified = simplifyCondition(exclusive);\n if (simplified.kind !== 'false') {\n exclusiveBranches.push(simplified);\n }\n }\n priorBranches.push(branch);\n }\n\n if (exclusiveBranches.length === 0) {\n return child;\n }\n if (exclusiveBranches.length === 1) {\n return exclusiveBranches[0];\n }\n\n return {\n kind: 'compound' as const,\n operator: 'OR' as const,\n children: exclusiveBranches,\n };\n });\n}\n\n/**\n * Check if OR branches produce different at-rule contexts when\n * materialized. If so, the Cartesian product in andToCSS will\n * create overlapping CSS variants that need exclusive expansion.\n *\n * Exported so Stage 2a (`expandOrConditions` in `exclusive.ts`) can\n * reuse the same heuristic and skip OR expansion when every branch\n * lives in the same at-rule/root/parent/own context — pure-selector\n * ORs are better collapsed into `:is(...)` at materialization time\n * than expanded into mutually-exclusive `A | (B & !A) | …` cascades.\n */\nexport function branchesProduceDifferentContexts(\n branches: ConditionNode[],\n): boolean {\n const contextKeys = new Set<string>();\n\n for (const branch of branches) {\n const css = conditionToCSSInner(branch);\n if (css.isImpossible) continue;\n\n for (const v of css.variants) {\n contextKeys.add(getVariantContextKey(v));\n }\n }\n\n return contextKeys.size > 1;\n}\n\n/**\n * Combine OR conditions into CSS\n *\n * OR in CSS means multiple selector variants (DNF).\n * After deduplication, variants that differ only in their base\n * modifier/pseudo conditions are merged into :is() groups.\n *\n * Note: OR exclusivity is handled at the pipeline level (expandOrConditions),\n * so here we just collect all variants. Any remaining ORs in the condition\n * tree (e.g., from De Morgan expansion) are handled as simple alternatives.\n */\n/**\n * Serialize a single negated own-element selector leaf (modifier or pseudo)\n * to its *positive* selector string, for use inside a combined `:not(...)`.\n *\n * Returns `null` when the node is not a negated, own-element selector leaf\n * (e.g. positive, or a media/container/parent/root/own/supports/starting\n * wrapper, or a compound), which means it cannot participate in De Morgan\n * recombination.\n */\nfunction negatedSelectorLeafToPositiveSelector(\n node: ConditionNode,\n): string | null {\n if (node.kind !== 'state' || !node.negated) return null;\n\n if (node.type === 'modifier') {\n return modifierToCSS({\n attribute: node.attribute,\n value: node.value,\n operator: node.operator,\n negated: false,\n });\n }\n\n if (node.type === 'pseudo') {\n // `pseudo` may itself be a `:is(X)`/`:where(X)` wrapper (from a parsed\n // `:not(X)`); unwrap so the recombined `:not(...)` stays compound-safe.\n const p = node.pseudo;\n if ((p.startsWith(':is(') || p.startsWith(':where(')) && !p.includes(',')) {\n const inner = p.slice(p.indexOf('(') + 1, -1);\n if (!/\\s/.test(inner)) return inner;\n return `:is(${inner})`;\n }\n return p;\n }\n\n return null;\n}\n\n/**\n * De Morgan recombination for an OR whose every branch is a negated\n * own-element selector leaf:\n *\n * OR(¬a, ¬b, ¬c) ≡ ¬(a ∧ b ∧ c) → single `:not(a b c)`\n *\n * This keeps the catch-all/default exclusive condition (which has no\n * positive terms to prune against) from exploding into a Cartesian product\n * of OR branches at `andToCSS`. Returns `null` when recombination does not\n * apply, so genuine unions (e.g. `:hover | :focus`) fall through to the\n * normal per-branch materialization.\n */\nfunction tryRecombineNegatedSelectorOr(\n children: ConditionNode[],\n): CSSComponents | null {\n if (children.length < 2) return null;\n\n const positiveSelectors: string[] = [];\n for (const child of children) {\n const sel = negatedSelectorLeafToPositiveSelector(child);\n if (sel === null) return null;\n positiveSelectors.push(sel);\n }\n\n // Stable ordering for deterministic hashing/dedupe.\n positiveSelectors.sort();\n const compound = positiveSelectors.join('');\n\n const v = emptyVariant();\n v.pseudoConditions.push({ pseudo: `:is(${compound})`, negated: true });\n return { variants: [v], isImpossible: false };\n}\n\nfunction orToCSS(children: ConditionNode[]): CSSComponents {\n // De Morgan recombination: OR(¬a, ¬b, ...) → single :not(a b ...).\n const recombined = tryRecombineNegatedSelectorOr(children);\n if (recombined !== null) {\n return recombined;\n }\n\n const allVariants: SelectorVariant[] = [];\n\n for (const child of children) {\n const childCSS = conditionToCSSInner(child);\n if (childCSS.isImpossible) continue;\n\n allVariants.push(...childCSS.variants);\n }\n\n if (allVariants.length === 0) {\n return { variants: [], isImpossible: true };\n }\n\n return {\n variants: dedupeVariants(allVariants),\n isImpossible: false,\n };\n}\n\n// ============================================================================\n// OR → :is() Merging\n// ============================================================================\n\n/**\n * Find keys present in ALL condition arrays.\n */\nfunction findCommonKeys<T>(\n conditionSets: T[][],\n getKey: (item: T) => string,\n): Set<string> {\n if (conditionSets.length === 0) return new Set();\n\n const common = new Set(conditionSets[0].map(getKey));\n for (let i = 1; i < conditionSets.length; i++) {\n const keys = new Set(conditionSets[i].map(getKey));\n for (const key of common) {\n if (!keys.has(key)) common.delete(key);\n }\n }\n return common;\n}\n\n/**\n * Merge OR variants that share the same \"context\" (at-rules, root, parent,\n * own, starting) into a single variant with a SelectorGroup.\n *\n * Variants with no modifier/pseudo conditions are kept separate (they match\n * unconditionally and can't be expressed inside :is()).\n */\nexport function mergeVariantsIntoSelectorGroups(\n variants: SelectorVariant[],\n): SelectorVariant[] {\n if (variants.length <= 1) return variants;\n\n // Group variants by their context (everything except flat modifier/pseudo)\n const groups = new Map<string, SelectorVariant[]>();\n for (const v of variants) {\n const key = getVariantContextKey(v);\n const group = groups.get(key);\n if (group) group.push(v);\n else groups.set(key, [v]);\n }\n\n const result: SelectorVariant[] = [];\n for (const group of groups.values()) {\n if (group.length === 1) {\n result.push(group[0]);\n continue;\n }\n\n // Separate variants with no selector conditions (can't merge into :is())\n const withSelectors: SelectorVariant[] = [];\n const withoutSelectors: SelectorVariant[] = [];\n for (const v of group) {\n if (\n v.modifierConditions.length === 0 &&\n v.pseudoConditions.length === 0\n ) {\n withoutSelectors.push(v);\n } else {\n withSelectors.push(v);\n }\n }\n\n result.push(...withoutSelectors);\n\n if (withSelectors.length <= 1) {\n result.push(...withSelectors);\n continue;\n }\n\n // Factor out common conditions and create a SelectorGroup\n result.push(factorAndGroup(withSelectors));\n }\n\n return result;\n}\n\n/**\n * Factor common modifier/pseudo conditions out of variants and create\n * a single variant with a SelectorGroup for the remaining (differing)\n * conditions.\n *\n * Precondition: all variants must share the same context key (identical\n * at-rules, root/parent/own/selector groups, startingStyle).\n */\nfunction factorAndGroup(variants: SelectorVariant[]): SelectorVariant {\n if (process.env.NODE_ENV !== 'production') {\n const key0 = getVariantContextKey(variants[0]);\n for (let i = 1; i < variants.length; i++) {\n const keyI = getVariantContextKey(variants[i]);\n if (keyI !== key0) {\n throw new Error(\n `factorAndGroup: context key mismatch at index ${i}.\\n` +\n ` expected: ${key0}\\n got: ${keyI}`,\n );\n }\n }\n }\n\n // Find common modifier and pseudo keys across ALL variants\n const commonModKeys = findCommonKeys(\n variants.map((v) => v.modifierConditions),\n getModifierKey,\n );\n const commonPseudoKeys = findCommonKeys(\n variants.map((v) => v.pseudoConditions),\n getPseudoKey,\n );\n\n // Extract common conditions from first variant\n const commonModifiers = variants[0].modifierConditions.filter((m) =>\n commonModKeys.has(getModifierKey(m)),\n );\n const commonPseudos = variants[0].pseudoConditions.filter((p) =>\n commonPseudoKeys.has(getPseudoKey(p)),\n );\n\n // Build branches from remaining (non-common) conditions.\n // If any variant has only common conditions (empty branch), it matches\n // unconditionally within this context — the :is() group would lose it.\n // In that case, return the broadest variant (common conditions only).\n const branches: ParsedSelectorCondition[][] = [];\n let hasEmptyBranch = false;\n for (const v of variants) {\n const branch: ParsedSelectorCondition[] = [];\n for (const mod of v.modifierConditions) {\n if (!commonModKeys.has(getModifierKey(mod))) branch.push(mod);\n }\n for (const pseudo of v.pseudoConditions) {\n if (!commonPseudoKeys.has(getPseudoKey(pseudo))) branch.push(pseudo);\n }\n if (branch.length > 0) {\n branches.push(branch);\n } else {\n hasEmptyBranch = true;\n }\n }\n\n // If a variant has only common conditions, it's the broadest match —\n // the :is() group with specific branches is subsumed by it.\n // Return the variant with common conditions only.\n if (hasEmptyBranch) {\n return {\n ...variants[0],\n modifierConditions: commonModifiers,\n pseudoConditions: commonPseudos,\n };\n }\n\n // Try to factor branches into independent :is() groups per attribute\n // e.g. 4 branches for 2 attrs × 2 values → two :is() groups of 2\n const factoredGroups = tryFactorIntoDimensions(branches);\n if (factoredGroups) {\n return {\n modifierConditions: commonModifiers,\n pseudoConditions: commonPseudos,\n selectorGroups: [...variants[0].selectorGroups, ...factoredGroups],\n ownGroups: [...variants[0].ownGroups],\n mediaConditions: [...variants[0].mediaConditions],\n containerConditions: [...variants[0].containerConditions],\n supportsConditions: [...variants[0].supportsConditions],\n rootGroups: [...variants[0].rootGroups],\n parentGroups: [...variants[0].parentGroups],\n startingStyle: variants[0].startingStyle,\n };\n }\n\n return {\n modifierConditions: commonModifiers,\n pseudoConditions: commonPseudos,\n selectorGroups: [\n ...variants[0].selectorGroups,\n { branches, negated: false },\n ],\n ownGroups: [...variants[0].ownGroups],\n mediaConditions: [...variants[0].mediaConditions],\n containerConditions: [...variants[0].containerConditions],\n supportsConditions: [...variants[0].supportsConditions],\n rootGroups: [...variants[0].rootGroups],\n parentGroups: [...variants[0].parentGroups],\n startingStyle: variants[0].startingStyle,\n };\n}\n\n/**\n * Detect when branches form a complete Cartesian product of independent\n * modifier attribute dimensions and return one SelectorGroup per dimension.\n *\n * Example: 4 branches for 2 attributes × 2 values each →\n * :is(A1, A2):is(B1, B2) instead of :is(A1B1, A1B2, A2B1, A2B2)\n */\nfunction tryFactorIntoDimensions(\n branches: ParsedSelectorCondition[][],\n): SelectorGroup[] | null {\n if (branches.length < 4) return null;\n\n // Only factor modifier-only branches\n const dimensions = new Map<string, Map<string, ParsedModifierCondition>>();\n for (const branch of branches) {\n for (const cond of branch) {\n if (!('attribute' in cond)) return null;\n if (!dimensions.has(cond.attribute)) {\n dimensions.set(cond.attribute, new Map());\n }\n dimensions.get(cond.attribute)!.set(getModifierKey(cond), cond);\n }\n }\n\n if (dimensions.size < 2) return null;\n\n // Each branch must have exactly one condition per dimension\n for (const branch of branches) {\n const seen = new Set<string>();\n for (const cond of branch) {\n const attr = (cond as ParsedModifierCondition).attribute;\n if (seen.has(attr)) return null;\n seen.add(attr);\n }\n if (seen.size !== dimensions.size) return null;\n }\n\n // Branch count must equal product of dimension sizes (complete product)\n let expectedCount = 1;\n for (const vals of dimensions.values()) {\n expectedCount *= vals.size;\n }\n if (branches.length !== expectedCount) return null;\n\n return [...dimensions.values()].map((vals) => ({\n branches: [...vals.values()].map((cond) => [\n cond as ParsedSelectorCondition,\n ]),\n negated: false,\n }));\n}\n\n// ============================================================================\n// Utility Functions\n// ============================================================================\n\n/**\n * Build at-rules array from a variant\n */\nexport function buildAtRulesFromVariant(variant: SelectorVariant): string[] {\n const atRules: string[] = [];\n\n // Add media rules - combine all conditions with \"and\"\n if (variant.mediaConditions.length > 0) {\n const conditionParts = variant.mediaConditions.map((c) => {\n if (c.subtype === 'type') {\n // Media type: print, screen, etc.\n return c.negated ? `not ${c.condition}` : c.condition;\n } else {\n // Feature or dimension: use not (condition) syntax for negation\n // MQ Level 4 requires parentheses around the condition for negation\n return c.negated ? `(not ${c.condition})` : c.condition;\n }\n });\n atRules.push(`@media ${conditionParts.sort().join(' and ')}`);\n }\n\n // Add container rules - group by container name and combine with \"and\"\n if (variant.containerConditions.length > 0) {\n // Group conditions by container name (undefined = unnamed/nearest)\n const byName = new Map<string | undefined, ParsedContainerCondition[]>();\n for (const cond of variant.containerConditions) {\n const group = byName.get(cond.name) || [];\n group.push(cond);\n byName.set(cond.name, group);\n }\n\n // Build one @container rule per container name\n for (const [name, conditions] of byName) {\n // CSS Container Query syntax requires parentheses around negated conditions:\n // @container (not style(--x)) and style(--y) - NOT @container not style(--x) and style(--y)\n const conditionParts = conditions.map((c) =>\n c.negated ? `(not ${c.condition})` : c.condition,\n );\n const namePrefix = name ? `${name} ` : '';\n atRules.push(`@container ${namePrefix}${conditionParts.join(' and ')}`);\n }\n }\n\n // Add supports rules - combine all conditions with \"and\"\n if (variant.supportsConditions.length > 0) {\n const conditionParts = variant.supportsConditions.map((c) => {\n // Build the condition based on subtype\n // feature: (display: grid) or (not (display: grid))\n // selector: selector(:has(*)) or (not selector(:has(*)))\n if (c.subtype === 'selector') {\n const selectorCond = `selector(${c.condition})`;\n return c.negated ? `(not ${selectorCond})` : selectorCond;\n } else {\n const featureCond = `(${c.condition})`;\n return c.negated ? `(not ${featureCond})` : featureCond;\n }\n });\n atRules.push(`@supports ${conditionParts.join(' and ')}`);\n }\n\n return atRules;\n}\n","/**\n * Structured warning system for the pipeline.\n *\n * Provides typed warning codes and a configurable handler so consumers\n * can programmatically intercept, suppress, or reroute warnings.\n */\n\ntype TastyWarningCode =\n | 'INVALID_SELECTOR_AFFIX'\n | 'XOR_CHAIN_TOO_LONG'\n | 'INTERNAL_PSEUDO_USED'\n | 'INVALID_TOP_LEVEL_PSEUDO_KEY'\n | 'INVALID_FALLBACK_KEY'\n | 'MISPLACED_DEFAULT_STATE'\n | 'REDUNDANT_DEFAULT_STATE'\n | 'HANDLER_CAMEL_CASE_KEY';\n\ninterface TastyWarning {\n code: TastyWarningCode;\n message: string;\n}\n\ntype TastyWarningHandler = (warning: TastyWarning) => void;\n\nconst defaultWarningHandler: TastyWarningHandler = (warning) => {\n // Diagnostic only — stripped from production builds. A custom handler\n // installed via `setWarningHandler` still receives every warning in\n // production, since `emitWarning` itself stays unconditional.\n if (process.env.NODE_ENV !== 'production') {\n console.warn(`[Tasty] ${warning.message}`);\n }\n};\n\nlet warningHandler: TastyWarningHandler = defaultWarningHandler;\n\n/**\n * Set a custom warning handler for pipeline warnings.\n * Returns a function that restores the previous handler.\n */\nexport function setWarningHandler(handler: TastyWarningHandler): () => void {\n const previous = warningHandler;\n warningHandler = handler;\n return () => {\n warningHandler = previous;\n };\n}\n\n/**\n * Emit a structured pipeline warning via the configured handler.\n */\nexport function emitWarning(code: TastyWarningCode, message: string): void {\n warningHandler({ code, message });\n}\n","/**\n * Exclusive Condition Builder\n *\n * Transforms parsed style entries into exclusive conditions.\n * Each entry's condition is ANDed with the negation of all higher-priority conditions,\n * ensuring exactly one condition matches at any given time.\n */\n\nimport type { StyleValue } from '../utils/styles';\n\nimport type { ConditionNode } from './conditions';\nimport { and, isCompoundCondition, not, or, trueCondition } from './conditions';\nimport { branchesProduceDifferentContexts } from './materialize';\nimport { simplifyCondition } from './simplify';\nimport { emitWarning } from './warnings';\n\n// ============================================================================\n// Types\n// ============================================================================\n\n/**\n * Parsed style entry with condition\n */\ninterface ParsedStyleEntry {\n styleKey: string; // e.g., 'padding', 'fill'\n stateKey: string; // Original key: '', 'compact', '@media(w < 768px)'\n value: StyleValue; // The style value (before handler processing)\n condition: ConditionNode; // Parsed condition tree\n priority: number; // Order in original object (higher = higher priority)\n /**\n * When true (set by the standalone `_` key), this entry is a map-wide\n * fallback floor. It always applies (its condition is `TRUE`), opts out\n * of RECEIVING negation from higher-priority entries, and never negates\n * lower-priority entries. It is pulled out of the negation cascade and\n * handled separately. See `buildExclusiveConditions`.\n */\n floor?: boolean;\n}\n\n/**\n * Style entry with exclusive condition\n */\nexport interface ExclusiveStyleEntry extends ParsedStyleEntry {\n exclusiveCondition: ConditionNode; // condition & !higherPriorityConditions\n}\n\n// ============================================================================\n// Main Function\n// ============================================================================\n\n/**\n * Build exclusive conditions for a list of parsed style entries.\n *\n * The entries should be ordered by priority (highest priority first).\n *\n * For each entry, we compute:\n * exclusiveCondition = condition & !prior[0] & !prior[1] & ...\n *\n * This ensures exactly one condition matches at any time.\n *\n * Example:\n * Input (ordered highest to lowest priority):\n * A: value1 (priority 2)\n * B: value2 (priority 1)\n * C: value3 (priority 0)\n *\n * Output:\n * A: A\n * B: B & !A\n * C: C & !A & !B\n *\n * @param entries Parsed style entries ordered by priority (highest first)\n * @returns Entries with exclusive conditions, filtered to remove impossible ones\n */\nexport function buildExclusiveConditions(\n entries: ParsedStyleEntry[],\n): ExclusiveStyleEntry[] {\n const result: ExclusiveStyleEntry[] = [];\n const priorConditions: ConditionNode[] = [];\n\n // Pull the `_` fallback floor out of the negation cascade entirely. It\n // always applies (TRUE condition), never receives negation, and never\n // negates lower-priority entries — so the remaining entries can be built\n // with a plain, unconditional negation pass. The floor is re-appended\n // afterward with its TRUE exclusive condition.\n const floors: ParsedStyleEntry[] = [];\n\n for (const entry of entries) {\n if (entry.floor) {\n floors.push(entry);\n continue;\n }\n\n // Build: condition & !prior[0] & !prior[1] & ...\n let exclusive: ConditionNode = entry.condition;\n\n for (const prior of priorConditions) {\n // Skip negating \"always true\" (default state) - it would become \"always false\"\n if (prior.kind === 'true') {\n continue;\n }\n\n // Cheap mutual-exclusivity pre-check: if this entry's own condition\n // already contradicts `prior` (e.g. `[theme=purple]` vs a prior\n // `[theme=green] & ...`), then `prior` can never match when this entry\n // does, so `!prior` is always true here and adds nothing. Skipping it\n // avoids De Morgan'ing `prior` into a wide OR of negations that would\n // otherwise feed an exponential Cartesian product at materialization.\n //\n // This only fires when the contradiction is structurally provable via\n // `simplifyCondition` (memoized, operates on the small pairwise AND).\n // The default entry (no positive terms) is unaffected and keeps its\n // full negation chain, which `orToCSS` recombines into compact :not().\n if (\n entry.condition.kind !== 'true' &&\n simplifyCondition(and(entry.condition, prior)).kind === 'false'\n ) {\n continue;\n }\n\n exclusive = and(exclusive, not(prior));\n }\n\n // Simplify the exclusive condition\n const simplified = simplifyCondition(exclusive);\n\n // Skip impossible conditions (simplified to FALSE)\n if (simplified.kind === 'false') {\n continue;\n }\n\n result.push({\n ...entry,\n exclusiveCondition: simplified,\n });\n\n // Add non-default conditions to prior list for subsequent entries\n if (entry.condition.kind !== 'true') {\n priorConditions.push(entry.condition);\n }\n }\n\n // Re-append the fallback floor(s). Their exclusive condition is just their\n // own (TRUE) condition: always active, never negated.\n for (const floor of floors) {\n result.push({\n ...floor,\n exclusiveCondition: floor.condition,\n });\n }\n\n return result;\n}\n\n/**\n * Parse style entries from a value mapping object.\n *\n * @param styleKey The style key (e.g., 'padding')\n * @param valueMap The value mapping { '': '2x', 'compact': '1x', '@media(w < 768px)': '0.5x' }\n * @param parseCondition Function to parse state keys into conditions\n * @returns Parsed entries ordered by priority (highest first)\n */\nexport function parseStyleEntries(\n styleKey: string,\n valueMap: Record<string, StyleValue>,\n parseCondition: (stateKey: string) => ConditionNode,\n): ParsedStyleEntry[] {\n const entries: ParsedStyleEntry[] = [];\n let floorEntry: ParsedStyleEntry | null = null;\n const keys = Object.keys(valueMap);\n\n keys.forEach((stateKey) => {\n const value = valueMap[stateKey];\n\n // The standalone `_` key is the map-wide fallback floor. It must be used\n // on its own — it cannot be combined with state logic (`_ & hovered`,\n // `_ | x`). A misused `_` is warned about and ignored.\n if (stateKey === '_') {\n floorEntry = {\n styleKey,\n stateKey,\n value,\n condition: trueCondition(),\n priority: 0,\n floor: true,\n };\n return;\n }\n\n if (isMisusedFallbackKey(stateKey)) {\n emitWarning(\n 'INVALID_FALLBACK_KEY',\n `Style key \"${stateKey}\" (in \"${styleKey}\") combines the fallback \"_\" with ` +\n `other state logic. \"_\" can only be used on its own as a map-wide ` +\n `fallback floor. The key has been ignored.`,\n );\n return;\n }\n\n const condition =\n stateKey === '' ? trueCondition() : parseCondition(stateKey);\n\n entries.push({\n styleKey,\n stateKey,\n value,\n condition,\n priority: 0,\n });\n });\n\n // A floor combined only with a bare `\"\"` default (and no other states) is\n // redundant: the `\"\"` default would always be superseded by the floor, so\n // only the floor's value matters. Drop the `\"\"` default and warn.\n if (floorEntry !== null) {\n const hasOtherStates = entries.some((e) => e.condition.kind !== 'true');\n const hasDefault = entries.some((e) => e.condition.kind === 'true');\n if (!hasOtherStates && hasDefault) {\n emitWarning(\n 'REDUNDANT_DEFAULT_STATE',\n `Style \"${styleKey}\" defines both a \"_\" fallback and a \"\" default with no ` +\n `other states. The \"\" default is redundant (always superseded by \"_\"); ` +\n `the \"_\" value is used and the \"\" default is ignored.`,\n );\n // Only the floor remains; drop the redundant bare default.\n entries.length = 0;\n }\n }\n\n const normalized = normalizeDefaultStates(entries, styleKey);\n\n // Assign contiguous priorities: the fallback floor is always lowest\n // priority (0) so it sits first in the cascade (emitted before the states\n // that layer over it); the remaining entries follow in authored order.\n const ordered =\n floorEntry !== null ? [floorEntry, ...normalized] : normalized;\n ordered.forEach((entry, index) => {\n entry.priority = index;\n });\n\n // Reverse so highest priority (last in object) comes first for exclusive building\n // buildExclusiveConditions expects highest priority first\n ordered.reverse();\n\n return ordered;\n}\n\n/**\n * Detect a misused standalone `_` fallback key: a key that is not exactly\n * `_` but contains `_` as a standalone atom among state-logic operators\n * (`&`, `|`, `^`, `,`) or grouping parens. A `_` embedded in a longer token\n * (e.g. a modifier named `_private`) is not a misuse.\n */\nfunction isMisusedFallbackKey(stateKey: string): boolean {\n if (stateKey === '_' || !stateKey.includes('_')) return false;\n return /(?:^|[\\s&|^,(])_(?:[\\s&|^,)]|$)/.test(stateKey);\n}\n\n/**\n * Resolve the bare `''` default state (`condition.kind === 'true'`) in a\n * style value map.\n *\n * The bare default only behaves correctly as the **first** (lowest-priority)\n * key. When it appears later, `buildExclusiveConditions` processes it first\n * (after the reverse), never adds it to the prior list, and never negates it\n * — so it silently overrides every state authored before it.\n *\n * This function, given entries in authored order, moves a misplaced bare\n * default to the front (lowest priority), preserving the relative order of\n * all other entries, and emits a `MISPLACED_DEFAULT_STATE` warning.\n *\n * The `_` fallback floor is pulled out before this runs (see\n * `parseStyleEntries`), so only the bare `''` default is considered here.\n */\nfunction normalizeDefaultStates(\n entries: ParsedStyleEntry[],\n styleKey: string,\n): ParsedStyleEntry[] {\n const defaultPos = entries.findIndex((e) => e.condition.kind === 'true');\n\n // No bare default, or already first: nothing to do (the common case).\n if (defaultPos <= 0) {\n return entries;\n }\n\n const defaultEntry = entries[defaultPos];\n emitWarning(\n 'MISPLACED_DEFAULT_STATE',\n `Style \"${styleKey}\" defines the default state \"${defaultEntry.stateKey}\" ` +\n `after other states. A bare default (\"\") must be the first key, ` +\n `otherwise it overrides the states above it. It has been moved to the ` +\n `first position. Define default states first.`,\n );\n\n return [\n defaultEntry,\n ...entries.slice(0, defaultPos),\n ...entries.slice(defaultPos + 1),\n ];\n}\n\n/**\n * Merge parsed entries that share the same value.\n *\n * When multiple **non-default** state keys map to the same value, their\n * conditions can be combined with OR and treated as a single entry.\n * This must happen **before** exclusive expansion and OR branch splitting\n * to avoid combinatorial explosion and duplicate CSS output.\n *\n * **Merging must preserve the authored cascade.** Merging two same-value\n * entries with priorities `p_h > p_l` lifts the lower-priority entry up\n * to `p_h` and changes the \"blocker\" for intermediate-priority entries\n * from `!C_h` to `!(C_h | C_l) = !C_h & !C_l`. The added `!C_l`\n * constraint can incorrectly block an intermediate entry that should\n * have won.\n *\n * Two same-value entries with conditions `C_h` (higher priority) and\n * `C_l` (lower priority) are safe to merge iff for every entry\n * `e_m` strictly between them in priority with a different value,\n *\n * simplify(C_m & C_l & !C_h) = FALSE\n *\n * i.e. there is no scenario where the intermediate state could have\n * matched (`C_m`), the lower-priority same-value entry would also have\n * matched (`C_l`), and the higher-priority entry would not (`!C_h`).\n * In such scenarios the intermediate is supposed to win; the merge\n * would block it by introducing `!C_l`.\n *\n * Example (UNSAFE — must not merge):\n * `{ hovered: 'red', pressed: 'blue', disabled: 'red' }`.\n * C_h = disabled, C_l = hovered, C_m = pressed. `pressed & hovered &\n * !disabled` is satisfiable (three independent modifiers), so the\n * intermediate `pressed` would lose to a merged red rule when both\n * `pressed` and `hovered` are active — breaking the cascade\n * `disabled > pressed > hovered`.\n *\n * Example (SAFE — still merges):\n * `{ '': light, '@dark': dark, '@hc': hc, '@dark & @hc': dark }`.\n * C_h = `@dark & @hc`, C_l = `@dark`, C_m = `@hc`.\n * `@hc & @dark & !(@dark & @hc) = @hc & @dark & (!@dark | !@hc)`\n * simplifies to FALSE, so merging the two darks into one `@dark` rule\n * at the higher priority does not affect the `@hc` rule.\n *\n * Default (TRUE) entries are never merged with non-default entries.\n * Merging `TRUE | X` collapses to `TRUE`, destroying the non-default\n * condition's participation in exclusive building. Stage 6\n * `mergeByValue` handles combining rules with identical CSS output\n * after exclusive conditions are correctly built.\n *\n * The merged entry keeps the highest priority of the merged entries.\n */\nexport function mergeEntriesByValue(\n entries: ParsedStyleEntry[],\n): ParsedStyleEntry[] {\n if (entries.length <= 1) return entries;\n\n const merged: ParsedStyleEntry[] = [];\n\n for (const entry of entries) {\n // Defaults are never merged with non-defaults. The `_` fallback floor\n // has a `TRUE` condition, so this same guard excludes it from merging;\n // it participates in Stage 6 `mergeByValue` later instead.\n if (entry.condition.kind === 'true') {\n merged.push(entry);\n continue;\n }\n\n const valueKey = serializeValue(entry.value);\n let mergeIdx = -1;\n\n // Find the most recent merged entry with the same value such that\n // merging is provably safe with respect to every different-value\n // entry strictly between them in priority order.\n for (let j = merged.length - 1; j >= 0; j--) {\n const prev = merged[j];\n if (prev.condition.kind === 'true') continue;\n if (serializeValue(prev.value) !== valueKey) continue;\n\n let safe = true;\n for (let k = j + 1; k < merged.length; k++) {\n const inter = merged[k];\n if (inter.condition.kind === 'true') continue;\n if (serializeValue(inter.value) === valueKey) continue;\n\n // Safety: simplify(C_m & C_l & !C_h) must be FALSE.\n // C_h = prev.condition, C_l = entry.condition, C_m = inter.condition.\n const conflict = simplifyCondition(\n and(inter.condition, entry.condition, not(prev.condition)),\n );\n if (conflict.kind !== 'false') {\n safe = false;\n break;\n }\n }\n\n if (safe) {\n mergeIdx = j;\n break;\n }\n }\n\n if (mergeIdx >= 0) {\n const prev = merged[mergeIdx];\n const newCondition = simplifyCondition(\n or(prev.condition, entry.condition),\n );\n // `prev` was processed before `entry`, so its priority is always\n // greater or equal. Keep `Math.max` for clarity of intent.\n merged[mergeIdx] = {\n styleKey: prev.styleKey,\n stateKey: `${prev.stateKey} | ${entry.stateKey}`,\n value: prev.value,\n condition: newCondition,\n priority: Math.max(prev.priority, entry.priority),\n };\n } else {\n merged.push(entry);\n }\n }\n\n // `merged` is already highest-priority-first by construction: input\n // entries arrive in that order, merges update an entry in place\n // without changing its priority, and no insert/delete reorders the\n // array.\n return merged;\n}\n\nfunction serializeValue(value: StyleValue): string {\n if (value === null || value === undefined) return 'null';\n if (typeof value === 'string' || typeof value === 'number') {\n return String(value);\n }\n return JSON.stringify(value);\n}\n\n// ============================================================================\n// Compound State Extraction\n// ============================================================================\n\n/**\n * Eliminate redundant state dimensions from a value map.\n *\n * When a value map contains compound AND state keys (e.g. `@dark & @hc`),\n * checks whether any state atom is a \"don't-care\" variable — i.e. the\n * value is the same whether that atom is present or absent. Redundant\n * atoms are removed from all keys and duplicate entries are collapsed.\n *\n * This runs **before** condition parsing so that downstream stages\n * (`mergeEntriesByValue`, `buildExclusiveConditions`, materialization)\n * never see the irrelevant dimension, producing simpler, smaller CSS.\n *\n * Only pure top-level AND combinations are eligible. Keys that contain\n * `|`, `^`, or `,` at the top level are treated as opaque single atoms.\n *\n * @example\n * { '': A, '@dark': B, '@hc': A, '@dark & @hc': B }\n * // @hc is redundant → { '': A, '@dark': B }\n */\nexport function extractCompoundStates(\n valueMap: Record<string, StyleValue>,\n): Record<string, StyleValue> {\n const keys = Object.keys(valueMap);\n\n if (keys.length < 3 || !keys.some((k) => k.includes('&'))) {\n return valueMap;\n }\n\n const entries = keys.map((key) => {\n const atoms = splitTopLevelAnd(key);\n // Keys containing the `_` fallback floor must stay opaque so `_` is never\n // dropped as a \"redundant atom\" or collapsed into the `\"\"` default.\n // (`_` is handled later in parseStyleEntries.)\n const isOpaque = atoms === null || atoms.includes('_');\n return {\n // null means the key has non-AND operators; treat the whole key\n // as a single opaque atom so it never matches partial pairs.\n atoms: isOpaque ? [key] : (atoms as string[]),\n value: valueMap[key],\n };\n });\n\n const allAtoms = new Set<string>();\n for (const e of entries) {\n for (const a of e.atoms) allAtoms.add(a);\n }\n\n const redundant = new Set<string>();\n for (const atom of allAtoms) {\n if (isAtomRedundant(entries, atom)) {\n redundant.add(atom);\n }\n }\n\n if (redundant.size === 0) return valueMap;\n\n const newMap: Record<string, StyleValue> = {};\n for (const e of entries) {\n const filtered = e.atoms.filter((a) => !redundant.has(a));\n const newKey = filtered.join(' & ');\n if (!(newKey in newMap)) {\n newMap[newKey] = e.value;\n }\n }\n\n return newMap;\n}\n\n/**\n * Split a state key by top-level `&` operators.\n *\n * Returns `null` if the key contains `|`, `^`, or `,` at the top level\n * (making it ineligible for atom-level extraction).\n * Returns `[]` for the empty string (default key).\n */\nfunction splitTopLevelAnd(key: string): string[] | null {\n if (key === '') return [];\n\n const parts: string[] = [];\n let depth = 0;\n let current = '';\n\n for (const ch of key) {\n if (ch === '(' || ch === '[') depth++;\n else if (ch === ')' || ch === ']') depth--;\n\n if (depth === 0) {\n if (ch === '&') {\n const trimmed = current.trim();\n if (trimmed) parts.push(trimmed);\n current = '';\n continue;\n }\n if (ch === '|' || ch === '^' || ch === ',') {\n return null;\n }\n }\n\n current += ch;\n }\n\n const trimmed = current.trim();\n if (trimmed) parts.push(trimmed);\n\n return parts;\n}\n\n/**\n * An atom is redundant when every entry that contains it has a matching\n * partner (same remaining atoms, atom absent) with the same value.\n */\nfunction isAtomRedundant(\n entries: { atoms: string[]; value: StyleValue }[],\n atom: string,\n): boolean {\n const withAtom = entries.filter((e) => e.atoms.includes(atom));\n if (withAtom.length === 0) return false;\n\n for (const wa of withAtom) {\n const remaining = wa.atoms.filter((a) => a !== atom);\n\n const pair = entries.find(\n (e) =>\n !e.atoms.includes(atom) &&\n e.atoms.length === remaining.length &&\n remaining.every((r) => e.atoms.includes(r)),\n );\n\n if (!pair) return false;\n if (serializeValue(wa.value) !== serializeValue(pair.value)) return false;\n }\n\n return true;\n}\n\n/**\n * Check if a value is a style value mapping (object with state keys)\n */\nexport function isValueMapping(\n value: StyleValue | Record<string, StyleValue>,\n): value is Record<string, StyleValue> {\n return (\n value !== null &&\n typeof value === 'object' &&\n !Array.isArray(value) &&\n !(value instanceof Date)\n );\n}\n\n// ============================================================================\n// OR Expansion\n// ============================================================================\n\n/**\n * Expand OR conditions in parsed entries into multiple exclusive entries.\n *\n * For an entry with condition `A | B | C`, this creates 3 entries:\n * - condition: A\n * - condition: B & !A\n * - condition: C & !A & !B\n *\n * This ensures OR branches are mutually exclusive BEFORE the main\n * exclusive condition building pass.\n *\n * @param entries Parsed entries (may contain OR conditions)\n * @returns Expanded entries with OR branches made exclusive\n */\nexport function expandOrConditions(\n entries: ParsedStyleEntry[],\n): ParsedStyleEntry[] {\n const result: ParsedStyleEntry[] = [];\n\n for (const entry of entries) {\n const expanded = expandSingleEntry(entry);\n result.push(...expanded);\n }\n\n return result;\n}\n\n/**\n * Expand a single entry's OR condition into multiple exclusive entries.\n *\n * Note: branches are NOT sorted by at-rule context here (unlike the\n * `expandExclusiveOrs` pass below). User-authored ORs in state keys aren't\n * the product of De Morgan negation, so each branch is expected to render\n * independently in its own scope and at-rule sort isn't load-bearing.\n * The post-build pass needs the sort because it has to preserve at-rule\n * wrapping across branches that came from negating a compound at-rule.\n *\n * Skip optimisation: when every branch renders into the same at-rule /\n * root / parent / own context (see \"Key Design Decision #2\" in\n * `docs/pipeline.md`), forcing mutual exclusivity here produces dead\n * `B & !A`-style branches that materialization later folds back into\n * `:is(A, B)`. Bail out and let `materialize.ts` collapse the OR via\n * `mergeVariantsIntoSelectorGroups`. Cross-entry exclusivity is still\n * enforced by `buildExclusiveConditions`; the post-build `expandExclusiveOrs`\n * pass still handles De Morgan ORs whose branches actually differ in\n * context.\n */\nfunction expandSingleEntry(entry: ParsedStyleEntry): ParsedStyleEntry[] {\n const orBranches = collectOrBranches(entry.condition);\n\n // If no OR (single branch), return as-is\n if (orBranches.length <= 1) {\n return [entry];\n }\n\n // Skip OR expansion when all branches share the same at-rule context.\n // Pure-selector ORs (e.g. `:hover | :focus`,\n // `:-webkit-autofill | :autofill`) are better merged into `:is(...)` at\n // materialization than expanded into mutually-exclusive cascades.\n if (!branchesProduceDifferentContexts(orBranches)) {\n return [entry];\n }\n\n // Make each OR branch exclusive from prior branches\n const result: ParsedStyleEntry[] = [];\n const priorBranches: ConditionNode[] = [];\n\n for (let i = 0; i < orBranches.length; i++) {\n const branch = orBranches[i];\n\n // Build: branch & !prior[0] & !prior[1] & ...\n let exclusiveBranch: ConditionNode = branch;\n for (const prior of priorBranches) {\n exclusiveBranch = and(exclusiveBranch, not(prior));\n }\n\n // Simplify to detect impossible combinations\n const simplified = simplifyCondition(exclusiveBranch);\n\n // Skip impossible branches\n if (simplified.kind === 'false') {\n priorBranches.push(branch);\n continue;\n }\n\n result.push({\n ...entry,\n stateKey: `${entry.stateKey}[${i}]`, // Mark as expanded branch\n condition: simplified,\n // Keep same priority - all branches from same entry have same priority\n });\n\n priorBranches.push(branch);\n }\n\n return result;\n}\n\n/**\n * Collect top-level OR branches from a condition.\n *\n * For `A | B | C`, returns [A, B, C]\n * For `A & B`, returns [A & B] (single branch)\n * For `A | (B & C)`, returns [A, B & C]\n */\nfunction collectOrBranches(condition: ConditionNode): ConditionNode[] {\n if (condition.kind === 'true' || condition.kind === 'false') {\n return [condition];\n }\n\n if (isCompoundCondition(condition) && condition.operator === 'OR') {\n // Flatten nested ORs\n const branches: ConditionNode[] = [];\n for (const child of condition.children) {\n branches.push(...collectOrBranches(child));\n }\n return branches;\n }\n\n // Not an OR - return as single branch\n return [condition];\n}\n\n// ============================================================================\n// Post-Build OR Expansion (for De Morgan ORs)\n// ============================================================================\n\n/**\n * Expand OR conditions in exclusive entries AFTER buildExclusiveConditions.\n *\n * This handles ORs that arise from De Morgan expansion during negation:\n * !(A & B) = !A | !B\n *\n * These ORs need to be made exclusive to avoid overlapping CSS rules:\n * !A | !B → !A | (A & !B)\n *\n * This is logically equivalent but ensures each branch has proper context.\n *\n * Example:\n * Input: { \"\": V1, \"@supports(...) & :has()\": V2 }\n * V2's exclusive = @supports & :has\n * V1's exclusive = !(@supports & :has) = !@supports | !:has\n *\n * Without this fix: V1 gets two rules:\n * - @supports (not ...) → V1 ✓\n * - :not(:has()) → V1 ✗ (missing @supports context!)\n *\n * With this fix: V1 gets two exclusive rules:\n * - @supports (not ...) → V1 ✓\n * - @supports (...) { :not(:has()) } → V1 ✓ (proper context!)\n */\nexport function expandExclusiveOrs(\n entries: ExclusiveStyleEntry[],\n): ExclusiveStyleEntry[] {\n const result: ExclusiveStyleEntry[] = [];\n\n for (const entry of entries) {\n const expanded = expandExclusiveConditionOrs(entry);\n result.push(...expanded);\n }\n\n return result;\n}\n\n/**\n * Rank an OR branch for exclusive expansion ordering. Lower rank is\n * processed first (becomes the more \"outer\" / less-constrained branch):\n * 0 — branch involves `@supports` (feature-detection guard)\n * 1 — branch involves another at-rule (media / container / starting)\n * 2 — branch is pure selector context (modifiers / pseudos)\n */\nfunction orBranchRank(node: ConditionNode): 0 | 1 | 2 {\n if (node.kind === 'state') {\n if (node.type === 'supports') return 0;\n if (\n node.type === 'media' ||\n node.type === 'container' ||\n node.type === 'starting'\n ) {\n return 1;\n }\n } else if (node.kind === 'compound') {\n let rank: 0 | 1 | 2 = 2;\n for (const child of node.children) {\n const childRank = orBranchRank(child);\n if (childRank === 0) return 0;\n if (childRank === 1) rank = 1;\n }\n return rank;\n }\n\n return 2;\n}\n\n/**\n * Sort OR branches to prioritize at-rule conditions first, with\n * `@supports` branches ahead of all other at-rules.\n *\n * This is critical for correct CSS generation. For `!A | !B` where A is at-rule\n * and B is modifier, we want:\n * - Branch 0: !A (at-rule negation - covers \"no @supports/media\" case)\n * - Branch 1: A & !B (modifier negation with at-rule context)\n *\n * If we process in wrong order (!B first), we'd get:\n * - Branch 0: !B (modifier negation WITHOUT at-rule context - WRONG!)\n * - Branch 1: B & !A (at-rule negation with modifier - incomplete coverage)\n *\n * The extra `@supports`-first tier matters when a feature query guards a\n * dependent query. For `!(S & C) = !S | !C` (S = `@supports(...)`, C =\n * `@container scroll-state(...)`), `simplify` sorts the branches\n * alphabetically into `[!C, !S]`. Expanding in that order would emit `!C`\n * as a bare `@container (not scroll-state(...))` — meaningless where the\n * feature is unsupported, so the default would never apply there. Putting\n * `!S` first yields `!S | (S & !C)`: a bare supports fallback plus the\n * dependent negation nested in the supported scope.\n */\nfunction sortOrBranchesForExpansion(\n branches: ConditionNode[],\n): ConditionNode[] {\n return branches.sort((a, b) => orBranchRank(a) - orBranchRank(b));\n}\n\n/**\n * Expand ORs in a single entry's exclusive condition\n */\nfunction expandExclusiveConditionOrs(\n entry: ExclusiveStyleEntry,\n): ExclusiveStyleEntry[] {\n let orBranches = collectOrBranches(entry.exclusiveCondition);\n\n // If no OR (single branch), return as-is\n if (orBranches.length <= 1) {\n return [entry];\n }\n\n // Skip OR expansion when all branches share the same at-rule context.\n // De Morgan ORs across different at-rule scopes (e.g.\n // `!@supports | !:has`) still need exclusive splitting so each branch\n // ends up in the correct at-rule wrapper, but pure-selector ORs\n // (`:hover | :focus`, `:-webkit-autofill | :autofill`) collapse\n // cleanly via `:is(...)` at materialization. Matches the same\n // heuristic used by `makeOrBranchesExclusive` in `materialize.ts` and\n // by Stage 2a above.\n if (!branchesProduceDifferentContexts(orBranches)) {\n return [entry];\n }\n\n // Sort branches so at-rule conditions come first\n // This ensures proper context inheritance during expansion\n orBranches = sortOrBranchesForExpansion(orBranches);\n\n // Make each OR branch exclusive from prior branches\n const result: ExclusiveStyleEntry[] = [];\n const priorBranches: ConditionNode[] = [];\n\n for (let i = 0; i < orBranches.length; i++) {\n const branch = orBranches[i];\n\n // Build: branch & !prior[0] & !prior[1] & ...\n // This transforms: !A | !B → !A, !B & !!A = !A, (A & !B)\n let exclusiveBranch: ConditionNode = branch;\n for (const prior of priorBranches) {\n exclusiveBranch = and(exclusiveBranch, not(prior));\n }\n\n // Simplify to detect impossible combinations and clean up double negations\n const simplified = simplifyCondition(exclusiveBranch);\n\n // Skip impossible branches\n if (simplified.kind === 'false') {\n priorBranches.push(branch);\n continue;\n }\n\n result.push({\n ...entry,\n stateKey: `${entry.stateKey}[or:${i}]`, // Mark as expanded OR branch\n exclusiveCondition: simplified,\n });\n\n priorBranches.push(branch);\n }\n\n return result;\n}\n","export function camelToKebab(str: string): string {\n return str.replace(/([a-z0-9])([A-Z])/g, '$1-$2').toLowerCase();\n}\n","/**\n * Shared utility for transforming capitalized PascalCase element names\n * in CSS selector content to `[data-element=\"...\"]` attribute selectors.\n *\n * Lowercase words are treated as HTML tags and left unchanged.\n */\n\n/**\n * Matches a capitalized PascalCase word at the start of the string\n * or after a CSS combinator/separator character.\n */\nconst ELEMENT_NAME_RE = /(^|[\\s>+~,(])([A-Z][a-zA-Z0-9]*)/g;\n\n/**\n * Replace capitalized PascalCase words with `[data-element=\"Name\"]` selectors.\n *\n * @example\n * transformSelectorContent('> Field + input:checked')\n * // → '> [data-element=\"Field\"] + input:checked'\n *\n * transformSelectorContent('Body > Row')\n * // → '[data-element=\"Body\"] > [data-element=\"Row\"]'\n *\n * transformSelectorContent('button')\n * // → 'button' (lowercase = HTML tag, unchanged)\n */\nexport function transformSelectorContent(content: string): string {\n return content.replace(\n ELEMENT_NAME_RE,\n (_, prefix, name) => `${prefix}[data-element=\"${name}\"]`,\n );\n}\n","/**\n * State Key Parser\n *\n * Parses state notation strings (like 'hovered & !disabled', '@media(w < 768px)')\n * into ConditionNode trees for processing in the pipeline.\n */\n\nimport { Lru } from '../parser/lru';\nimport type { StateParserContext } from '../states';\nimport {\n expandDimensionShorthands,\n expandTastyUnits,\n findTopLevelComma,\n resolvePredefinedState,\n} from '../states';\nimport { camelToKebab } from '../utils/case-converter';\nimport { isDevEnv } from '../utils/is-dev-env';\nimport { transformSelectorContent } from '../utils/selector-transform';\n\nimport type { ConditionNode, NumericBound } from './conditions';\nimport { emitWarning } from './warnings';\nimport {\n and,\n createContainerDimensionCondition,\n createContainerRawCondition,\n createContainerStyleCondition,\n createMediaDimensionCondition,\n createMediaFeatureCondition,\n createMediaTypeCondition,\n createModifierCondition,\n createOwnCondition,\n createParentCondition,\n createPseudoCondition,\n createRootCondition,\n createStartingCondition,\n createSupportsCondition,\n not,\n or,\n trueCondition,\n} from './conditions';\n\n// ============================================================================\n// Constants\n// ============================================================================\n\n/**\n * Maximum XOR operands before emitting a performance warning.\n * A ^ B ^ C ^ D = 8 OR branches (2^(n-1)), so chains above 4\n * risk exponential blowup in downstream processing.\n */\nconst MAX_XOR_CHAIN_LENGTH = 4;\n\n// ============================================================================\n// Types\n// ============================================================================\n\nexport interface ParseStateKeyOptions {\n context?: StateParserContext;\n isSubElement?: boolean;\n}\n\n// ============================================================================\n// Caching\n// ============================================================================\n\n// Cache for parsed state keys (key -> ConditionNode)\nconst parseCache = new Lru<string, ConditionNode>(5000);\n\n// ============================================================================\n// Internal-pseudo Detection\n// ============================================================================\n\n/**\n * Chrome-internal pseudo-classes (e.g. `:-internal-autofill-selected`,\n * `:-internal-autofill-previewed`) cannot be targeted from user CSS and\n * may invalidate the surrounding rule in Safari even when wrapped in\n * forgiving `:is(...)`. The regex matches both bare uses and references\n * inside enhanced pseudo arguments like `:is(:-webkit-autofill,\n * :-internal-autofill-selected)`.\n */\nconst INTERNAL_PSEUDO_PATTERN = /:-internal-[a-z0-9-]+/g;\n\n// ============================================================================\n// Tokenizer Patterns\n// ============================================================================\n\nconst SIMPLE_MODIFIER_PATTERN = /^[a-z][a-z0-9-]+$/i;\nconst FUNCTION_START_PATTERN =\n /@(?:media|supports|root|parent|own)?\\(|:(?:is|has|not|where)\\(/iy;\nconst SIMPLE_TOKEN_PATTERN =\n /@media:[a-z]+|@[a-z][a-z0-9-]*|[a-z][a-z0-9-]*(?:\\^=|\\$=|\\*=|=)(?:\"[^\"]*\"|'[^']*'|[^\\s&|!^()]+)|[a-z][a-z0-9-]+|:[-a-z][a-z0-9-]*(?:\\([^)]+\\))?|\\.[a-z][a-z0-9-]+/iy;\n\n// ============================================================================\n// Tokenizer\n// ============================================================================\n\n/**\n * Tokenize a state notation string\n */\nfunction tokenize(stateKey: string): string[] {\n const tokens: string[] = [];\n const source = stateKey.includes(',')\n ? replaceCommasOutsideParens(stateKey)\n : stateKey;\n\n let i = 0;\n while (i < source.length) {\n const ch = source[i];\n\n if (\n ch === '&' ||\n ch === '|' ||\n ch === '!' ||\n ch === '^' ||\n ch === '(' ||\n ch === ')'\n ) {\n tokens.push(ch);\n i++;\n continue;\n }\n\n FUNCTION_START_PATTERN.lastIndex = i;\n const functionStart = FUNCTION_START_PATTERN.exec(source);\n if (functionStart) {\n const open = FUNCTION_START_PATTERN.lastIndex - 1;\n const isMedia = ch === '@' && functionStart[0].length === 7;\n const mediaClose = isMedia ? source.indexOf(')', open + 1) : -1;\n const end = isMedia\n ? mediaClose > open + 1\n ? mediaClose + 1\n : -1\n : findBalancedEnd(source, open);\n if (end !== -1) {\n tokens.push(source.slice(i, end));\n i = end;\n continue;\n }\n }\n\n if (ch === '[') {\n const end = source.indexOf(']', i + 1);\n if (end > i + 1) {\n tokens.push(source.slice(i, end + 1));\n i = end + 1;\n continue;\n }\n }\n\n SIMPLE_TOKEN_PATTERN.lastIndex = i;\n const simple = SIMPLE_TOKEN_PATTERN.exec(source);\n if (simple) {\n tokens.push(simple[0]);\n i = SIMPLE_TOKEN_PATTERN.lastIndex;\n continue;\n }\n\n i++;\n }\n\n return tokens;\n}\n\n/** Return the index after a balanced function, preserving the two-level limit. */\nfunction findBalancedEnd(source: string, open: number): number {\n let depth = 0;\n for (let i = open; i < source.length; i++) {\n if (source[i] === '(') {\n if (++depth > 3) return -1;\n } else if (source[i] === ')' && --depth === 0) {\n return i + 1;\n }\n }\n return -1;\n}\n\n/**\n * Replace commas with | only outside of parentheses\n */\nfunction replaceCommasOutsideParens(str: string): string {\n let result = '';\n let depth = 0;\n\n for (const char of str) {\n if (char === '(') {\n depth++;\n } else if (char === ')') {\n depth--;\n }\n result += char === ',' && depth === 0 ? '|' : char;\n }\n\n return result;\n}\n\n// ============================================================================\n// Recursive Descent Parser\n// ============================================================================\n\n/**\n * Parser state\n */\nclass Parser {\n private tokens: string[];\n private pos = 0;\n private options: ParseStateKeyOptions;\n\n constructor(tokens: string[], options: ParseStateKeyOptions) {\n this.tokens = tokens;\n this.options = options;\n }\n\n parse(): ConditionNode {\n if (this.tokens.length === 0) {\n return trueCondition();\n }\n return this.parseExpression();\n }\n\n private match(token: string): boolean {\n if (this.tokens[this.pos] === token) {\n this.pos++;\n return true;\n }\n return false;\n }\n\n /**\n * Parse expression with operator precedence:\n * ! (NOT) > ^ (XOR) > | (OR) > & (AND)\n */\n private parseExpression(): ConditionNode {\n return this.parseAnd();\n }\n\n private parseAnd(): ConditionNode {\n let left = this.parseOr();\n\n while (this.tokens[this.pos] === '&') {\n this.pos++;\n const right = this.parseOr();\n left = and(left, right);\n }\n\n return left;\n }\n\n private parseOr(): ConditionNode {\n let left = this.parseXor();\n\n while (this.tokens[this.pos] === '|') {\n this.pos++;\n const right = this.parseXor();\n left = or(left, right);\n }\n\n return left;\n }\n\n private parseXor(): ConditionNode {\n let left = this.parseUnary();\n let operandCount = 1;\n\n while (this.tokens[this.pos] === '^') {\n this.pos++;\n const right = this.parseUnary();\n operandCount++;\n\n if (operandCount > MAX_XOR_CHAIN_LENGTH) {\n emitWarning(\n 'XOR_CHAIN_TOO_LONG',\n `XOR chain with ${operandCount} operands produces ${Math.pow(2, operandCount - 1)} OR branches. ` +\n `Consider breaking into smaller expressions to avoid exponential growth.`,\n );\n }\n\n // XOR: (A & !B) | (!A & B)\n left = or(and(left, not(right)), and(not(left), right));\n }\n\n return left;\n }\n\n private parseUnary(): ConditionNode {\n if (this.match('!')) {\n const operand = this.parseUnary();\n return not(operand);\n }\n return this.parsePrimary();\n }\n\n private parsePrimary(): ConditionNode {\n // Handle parentheses\n if (this.match('(')) {\n const expr = this.parseExpression();\n this.match(')'); // Consume closing paren (lenient if missing)\n return expr;\n }\n\n // Handle state tokens\n const token = this.tokens[this.pos];\n // Every operator/group token is one character; every state token emitted by\n // tokenize() is at least two characters long.\n if (token && token.length > 1) {\n this.pos++;\n return this.parseStateToken(token);\n }\n\n // Fallback for empty/invalid - return TRUE\n return trueCondition();\n }\n\n /**\n * Parse a state token into a ConditionNode\n */\n private parseStateToken(value: string): ConditionNode {\n // @starting\n if (value === '@starting') {\n return createStartingCondition(false, value);\n }\n\n // @media:type (e.g., @media:print)\n if (value.startsWith('@media:')) {\n const mediaType = value.slice(7) as 'print' | 'screen' | 'all' | 'speech';\n return createMediaTypeCondition(mediaType, false, value);\n }\n\n // @media(...) - media query\n if (value.startsWith('@media(')) {\n return this.parseMediaQuery(value);\n }\n\n // @supports(...) - feature/selector support query\n if (value.startsWith('@supports(')) {\n return this.parseSupportsQuery(value);\n }\n\n // @root(...) - root state\n if (value.startsWith('@root(')) {\n return this.parseRootState(value);\n }\n\n // @parent(...) - parent element state\n if (value.startsWith('@parent(')) {\n return this.parseParentState(value);\n }\n\n // @own(...) - own state (sub-element)\n if (value.startsWith('@own(')) {\n return this.parseOwnState(value);\n }\n\n // @(...) - container query\n if (value.startsWith('@(')) {\n return this.parseContainerQuery(value);\n }\n\n // @name - predefined state\n if (value.startsWith('@') && /^@[A-Za-z][A-Za-z0-9-]*$/.test(value)) {\n return this.parsePredefinedState(value);\n }\n\n // Enhanced pseudo-classes: :is(), :has(), :not(), :where()\n // Transform capitalized words to [data-element=\"...\"] selectors,\n // auto-complete trailing combinators with *, and\n // normalize :not(X) → negated :is(X) for deduplication.\n if (value.startsWith(':')) {\n const enhancedMatch = /^:(is|has|not|where)\\(/.exec(value);\n if (enhancedMatch) {\n const fn = enhancedMatch[1];\n const prefix = enhancedMatch[0];\n let content = transformSelectorContent(value.slice(prefix.length, -1));\n\n // Auto-complete trailing combinator: :has(Icon >) → :has(... > *)\n content = content.replace(/([>+~])\\s*$/, '$1 *');\n\n if (fn === 'not') {\n return createPseudoCondition(`:is(${content})`, true, value);\n }\n\n return createPseudoCondition(`:${fn}(${content})`, false, value);\n }\n\n return createPseudoCondition(value, false, value);\n }\n\n // Class selector (e.g., .active)\n if (value.startsWith('.')) {\n return createPseudoCondition(value, false, value);\n }\n\n // Attribute selector (e.g., [disabled], [data-state=\"active\"])\n // Single, simple attribute selectors become structured modifiers so the\n // pipeline can reason about their mutual exclusivity (same attribute,\n // different value can never match at once). Complex forms (~=, |=, case\n // flags, namespaces, multiple attrs, combinators) stay opaque pseudos.\n if (value.startsWith('[')) {\n const attrMatch =\n /^\\[\\s*([a-zA-Z_][\\w-]*)\\s*(?:(=|\\^=|\\$=|\\*=)\\s*(?:\"([^\"]*)\"|'([^']*)'|([^\\]\\s]+)))?\\s*\\]$/.exec(\n value,\n );\n if (attrMatch) {\n const [, attribute, operator, dq, sq, bare] = attrMatch;\n if (operator === undefined) {\n // Boolean attribute: [data-disabled]\n return createModifierCondition(\n attribute,\n undefined,\n '=',\n false,\n value,\n );\n }\n const attrValue = dq ?? sq ?? bare;\n return createModifierCondition(\n attribute,\n attrValue,\n operator as '=' | '^=' | '$=' | '*=',\n false,\n value,\n );\n }\n return createPseudoCondition(value, false, value);\n }\n\n // Value modifier (e.g., theme=danger, size=large)\n if (value.includes('=')) {\n return this.parseValueModifier(value);\n }\n\n // Boolean modifier (e.g., hovered, disabled)\n return createBooleanModifier(value);\n }\n\n /**\n * Parse @media(...) query\n */\n private parseMediaQuery(raw: string): ConditionNode {\n const content = raw.slice(7, -1); // Remove '@media(' and ')'\n if (!content.trim()) {\n return trueCondition();\n }\n\n // Expand shorthands and units\n let condition = expandDimensionShorthands(content);\n condition = expandTastyUnits(condition);\n\n // Check for feature queries (contains ':' but not dimension comparison)\n if (\n condition.includes(':') &&\n !condition.includes('<') &&\n !condition.includes('>') &&\n !condition.includes('=')\n ) {\n // Feature query: @media(prefers-contrast: high)\n const colonIdx = condition.indexOf(':');\n const feature = condition.slice(0, colonIdx).trim();\n const featureValue = condition.slice(colonIdx + 1).trim();\n return createMediaFeatureCondition(feature, featureValue, false, raw);\n }\n\n // Boolean feature query: @media(prefers-reduced-motion)\n if (\n !condition.includes('<') &&\n !condition.includes('>') &&\n !condition.includes('=')\n ) {\n return createMediaFeatureCondition(\n condition.trim(),\n undefined,\n false,\n raw,\n );\n }\n\n // Dimension query - parse bounds\n const { dimension, lowerBound, upperBound } =\n this.parseDimensionCondition(condition);\n\n if (!dimension) {\n // Fallback for unparseable - treat as pseudo\n return createPseudoCondition(raw, false, raw);\n }\n\n return createMediaDimensionCondition(\n dimension as 'width' | 'height',\n lowerBound,\n upperBound,\n false,\n raw,\n );\n }\n\n /**\n * Parse dimension condition string (e.g., \"width < 768px\", \"600px <= width < 1200px\")\n */\n private parseDimensionCondition(condition: string): {\n dimension?: string;\n lowerBound?: NumericBound;\n upperBound?: NumericBound;\n } {\n // Range syntax: \"600px <= width < 1200px\"\n const rangeMatch = condition.match(\n /^(.+?)\\s*(<=|<)\\s*(width|height|inline-size|block-size)\\s*(<=|<)\\s*(.+)$/,\n );\n if (rangeMatch) {\n const [, lowerValue, lowerOp, dimension, upperOp, upperValue] =\n rangeMatch;\n const lower = lowerValue.trim();\n const upper = upperValue.trim();\n return {\n dimension,\n lowerBound: {\n value: lower,\n valueNumeric: parseNumericValue(lower),\n inclusive: lowerOp === '<=',\n },\n upperBound: {\n value: upper,\n valueNumeric: parseNumericValue(upper),\n inclusive: upperOp === '<=',\n },\n };\n }\n\n // Simple comparison: \"width < 768px\"\n const simpleMatch = condition.match(\n /^(width|height|inline-size|block-size)\\s*(<=|>=|<|>|=)\\s*(.+)$/,\n );\n if (simpleMatch) {\n const [, dimension, operator, value] = simpleMatch;\n const trimmedValue = value.trim();\n const numeric = parseNumericValue(trimmedValue);\n\n if (operator === '<' || operator === '<=') {\n return {\n dimension,\n upperBound: {\n value: trimmedValue,\n valueNumeric: numeric,\n inclusive: operator === '<=',\n },\n };\n } else if (operator === '>' || operator === '>=') {\n return {\n dimension,\n lowerBound: {\n value: trimmedValue,\n valueNumeric: numeric,\n inclusive: operator === '>=',\n },\n };\n } else if (operator === '=') {\n // Exact match: both bounds are the same and inclusive\n return {\n dimension,\n lowerBound: {\n value: trimmedValue,\n valueNumeric: numeric,\n inclusive: true,\n },\n upperBound: {\n value: trimmedValue,\n valueNumeric: numeric,\n inclusive: true,\n },\n };\n }\n }\n\n // Reversed: \"768px > width\"\n const reversedMatch = condition.match(\n /^(.+?)\\s*(<=|>=|<|>|=)\\s*(width|height|inline-size|block-size)$/,\n );\n if (reversedMatch) {\n const [, value, operator, dimension] = reversedMatch;\n const trimmedValue = value.trim();\n const numeric = parseNumericValue(trimmedValue);\n\n // Reverse the operator\n if (operator === '<' || operator === '<=') {\n return {\n dimension,\n lowerBound: {\n value: trimmedValue,\n valueNumeric: numeric,\n inclusive: operator === '<=',\n },\n };\n } else if (operator === '>' || operator === '>=') {\n return {\n dimension,\n upperBound: {\n value: trimmedValue,\n valueNumeric: numeric,\n inclusive: operator === '>=',\n },\n };\n }\n }\n\n return {};\n }\n\n /**\n * Parse @root(...) state\n */\n private parseInnerCondition(\n raw: string,\n prefixLen: number,\n wrap: (inner: ConditionNode) => ConditionNode,\n ): ConditionNode {\n const content = raw.slice(prefixLen, -1);\n if (!content.trim()) return trueCondition();\n return wrap(parseStateKey(content, this.options));\n }\n\n private parseRootState(raw: string): ConditionNode {\n return this.parseInnerCondition(raw, 6, (inner) =>\n createRootCondition(inner, false, raw),\n );\n }\n\n /**\n * Parse @parent(...) state\n *\n * Syntax:\n * @parent(hovered) → :is([data-hovered] *)\n * @parent(theme=dark) → :is([data-theme=\"dark\"] *)\n * @parent(hovered, >) → :is([data-hovered] > *) (direct parent)\n * @parent(.my-class) → :is(.my-class *)\n */\n private parseParentState(raw: string): ConditionNode {\n const content = raw.slice(8, -1);\n let condition = content.trim();\n if (!condition) {\n return trueCondition();\n }\n\n let direct = false;\n\n const lastCommaIdx = condition.lastIndexOf(',');\n if (lastCommaIdx !== -1) {\n const afterComma = condition.slice(lastCommaIdx + 1).trim();\n if (afterComma === '>') {\n direct = true;\n condition = condition.slice(0, lastCommaIdx).trim();\n }\n }\n\n const innerCondition = parseStateKey(condition, this.options);\n return createParentCondition(innerCondition, direct, false, raw);\n }\n\n /**\n * Parse @supports(...) query\n *\n * Syntax:\n * @supports(display: grid) → @supports (display: grid)\n * @supports($, :has(*)) → @supports selector(:has(*))\n */\n private parseSupportsQuery(raw: string): ConditionNode {\n const content = raw.slice(10, -1); // Remove '@supports(' and ')'\n if (!content.trim()) {\n return trueCondition();\n }\n\n // Check for selector syntax: @supports($, :has(*))\n if (content.startsWith('$,')) {\n const selector = content.slice(2).trim(); // Remove '$,' prefix\n return createSupportsCondition('selector', selector, false, raw);\n }\n\n // Feature syntax: @supports(display: grid)\n return createSupportsCondition('feature', content, false, raw);\n }\n\n private parseOwnState(raw: string): ConditionNode {\n return this.parseInnerCondition(raw, 5, (inner) =>\n createOwnCondition(inner, false, raw),\n );\n }\n\n /**\n * Parse @(...) container query\n */\n private parseContainerQuery(raw: string): ConditionNode {\n const content = raw.slice(2, -1); // Remove '@(' and ')'\n if (!content.trim()) {\n return trueCondition();\n }\n\n // Check for named container: @(layout, w < 600px)\n // Use parentheses-aware comma search so inner commas (e.g., scroll-state(a, b)) are skipped\n const commaIdx = findTopLevelComma(content);\n let containerName: string | undefined;\n let condition: string;\n\n if (commaIdx !== -1) {\n containerName = content.slice(0, commaIdx).trim();\n condition = content.slice(commaIdx + 1).trim();\n } else {\n condition = content.trim();\n }\n\n // Check for style query shorthand: @($variant=primary)\n if (condition.startsWith('$')) {\n const styleQuery = condition.slice(1); // Remove '$'\n const eqIdx = styleQuery.indexOf('=');\n\n if (eqIdx === -1) {\n // Existence check: @($variant)\n return createContainerStyleCondition(\n styleQuery,\n undefined,\n containerName,\n false,\n raw,\n );\n }\n\n const property = styleQuery.slice(0, eqIdx).trim();\n let propertyValue = styleQuery.slice(eqIdx + 1).trim();\n\n // Remove quotes if present\n if (\n (propertyValue.startsWith('\"') && propertyValue.endsWith('\"')) ||\n (propertyValue.startsWith(\"'\") && propertyValue.endsWith(\"'\"))\n ) {\n propertyValue = propertyValue.slice(1, -1);\n }\n\n return createContainerStyleCondition(\n property,\n propertyValue,\n containerName,\n false,\n raw,\n );\n }\n\n // Check for function-like syntax: scroll-state(...), style(...), etc.\n // Passes the condition through to CSS verbatim.\n if (/^[a-zA-Z][\\w-]*\\s*\\(/.test(condition)) {\n return createContainerRawCondition(condition, containerName, false, raw);\n }\n\n // Dimension query\n let expandedCondition = expandDimensionShorthands(condition);\n expandedCondition = expandTastyUnits(expandedCondition);\n\n const { dimension, lowerBound, upperBound } =\n this.parseDimensionCondition(expandedCondition);\n\n if (!dimension) {\n // Fallback\n return createPseudoCondition(raw, false, raw);\n }\n\n return createContainerDimensionCondition(\n dimension as 'width' | 'height',\n lowerBound,\n upperBound,\n containerName,\n false,\n raw,\n );\n }\n\n /**\n * Parse predefined state (@mobile, @dark, etc.)\n */\n private parsePredefinedState(raw: string): ConditionNode {\n const ctx = this.options.context;\n if (!ctx) {\n // No context - can't resolve predefined states\n return createPseudoCondition(raw, false, raw);\n }\n\n const resolved = resolvePredefinedState(raw, ctx);\n if (!resolved) {\n // Undefined predefined state - treat as modifier\n return createModifierCondition(\n `data-${camelToKebab(raw.slice(1))}`,\n undefined,\n '=',\n false,\n raw,\n );\n }\n\n // Parse the resolved value recursively\n return parseStateKey(resolved, this.options);\n }\n\n /**\n * Parse value modifier (e.g., theme=danger, size^=sm)\n */\n private parseValueModifier(raw: string): ConditionNode {\n // Match operators: =, ^=, $=, *=\n const opMatch = raw.match(/^([a-z][a-z0-9-]*)(\\^=|\\$=|\\*=|=)(.+)$/i);\n if (!opMatch) {\n return createModifierCondition(\n `data-${camelToKebab(raw)}`,\n undefined,\n '=',\n false,\n raw,\n );\n }\n\n const [, key, operator, value] = opMatch;\n let cleanValue = value;\n\n // Remove quotes if present\n if (\n (cleanValue.startsWith('\"') && cleanValue.endsWith('\"')) ||\n (cleanValue.startsWith(\"'\") && cleanValue.endsWith(\"'\"))\n ) {\n cleanValue = cleanValue.slice(1, -1);\n }\n\n return createModifierCondition(\n `data-${camelToKebab(key)}`,\n cleanValue,\n operator as '=' | '^=' | '$=' | '*=',\n false,\n raw,\n );\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Parse a numeric value from a CSS value string\n */\nfunction parseNumericValue(value: string): number | null {\n const match = value.match(/^(\\d+(?:\\.\\d+)?)(px|em|rem|vh|vw|%)?$/);\n if (match) {\n return parseFloat(match[1]);\n }\n return null;\n}\n\nfunction createBooleanModifier(raw: string): ConditionNode {\n return createModifierCondition(\n `data-${camelToKebab(raw)}`,\n undefined,\n '=',\n false,\n raw,\n );\n}\n\n// ============================================================================\n// Main Export\n// ============================================================================\n\n/**\n * Parse a state key string into a ConditionNode\n */\nexport function parseStateKey(\n stateKey: string,\n options: ParseStateKeyOptions = {},\n): ConditionNode {\n // Handle empty/default state\n if (!stateKey) return trueCondition();\n\n const trimmed = stateKey.trim();\n if (!trimmed) return trueCondition();\n\n // Build cache key including local predefined states (they affect parsing)\n // Global predefined states are set once at initialization and don't change\n const ctx = options.context;\n const localStatesKey =\n ctx && Object.keys(ctx.localPredefinedStates).length > 0\n ? JSON.stringify(ctx.localPredefinedStates)\n : '';\n const cacheKey =\n trimmed + '\\0' + (options.isSubElement ? '1' : '0') + '\\0' + localStatesKey;\n\n // Check cache\n const cached = parseCache.get(cacheKey);\n if (cached) {\n return cached;\n }\n\n // Warn about `:-internal-*` pseudo-classes. The cache miss above\n // means we only emit the warning the first time we encounter a\n // given key (subsequent identical keys reuse the cached result and\n // skip this scan). The regex catches both bare uses and references\n // inside `:is(...)` / `:has(...)` / `:not(...)` / `:where(...)`.\n //\n // Gated behind `isDevEnv()` because this is a developer-only aid.\n // `isDevEnv()` uses bracket notation on `process.env` to survive\n // tasty's own bundling and also returns `false` under `NODE_ENV=test`\n // / `NODE_ENV=production`, so the warning only fires in real dev.\n if (isDevEnv()) {\n INTERNAL_PSEUDO_PATTERN.lastIndex = 0;\n const internalMatches = trimmed.match(INTERNAL_PSEUDO_PATTERN);\n if (internalMatches && internalMatches.length > 0) {\n const unique = Array.from(new Set(internalMatches));\n emitWarning(\n 'INTERNAL_PSEUDO_USED',\n `State key \"${trimmed}\" references internal pseudo-class${unique.length > 1 ? 'es' : ''} ${unique.map((p) => `\\`${p}\\``).join(', ')}. ` +\n `These are unmatchable from user CSS and can invalidate the surrounding rule in Safari (even inside \\`:is(...)\\`). ` +\n `Use \\`:-webkit-autofill | :autofill\\` instead for autofill states.`,\n );\n }\n }\n\n const result = SIMPLE_MODIFIER_PATTERN.test(trimmed)\n ? createBooleanModifier(trimmed)\n : new Parser(tokenize(trimmed), options).parse();\n\n // Cache result\n parseCache.set(cacheKey, result);\n\n return result;\n}\n\n/**\n * Clear the parse cache (for testing)\n */\nexport function clearParseCache(): void {\n parseCache.clear();\n}\n","/**\n * Tasty Style Rendering Pipeline\n *\n * Main entrypoint for the style rendering pipeline. Transforms a `Styles`\n * object into an array of `CSSRule` objects ready for DOM injection.\n *\n * Per-handler stages (see docs/pipeline.md for full detail):\n * 0. PRE-PARSE NORMALIZATION - extractCompoundStates (exclusive.ts)\n * 1. PARSE CONDITIONS - parseStyleEntries + parseStateKey\n * 1b. MERGE ENTRIES BY VALUE - mergeEntriesByValue (exclusive.ts)\n * 2a. EXPAND USER OR BRANCHES - expandOrConditions (exclusive.ts)\n * 2b. BUILD EXCLUSIVE CONDITIONS - buildExclusiveConditions\n * 3. EXPAND DE MORGAN ORs - expandExclusiveOrs (exclusive.ts)\n * 4. COMPUTE STATE COMBINATIONS - computeStateCombinations\n * 5. CALL HANDLERS - run style handlers for each snapshot\n * 6. MERGE BY VALUE - mergeByValue (index.ts)\n * 7. MATERIALIZE CSS - conditionToCSS + materializeComputedRule\n *\n * Simplification (`simplifyCondition`) runs inside most stages; calls are\n * memoized by condition unique-id. The post-pass in `runPipeline` dedupes\n * identical rules and emits all `@starting-style` rules last so they win\n * the cascade over their equal-specificity normal counterparts.\n */\n\nimport { Lru } from '../parser/lru';\nimport type { StateParserContext } from '../states';\nimport {\n createStateParserContext,\n extractLocalPredefinedStates,\n} from '../states';\nimport { createStyle, STYLE_HANDLER_MAP } from '../styles';\nimport type { Styles } from '../styles/types';\nimport { isDevEnv } from '../utils/is-dev-env';\nimport { isSelector } from '../utils/is-selector';\nimport { toSnakeCase } from '../utils/string';\nimport type {\n StyleHandler,\n StyleMap,\n StyleValue,\n StyleValueStateMap,\n} from '../utils/styles';\nimport { stringifyStyles } from '../utils/styles';\n\nimport type { ConditionNode } from './conditions';\nimport { and, or, trueCondition } from './conditions';\nimport type { ExclusiveStyleEntry } from './exclusive';\nimport {\n buildExclusiveConditions,\n expandExclusiveOrs,\n expandOrConditions,\n extractCompoundStates,\n isValueMapping,\n mergeEntriesByValue,\n parseStyleEntries,\n} from './exclusive';\nimport type { CSSRule, SelectorVariant } from './materialize-types';\nimport {\n branchToCSS,\n buildAtRulesFromVariant,\n conditionToCSS,\n mergeVariantsIntoSelectorGroups,\n optimizeGroups,\n parentGroupsToCSS,\n rootGroupsToCSS,\n selectorGroupToCSS,\n wrapWhere,\n} from './materialize';\nimport { parseStateKey } from './parseStateKey';\nimport { simplifyCondition } from './simplify';\nimport { emitWarning } from './warnings';\n\n/** Any uppercase letter — a CSS property name should never contain one. */\nconst RE_UPPER_CASE = /[A-Z]/;\n\n// ============================================================================\n// Types (compatible with old renderStyles API)\n// ============================================================================\n\n/**\n * Matches the old StyleResult interface for backward compatibility\n */\nexport interface StyleResult {\n selector: string;\n declarations: string;\n atRules?: string[];\n needsClassName?: boolean;\n rootPrefix?: string;\n /** When true, declarations are wrapped in @starting-style { ... } inside the selector rule */\n startingStyle?: boolean;\n}\n\n/**\n * Matches the old RenderResult interface for backward compatibility\n */\nexport interface RenderResult {\n rules: StyleResult[];\n className?: string;\n}\n\ninterface ComputedRule {\n condition: ConditionNode;\n declarations: Record<string, string>;\n selectorSuffix: string;\n /**\n * Cascade order hint (source priority of the highest-priority style entry\n * that contributed to this rule). Higher = should appear later in the\n * stylesheet so it wins the cascade. Used to emit `_` fallback floor rules\n * before the higher-priority rules that layer over them, since `:where()`\n * makes all rules share specificity and source order decides the winner.\n */\n order: number;\n}\n\n// ============================================================================\n// Caching\n// ============================================================================\n\nconst pipelineCache = new Lru<string, CSSRule[]>(5000);\n\n/**\n * Check if a cache key exists in the pipeline cache.\n * Used by renderStylesForChunk to avoid building filtered styles on cache hit.\n */\nexport function hasPipelineCacheEntry(cacheKey: string): boolean {\n return pipelineCache.get(cacheKey) !== undefined;\n}\n\n/**\n * Clear the pipeline cache (for testing)\n */\nexport function clearPipelineCache(): void {\n pipelineCache.clear();\n}\n\n// ============================================================================\n// Pipeline Implementation\n// ============================================================================\n\nfunction runPipeline(\n styles: Styles,\n parserContext: StateParserContext,\n): CSSRule[] {\n const allRules: CSSRule[] = [];\n\n // Process styles recursively (including nested selectors)\n processStyles(styles, '', parserContext, allRules);\n\n // Deduplicate and partition in one pass. @starting-style rules must come\n // after normal rules for the same selector because source order decides\n // the cascade between their equal-specificity selectors.\n const seen = new Set<string>();\n const normal: CSSRule[] = [];\n const starting: CSSRule[] = [];\n\n for (const rule of allRules) {\n const key = `${rule.selector}|${rule.declarations}|${rule.atRules?.join('|') ?? ''}|${rule.rootPrefix || ''}|${rule.startingStyle ? '1' : '0'}`;\n if (seen.has(key)) continue;\n seen.add(key);\n (rule.startingStyle ? starting : normal).push(rule);\n }\n\n // Order rules by their cascade order hint (ascending source priority) so\n // higher-priority rules come later and win. This is load-bearing once\n // selector specificity is equalized via `:where()`: `_` fallback floor\n // rules (low order) must precede the higher-priority rules that layer over\n // them. The sort is stable, so equal-order rules keep their emission\n // order. Mutually-exclusive rules are unaffected by ordering.\n const stableOrdered = stableSortByOrder(normal);\n\n return stableOrdered.concat(stableSortByOrder(starting));\n}\n\n/**\n * Stable sort CSS rules by their `order` hint ascending. Rules without an\n * `order` are treated as 0. `Array.prototype.sort` is stable (ES2019+,\n * Node >= 20), so equal-order rules keep their emission order — the `_`\n * fallback floor (low order) stays before the overrides that layer over it.\n */\nfunction stableSortByOrder(rules: CSSRule[]): CSSRule[] {\n if (rules.length <= 1) return rules;\n return [...rules].sort((a, b) => (a.order ?? 0) - (b.order ?? 0));\n}\n\n/**\n * Process styles at a given nesting level.\n *\n * Splits keys into nested-selector keys and style-handler keys, recurses\n * into nested selectors, then runs the per-handler stages 1–7 over the\n * style keys.\n */\nfunction processStyles(\n styles: Styles,\n selectorSuffix: string,\n parserContext: StateParserContext,\n allRules: CSSRule[],\n): void {\n const keys = Object.keys(styles);\n\n // Separate selector keys from style keys.\n // Skip @keyframes (processed separately) and other @-prefixed keys\n // (predefined states), which are not handler entries.\n const selectorKeys: string[] = [];\n const styleKeys: string[] = [];\n for (const key of keys) {\n if (isSelector(key)) {\n selectorKeys.push(key);\n continue;\n }\n if (key.startsWith('@')) continue;\n\n // Reject top-level pseudo-class / pseudo-element keys like ':hover',\n // '::before', ':has(...)'. These are not valid Tasty style keys —\n // pseudo-states belong inside a value map (e.g. `color: { ':hover': '...' }`),\n // and nested-declaration form requires an `&` prefix (e.g. `'&:hover': {…}`).\n // Without `&`, a key like ':hover' falls through to a generic style\n // handler and produces malformed CSS, so we drop it and warn in dev.\n if (key.startsWith(':')) {\n emitWarning(\n 'INVALID_TOP_LEVEL_PSEUDO_KEY',\n `Style key \"${key}\" starts with ':' which is not a valid Tasty style key. ` +\n `Use \"&${key}\" for nested-selector form, or move the state into a value map ` +\n `(e.g. \\`{ color: { '${key}': value } }\\`). The key has been ignored.`,\n );\n continue;\n }\n\n styleKeys.push(key);\n }\n\n // Process nested selectors first\n processNestedSelectors(\n styles,\n selectorKeys,\n selectorSuffix,\n parserContext,\n allRules,\n );\n\n // Process the handler queue for this level's style keys\n const handlerQueue = buildHandlerQueue(styleKeys, styles);\n processHandlerQueue(handlerQueue, selectorSuffix, parserContext, allRules);\n}\n\n/**\n * Recurse into nested selector keys. Each nested key may expand into multiple\n * suffixes (comma-separated patterns); each suffix is processed independently\n * with the parent's parser context augmented for sub-element scope.\n */\nfunction processNestedSelectors(\n styles: Styles,\n selectorKeys: string[],\n selectorSuffix: string,\n parserContext: StateParserContext,\n allRules: CSSRule[],\n): void {\n for (const key of selectorKeys) {\n const nestedStyles = styles[key] as Styles;\n if (!nestedStyles || typeof nestedStyles !== 'object') continue;\n\n // Get all selectors (handles comma-separated patterns)\n const suffixes = getAllSelectors(key, nestedStyles);\n if (!suffixes) continue; // Invalid selector, skip\n\n // Remove $ from nested styles\n const { $: _$, ...cleanedStyles } = nestedStyles;\n\n // Extract local predefined states scoped to this sub-element\n const subLocalStates = extractLocalPredefinedStates(cleanedStyles);\n const hasSubStates = Object.keys(subLocalStates).length > 0;\n const subContext: StateParserContext = {\n ...parserContext,\n isSubElement: true,\n localPredefinedStates: hasSubStates\n ? { ...parserContext.localPredefinedStates, ...subLocalStates }\n : parserContext.localPredefinedStates,\n };\n\n // Process for each selector (multiple selectors = same styles applied to each)\n for (const suffix of suffixes) {\n processStyles(\n cleanedStyles,\n selectorSuffix + suffix,\n subContext,\n allRules,\n );\n }\n }\n}\n\n/**\n * Run the per-handler pipeline (stages 1–7) over a handler queue and append\n * the resulting CSS rules to `allRules`.\n */\nfunction processHandlerQueue(\n handlerQueue: ReturnType<typeof buildHandlerQueue>,\n selectorSuffix: string,\n parserContext: StateParserContext,\n allRules: CSSRule[],\n): void {\n for (const { handler, styleMap, hasStateMap } of handlerQueue) {\n const lookupStyles = handler.__lookupStyles;\n\n // State-free handlers have exactly one unconditional snapshot. Avoid the\n // exclusive-condition and Cartesian-product pipeline in this common case.\n const stateSnapshots = hasStateMap\n ? computeStateCombinations(\n buildExclusivesForHandler(lookupStyles, styleMap, parserContext),\n lookupStyles,\n )\n : [\n {\n condition: trueCondition(),\n values: styleMap as Record<string, StyleValue>,\n order: 0,\n },\n ];\n\n // Stage 5: Call handler for each snapshot\n const computedRules = invokeHandler(\n handler,\n stateSnapshots,\n selectorSuffix,\n );\n\n // Stage 6: Merge rules with identical CSS output\n const mergedRules = mergeByValue(computedRules);\n\n // Stage 7: Materialize to CSS\n for (const rule of mergedRules) {\n const cssRules = materializeComputedRule(rule);\n allRules.push(...cssRules);\n }\n }\n}\n\n/**\n * Stages 0–3 for a single handler: take the handler's looked-up style names,\n * resolve each style's value map into a list of mutually-exclusive entries.\n * Simple non-mapping values produce a single TRUE-conditioned entry.\n */\nfunction buildExclusivesForHandler(\n lookupStyles: readonly string[],\n styleMap: StyleMap,\n parserContext: StateParserContext,\n): Map<string, ExclusiveStyleEntry[]> {\n const exclusiveByStyle = new Map<string, ExclusiveStyleEntry[]>();\n\n for (const styleName of lookupStyles) {\n const value = styleMap[styleName];\n if (value === undefined) continue;\n\n if (isValueMapping(value)) {\n // Stage 0: Eliminate redundant compound state dimensions before parsing.\n // E.g. { '': A, '@dark': B, '@hc': A, '@dark & @hc': B }\n // reduces to { '': A, '@dark': B } because @hc is irrelevant.\n const reduced = extractCompoundStates(\n value as Record<string, StyleValue>,\n );\n\n // Stage 1: Parse entries from value mapping.\n const parsed = parseStyleEntries(styleName, reduced, (stateKey) =>\n parseStateKey(stateKey, { context: parserContext }),\n );\n\n // Stage 1b: Merge same-value entries before exclusive expansion to\n // prevent combinatorial blowup (e.g. @dark and @dark & @high-contrast\n // mapping to the same color). Merges happen only when provably safe\n // with respect to intermediate-priority entries, so the authored\n // cascade is preserved.\n const merged = mergeEntriesByValue(parsed);\n\n // Stage 2a: Expand user OR conditions into exclusive branches\n // (`A | B | C` becomes `A`, `B & !A`, `C & !A & !B`).\n const expanded = expandOrConditions(merged);\n\n // Stage 2b: Build exclusive conditions across all entries.\n const exclusive = buildExclusiveConditions(expanded);\n\n // Stage 3: Expand De Morgan ORs from negation into at-rule-aware\n // exclusive branches. `!A | !B` → `!A`, `A & !B`. Each branch keeps\n // the correct at-rule context.\n const fullyExpanded = expandExclusiveOrs(exclusive);\n exclusiveByStyle.set(styleName, fullyExpanded);\n } else {\n // Simple value — single entry with TRUE condition.\n exclusiveByStyle.set(styleName, [\n {\n styleKey: styleName,\n stateKey: '',\n value,\n condition: trueCondition(),\n priority: 0,\n exclusiveCondition: trueCondition(),\n },\n ]);\n }\n }\n\n return exclusiveByStyle;\n}\n\n/**\n * Stage 5: invoke the handler for each state snapshot and translate its\n * return value into ComputedRule entries (one per declaration set, fanned\n * out across any `$` selector suffixes the handler returns).\n */\nfunction invokeHandler(\n handler: StyleHandler,\n stateSnapshots: ReturnType<typeof computeStateCombinations>,\n selectorSuffix: string,\n): ComputedRule[] {\n const computedRules: ComputedRule[] = [];\n\n for (const snapshot of stateSnapshots) {\n const result = handler(snapshot.values as StyleValueStateMap);\n if (!result) continue;\n\n // Handler may return single or array\n const results = Array.isArray(result) ? result : [result];\n\n for (const r of results) {\n if (!r || typeof r !== 'object') continue;\n\n const { $, ...styleProps } = r;\n const declarations: Record<string, string> = {};\n\n for (const [prop, val] of Object.entries(styleProps)) {\n // Regex first so the common case is one cheap test; isDevEnv() is called\n // lazily (not captured at module load) only once a bad key is seen, which\n // is both free in production and assertable in tests.\n if (RE_UPPER_CASE.test(prop) && !prop.startsWith('--') && isDevEnv()) {\n // Custom properties are case-sensitive, hence the `--` exemption. Not\n // auto-corrected: silently rewriting a name is worse than a warning,\n // and no type can catch a non-literal return.\n emitWarning(\n 'HANDLER_CAMEL_CASE_KEY',\n `A style handler returned \"${prop}\". CSS property names must be ` +\n `kebab-case (\"${toSnakeCase(prop)}\"). The declaration was ` +\n `emitted verbatim and the browser will ignore it.`,\n );\n }\n\n if (val != null && val !== '') {\n declarations[prop] = String(val);\n }\n }\n\n if (Object.keys(declarations).length === 0) continue;\n\n // Handle $ suffixes\n const suffixes = $\n ? (Array.isArray($) ? $ : [$]).map(\n (s) => selectorSuffix + normalizeSelectorSuffix(String(s)),\n )\n : [selectorSuffix];\n\n for (const suffix of suffixes) {\n computedRules.push({\n condition: snapshot.condition,\n declarations,\n selectorSuffix: suffix,\n order: snapshot.order,\n });\n }\n }\n }\n\n return computedRules;\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\nexport { isSelector } from '../utils/is-selector';\n\n/**\n * Result of processing a selector affix ($) pattern.\n *\n * @example\n * // Valid result with multiple selectors\n * { valid: true, selectors: ['> [data-element=\"Cell\"]', ' [data-element=\"Body\"] > [data-element=\"Cell\"]'] }\n *\n * // Invalid result with error message\n * { valid: false, reason: 'Selector affix \"+\" targets elements outside the root scope.' }\n */\ntype AffixResult =\n { valid: true; selectors: string[] } | { valid: false; reason: string };\n\n/**\n * Get all selector suffixes for a sub-element key.\n *\n * Handles three types of selector keys:\n * - `&` prefix: Raw selector suffix (e.g., `&:hover` → `:hover`)\n * - `.` prefix: Class selector (e.g., `.active` → ` .active`)\n * - Uppercase: Sub-element with optional `$` affix pattern\n *\n * @param key - The sub-element key (e.g., 'Label', '&:hover', '.active')\n * @param styles - The styles object, may contain `$` property for selector affix\n * @returns Array of selector suffixes, or null if invalid (with console warning)\n *\n * @example\n * getAllSelectors('Label', {})\n * // → [' [data-element=\"Label\"]']\n *\n * getAllSelectors('Cell', { $: '>, >Body>' })\n * // → ['> [data-element=\"Cell\"]', ' [data-element=\"Body\"] > [data-element=\"Cell\"]']\n */\nfunction getAllSelectors(key: string, styles?: Styles): string[] | null {\n if (key.startsWith('&')) {\n return [key.slice(1)];\n }\n\n if (key.startsWith('.')) {\n return [` ${key}`];\n }\n\n if (/^[A-Z]/.test(key)) {\n const affix = styles?.$;\n if (affix !== undefined) {\n const result = processAffix(String(affix), key);\n if (!result.valid) {\n emitWarning('INVALID_SELECTOR_AFFIX', result.reason);\n return null;\n }\n return result.selectors;\n }\n return [` [data-element=\"${key}\"]`];\n }\n\n return null;\n}\n\n/**\n * Process selector affix pattern and return selector(s)\n *\n * Supports:\n * - Direct child: '>'\n * - Chained elements: '>Body>Row>'\n * - HTML tags (no key injection): 'h1', '>ul>li', 'button:hover'\n * - Universal selector: '*', 'h1 *'\n * - Pseudo-elements on root: '::before'\n * - Pseudo on sub-element: '@::before', '>@:hover'\n * - Classes: '.active', '>@.active'\n * - Multiple selectors: '>, >Body>'\n * - Sibling combinators (after element): '>Item+', '>Item~'\n */\nfunction processAffix(affix: string, key: string): AffixResult {\n const trimmed = affix.trim();\n\n // Empty = default behavior (descendant selector with key)\n if (!trimmed) {\n return { valid: true, selectors: [` [data-element=\"${key}\"]`] };\n }\n\n // Split by comma for multiple selectors\n const patterns = trimmed.split(',').map((p) => p.trim());\n const selectors: string[] = [];\n\n for (const pattern of patterns) {\n const validation = validatePattern(pattern);\n if (!validation.valid) {\n return validation;\n }\n\n const selector = processSinglePattern(pattern, key);\n selectors.push(selector);\n }\n\n return { valid: true, selectors };\n}\n\n/**\n * Recognized token patterns for selector affix validation.\n *\n * These patterns are used to tokenize and validate `$` affix strings.\n * Order matters: more specific patterns must come first to avoid\n * partial matches (e.g., `::before` must match before `:` alone).\n *\n * Unrecognized tokens (like `#id`, `*`, or numbers) will cause validation to fail.\n */\nconst VALID_TOKEN_PATTERNS = [\n /^[>+~]/, // Combinators: >, +, ~\n /^\\*/, // Universal selector (*)\n /^[A-Z][a-zA-Z0-9]*/, // Uppercase element names → [data-element=\"...\"]\n /^@/, // @ placeholder for key injection position\n /^::?-?[a-z][a-z0-9-]*(?:\\([^)]*\\))?/, // Pseudo-elements/classes (:hover, ::before, :not(.x), ::-webkit-slider-thumb)\n /^\\.[a-zA-Z_-][a-zA-Z0-9_-]*/, // Class selectors (.active, .is-open)\n /^\\[[^\\]]+\\]/, // Attribute selectors ([type=\"text\"], [role])\n /^[a-z][a-z0-9-]*/, // HTML tag names (a, div, button, my-component)\n /^\\s+/, // Whitespace (ignored during parsing)\n /^&/, // Root reference (stripped, kept for backward compat)\n];\n\n/**\n * Scan a pattern for unrecognized tokens.\n *\n * Iterates through the pattern, consuming recognized tokens until\n * either the pattern is fully consumed (valid) or an unrecognized\n * character sequence is found (invalid).\n *\n * @param pattern - The selector pattern to validate\n * @returns The first unrecognized token found, or null if all tokens are valid\n *\n * @example\n * findUnrecognizedTokens('>Body>Row>') // → null (valid)\n * findUnrecognizedTokens('123') // → '123' (invalid)\n * findUnrecognizedTokens('#myId') // → '#' (invalid)\n */\nfunction findUnrecognizedTokens(pattern: string): string | null {\n let remaining = pattern;\n\n while (remaining.length > 0) {\n let matched = false;\n\n for (const regex of VALID_TOKEN_PATTERNS) {\n const match = remaining.match(regex);\n if (match) {\n remaining = remaining.slice(match[0].length);\n matched = true;\n break;\n }\n }\n\n if (!matched) {\n // Found unrecognized content - extract the problematic part\n const unrecognized = remaining.match(/^[^\\s>+~@.:[\\]A-Z]+/);\n return unrecognized ? unrecognized[0] : remaining[0];\n }\n }\n\n return null;\n}\n\n/**\n * Validate a selector pattern for structural correctness.\n *\n * Checks for:\n * 1. Out-of-scope selectors: Patterns starting with `+` or `~` target siblings\n * of the root element, which is outside the component's DOM scope.\n * 2. Consecutive combinators: Patterns like `>>` or `>+` are malformed CSS.\n * 3. Unrecognized tokens: Characters/sequences not matching valid CSS selectors.\n *\n * @param pattern - A single selector pattern (already split by comma)\n * @returns AffixResult indicating validity and error reason if invalid\n *\n * @example\n * validatePattern('>Body>Row>') // → { valid: true, selectors: [] }\n * validatePattern('+') // → { valid: false, reason: '...outside root scope...' }\n * validatePattern('>>') // → { valid: false, reason: '...consecutive combinators...' }\n */\nfunction validatePattern(pattern: string): AffixResult {\n const trimmed = pattern.trim();\n\n // Patterns starting with + or ~ target siblings of the root element,\n // which is outside the component's scope. Valid sibling patterns must\n // be preceded by an element: \">Item+\", \">Item~\"\n if (/^[+~]/.test(trimmed)) {\n return {\n valid: false,\n reason:\n `Selector affix \"${pattern}\" targets elements outside the root scope. ` +\n `Sibling selectors (+, ~) must be preceded by an element inside the root. ` +\n `Use \">Element+\" or \">Element~\" instead.`,\n };\n }\n\n // Check for consecutive combinators\n if (/[>+~]{2,}/.test(trimmed.replace(/\\s+/g, ''))) {\n return {\n valid: false,\n reason: `Selector affix \"${pattern}\" contains consecutive combinators.`,\n };\n }\n\n // Check for unrecognized tokens (e.g., lowercase text like \"foo\")\n const unrecognized = findUnrecognizedTokens(trimmed);\n if (unrecognized) {\n return {\n valid: false,\n reason:\n `Selector affix \"${pattern}\" contains unrecognized token \"${unrecognized}\". ` +\n `Valid tokens: combinators (>, +, ~), element names (Uppercase), ` +\n `@ placeholder, pseudo (:hover, ::before), class (.name), attribute ([attr]).`,\n };\n }\n\n return { valid: true, selectors: [] };\n}\n\n/**\n * Process a single selector pattern into a CSS selector suffix.\n *\n * This is the main transformation function that converts a `$` affix pattern\n * into a valid CSS selector suffix. It handles:\n *\n * 1. `@` placeholder replacement with `[data-element=\"key\"]`\n * 2. Key injection based on pattern ending (see `shouldInjectKey`)\n * 3. Proper spacing for descendant vs direct child selectors\n *\n * @param pattern - A single validated selector pattern\n * @param key - The sub-element key to inject (e.g., 'Label', 'Cell')\n * @returns CSS selector suffix ready to append to the root selector\n *\n * @example\n * processSinglePattern('>', 'Row')\n * // → '> [data-element=\"Row\"]'\n *\n * processSinglePattern('>Body>Row>', 'Cell')\n * // → '> [data-element=\"Body\"] > [data-element=\"Row\"] > [data-element=\"Cell\"]'\n *\n * processSinglePattern('&::before', 'Before')\n * // → '::before' (& attaches pseudo directly to root, no key injection)\n *\n * processSinglePattern('>@:hover', 'Item')\n * // → '> [data-element=\"Item\"]:hover'\n */\nfunction processSinglePattern(pattern: string, key: string): string {\n // Explicit & means \"attach directly to root\" (no space prefix)\n const startsWithAmpersand = pattern.startsWith('&');\n const normalized = (startsWithAmpersand ? pattern.slice(1) : pattern).trim();\n\n if (!normalized) {\n return ` [data-element=\"${key}\"]`;\n }\n\n // Pseudo-elements/classes at start (used for @ placeholder branch only)\n const startsWithPseudo = /^::?[a-z]/.test(normalized);\n\n // Transform the pattern: convert element names and normalize spacing\n let result = transformPattern(normalized);\n\n // Handle @ placeholder: explicit key injection position\n if (result.includes('@')) {\n // Remove space between @ and following class/pseudo for proper attachment\n // e.g., \"@ .active\" → \"[el].active\", but \"@ > span\" → \"[el] > span\"\n result = result.replace(/@ (?=[.:])/g, '@');\n result = result.replace(/@/g, `[data-element=\"${key}\"]`);\n\n if (!startsWithPseudo && !result.startsWith(' ')) {\n result = ' ' + result;\n }\n return result;\n }\n\n // Auto-inject key based on pattern ending (see shouldInjectKey for rules)\n if (shouldInjectKey(normalized, key)) {\n result = result + ' ' + `[data-element=\"${key}\"]`;\n }\n\n // & prefix skips space so the suffix attaches directly to the root selector\n if (!startsWithAmpersand && !result.startsWith(' ')) {\n result = ' ' + result;\n }\n\n return result;\n}\n\n/**\n * Transform a selector pattern by converting element names and normalizing spacing.\n *\n * This is a character-by-character tokenizer that:\n * - Converts uppercase names to `[data-element=\"Name\"]` selectors\n * - Adds proper spacing around combinators (>, +, ~)\n * - Preserves lowercase tags, classes, pseudos, and attributes as-is\n * - Keeps @ placeholder for later replacement\n *\n * The tokenizer handles these token types in order:\n * 1. Whitespace (skipped)\n * 2. Combinators: >, +, ~ (add surrounding spaces)\n * 3. Universal selector: * (keep as-is with spacing)\n * 4. Uppercase names: Body, Row (convert to [data-element=\"...\"])\n * 5. @ placeholder (keep for later replacement)\n * 6. Pseudo: :hover, ::before (attach to previous token)\n * 7. Tags: a, div, button (keep as-is with spacing)\n * 8. Classes: .active (attach to previous element/tag/placeholder)\n * 9. Attributes: [type=\"text\"] (keep as-is)\n *\n * @param pattern - The raw selector pattern to transform\n * @returns Transformed pattern with proper CSS selector syntax\n *\n * @example\n * transformPattern('>Body>Row>')\n * // → '> [data-element=\"Body\"] > [data-element=\"Row\"] >'\n *\n * transformPattern('button.primary:hover')\n * // → 'button.primary:hover'\n */\nfunction transformPattern(pattern: string): string {\n let result = '';\n let lastCh = '';\n let i = 0;\n\n while (i < pattern.length) {\n const char = pattern[i];\n\n if (/\\s/.test(char)) {\n i++;\n continue;\n }\n\n if (/[>+~]/.test(char)) {\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n result += char;\n lastCh = char;\n i++;\n continue;\n }\n\n if (char === '*') {\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n result += '*';\n lastCh = '*';\n i++;\n continue;\n }\n\n if (/[A-Z]/.test(char)) {\n const nameStart = i;\n while (i < pattern.length && /[a-zA-Z0-9]/.test(pattern[i])) {\n i++;\n }\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n const segment = `[data-element=\"${pattern.slice(nameStart, i)}\"]`;\n result += segment;\n lastCh = ']';\n continue;\n }\n\n if (char === '@') {\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n result += '@';\n lastCh = '@';\n i++;\n continue;\n }\n\n if (char === ':') {\n const pseudoStart = i;\n while (\n i < pattern.length &&\n !/[\\s>+~,@]/.test(pattern[i]) &&\n !/[A-Z]/.test(pattern[i])\n ) {\n i++;\n }\n const segment = pattern.slice(pseudoStart, i);\n result += segment;\n lastCh = segment[segment.length - 1] || lastCh;\n continue;\n }\n\n if (/[a-z]/.test(char)) {\n const tagStart = i;\n while (i < pattern.length && /[a-z0-9-]/.test(pattern[i])) {\n i++;\n }\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n const segment = pattern.slice(tagStart, i);\n result += segment;\n lastCh = segment[segment.length - 1] || lastCh;\n continue;\n }\n\n if (char === '.') {\n const attachToLast =\n lastCh === ']' || lastCh === '@' || /[a-zA-Z0-9-]/.test(lastCh);\n if (result && !attachToLast && lastCh !== ' ') {\n result += ' ';\n }\n const clsStart = i;\n i++;\n while (i < pattern.length && /[a-zA-Z0-9_-]/.test(pattern[i])) {\n i++;\n }\n const segment = pattern.slice(clsStart, i);\n result += segment;\n lastCh = segment[segment.length - 1] || lastCh;\n continue;\n }\n\n if (char === '[') {\n const attachToLast =\n lastCh === ']' || lastCh === '@' || /[a-zA-Z0-9-]/.test(lastCh);\n if (result && !attachToLast && lastCh !== ' ') {\n result += ' ';\n }\n const attrStart = i;\n let depth = 0;\n while (i < pattern.length) {\n if (pattern[i] === '[') depth++;\n if (pattern[i] === ']') depth--;\n i++;\n if (depth === 0) break;\n }\n result += pattern.slice(attrStart, i);\n lastCh = ']';\n continue;\n }\n\n result += char;\n lastCh = char;\n i++;\n }\n\n return result;\n}\n\n/**\n * Determine if the sub-element key should be auto-injected based on pattern ending.\n *\n * Key injection rules (when no @ placeholder is present):\n *\n * | Pattern Ending | Inject Key? | Example | Result |\n * |----------------|-------------|---------|--------|\n * | Combinator (>, +, ~) | Yes | `'>Body>'` | `> [data-element=\"Body\"] > [el]` |\n * | Uppercase element | Yes | `'>Body>Row'` | `> [el1] > [el2] [key]` |\n * | Lowercase tag | No | `'h1'` | ` h1` |\n * | Universal (*) | No | `'h1 *'` | ` h1 *` |\n * | Pseudo (:hover, ::before) | No | `'::before'` | `::before` |\n * | Class (.active) | No | `'.active'` | `.active` |\n * | Attribute ([type]) | No | `'[type=\"text\"]'` | `[type=\"text\"]` |\n *\n * @param pattern - The normalized pattern (after stripping &)\n * @param key - The sub-element key being styled. If the trailing element name\n * equals this key, it acts as an explicit placeholder for the key\n * (same role as `@`) and no auto-injection happens.\n * @returns true if key should be injected, false otherwise\n *\n * @example\n * shouldInjectKey('>', 'Key') // → true (trailing combinator)\n * shouldInjectKey('>Body>Row', 'Key') // → true (ends with different element)\n * shouldInjectKey('>Body>Key', 'Key') // → false (trailing name === key)\n * shouldInjectKey('Key', 'Key') // → false (sole element === key)\n * shouldInjectKey('h1', 'Key') // → false (ends with tag)\n * shouldInjectKey('*', 'Key') // → false (universal selector)\n * shouldInjectKey('::before', 'Key') // → false (ends with pseudo)\n * shouldInjectKey('.active', 'Key') // → false (ends with class)\n * shouldInjectKey('a:hover', 'Key') // → false (ends with pseudo)\n * shouldInjectKey('button.primary', 'Key') // → false (ends with class)\n */\nfunction shouldInjectKey(pattern: string, key: string): boolean {\n const trimmed = pattern.trim();\n\n // Rule 1: Ends with combinator → inject key after it\n // e.g., '>' → '> [data-element=\"Key\"]'\n if (/[>+~]$/.test(trimmed)) {\n return true;\n }\n\n // Rule 2: Ends with uppercase element name. The lookbehind ensures we're\n // matching a standalone element name, not part of a class like .myClass.\n // If that trailing name is the sub-element's own key, it already represents\n // the target element (acts like the `@` placeholder) — no re-injection.\n // Otherwise inject the key as a descendant of the trailing element.\n // e.g., '>Body' (key=Cell) → '> [data-element=\"Body\"] [data-element=\"Cell\"]'\n // '>Body>Cell' (key=Cell) → '> [data-element=\"Body\"] > [data-element=\"Cell\"]'\n const trailingElement = trimmed.match(/(?:^|[\\s>+~\\]:])([A-Z][a-zA-Z0-9]*)$/);\n if (trailingElement) {\n return trailingElement[1] !== key;\n }\n\n // Otherwise (tags, universal *, pseudo, class, attribute) → no injection\n // The pattern is complete as-is, applying to root or a specific selector\n return false;\n}\n\n/**\n * Normalize selector suffix from $ property\n */\nfunction normalizeSelectorSuffix(suffix: string): string {\n if (!suffix) return '';\n return suffix.startsWith('&') ? suffix.slice(1) : suffix;\n}\n\n/**\n * Build handler queue from style keys\n */\nfunction buildHandlerQueue(\n styleKeys: string[],\n styles: Styles,\n): { handler: StyleHandler; styleMap: StyleMap; hasStateMap: boolean }[] {\n const queue: {\n handler: StyleHandler;\n styleMap: StyleMap;\n hasStateMap: boolean;\n }[] = [];\n const seenHandlers = new Set<StyleHandler>();\n\n for (const styleName of styleKeys) {\n let handlers: StyleHandler[] = STYLE_HANDLER_MAP[styleName];\n\n if (!handlers) {\n handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];\n }\n\n for (const handler of handlers) {\n if (seenHandlers.has(handler)) continue;\n seenHandlers.add(handler);\n\n const lookupStyles = handler.__lookupStyles;\n const styleMap: StyleMap = {};\n let hasStateMap = false;\n\n for (const name of lookupStyles) {\n const val = styles[name];\n if (val !== undefined) {\n styleMap[name] = val as StyleValue | StyleValueStateMap;\n hasStateMap ||= isValueMapping(\n val as StyleValue | Record<string, StyleValue>,\n );\n }\n }\n\n queue.push({ handler, styleMap, hasStateMap });\n }\n }\n\n return queue;\n}\n\n/**\n * Compute all valid state combinations for a handler's lookup styles\n */\nfunction computeStateCombinations(\n exclusiveByStyle: Map<string, ExclusiveStyleEntry[]>,\n lookupStyles: string[],\n): {\n condition: ConditionNode;\n values: Record<string, StyleValue>;\n order: number;\n}[] {\n // Get entries for each style\n const entriesPerStyle = lookupStyles.map(\n (style) => exclusiveByStyle.get(style) || [],\n );\n\n // Cartesian product of all combinations\n const combinations = cartesianProduct(entriesPerStyle);\n\n // Build snapshots, simplifying and filtering impossible combinations\n const snapshots: {\n condition: ConditionNode;\n values: Record<string, StyleValue>;\n order: number;\n }[] = [];\n\n for (const combo of combinations) {\n // Combine all exclusive conditions with AND\n const conditions = combo.map((e) => e.exclusiveCondition);\n const combined = and(...conditions);\n const simplified = simplifyCondition(combined);\n\n // Skip impossible combinations\n if (simplified.kind === 'false') continue;\n\n // Build values map\n const values: Record<string, StyleValue> = {};\n // Cascade order = highest source priority among the contributing entries.\n let order = 0;\n for (const entry of combo) {\n values[entry.styleKey] = entry.value;\n if (entry.priority > order) order = entry.priority;\n }\n\n snapshots.push({\n condition: simplified,\n values,\n order,\n });\n }\n\n return snapshots;\n}\n\n/**\n * Cartesian product of arrays\n */\nfunction cartesianProduct<T>(arrays: T[][]): T[][] {\n let result: T[][] = [[]];\n for (const arr of arrays) {\n if (arr.length === 0) continue;\n\n const next: T[][] = [];\n for (const combo of result) {\n for (const item of arr) {\n const newCombo = new Array<T>(combo.length + 1);\n for (let i = 0; i < combo.length; i++) newCombo[i] = combo[i];\n newCombo[combo.length] = item;\n next.push(newCombo);\n }\n }\n result = next;\n }\n return result;\n}\n\nconst declStringCache = new WeakMap<Record<string, string>, string>();\n\nfunction stringifyDeclarations(decl: Record<string, string>): string {\n let cached = declStringCache.get(decl);\n if (cached === undefined) {\n cached = JSON.stringify(decl);\n declStringCache.set(decl, cached);\n }\n return cached;\n}\n\n/**\n * Merge rules with identical CSS output\n */\nfunction mergeByValue(rules: ComputedRule[]): ComputedRule[] {\n if (rules.length <= 1) return rules;\n\n const groups = new Map<string, ComputedRule[]>();\n\n for (const rule of rules) {\n const key = `${rule.selectorSuffix}|${stringifyDeclarations(rule.declarations)}`;\n const group = groups.get(key);\n if (group) group.push(rule);\n else groups.set(key, [rule]);\n }\n\n // Merge conditions with OR for each group\n const merged: ComputedRule[] = [];\n\n for (const [, groupRules] of groups) {\n if (groupRules.length === 1) {\n merged.push(groupRules[0]);\n } else {\n // Merge conditions with OR\n const mergedCondition = simplifyCondition(\n or(...groupRules.map((r) => r.condition)),\n );\n // Take the lowest order so a merged group carrying a fallback's value\n // keeps the fallback's early cascade position.\n let order = groupRules[0].order;\n for (const r of groupRules) if (r.order < order) order = r.order;\n merged.push({\n condition: mergedCondition,\n declarations: groupRules[0].declarations,\n selectorSuffix: groupRules[0].selectorSuffix,\n order,\n });\n }\n }\n\n return merged;\n}\n\n/**\n * Build selector fragment from a variant (without className prefix)\n */\nfunction buildSelectorFromVariant(\n variant: SelectorVariant,\n selectorSuffix: string,\n): string {\n let selector = '';\n\n // Root-element state segment: flat modifiers/pseudos + :is()/:not()\n // groups, all attaching to the root element. Combine into a single\n // `:where(...)` so the whole segment carries zero specificity (the\n // doubled class is the only anchor). See `wrapWhere`.\n let rootSegment = branchToCSS([\n ...variant.modifierConditions,\n ...variant.pseudoConditions,\n ]);\n for (const group of variant.selectorGroups) {\n rootSegment += selectorGroupToCSS(group);\n }\n selector += wrapWhere(rootSegment);\n\n // Add parent selectors (before sub-element suffix). parentGroupsToCSS\n // already wraps each group in :where() so ancestor state adds no\n // specificity.\n if (variant.parentGroups.length > 0) {\n selector += parentGroupsToCSS(variant.parentGroups);\n }\n\n selector += selectorSuffix;\n\n // Sub-element (own) state segment: wrapped in its own separate\n // `:where(...)` so the sub-element's own structural specificity\n // ([data-element=\"X\"]) is preserved while its states are zeroed.\n const ownOptimized = optimizeGroups(variant.ownGroups);\n let ownSegment = '';\n for (const group of ownOptimized) {\n ownSegment += selectorGroupToCSS(group);\n }\n selector += wrapWhere(ownSegment);\n\n return selector;\n}\n\n/**\n * Materialize a computed rule to final CSS format\n *\n * Returns an array because OR conditions may generate multiple CSS rules\n * (when different branches have different at-rules)\n */\nfunction materializeComputedRule(rule: ComputedRule): CSSRule[] {\n const components = conditionToCSS(rule.condition);\n\n if (components.isImpossible || components.variants.length === 0) {\n return [];\n }\n\n const declarations = Object.entries(rule.declarations)\n .map(([prop, value]) => `${prop}: ${value};`)\n .join(' ');\n\n // Group variants by their at-rules + startingStyle (variants with same context can be combined with commas)\n const byAtRules = new Map<\n string,\n {\n variants: SelectorVariant[];\n atRules: string[];\n rootPrefix?: string;\n startingStyle?: boolean;\n }\n >();\n\n for (const variant of components.variants) {\n const atRules = buildAtRulesFromVariant(variant);\n const startingStyle = variant.startingStyle;\n const rootPrefix = rootGroupsToCSS(variant.rootGroups);\n const key =\n atRules.sort().join('|||') +\n '###' +\n (rootPrefix || '') +\n '###' +\n (startingStyle ? '1' : '0');\n\n const group = byAtRules.get(key);\n if (group) {\n group.variants.push(variant);\n } else {\n byAtRules.set(key, {\n variants: [variant],\n atRules,\n rootPrefix,\n startingStyle: startingStyle || undefined,\n });\n }\n }\n\n // Generate one CSSRule per at-rules group\n const rules: CSSRule[] = [];\n for (const [, group] of byAtRules) {\n // Merge variants that differ only in flat modifier/pseudo conditions\n // into :is() groups before building selector strings\n const mergedVariants = mergeVariantsIntoSelectorGroups(group.variants);\n\n // Build selector fragments for each variant (will be joined with className later)\n const selectorFragments = mergedVariants.map((v) =>\n buildSelectorFromVariant(v, rule.selectorSuffix),\n );\n\n // Store as array if multiple, string if single\n const selector =\n selectorFragments.length === 1 ? selectorFragments[0] : selectorFragments;\n\n const cssRule: CSSRule = {\n selector,\n declarations,\n order: rule.order,\n };\n\n if (group.atRules.length > 0) {\n cssRule.atRules = group.atRules;\n }\n\n if (group.rootPrefix) {\n cssRule.rootPrefix = group.rootPrefix;\n }\n\n if (group.startingStyle) {\n cssRule.startingStyle = true;\n }\n\n rules.push(cssRule);\n }\n\n return rules;\n}\n\n// ============================================================================\n// StyleResult merging (group by selector + at-rules)\n// ============================================================================\n\n/**\n * Merge StyleResult entries that share the same selector and at-rules,\n * concatenating their declarations into a single rule.\n *\n * This reduces CSS output size when many style keys (e.g. design tokens)\n * resolve to the same selector/state combination.\n */\nfunction mergeStyleResults(results: StyleResult[]): StyleResult[] {\n if (results.length <= 1) return results;\n\n const groups = new Map<string, StyleResult>();\n\n for (const result of results) {\n const atKey = result.atRules?.join('|') ?? '';\n const key = `${atKey}||${result.selector}||${result.startingStyle ? '1' : '0'}`;\n\n const existing = groups.get(key);\n if (existing) {\n existing.declarations = existing.declarations\n ? `${existing.declarations} ${result.declarations}`\n : result.declarations;\n } else {\n groups.set(key, { ...result });\n }\n }\n\n return Array.from(groups.values());\n}\n\n// ============================================================================\n// Public API: renderStyles (compatible with old API)\n// ============================================================================\n\n/**\n * Options for renderStyles when using direct selector mode.\n */\ninterface RenderStylesOptions {\n /**\n * Whether to double the class selector for increased specificity.\n * When true, `.myClass` becomes `.myClass.myClass` for higher specificity.\n *\n * @default false - User-provided selectors are not doubled.\n *\n * Note: This only applies when a classNameOrSelector is provided.\n * When renderStyles returns RenderResult with needsClassName=true,\n * the injector handles doubling automatically.\n */\n doubleSelector?: boolean;\n}\n\n/**\n * Render styles to CSS rules.\n *\n * When called without classNameOrSelector, returns RenderResult with needsClassName=true.\n * When called with a selector/className string, returns StyleResult[] for direct injection.\n */\nexport function renderStyles(\n styles?: Styles,\n classNameOrSelector?: undefined,\n options?: undefined,\n pipelineCacheKey?: string,\n): RenderResult;\nexport function renderStyles(\n styles: Styles | undefined,\n classNameOrSelector: string,\n options?: RenderStylesOptions,\n): StyleResult[];\nexport function renderStyles(\n styles?: Styles,\n classNameOrSelector?: string,\n options?: RenderStylesOptions,\n pipelineCacheKey?: string,\n): RenderResult | StyleResult[] {\n // Check if we have a direct selector/className\n const directSelector = !!classNameOrSelector;\n\n // Check cache first when a pre-computed key is available.\n // This allows callers to skip building the styles object on cache hit.\n let rules: CSSRule[] | undefined;\n if (pipelineCacheKey) {\n rules = pipelineCache.get(pipelineCacheKey);\n }\n\n if (!rules && !styles) {\n return directSelector ? [] : { rules: [] };\n }\n\n // Use pre-computed cache key when available (from chunk path),\n // falling back to stringifyStyles for direct renderStyles() calls\n const cacheKey = pipelineCacheKey || stringifyStyles(styles!);\n if (!rules) {\n rules = pipelineCache.get(cacheKey);\n }\n\n if (!rules) {\n // styles is guaranteed non-null here: early return above handles (!rules && !styles)\n const parserContext = createStateParserContext(styles!);\n rules = runPipeline(styles!, parserContext);\n pipelineCache.set(cacheKey, rules);\n }\n\n // Direct selector/className mode: return StyleResult[] directly\n if (directSelector) {\n const shouldDouble = options?.doubleSelector ?? false;\n\n const results = rules.map((rule): StyleResult => {\n // Handle selector as array (OR conditions) or string\n const selectorParts = Array.isArray(rule.selector)\n ? rule.selector\n : rule.selector\n ? [rule.selector]\n : [''];\n\n const finalSelector = selectorParts\n .map((part) => {\n let sel = part\n ? `${classNameOrSelector}${part}`\n : classNameOrSelector;\n\n // Double class selector for increased specificity if requested\n // This is used when the caller explicitly wants higher specificity\n if (shouldDouble && sel.startsWith('.')) {\n const classMatch = sel.match(/^\\.[a-zA-Z_-][a-zA-Z0-9_-]*/);\n if (classMatch) {\n const baseClass = classMatch[0];\n sel = baseClass + sel;\n }\n }\n\n // Handle root prefix for this selector\n if (rule.rootPrefix) {\n sel = `${rule.rootPrefix} ${sel}`;\n }\n\n return sel;\n })\n .join(', ');\n\n const result: StyleResult = {\n selector: finalSelector,\n declarations: rule.declarations,\n };\n\n if (rule.atRules && rule.atRules.length > 0) {\n result.atRules = rule.atRules;\n }\n\n if (rule.startingStyle) {\n result.startingStyle = true;\n }\n\n return result;\n });\n\n return mergeStyleResults(results);\n }\n\n // No className mode: return RenderResult with needsClassName flag\n // Normalize selector to string (join array with placeholder that injector will handle)\n return {\n rules: rules.map((r): StyleResult => ({\n selector: Array.isArray(r.selector) ? r.selector.join('|||') : r.selector,\n declarations: r.declarations,\n atRules: r.atRules,\n needsClassName: true,\n rootPrefix: r.rootPrefix,\n startingStyle: r.startingStyle,\n })),\n };\n}\n\nexport type { ConditionNode } from './conditions';\nexport { parseStateKey } from './parseStateKey';\n","import {\n LOGICAL_BORDER_STYLES,\n LOGICAL_INSET_STYLES,\n LOGICAL_MARGIN_STYLES,\n LOGICAL_PADDING_STYLES,\n LOGICAL_SCROLL_MARGIN_STYLES,\n LOGICAL_SCROLL_PADDING_STYLES,\n LOGICAL_SIZE_STYLES,\n} from './logical-list';\n\nexport const BASE_STYLES = [\n 'display',\n 'font',\n 'preset',\n 'hide',\n 'whiteSpace',\n 'opacity',\n 'transition',\n] as const;\n\nexport const POSITION_STYLES = [\n 'gridArea',\n 'order',\n 'gridColumn',\n 'gridRow',\n 'placeSelf',\n 'alignSelf',\n 'justifySelf',\n 'zIndex',\n 'margin',\n ...LOGICAL_MARGIN_STYLES,\n 'inset',\n ...LOGICAL_INSET_STYLES,\n 'position',\n 'scrollMargin',\n ...LOGICAL_SCROLL_MARGIN_STYLES,\n 'scrollPadding',\n ...LOGICAL_SCROLL_PADDING_STYLES,\n] as const;\n\nexport const BLOCK_INNER_STYLES = [\n 'padding',\n ...LOGICAL_PADDING_STYLES,\n 'overflow',\n 'scrollbar',\n 'textAlign',\n] as const;\n\nexport const BLOCK_OUTER_STYLES = [\n 'border',\n ...LOGICAL_BORDER_STYLES,\n 'radius',\n 'shadow',\n 'outline',\n] as const;\n\nexport const BLOCK_STYLES = [\n ...BLOCK_INNER_STYLES,\n ...BLOCK_OUTER_STYLES,\n] as const;\n\nexport const COLOR_STYLES = ['color', 'fill', 'fade', 'image'] as const;\n\nexport const TEXT_STYLES = [\n 'textTransform',\n 'fontWeight',\n 'fontStyle',\n] as const;\n\nexport const DIMENSION_STYLES = [\n 'width',\n 'height',\n ...LOGICAL_SIZE_STYLES,\n 'flexBasis',\n 'flexGrow',\n 'flexShrink',\n 'flex',\n] as const;\n\nexport const FLOW_STYLES = [\n 'flow',\n 'place',\n 'placeItems',\n 'placeContent',\n 'alignItems',\n 'alignContent',\n 'justifyItems',\n 'justifyContent',\n 'align',\n 'justify',\n 'gap',\n 'columnGap',\n 'rowGap',\n 'gridColumns',\n 'gridRows',\n 'gridTemplate',\n 'gridAreas',\n] as const;\n\nexport const CONTAINER_STYLES = [\n ...BASE_STYLES,\n ...COLOR_STYLES,\n ...DIMENSION_STYLES,\n ...POSITION_STYLES,\n ...BLOCK_STYLES,\n ...FLOW_STYLES,\n] as const;\n\nexport const OUTER_STYLES = [\n ...POSITION_STYLES,\n ...DIMENSION_STYLES,\n ...BLOCK_OUTER_STYLES,\n] as const;\n\nexport const INNER_STYLES = [\n ...BASE_STYLES,\n ...COLOR_STYLES,\n ...BLOCK_INNER_STYLES,\n ...FLOW_STYLES,\n] as const;\n","/**\n * Registry for style properties promoted to base props on every tasty component.\n *\n * `BASE_STYLES` stays a frozen `as const` — a dozen type helpers in `src/types.ts`\n * are derived from it — so `configure({ baseStyleProps })` records the additions\n * here instead. A version counter lets each `tasty()` factory memoize its prop\n * list and refresh only when the registry changes: factories are created at module\n * eval, which can run *before* `configure()`, and `resetConfig()` (plus the\n * zero-runtime Babel worker) reopens configuration, so a one-shot lazy init would\n * go stale.\n */\n\nimport { isDevEnv } from '../utils/is-dev-env';\n\nimport { BASE_STYLES } from './list';\n\n/** Props consumed by `tasty()` itself, which a style name must never shadow. */\nconst RESERVED_PROP_NAMES = new Set<string>([\n 'as',\n 'styles',\n 'variant',\n 'mods',\n 'element',\n 'qa',\n 'qaVal',\n 'className',\n 'tokens',\n 'style',\n 'theme',\n 'children',\n 'ref',\n 'key',\n]);\n\nconst VALID_NAME = /^[a-z][a-zA-Z0-9]*$/;\n\ninterface BaseStylePropsRegistry {\n /** Style names added on top of BASE_STYLES. */\n list: readonly string[];\n /** Bumped on every change; factories compare against it to refresh their memo. */\n version: number;\n}\n\nconst GTKEY = '__tasty_base_style_props__';\n\nconst globalStore = globalThis as unknown as Record<string, unknown>;\n\nexport const baseStylePropsRegistry: BaseStylePropsRegistry =\n (globalStore[GTKEY] as BaseStylePropsRegistry | undefined) ??\n ((globalStore[GTKEY] = { list: [], version: 0 }) as BaseStylePropsRegistry);\n\n/**\n * Expose style properties as top-level props on every tasty component, in\n * addition to `BASE_STYLES`.\n *\n * Each name costs one property check per render of every component, forever, so\n * keep the list short. The effect is app-global and cannot be scoped to a subtree;\n * use a factory's own `styleProps` for anything narrower.\n */\nexport function registerBaseStyleProps(names: readonly string[]): void {\n const added: string[] = [];\n\n for (const name of names) {\n if (isDevEnv()) {\n if (!VALID_NAME.test(name)) {\n console.warn(\n `[Tasty] baseStyleProps entry \"${name}\" is invalid. Names must start ` +\n `with a lowercase letter and contain only letters and digits ` +\n `(capitalised names are sub-element selectors, and \"@\", \"$\", \"#\", ` +\n `\".\", \"&\", \"_\" prefixes are reserved).`,\n );\n continue;\n }\n\n if (RESERVED_PROP_NAMES.has(name)) {\n console.warn(\n `[Tasty] baseStyleProps entry \"${name}\" collides with a prop tasty() ` +\n `consumes itself and was ignored.`,\n );\n continue;\n }\n } else if (!VALID_NAME.test(name) || RESERVED_PROP_NAMES.has(name)) {\n continue;\n }\n\n if (\n (BASE_STYLES as readonly string[]).includes(name) ||\n baseStylePropsRegistry.list.includes(name) ||\n added.includes(name)\n ) {\n continue;\n }\n\n added.push(name);\n }\n\n if (added.length === 0) return;\n\n baseStylePropsRegistry.list = baseStylePropsRegistry.list.concat(added);\n baseStylePropsRegistry.version++;\n}\n\n/** Style names promoted via `configure({ baseStyleProps })`. */\nexport function getBaseStyleProps(): readonly string[] {\n return baseStylePropsRegistry.list;\n}\n\n/** Drop promoted base style props. Called by `resetConfig()`. */\nexport function resetBaseStyleProps(): void {\n if (baseStylePropsRegistry.list.length === 0) return;\n\n baseStylePropsRegistry.list = [];\n // Must bump on reset too, or factory memos keep the stale list.\n baseStylePropsRegistry.version++;\n}\n","/**\n * Style chunk definitions for CSS chunking optimization.\n *\n * Styles are grouped into chunks based on:\n * 1. Handler dependencies - styles that share a handler MUST be in the same chunk\n * 2. Logical grouping - related styles grouped for better cache reuse\n *\n * See STYLE_CHUNKING_SPEC.md for detailed rationale.\n *\n * ============================================================================\n * ⚠️ CRITICAL ARCHITECTURAL CONSTRAINT: NO CROSS-CHUNK HANDLER DEPENDENCIES\n * ============================================================================\n *\n * Style handlers declare their dependencies via `__lookupStyles` array.\n * This creates a dependency graph where handlers read multiple style props.\n *\n * **ALL styles in a handler's `__lookupStyles` MUST be in the SAME chunk.**\n *\n * Why this matters:\n * 1. Each chunk computes a cache key from ONLY its own style values\n * 2. If a handler reads a style from another chunk, that value isn't in the cache key\n * 3. Changing the cross-chunk style won't invalidate this chunk's cache\n * 4. Result: stale CSS output or incorrect cache hits\n *\n * Example of a violation:\n * ```\n * // flowStyle.__lookupStyles = ['display', 'flow']\n * // If 'display' is in DISPLAY chunk and 'flow' is in LAYOUT chunk:\n * // - User sets { display: 'grid', flow: 'column' }\n * // - LAYOUT chunk caches CSS with flow=column, display=grid\n * // - User changes to { display: 'flex', flow: 'column' }\n * // - LAYOUT chunk cache key unchanged (only has 'flow')\n * // - Returns stale CSS computed with display=grid!\n * ```\n *\n * Before adding/moving styles, verify:\n * 1. Find all handlers that use this style (grep for the style name in __lookupStyles)\n * 2. Ensure ALL styles from each handler's __lookupStyles are in the same chunk\n *\n * For **custom** handlers registered through `configure({ handlers })` this is no\n * longer only a convention: `alignHandlerChunks()` in `styles/predefined.ts` pulls\n * any style name the lists below don't know into its handler's existing chunk, and\n * warns when a handler bridges two chunks defined here. The lists below are still\n * hand-maintained, so the constraint must be checked by hand when editing them.\n * ============================================================================\n */\n\nimport { isSelector } from '../utils/is-selector';\n\nimport { CHUNK_NAMES, STYLE_TO_CHUNK } from './style-chunk-map';\nimport type { ChunkName } from './style-chunk-map';\n\n// ============================================================================\n// Chunk Style Lists\n// ============================================================================\n\n// The chunk style lists and the style→chunk map live in `style-chunk-map.ts` so\n// that the map is populated by importing *that* module, independent of whether\n// this one has been loaded. Re-exported here for the original import paths.\nexport {\n APPEARANCE_CHUNK_STYLES,\n DIMENSION_CHUNK_STYLES,\n DISPLAY_CHUNK_STYLES,\n FONT_CHUNK_STYLES,\n LAYOUT_CHUNK_STYLES,\n POSITION_CHUNK_STYLES,\n} from './style-chunk-map';\nexport { CHUNK_NAMES, STYLE_TO_CHUNK } from './style-chunk-map';\nexport type { ChunkName } from './style-chunk-map';\n\n// ============================================================================\n// Chunk Priority Order\n// ============================================================================\n\n/**\n * Chunk processing order. This ensures deterministic className allocation\n * regardless of style key order in the input.\n */\nconst CHUNK_ORDER: readonly string[] = [\n CHUNK_NAMES.APPEARANCE,\n CHUNK_NAMES.FONT,\n CHUNK_NAMES.DIMENSION,\n CHUNK_NAMES.DISPLAY,\n CHUNK_NAMES.LAYOUT,\n CHUNK_NAMES.POSITION,\n CHUNK_NAMES.MISC,\n CHUNK_NAMES.SUBCOMPONENTS,\n] as const;\n\n// ============================================================================\n// Chunk Info Interface\n// ============================================================================\n\nexport interface ChunkInfo {\n /** Name of the chunk */\n name: ChunkName | string;\n /** Style keys belonging to this chunk */\n styleKeys: string[];\n}\n\n// ============================================================================\n// Style Categorization\n// ============================================================================\n\n/**\n * Categorize style keys into chunks.\n *\n * Returns chunks in a deterministic order (by CHUNK_ORDER) regardless\n * of the order of keys in the input styles object.\n *\n * @param styles - The styles object to categorize\n * @returns Map of chunk name to array of style keys in that chunk (in priority order)\n */\nexport function categorizeStyleKeys(\n styles: Record<string, unknown>,\n): Map<string, string[]> {\n // First pass: collect keys into chunks (unordered)\n const chunkData: Record<string, string[]> = {};\n\n for (const key of Object.keys(styles)) {\n // Skip the $ helper key (used for selector combinators)\n // Skip @keyframes and @property (processed separately in useStyles)\n // Skip recipe (resolved before pipeline by resolveRecipes)\n if (\n key === '$' ||\n key === '@keyframes' ||\n key === '@property' ||\n key === '@font-face' ||\n key === '@counter-style' ||\n key === '@function' ||\n key === 'recipe'\n ) {\n continue;\n }\n\n // All selectors share their own chunk; unknown styles fall back to misc.\n const chunkName = isSelector(key)\n ? CHUNK_NAMES.SUBCOMPONENTS\n : (STYLE_TO_CHUNK.get(key) ?? CHUNK_NAMES.MISC);\n (chunkData[chunkName] ??= []).push(key);\n }\n\n // Second pass: build ordered Map based on CHUNK_ORDER\n const orderedChunks = new Map<string, string[]>();\n\n // Add chunks in priority order\n for (const chunkName of CHUNK_ORDER) {\n const styleKeys = chunkData[chunkName];\n if (styleKeys?.length) {\n // Sort keys within chunk for consistent cache key generation\n orderedChunks.set(chunkName, styleKeys.sort());\n }\n }\n\n // Handle any unknown chunks (shouldn't happen, but be defensive)\n for (const chunkName of Object.keys(chunkData)) {\n if (!orderedChunks.has(chunkName)) {\n orderedChunks.set(chunkName, chunkData[chunkName].sort());\n }\n }\n\n return orderedChunks;\n}\n","/**\n * Chunk-specific cache key generation.\n *\n * Generates cache keys that only include styles relevant to a specific chunk,\n * enabling more granular caching and reuse.\n *\n * Enhanced to support predefined states:\n * - Global predefined states don't affect cache keys (constant across app)\n * - Local predefined states only affect cache keys if referenced in the chunk\n */\n\nimport {\n extractLocalPredefinedStates,\n extractPredefinedStateRefs,\n} from '../states';\nimport type { Styles } from '../styles/types';\n\nconst _stableStringifyCache = new WeakMap<object, string>();\n\ninterface ChunkKeyEntry {\n /**\n * Flat `[key0, value0, key1, value1, …]` record of exactly what the key was\n * built from. Interleaving keeps an entry to one allocation.\n */\n snapshot: unknown[];\n key: string;\n}\n\n/**\n * Per-styles-object memo of generated keys, keyed by chunk name.\n *\n * Reading from this is free, so every call checks it. Writing to it is not:\n * the `WeakMap.set` plus the snapshot allocation measured ~35% of the cost of\n * generating a key from scratch, and it is pure waste for a styles object that\n * is never seen again. Callers therefore have to opt in via `reusable`, and\n * only for an object they know outlives the render that produced it.\n *\n * `Styles` is a plain mutable object, and nothing in the public\n * `computeStyles` / `useStyles` contract asks callers to freeze it, so a hit is\n * only returned after re-reading every value the key was built from and\n * confirming none of them changed. That check is deliberately shallow: it\n * compares the same references `stableStringify` would have looked up in\n * `_stableStringifyCache`, so a memoized key is stale in exactly the cases the\n * un-memoized function was already stale in — an object-valued style mutated\n * in place — and in no others.\n */\nconst _chunkKeyCache = new WeakMap<object, Map<string, ChunkKeyEntry>>();\n\n/**\n * Is `entry` still a valid key for this chunk of `styles`?\n *\n * True only when the chunk asks for the same style keys, in the same order,\n * and every one of them still reads back the value the key was built from.\n */\nfunction isEntryFresh(\n styles: Styles,\n entry: ChunkKeyEntry,\n styleKeys: string[],\n): boolean {\n const snapshot = entry.snapshot;\n const length = styleKeys.length;\n\n if (snapshot.length !== length * 2) return false;\n\n for (let i = 0, at = 0; i < length; i++, at += 2) {\n const key = styleKeys[i];\n if (snapshot[at] !== key || styles[key] !== snapshot[at + 1]) return false;\n }\n\n return true;\n}\n\n/**\n * Recursively serialize a value with sorted keys for stable output.\n * This ensures that {a: 1, b: 2} and {b: 2, a: 1} produce the same string.\n * Uses a WeakMap cache for object values to avoid re-serializing the same references.\n */\nfunction stableStringify(value: unknown): string {\n if (value === null || value === undefined) return String(value);\n if (typeof value !== 'object') {\n return JSON.stringify(value);\n }\n\n const cached = _stableStringifyCache.get(value as object);\n if (cached !== undefined) return cached;\n\n let result: string;\n if (Array.isArray(value)) {\n result = '[' + value.map(stableStringify).join(',') + ']';\n } else {\n const obj = value as Record<string, unknown>;\n result = '{';\n for (const key of Object.keys(obj).sort()) {\n if (obj[key] !== undefined) {\n if (result.length > 1) result += ',';\n result += `${JSON.stringify(key)}:${stableStringify(obj[key])}`;\n }\n }\n result += '}';\n }\n\n _stableStringifyCache.set(value as object, result);\n return result;\n}\n\n/**\n * Generate a cache key for a specific chunk.\n *\n * Only includes the styles that belong to this chunk, allowing\n * chunks to be cached independently.\n *\n * Also includes relevant local predefined states that are referenced\n * by this chunk's styles.\n *\n * @param styles - The full styles object\n * @param chunkName - Name of the chunk\n * @param styleKeys - Keys of styles belonging to this chunk\n * @param reusable - Pass `true` only when `styles` outlives this render and\n * will be keyed again — a `tasty()` factory's own styles object, for\n * instance. It stores the result so the next render can skip serializing\n * every value again, which is worth doing only if there is a next render for\n * this exact object. Freshly merged per-render objects must leave it `false`:\n * storing them costs more than the key they would never reuse. Reading an\n * existing entry does not require it.\n * @returns A stable cache key string\n */\nexport function generateChunkCacheKey(\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n reusable = false,\n): string {\n let perStyles = _chunkKeyCache.get(styles as object);\n\n if (perStyles !== undefined) {\n const entry = perStyles.get(chunkName);\n if (entry !== undefined && isEntryFresh(styles, entry, styleKeys)) {\n return entry.key;\n }\n }\n\n const length = styleKeys.length;\n const snapshot: unknown[] = new Array(length * 2);\n\n for (let i = 0, at = 0; i < length; i++, at += 2) {\n const styleKey = styleKeys[i];\n snapshot[at] = styleKey;\n snapshot[at + 1] = styles[styleKey];\n }\n\n // Serialize only after every top-level value is captured, preserving the\n // observable read order for accessor-backed style objects.\n let key = chunkName;\n let chunkStylesStr = '';\n\n for (let at = 0; at < snapshot.length; at += 2) {\n const value = snapshot[at + 1];\n if (value !== undefined) {\n const serialized = stableStringify(value);\n key += `\\0${snapshot[at] as string}:${serialized}`;\n chunkStylesStr += serialized;\n }\n }\n\n const localStates = extractLocalPredefinedStates(styles);\n\n if (Object.keys(localStates).length > 0) {\n const relevantLocalStates: string[] = [];\n\n for (const stateName of extractPredefinedStateRefs(chunkStylesStr)) {\n if (localStates[stateName]) {\n relevantLocalStates.push(`${stateName}=${localStates[stateName]}`);\n }\n }\n\n if (relevantLocalStates.length > 0) {\n relevantLocalStates.sort();\n key = `[states:${relevantLocalStates.join('|')}]\\0${key}`;\n }\n }\n\n if (reusable) {\n if (perStyles === undefined) {\n perStyles = new Map();\n _chunkKeyCache.set(styles as object, perStyles);\n }\n perStyles.set(chunkName, { snapshot, key });\n }\n\n return key;\n}\n","/**\n * Chunk-specific style rendering.\n *\n * Renders styles for a specific chunk by filtering the styles object\n * to only include relevant keys before passing to renderStyles.\n */\n\nimport type { RenderResult } from '../pipeline';\nimport { hasPipelineCacheEntry, renderStyles } from '../pipeline';\nimport { extractLocalPredefinedStates } from '../states';\nimport type { Styles } from '../styles/types';\n\nimport { CHUNK_NAMES } from './definitions';\n\n/**\n * Build a filtered styles object for a regular chunk.\n */\nfunction buildFilteredStyles(styles: Styles, styleKeys: string[]): Styles {\n const localPredefinedStates = extractLocalPredefinedStates(styles);\n const filteredStyles: Styles = {};\n\n for (const [key, value] of Object.entries(localPredefinedStates)) {\n filteredStyles[key] = value;\n }\n\n for (const key of styleKeys) {\n const value = styles[key];\n if (value !== undefined) {\n filteredStyles[key] = value;\n }\n }\n\n return filteredStyles;\n}\n\n/**\n * Build a filtered styles object for the subcomponents chunk.\n */\nfunction buildSubcomponentFilteredStyles(\n styles: Styles,\n selectorKeys: string[],\n): Styles {\n const localPredefinedStates = extractLocalPredefinedStates(styles);\n const filteredStyles: Styles = {};\n\n for (const [key, value] of Object.entries(localPredefinedStates)) {\n filteredStyles[key] = value;\n }\n\n for (const key of selectorKeys) {\n const value = styles[key];\n if (value !== undefined) {\n filteredStyles[key] = value;\n }\n }\n\n if (styles.$ !== undefined) {\n filteredStyles.$ = styles.$;\n }\n\n return filteredStyles;\n}\n\n/**\n * Render styles for a specific chunk.\n *\n * On pipeline cache hit, avoids building the filtered styles object entirely.\n * Only constructs it on cache miss when the pipeline actually needs the styles.\n *\n * IMPORTANT: Local predefined states (e.g., '@mobile': '@media(w < 600px)')\n * are always included in the filtered styles, regardless of which chunk is\n * being rendered. This ensures that state references like '@mobile' in any\n * chunk can be properly resolved by the pipeline.\n *\n * @param styles - The full styles object\n * @param chunkName - Name of the chunk being rendered\n * @param styleKeys - Keys of styles belonging to this chunk\n * @returns RenderResult with rules for this chunk\n */\nexport function renderStylesForChunk(\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n pipelineCacheKey?: string,\n): RenderResult {\n if (styleKeys.length === 0) {\n return { rules: [], className: '' };\n }\n\n // Fast path: skip building filteredStyles when pipeline has a cached result\n if (pipelineCacheKey && hasPipelineCacheEntry(pipelineCacheKey)) {\n return renderStyles(undefined, undefined, undefined, pipelineCacheKey);\n }\n\n // Cache miss: build filtered styles and run pipeline\n const filteredStyles =\n chunkName === CHUNK_NAMES.SUBCOMPONENTS\n ? buildSubcomponentFilteredStyles(styles, styleKeys)\n : buildFilteredStyles(styles, styleKeys);\n\n return renderStyles(filteredStyles, undefined, undefined, pipelineCacheKey);\n}\n"],"mappings":";;;AAMA,IAAI,kBAAkB;AACtB,IAAI,kBAAkD;AAEtD,MAAM,kBAAkB;AAExB,SAAgB,qBAA8B;CAC5C,OAAO;AACT;AAGA,SAAgB,2BAAoC;CAClD,IAAI,iBAAiB,OAAO;CAC5B,kBAAkB;CAClB,OAAO;AACT;AAEA,SAAgB,4BAAkC;CAChD,kBAAkB;AACpB;AAGA,SAAgB,6BAAsC;CACpD,MAAM,SAAU,WAAuC;CAEvD,QAAQ,mBAAmB,OAAA,EAAS,cAAc;AACpD;AAEA,SAAgB,wBAAwB,WAE/B;CACP,kBAAkB;EAAE,GAAI,mBAAmB,CAAC;EAAI,GAAG;CAAU;CAC7D,WAAwC,mBAAmB;AAC7D;AAEA,SAAgB,4BAAkC;CAChD,kBAAkB;CAClB,OAAQ,WAAuC;AACjD;;;ACQA,MAAM,iBAAiB,IAAI,IAAI;CAC7B;CACA;CACA;CACA;CACA;CACA;CACA;CAGA;AACF,CAAC;AAED,MAAM,gCAAgC;AAEtC,SAAS,oBAAoB,MAAuB;CAClD,OACE,SAAS,YACT,SAAS,WACT,SAAS,aACT,SAAS;AAEb;AAGA,IAAI,yBAAiD,CAAC;AAGtD,MAAM,kCAAkB,IAAI,IAAY;AAExC,MAAMA,YAAU,SAAS;AAKzB,SAAS,SAAS,KAAa,SAAuB;CACpD,IAAIA,aAAW,CAAC,gBAAgB,IAAI,GAAG,GAAG;EACxC,gBAAgB,IAAI,GAAG;EACvB,QAAQ,KAAK,OAAO;CACtB;AACF;AAKA,SAAgB,0BACd,QACM;CACN,IAAI,mBAAmB,GAAG;EACxB,MAAM,gBAAgB,OAAO,KAAK,MAA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AAa,qBAAqB;CAChC;CACA;CACA;AACF;AAGA,MAAa,sBAAsB,CAAC,aAAa,YAAY;AAG7D,MAAa,8BAA8B,CACzC,GAAG,mBACH,GAAG,kBACL;AAEA,MAAa,yBAAyB,CACpC,gBACA,eACF;AAEA,MAAa,wBAAwB,CAAC,eAAe,cAAc;AAEnE,MAAa,uBAAuB,CAAC,cAAc,aAAa;AAEhE,MAAa,+BAA+B,CAC1C,qBACA,oBACF;AAEA,MAAa,gCAAgC,CAC3C,sBACA,qBACF;AAEA,MAAa,wBAAwB,CAAC,eAAe,cAAc;;;ACfnE,MAAa,cAAc;CAEzB,UAAU;CACV,eAAe;CACf,YAAY;CACZ,MAAM;CACN,WAAW;CACX,SAAS;CACT,QAAQ;CACR,UAAU;CACV,MAAM;AACR;AAaA,MAAa,0BAA0B;CACrC;CACA;CACA;CACA;CACA,GAAG;CACH;CACA;CACA;CACA;CACA;AACF;AAUA,MAAa,oBAAoB;CAE/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;AACF;AAcA,MAAa,yBAAyB;CAEpC;CACA;CACA;CACA;CACA;CACA,GAAG;CAEH;CACA;CACA;CACA;CACA;CACA,GAAG;CAEH;CACA;CACA;CAEA;CACA;CACA;CACA,GAAG;CACH;CACA;CACA;CACA;AACF;AAYA,MAAa,uBAAuB;CAElC;CACA;CACA;CACA;CACA;CAEA;CAEA;CAEA;AACF;AASA,MAAa,sBAAsB;CAEjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AASA,MAAa,wBAAwB;CACnC;CAEA;CACA,GAAG;CACH;CACA;CACA;CACA;CAEA,GAAG;CACH,GAAG;CACH;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAWA,MAAa,iCAAiB,IAAI,IAAuB;AAGzD,IAAI,kBAAiD;AAErD,SAAS,0BAAgC;CACvC,K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ACF;AAKA,SAAgB,8BACd,WACA,YACA,YACA,UAAU,OACV,KACgB;CAChB,OAAO;EACL,MAAM;EACN,MAAM;EACN,SAAS;EACT;EACA,KAAK,OAAO,UAAU,UAAU;EAChC,UAAU,cACR,aACA;GAAE;GAAW;GAAY;EAAW,GACpC,OACF;EACA;EACA;EACA;CACF;AACF;AAKA,SAAgB,4BACd,SACA,cACA,UAAU,OACV,KACgB;CAChB,OAAO;EACL,MAAM;EACN,MAAM;EACN,SAAS;EACT;EACA,KAAK,OAAO,UAAU,UAAU,eAAe,KAAK,iBAAiB,GAAG;EACxE,UAAU,cAAc,WAAW;GAAE;GAAS;EAAa,GAAG,OAAO;EACrE;EACA;CACF;AACF;AAKA,SAAgB,yBACd,WACA,UAAU,OACV,KACgB;CAChB,OAAO;EACL,MAAM;EACN,MAAM;EACN,SAAS;EACT;EACA,KAAK,OAAO,UAAU;EACtB,UAAU,cAAc,QAAQ,EAAE,UAAU,GAAG,OAAO;EACtD;CACF;AACF;AAKA,SAAgB,kCACd,WACA,YACA,YACA,eACA,UAAU,OACV,KACoB;CACpB,OAAO;EACL,MAAM;EACN,MAAM;EACN,SAAS;EACT;EACA,KAAK,OAAO,KAAK,gBAAgB,gBAAgB,OAAO,KAAK,UAAU;EACvE,UAAU,kBACR,aACA;GAAE;GAAe;GAAW;GAAY;EAAW,GACnD,OACF;EACA;EACA;EACA;EACA;CACF;AACF;AAKA,SAAgB,8BACd,UACA,eACA,eACA,UAAU,OACV,KACoB;CACpB,OAAO;EACL,MAAM;EACN,MAAM;EACN,SAAS;EACT;EACA,KACE,OACA,KAAK,gBAAgB,gBAAgB,OAAO,GAAG,GAAG,WAAW,gBAAgB,MAAM,gBAAgB,GAAG;EACxG,UAAU,kBACR,SACA;GAAE;GAAe;GAAU;EAAc,GACzC,OACF;EACA;EACA;EACA;CACF;AACF;AAMA,SAAgB,4BACd,cACA,eACA,UAAU,OACV,KACoB;CACpB,OAAO;EACL,MAAM;EACN,MAAM;EACN,SAAS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