@tenphi/tasty 0.7.1 → 0.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.
@@ -130,8 +130,7 @@ const DISPLAY_CHUNK_STYLES = [
130
130
  "whiteSpace",
131
131
  "flow",
132
132
  "gap",
133
- "scrollbar",
134
- "styledScrollbar"
133
+ "scrollbar"
135
134
  ];
136
135
  /**
137
136
  * Layout chunk - flex/grid alignment and grid templates
@@ -1 +1 @@
1
- {"version":3,"file":"definitions.js","names":[],"sources":["../../src/chunks/definitions.ts"],"sourcesContent":["/**\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 */\n\nimport { isSelector } from '../pipeline';\n\n// ============================================================================\n// Chunk Style Lists\n// ============================================================================\n\n/**\n * Appearance chunk - visual styling with independent handlers\n */\nexport const APPEARANCE_CHUNK_STYLES = [\n 'fill', // fillStyle (independent)\n 'color', // colorStyle (independent)\n 'opacity', // independent\n 'border', // borderStyle (independent)\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 */\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, paddingBlock/Inline\n * ⚠️ marginStyle: margin, marginTop/Right/Bottom/Left, marginBlock/Inline\n * ⚠️ widthStyle: width, minWidth, maxWidth\n * ⚠️ heightStyle: height, minHeight, maxHeight\n */\nexport const DIMENSION_CHUNK_STYLES = [\n // All from paddingStyle handler - MUST stay together\n 'padding',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n 'paddingBlock',\n 'paddingInline',\n // All from marginStyle handler - MUST stay together\n 'margin',\n 'marginTop',\n 'marginRight',\n 'marginBottom',\n 'marginLeft',\n 'marginBlock',\n 'marginInline',\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 '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 */\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 'styledScrollbar', // styledScrollbarStyle (deprecated)\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 */\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', // alignStyle (independent)\n 'justify', // justifyStyle (independent)\n 'place', // placeStyle (independent)\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, insetBlock, insetInline, top, right, bottom, left\n */\nexport const POSITION_CHUNK_STYLES = [\n 'position',\n // All from insetStyle handler - MUST stay together\n 'inset',\n 'insetBlock',\n 'insetInline',\n 'top',\n 'right',\n 'bottom',\n 'left',\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// Chunk Names\n// ============================================================================\n\nexport const CHUNK_NAMES = {\n /** Special chunk for styles that cannot be split (e.g., @starting-style) */\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// Style-to-Chunk Lookup Map (O(1) categorization)\n// ============================================================================\n\n/**\n * Pre-computed map for O(1) style-to-chunk lookup.\n * Built once at module load time.\n */\nexport const STYLE_TO_CHUNK = new Map<string, ChunkName>();\n\n// Populate the lookup map\nfunction populateStyleToChunkMap() {\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// Initialize at module load\npopulateStyleToChunkMap();\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 * Map from chunk name to its priority index for sorting.\n */\nconst _CHUNK_PRIORITY = new Map<string, number>(\n CHUNK_ORDER.map((name, index) => [name, index]),\n);\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 const keys = Object.keys(styles);\n\n for (const key of keys) {\n // Skip the $ helper key (used for selector combinators)\n // Skip @keyframes and @properties (processed separately in useStyles)\n // Skip recipe (resolved before pipeline by resolveRecipes)\n if (\n key === '$' ||\n key === '@keyframes' ||\n key === '@properties' ||\n key === 'recipe'\n ) {\n continue;\n }\n\n if (isSelector(key)) {\n // All selectors go into the subcomponents chunk\n if (!chunkData[CHUNK_NAMES.SUBCOMPONENTS]) {\n chunkData[CHUNK_NAMES.SUBCOMPONENTS] = [];\n }\n chunkData[CHUNK_NAMES.SUBCOMPONENTS].push(key);\n } else {\n // Look up the chunk for this style, default to misc\n const chunkName = STYLE_TO_CHUNK.get(key) ?? CHUNK_NAMES.MISC;\n if (!chunkData[chunkName]) {\n chunkData[chunkName] = [];\n }\n chunkData[chunkName].push(key);\n }\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 if (chunkData[chunkName] && chunkData[chunkName].length > 0) {\n // Sort keys within chunk for consistent cache key generation\n orderedChunks.set(chunkName, chunkData[chunkName].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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAa,0BAA0B;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;AASD,MAAa,oBAAoB;CAE/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;AAWD,MAAa,yBAAyB;CAEpC;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;AAWD,MAAa,uBAAuB;CAElC;CACA;CACA;CACA;CACA;CAEA;CAEA;CAEA;CACA;CACD;;;;;;;AAQD,MAAa,sBAAsB;CAEjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;AAQD,MAAa,wBAAwB;CACnC;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAMD,MAAa,cAAc;CAEzB,UAAU;CACV,eAAe;CACf,YAAY;CACZ,MAAM;CACN,WAAW;CACX,SAAS;CACT,QAAQ;CACR,UAAU;CAC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S,EAExD,eAAc,IAAI,WAAW,UAAU,WAAW,MAAM,CAAC;AAK7D,MAAK,MAAM,aAAa,OAAO,KAAK,UAAU,CAC5C,KAAI,CAAC,cAAc,IAAI,UAAU,CAC/B,eAAc,IAAI,WAAW,UAAU,WAAW,MAAM,CAAC;AAI7D,QAAO"}
1
+ {"version":3,"file":"definitions.js","names":[],"sources":["../../src/chunks/definitions.ts"],"sourcesContent":["/**\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 */\n\nimport { isSelector } from '../pipeline';\n\n// ============================================================================\n// Chunk Style Lists\n// ============================================================================\n\n/**\n * Appearance chunk - visual styling with independent handlers\n */\nexport const APPEARANCE_CHUNK_STYLES = [\n 'fill', // fillStyle (independent)\n 'color', // colorStyle (independent)\n 'opacity', // independent\n 'border', // borderStyle (independent)\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 */\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, paddingBlock/Inline\n * ⚠️ marginStyle: margin, marginTop/Right/Bottom/Left, marginBlock/Inline\n * ⚠️ widthStyle: width, minWidth, maxWidth\n * ⚠️ heightStyle: height, minHeight, maxHeight\n */\nexport const DIMENSION_CHUNK_STYLES = [\n // All from paddingStyle handler - MUST stay together\n 'padding',\n 'paddingTop',\n 'paddingRight',\n 'paddingBottom',\n 'paddingLeft',\n 'paddingBlock',\n 'paddingInline',\n // All from marginStyle handler - MUST stay together\n 'margin',\n 'marginTop',\n 'marginRight',\n 'marginBottom',\n 'marginLeft',\n 'marginBlock',\n 'marginInline',\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 '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 */\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 */\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', // alignStyle (independent)\n 'justify', // justifyStyle (independent)\n 'place', // placeStyle (independent)\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, insetBlock, insetInline, top, right, bottom, left\n */\nexport const POSITION_CHUNK_STYLES = [\n 'position',\n // All from insetStyle handler - MUST stay together\n 'inset',\n 'insetBlock',\n 'insetInline',\n 'top',\n 'right',\n 'bottom',\n 'left',\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// Chunk Names\n// ============================================================================\n\nexport const CHUNK_NAMES = {\n /** Special chunk for styles that cannot be split (e.g., @starting-style) */\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// Style-to-Chunk Lookup Map (O(1) categorization)\n// ============================================================================\n\n/**\n * Pre-computed map for O(1) style-to-chunk lookup.\n * Built once at module load time.\n */\nexport const STYLE_TO_CHUNK = new Map<string, ChunkName>();\n\n// Populate the lookup map\nfunction populateStyleToChunkMap() {\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// Initialize at module load\npopulateStyleToChunkMap();\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 * Map from chunk name to its priority index for sorting.\n */\nconst _CHUNK_PRIORITY = new Map<string, number>(\n CHUNK_ORDER.map((name, index) => [name, index]),\n);\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 const keys = Object.keys(styles);\n\n for (const key of keys) {\n // Skip the $ helper key (used for selector combinators)\n // Skip @keyframes and @properties (processed separately in useStyles)\n // Skip recipe (resolved before pipeline by resolveRecipes)\n if (\n key === '$' ||\n key === '@keyframes' ||\n key === '@properties' ||\n key === 'recipe'\n ) {\n continue;\n }\n\n if (isSelector(key)) {\n // All selectors go into the subcomponents chunk\n if (!chunkData[CHUNK_NAMES.SUBCOMPONENTS]) {\n chunkData[CHUNK_NAMES.SUBCOMPONENTS] = [];\n }\n chunkData[CHUNK_NAMES.SUBCOMPONENTS].push(key);\n } else {\n // Look up the chunk for this style, default to misc\n const chunkName = STYLE_TO_CHUNK.get(key) ?? CHUNK_NAMES.MISC;\n if (!chunkData[chunkName]) {\n chunkData[chunkName] = [];\n }\n chunkData[chunkName].push(key);\n }\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 if (chunkData[chunkName] && chunkData[chunkName].length > 0) {\n // Sort keys within chunk for consistent cache key generation\n orderedChunks.set(chunkName, chunkData[chunkName].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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkDA,MAAa,0BAA0B;CACrC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;AASD,MAAa,oBAAoB;CAE/B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;AAWD,MAAa,yBAAyB;CAEpC;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;;;;AAWD,MAAa,uBAAuB;CAElC;CACA;CACA;CACA;CACA;CAEA;CAEA;CAEA;CACD;;;;;;;AAQD,MAAa,sBAAsB;CAEjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;;;;;;;AAQD,MAAa,wBAAwB;CACnC;CAEA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACD;AAMD,MAAa,cAAc;CAEzB,UAAU;CACV,eAAe;CACf,YAAY;CACZ,MAAM;CACN,WAAW;CACX,SAAS;CACT,QAAQ;CACR,UAAU;CACV,MAAM;CACP;;;;;AAYD,MAAa,iCAAiB,IAAI,KAAwB;AAG1D,SAAS,0BAA0B;AACjC,MAAK,MAAM,SAAS,wBAClB,gBAAe,IAAI,OAAO,YAAY,WAAW;AAEnD,MAAK,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,WAAW,UAAU,WAAW,MAAM,CAAC;AAI7D,QAAO"}
@@ -3,7 +3,7 @@ import { CSSProperties } from "../utils/css-types.js";
3
3
  import { Bucket, ParserOptions, ProcessedStyle, StyleDetails, StyleDetailsPart, UnitHandler } from "../parser/types.js";
4
4
  import { StyleParser } from "../parser/parser.js";
5
5
  import { AtRuleContext, ParsedAdvancedState, StateParserContext, createStateParserContext, getGlobalPredefinedStates, setGlobalPredefinedStates } from "../states/index.js";
6
- import { COMPUTE_FUNC_MAP, CSSMap, CUSTOM_UNITS, ComputeModel, DIRECTIONS, ParsedColor, RawStyleHandler, STATE_OPERATORS, STATE_OPERATOR_LIST, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleMap, StylePropValue, StyleStateData, StyleStateDataList, StyleStateDataListMap, StyleStateMap, StyleValue, StyleValueStateMap, buildAtRuleContext, computeState, customFunc, extendStyles, extractStyles, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getModSelector, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "../utils/styles.js";
6
+ import { COMPUTE_FUNC_MAP, CSSMap, CUSTOM_UNITS, ComputeModel, DIRECTIONS, ParsedColor, RawStyleHandler, STATE_OPERATORS, STATE_OPERATOR_LIST, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleMap, StylePropValue, StyleStateData, StyleStateDataList, StyleStateDataListMap, StyleStateMap, StyleValue, StyleValueStateMap, buildAtRuleContext, computeState, customFunc, extendStyles, extractStyles, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "../utils/styles.js";
7
7
  import { NoType, NotSelector, RecipeStyles, Selector, Styles, StylesInterface, StylesWithoutSelectors, SuffixForSelector, TastyNamedColors, TastyPresetNames } from "../styles/types.js";
8
8
  import { ConditionNode } from "../pipeline/conditions.js";
9
9
  import { ParseStateKeyOptions, parseStateKey } from "../pipeline/parseStateKey.js";
@@ -30,4 +30,4 @@ import { hslToRgbValues, processTokens, stringifyTokens } from "../utils/process
30
30
  import { TypographyPreset } from "../tokens/typography.js";
31
31
  import { generateTypographyTokens } from "../utils/typography.js";
32
32
  import { tastyDebug } from "../debug.js";
33
- export { type AtRuleContext, BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, type BaseStyleProps, type BlockInnerStyleProps, type BlockOuterStyleProps, type BlockStyleProps, Bucket, CHUNK_NAMES, COLOR_STYLES, COMPUTE_FUNC_MAP, CONTAINER_STYLES, CSSMap, type CSSProperties, CUSTOM_UNITS, CacheMetrics, type ChunkInfo, type ChunkName, type ColorStyleProps, ComputeModel, type ConditionNode, type ContainerStyleProps, DIMENSION_STYLES, DIRECTIONS, type DimensionStyleProps, DisposeFunction, FLOW_STYLES, type FlowStyleProps, type GlobalStyledProps, INNER_STYLES, InjectResult, type InnerStyleProps, KeyframesCacheEntry, KeyframesInfo, KeyframesResult, KeyframesSteps, type ModValue, type Mods, type NoType, type NotSelector, OUTER_STYLES, type OuterStyleProps, POSITION_STYLES, type ParseStateKeyOptions, type ParsedAdvancedState, ParsedColor, type ParserOptions, type PositionStyleProps, type ProcessedStyle, PropertyDefinition, PropertyOptions, type Props, RawCSSResult, RawStyleHandler, type RecipeStyles, type RenderResult, RootRegistry, RuleInfo, STATE_OPERATORS, STATE_OPERATOR_LIST, STYLE_TO_CHUNK, type Selector, SheetInfo, SheetManager, type ShortGridStyles, type StateParserContext, type StyleDetails, type StyleDetailsPart, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleInjector, StyleInjectorConfig, StyleMap, StyleParser, StylePropValue, type StyleResult, StyleRule, StyleStateData, StyleStateDataList, StyleStateDataListMap, StyleStateMap, StyleValue, StyleValueStateMap, type Styles, type StylesInterface, type StylesWithoutSelectors, type SuffixForSelector, TEXT_STYLES, type TagName, type TastyConfig, type TastyExtensionConfig, type TastyNamedColors, type TastyPlugin, type TastyPluginFactory, type TastyPresetNames, type TastyThemeNames, type TextStyleProps, type TokenValue, type Tokens, TypographyPreset, type UnitHandler, allocateClassName, buildAtRuleContext, categorizeStyleKeys, cleanup, color, computeState, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, extendStyles, extractStyles, filterBaseProps, filterMods, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getModSelector, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isAdvancedStateToken, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStateNotation, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, styleStateMapToStyleStateDataList, tastyDebug, warn };
33
+ export { type AtRuleContext, BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, type BaseStyleProps, type BlockInnerStyleProps, type BlockOuterStyleProps, type BlockStyleProps, Bucket, CHUNK_NAMES, COLOR_STYLES, COMPUTE_FUNC_MAP, CONTAINER_STYLES, CSSMap, type CSSProperties, CUSTOM_UNITS, CacheMetrics, type ChunkInfo, type ChunkName, type ColorStyleProps, ComputeModel, type ConditionNode, type ContainerStyleProps, DIMENSION_STYLES, DIRECTIONS, type DimensionStyleProps, DisposeFunction, FLOW_STYLES, type FlowStyleProps, type GlobalStyledProps, INNER_STYLES, InjectResult, type InnerStyleProps, KeyframesCacheEntry, KeyframesInfo, KeyframesResult, KeyframesSteps, type ModValue, type Mods, type NoType, type NotSelector, OUTER_STYLES, type OuterStyleProps, POSITION_STYLES, type ParseStateKeyOptions, type ParsedAdvancedState, ParsedColor, type ParserOptions, type PositionStyleProps, type ProcessedStyle, PropertyDefinition, PropertyOptions, type Props, RawCSSResult, RawStyleHandler, type RecipeStyles, type RenderResult, RootRegistry, RuleInfo, STATE_OPERATORS, STATE_OPERATOR_LIST, STYLE_TO_CHUNK, type Selector, SheetInfo, SheetManager, type ShortGridStyles, type StateParserContext, type StyleDetails, type StyleDetailsPart, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleInjector, StyleInjectorConfig, StyleMap, StyleParser, StylePropValue, type StyleResult, StyleRule, StyleStateData, StyleStateDataList, StyleStateDataListMap, StyleStateMap, StyleValue, StyleValueStateMap, type Styles, type StylesInterface, type StylesWithoutSelectors, type SuffixForSelector, TEXT_STYLES, type TagName, type TastyConfig, type TastyExtensionConfig, type TastyNamedColors, type TastyPlugin, type TastyPluginFactory, type TastyPresetNames, type TastyThemeNames, type TextStyleProps, type TokenValue, type Tokens, TypographyPreset, type UnitHandler, allocateClassName, buildAtRuleContext, categorizeStyleKeys, cleanup, color, computeState, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, extendStyles, extractStyles, filterBaseProps, filterMods, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isAdvancedStateToken, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStateNotation, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, styleStateMapToStyleStateDataList, tastyDebug, warn };
@@ -3,7 +3,8 @@ import { StyleParser } from "../parser/parser.js";
3
3
  import { okhslFunc, okhslPlugin } from "../plugins/okhsl-plugin.js";
4
4
  import { createStateParserContext, getGlobalPredefinedStates, setGlobalPredefinedStates } from "../states/index.js";
5
5
  import { hslToRgbValues, processTokens, stringifyTokens } from "../utils/process-tokens.js";
6
- import { COMPUTE_FUNC_MAP, CUSTOM_UNITS, DIRECTIONS, STATE_OPERATORS, STATE_OPERATOR_LIST, buildAtRuleContext, computeState, customFunc, extendStyles, extractStyles, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getModSelector, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "../utils/styles.js";
6
+ import { COMPUTE_FUNC_MAP, CUSTOM_UNITS, DIRECTIONS, STATE_OPERATORS, STATE_OPERATOR_LIST, buildAtRuleContext, computeState, customFunc, extendStyles, extractStyles, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "../utils/styles.js";
7
+ import { deprecationWarning, warn } from "../utils/warnings.js";
7
8
  import { styleHandlers } from "../styles/predefined.js";
8
9
  import { SheetManager } from "../injector/sheet-manager.js";
9
10
  import { StyleInjector } from "../injector/injector.js";
@@ -19,8 +20,7 @@ import { _modAttrs } from "../utils/mod-attrs.js";
19
20
  import { dotize } from "../utils/dotize.js";
20
21
  import { mergeStyles } from "../utils/merge-styles.js";
21
22
  import { resolveRecipes } from "../utils/resolve-recipes.js";
22
- import { deprecationWarning, warn } from "../utils/warnings.js";
23
23
  import { generateTypographyTokens } from "../utils/typography.js";
24
24
  import { tastyDebug } from "../debug.js";
25
25
 
26
- export { BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, Bucket, CHUNK_NAMES, COLOR_STYLES, COMPUTE_FUNC_MAP, CONTAINER_STYLES, CUSTOM_UNITS, DIMENSION_STYLES, DIRECTIONS, FLOW_STYLES, INNER_STYLES, OUTER_STYLES, POSITION_STYLES, STATE_OPERATORS, STATE_OPERATOR_LIST, STYLE_TO_CHUNK, SheetManager, StyleInjector, StyleParser, TEXT_STYLES, allocateClassName, buildAtRuleContext, categorizeStyleKeys, cleanup, color, computeState, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, extendStyles, extractStyles, filterBaseProps, filterMods, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getModSelector, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isAdvancedStateToken, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStateNotation, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, styleStateMapToStyleStateDataList, tastyDebug, warn };
26
+ export { BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, Bucket, CHUNK_NAMES, COLOR_STYLES, COMPUTE_FUNC_MAP, CONTAINER_STYLES, CUSTOM_UNITS, DIMENSION_STYLES, DIRECTIONS, FLOW_STYLES, INNER_STYLES, OUTER_STYLES, POSITION_STYLES, STATE_OPERATORS, STATE_OPERATOR_LIST, STYLE_TO_CHUNK, SheetManager, StyleInjector, StyleParser, TEXT_STYLES, allocateClassName, buildAtRuleContext, categorizeStyleKeys, cleanup, color, computeState, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, extendStyles, extractStyles, filterBaseProps, filterMods, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isAdvancedStateToken, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStateNotation, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, styleStateMapToStyleStateDataList, tastyDebug, warn };
package/dist/index.d.ts CHANGED
@@ -3,7 +3,7 @@ import { CSSProperties } from "./utils/css-types.js";
3
3
  import { Bucket, ParserOptions, ProcessedStyle, StyleDetails, StyleDetailsPart, UnitHandler } from "./parser/types.js";
4
4
  import { StyleParser } from "./parser/parser.js";
5
5
  import { AtRuleContext, ParsedAdvancedState, StateParserContext, createStateParserContext, getGlobalPredefinedStates, setGlobalPredefinedStates } from "./states/index.js";
6
- import { COMPUTE_FUNC_MAP, CSSMap, CUSTOM_UNITS, ComputeModel, DIRECTIONS, ParsedColor, RawStyleHandler, STATE_OPERATORS, STATE_OPERATOR_LIST, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleMap, StylePropValue, StyleStateData, StyleStateDataList, StyleStateDataListMap, StyleStateMap, StyleValue, StyleValueStateMap, buildAtRuleContext, computeState, customFunc, extendStyles, extractStyles, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getModSelector, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "./utils/styles.js";
6
+ import { COMPUTE_FUNC_MAP, CSSMap, CUSTOM_UNITS, ComputeModel, DIRECTIONS, ParsedColor, RawStyleHandler, STATE_OPERATORS, STATE_OPERATOR_LIST, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleMap, StylePropValue, StyleStateData, StyleStateDataList, StyleStateDataListMap, StyleStateMap, StyleValue, StyleValueStateMap, buildAtRuleContext, computeState, customFunc, extendStyles, extractStyles, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "./utils/styles.js";
7
7
  import { NoType, NotSelector, RecipeStyles, Selector, Styles, StylesInterface, StylesWithoutSelectors, SuffixForSelector, TastyNamedColors, TastyPresetNames } from "./styles/types.js";
8
8
  import { ConditionNode } from "./pipeline/conditions.js";
9
9
  import { ParseStateKeyOptions, parseStateKey } from "./pipeline/parseStateKey.js";
@@ -44,5 +44,5 @@ declare module './utils/css-types' {
44
44
  interface CSSProperties extends CSSProperties$1 {}
45
45
  }
46
46
  //#endregion
47
- export { type AllBaseProps, type AllBasePropsWithMods, AtRuleContext, BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, type BaseProps, type BasePropsWithoutChildren, BaseStyleProps, BlockInnerStyleProps, BlockOuterStyleProps, BlockStyleProps, Bucket, CHUNK_NAMES, COLOR_STYLES, COMPUTE_FUNC_MAP, CONTAINER_STYLES, CSSMap, CSSProperties, CUSTOM_UNITS, CacheMetrics, ChunkInfo, ChunkName, ColorStyleProps, ComputeModel, ConditionNode, ContainerStyleProps, DIMENSION_STYLES, DIRECTIONS, DimensionStyleProps, DisposeFunction, Element, type ElementsDefinition, FLOW_STYLES, FlowStyleProps, GlobalStyledProps, INNER_STYLES, InjectResult, InnerStyleProps, KeyframesCacheEntry, KeyframesInfo, KeyframesResult, KeyframesSteps, ModValue, Mods, NoType, NotSelector, OUTER_STYLES, OuterStyleProps, POSITION_STYLES, ParseStateKeyOptions, ParsedAdvancedState, ParsedColor, ParserOptions, PositionStyleProps, ProcessedStyle, PropertyDefinition, PropertyOptions, Props, RawCSSResult, RawStyleHandler, RecipeStyles, RenderResult, RootRegistry, RuleInfo, STATE_OPERATORS, STATE_OPERATOR_LIST, STYLE_TO_CHUNK, Selector, SheetInfo, SheetManager, ShortGridStyles, StateParserContext, StyleDetails, StyleDetailsPart, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleInjector, StyleInjectorConfig, StyleMap, StyleParser, StylePropValue, StyleResult, StyleRule, StyleStateData, StyleStateDataList, StyleStateDataListMap, StyleStateMap, StyleValue, StyleValueStateMap, Styles, StylesInterface, StylesWithoutSelectors, type SubElementDefinition, type SubElementProps, SuffixForSelector, TEXT_STYLES, TagName, TastyConfig, type TastyElementOptions, type TastyElementProps, TastyExtensionConfig, TastyNamedColors, TastyPlugin, TastyPluginFactory, TastyPresetNames, type TastyProps, TastyThemeNames, TextStyleProps, TokenValue, Tokens, TypographyPreset, UnitHandler, type UsePropertyOptions, type UseStylesOptions, type UseStylesResult, type VariantMap, type WithVariant, allocateClassName, buildAtRuleContext, categorizeStyleKeys, cleanup, color, computeState, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, extendStyles, extractStyles, filterBaseProps, filterMods, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getDisplayName, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getModSelector, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isAdvancedStateToken, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStateNotation, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, styleStateMapToStyleStateDataList, tasty, tastyDebug, useGlobalStyles, useKeyframes, useProperty, useRawCSS, useStyles, warn };
47
+ export { type AllBaseProps, type AllBasePropsWithMods, AtRuleContext, BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, type BaseProps, type BasePropsWithoutChildren, BaseStyleProps, BlockInnerStyleProps, BlockOuterStyleProps, BlockStyleProps, Bucket, CHUNK_NAMES, COLOR_STYLES, COMPUTE_FUNC_MAP, CONTAINER_STYLES, CSSMap, CSSProperties, CUSTOM_UNITS, CacheMetrics, ChunkInfo, ChunkName, ColorStyleProps, ComputeModel, ConditionNode, ContainerStyleProps, DIMENSION_STYLES, DIRECTIONS, DimensionStyleProps, DisposeFunction, Element, type ElementsDefinition, FLOW_STYLES, FlowStyleProps, GlobalStyledProps, INNER_STYLES, InjectResult, InnerStyleProps, KeyframesCacheEntry, KeyframesInfo, KeyframesResult, KeyframesSteps, ModValue, Mods, NoType, NotSelector, OUTER_STYLES, OuterStyleProps, POSITION_STYLES, ParseStateKeyOptions, ParsedAdvancedState, ParsedColor, ParserOptions, PositionStyleProps, ProcessedStyle, PropertyDefinition, PropertyOptions, Props, RawCSSResult, RawStyleHandler, RecipeStyles, RenderResult, RootRegistry, RuleInfo, STATE_OPERATORS, STATE_OPERATOR_LIST, STYLE_TO_CHUNK, Selector, SheetInfo, SheetManager, ShortGridStyles, StateParserContext, StyleDetails, StyleDetailsPart, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleInjector, StyleInjectorConfig, StyleMap, StyleParser, StylePropValue, StyleResult, StyleRule, StyleStateData, StyleStateDataList, StyleStateDataListMap, StyleStateMap, StyleValue, StyleValueStateMap, Styles, StylesInterface, StylesWithoutSelectors, type SubElementDefinition, type SubElementProps, SuffixForSelector, TEXT_STYLES, TagName, TastyConfig, type TastyElementOptions, type TastyElementProps, TastyExtensionConfig, TastyNamedColors, TastyPlugin, TastyPluginFactory, TastyPresetNames, type TastyProps, TastyThemeNames, TextStyleProps, TokenValue, Tokens, TypographyPreset, UnitHandler, type UsePropertyOptions, type UseStylesOptions, type UseStylesResult, type VariantMap, type WithVariant, allocateClassName, buildAtRuleContext, categorizeStyleKeys, cleanup, color, computeState, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, extendStyles, extractStyles, filterBaseProps, filterMods, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getDisplayName, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isAdvancedStateToken, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStateNotation, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, styleStateMapToStyleStateDataList, tasty, tastyDebug, useGlobalStyles, useKeyframes, useProperty, useRawCSS, useStyles, warn };
48
48
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -3,7 +3,8 @@ import { StyleParser } from "./parser/parser.js";
3
3
  import { okhslFunc, okhslPlugin } from "./plugins/okhsl-plugin.js";
4
4
  import { createStateParserContext, getGlobalPredefinedStates, setGlobalPredefinedStates } from "./states/index.js";
5
5
  import { hslToRgbValues, processTokens, stringifyTokens } from "./utils/process-tokens.js";
6
- import { COMPUTE_FUNC_MAP, CUSTOM_UNITS, DIRECTIONS, STATE_OPERATORS, STATE_OPERATOR_LIST, buildAtRuleContext, computeState, customFunc, extendStyles, extractStyles, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getModSelector, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "./utils/styles.js";
6
+ import { COMPUTE_FUNC_MAP, CUSTOM_UNITS, DIRECTIONS, STATE_OPERATORS, STATE_OPERATOR_LIST, buildAtRuleContext, computeState, customFunc, extendStyles, extractStyles, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "./utils/styles.js";
7
+ import { deprecationWarning, warn } from "./utils/warnings.js";
7
8
  import { styleHandlers } from "./styles/predefined.js";
8
9
  import { SheetManager } from "./injector/sheet-manager.js";
9
10
  import { StyleInjector } from "./injector/injector.js";
@@ -19,7 +20,6 @@ import { _modAttrs } from "./utils/mod-attrs.js";
19
20
  import { dotize } from "./utils/dotize.js";
20
21
  import { mergeStyles } from "./utils/merge-styles.js";
21
22
  import { resolveRecipes } from "./utils/resolve-recipes.js";
22
- import { deprecationWarning, warn } from "./utils/warnings.js";
23
23
  import { generateTypographyTokens } from "./utils/typography.js";
24
24
  import { tastyDebug } from "./debug.js";
25
25
  import { useStyles } from "./hooks/useStyles.js";
@@ -30,4 +30,4 @@ import { useRawCSS } from "./hooks/useRawCSS.js";
30
30
  import { useKeyframes } from "./hooks/useKeyframes.js";
31
31
  import { useProperty } from "./hooks/useProperty.js";
32
32
 
33
- export { BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, Bucket, CHUNK_NAMES, COLOR_STYLES, COMPUTE_FUNC_MAP, CONTAINER_STYLES, CUSTOM_UNITS, DIMENSION_STYLES, DIRECTIONS, Element, FLOW_STYLES, INNER_STYLES, OUTER_STYLES, POSITION_STYLES, STATE_OPERATORS, STATE_OPERATOR_LIST, STYLE_TO_CHUNK, SheetManager, StyleInjector, StyleParser, TEXT_STYLES, allocateClassName, buildAtRuleContext, categorizeStyleKeys, cleanup, color, computeState, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, extendStyles, extractStyles, filterBaseProps, filterMods, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getDisplayName, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getModSelector, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isAdvancedStateToken, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStateNotation, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, styleStateMapToStyleStateDataList, tasty, tastyDebug, useGlobalStyles, useKeyframes, useProperty, useRawCSS, useStyles, warn };
33
+ export { BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, Bucket, CHUNK_NAMES, COLOR_STYLES, COMPUTE_FUNC_MAP, CONTAINER_STYLES, CUSTOM_UNITS, DIMENSION_STYLES, DIRECTIONS, Element, FLOW_STYLES, INNER_STYLES, OUTER_STYLES, POSITION_STYLES, STATE_OPERATORS, STATE_OPERATOR_LIST, STYLE_TO_CHUNK, SheetManager, StyleInjector, StyleParser, TEXT_STYLES, allocateClassName, buildAtRuleContext, categorizeStyleKeys, cleanup, color, computeState, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, extendStyles, extractStyles, filterBaseProps, filterMods, generateTypographyTokens, getConfig, getCssText, getCssTextForNode, getDisplayName, getGlobalFuncs, getGlobalKeyframes, getGlobalParser, getGlobalPredefinedStates, getGlobalPredefinedTokens, getGlobalRecipes, getIsTestEnvironment, getRawCSSText, getRgbValuesFromRgbaString, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, hexToRgb, hslToRgbValues, inject, injectGlobal, injectRawCSS, injector, isAdvancedStateToken, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStateNotation, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, styleStateMapToStyleStateDataList, tasty, tastyDebug, useGlobalStyles, useKeyframes, useProperty, useRawCSS, useStyles, warn };
@@ -1 +1 @@
1
- {"version":3,"file":"classify.js","names":[],"sources":["../../src/parser/classify.ts"],"sourcesContent":["import { getGlobalPredefinedTokens } from '../utils/styles';\n\nimport {\n COLOR_FUNCS,\n RE_HEX,\n RE_NUMBER,\n RE_RAW_UNIT,\n RE_UNIT_NUM,\n VALUE_KEYWORDS,\n} from './const';\nimport { StyleParser } from './parser';\nimport type { ParserOptions, ProcessedStyle } from './types';\nimport { Bucket } from './types';\n\n/**\n * Re-parses a value through the parser until it stabilizes (no changes)\n * or max iterations reached. This allows units to reference other units.\n * Example: { x: '8px', y: '2x' } -> '1y' resolves to '16px'\n */\nfunction resolveUntilStable(\n value: string,\n opts: ParserOptions,\n recurse: (str: string) => ProcessedStyle,\n maxIterations = 10,\n): string {\n let current = value;\n for (let i = 0; i < maxIterations; i++) {\n // Check if the current value contains a custom unit that needs resolution\n const unitMatch = current.match(RE_UNIT_NUM);\n if (!unitMatch) break; // Not a unit number, no resolution needed\n\n const unitName = unitMatch[1];\n // Only recurse if the unit is a custom unit we know about\n // Any unit not in opts.units is assumed to be a native CSS unit\n if (!opts.units || !(unitName in opts.units)) break;\n\n const result = recurse(current);\n if (result.output === current) break; // Stable\n current = result.output;\n }\n return current;\n}\n\nexport function classify(\n raw: string,\n opts: ParserOptions,\n recurse: (str: string) => ProcessedStyle,\n): { bucket: Bucket; processed: string } {\n const token = raw.trim();\n if (!token) return { bucket: Bucket.Mod, processed: '' };\n\n // Early-out: if the token contains unmatched parentheses treat it as invalid\n // and skip it. This avoids cases like `drop-shadow(` that are missing a\n // closing parenthesis (e.g., a user-typo in CSS). We count paren depth while\n // ignoring everything inside string literals to avoid false positives.\n {\n let depth = 0;\n let inQuote: string | 0 = 0;\n for (let i = 0; i < token.length; i++) {\n const ch = token[i];\n\n // track quote context so parentheses inside quotes are ignored\n if (inQuote) {\n if (ch === inQuote && token[i - 1] !== '\\\\') inQuote = 0;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inQuote = ch;\n continue;\n }\n\n if (ch === '(') depth++;\n else if (ch === ')') depth = Math.max(0, depth - 1);\n }\n\n if (depth !== 0) {\n // Unbalanced parens → treat as invalid token (skipped).\n console.warn(\n 'tasty: skipped invalid function token with unmatched parentheses:',\n token,\n );\n return { bucket: Bucket.Mod, processed: '' };\n }\n }\n\n // Quoted string literals should be treated as value tokens (e.g., \"\" for content)\n if (\n (token.startsWith('\"') && token.endsWith('\"')) ||\n (token.startsWith(\"'\") && token.endsWith(\"'\"))\n ) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 0. Double prefix for literal CSS property names ($$name -> --name, ##name -> --name-color)\n // Used in transitions and animations to reference the property name itself, not its value\n if (token.startsWith('$$')) {\n const name = token.slice(2);\n if (/^[a-z_][a-z0-9-_]*$/i.test(name)) {\n return { bucket: Bucket.Value, processed: `--${name}` };\n }\n }\n if (token.startsWith('##')) {\n const name = token.slice(2);\n if (/^[a-z_][a-z0-9-_]*$/i.test(name)) {\n return { bucket: Bucket.Value, processed: `--${name}-color` };\n }\n }\n\n // 0b. Special handling for #current (reserved keyword, cannot be overridden by predefined tokens)\n // #current maps to CSS currentcolor keyword\n if (token === '#current') {\n return { bucket: Bucket.Color, processed: 'currentcolor' };\n }\n\n // #current with opacity: #current.5 or #current.$opacity\n // Uses color-mix since currentcolor doesn't support rgb() alpha syntax\n const currentAlphaMatch = token.match(\n /^#current\\.(\\$[a-z_][a-z0-9-_]*|[0-9]+)$/i,\n );\n if (currentAlphaMatch) {\n const rawAlpha = currentAlphaMatch[1];\n let percentage: string;\n if (rawAlpha.startsWith('$')) {\n // Custom property: $disabled -> calc(var(--disabled) * 100%)\n const propName = rawAlpha.slice(1);\n percentage = `calc(var(--${propName}) * 100%)`;\n } else if (rawAlpha === '0') {\n percentage = '0%';\n } else {\n // Convert .5 -> 50%, .05 -> 5%\n percentage = `${parseFloat('.' + rawAlpha) * 100}%`;\n }\n return {\n bucket: Bucket.Color,\n processed: `color-mix(in oklab, currentcolor ${percentage}, transparent)`,\n };\n }\n\n // 0c. Check for predefined tokens (configured via configure({ tokens: {...} }))\n // Must happen before default $ and # handling to allow overriding\n if (token[0] === '$' || token[0] === '#') {\n const predefinedTokens = getGlobalPredefinedTokens();\n if (predefinedTokens) {\n // Exact match\n if (token in predefinedTokens) {\n const tokenValue = predefinedTokens[token];\n // Lowercase the token value to match parser behavior (parser lowercases input)\n return classify(tokenValue.toLowerCase(), opts, recurse);\n }\n // Check for color token with alpha suffix: #token.alpha or #token.$prop\n if (token[0] === '#') {\n const alphaMatch = token.match(\n /^(#[a-z0-9-]+)\\.(\\$[a-z_][a-z0-9-_]*|[0-9]+)$/i,\n );\n if (alphaMatch) {\n const [, baseToken, rawAlpha] = alphaMatch;\n if (baseToken in predefinedTokens) {\n const resolvedValue = predefinedTokens[baseToken];\n\n // If resolved value starts with # (color token), use standard alpha syntax\n if (resolvedValue.startsWith('#')) {\n // Lowercase to match parser behavior\n return classify(\n `${resolvedValue.toLowerCase()}.${rawAlpha}`,\n opts,\n recurse,\n );\n }\n\n // For color functions like rgb(), rgba(), hsl(), hwb(), etc., inject alpha\n // Includes all standard CSS color functions plus okhsl (plugin)\n const funcMatch = resolvedValue.match(\n /^(rgba?|hsla?|hwb|oklab|oklch|lab|lch|color|okhsl|device-cmyk|gray|color-mix|color-contrast)\\((.+)\\)$/i,\n );\n if (funcMatch) {\n const [, funcName, args] = funcMatch;\n // Handle $prop syntax for custom property alpha\n let alpha: string;\n if (rawAlpha.startsWith('$')) {\n const propName = rawAlpha.slice(1);\n alpha = `var(--${propName})`;\n } else {\n alpha = rawAlpha === '0' ? '0' : `.${rawAlpha}`;\n }\n // Normalize function name: rgba->rgb, hsla->hsl (modern syntax doesn't need 'a' suffix)\n const normalizedFunc = funcName.replace(/a$/i, '').toLowerCase();\n // Normalize to modern syntax: replace top-level commas with spaces\n // Preserves commas inside nested functions like min(), max(), clamp()\n const normalizeArgs = (a: string) => {\n let result = '';\n let depth = 0;\n for (let i = 0; i < a.length; i++) {\n const c = a[i];\n if (c === '(') {\n depth++;\n result += c;\n } else if (c === ')') {\n depth = Math.max(0, depth - 1);\n result += c;\n } else if (c === ',' && depth === 0) {\n // Skip comma and any following whitespace at top level\n while (i + 1 < a.length && /\\s/.test(a[i + 1])) i++;\n result += ' ';\n } else {\n result += c;\n }\n }\n return result;\n };\n // Helper: find last top-level occurrence of a character (ignores parentheses)\n const findLastTopLevel = (str: string, ch: string) => {\n let depth = 0;\n for (let i = str.length - 1; i >= 0; i--) {\n const c = str[i];\n if (c === ')') depth++;\n else if (c === '(') depth = Math.max(0, depth - 1);\n else if (c === ch && depth === 0) return i;\n }\n return -1;\n };\n\n // Check if already has alpha:\n // - Modern syntax: has `/` separator at top level (works with dynamic alpha like var()/calc())\n // - Legacy syntax: function ends with 'a' (rgba, hsla) and has exactly 4 top-level comma-separated values\n const slashIdx = findLastTopLevel(args, '/');\n const hasModernAlpha = slashIdx !== -1;\n\n // Count top-level commas to avoid commas inside nested functions\n let topLevelCommaCount = 0;\n let lastTopLevelComma = -1;\n {\n let depth = 0;\n for (let i = 0; i < args.length; i++) {\n const c = args[i];\n if (c === '(') depth++;\n else if (c === ')') depth = Math.max(0, depth - 1);\n else if (c === ',' && depth === 0) {\n topLevelCommaCount++;\n lastTopLevelComma = i;\n }\n }\n }\n\n const hasLegacyAlpha =\n !hasModernAlpha &&\n /a$/i.test(funcName) &&\n topLevelCommaCount === 3;\n\n const colorArgs =\n hasModernAlpha || hasLegacyAlpha\n ? normalizeArgs(\n hasModernAlpha\n ? args.slice(0, slashIdx).trim()\n : args.slice(0, lastTopLevelComma).trim(),\n )\n : normalizeArgs(args);\n\n const constructed = `${normalizedFunc}(${colorArgs} / ${alpha})`;\n\n // Custom functions (not native CSS) must be re-classified\n // so the function handler can convert them to valid CSS\n if (\n !COLOR_FUNCS.has(normalizedFunc) &&\n opts.funcs &&\n normalizedFunc in opts.funcs\n ) {\n return classify(constructed, opts, recurse);\n }\n\n return { bucket: Bucket.Color, processed: constructed };\n }\n\n // Fallback: try appending .alpha (may not work for all cases)\n return classify(`${resolvedValue}.${rawAlpha}`, opts, recurse);\n }\n }\n }\n }\n }\n\n // 0. Direct var(--*-color) token\n const varColorMatch = token.match(/^var\\(--([a-z0-9-]+)-color\\)$/);\n if (varColorMatch) {\n return { bucket: Bucket.Color, processed: token };\n }\n\n // 1. URL\n if (token.startsWith('url(')) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 2. Custom property\n if (token[0] === '$') {\n const identMatch = token.match(/^\\$([a-z_][a-z0-9-_]*)$/);\n if (identMatch) {\n const name = identMatch[1];\n const processed = `var(--${name})`;\n const bucketType = name.endsWith('-color') ? Bucket.Color : Bucket.Value;\n return {\n bucket: bucketType,\n processed,\n };\n }\n // invalid custom property → modifier\n }\n\n // 3. Hash colors (with optional alpha suffix e.g., #purple.5 or #purple.$disabled)\n if (token[0] === '#' && token.length > 1) {\n // alpha form: #name.alpha or #name.$prop\n const alphaMatch = token.match(\n /^#([a-z0-9-]+)\\.(\\$[a-z_][a-z0-9-_]*|[0-9]+)$/i,\n );\n if (alphaMatch) {\n const [, base, rawAlpha] = alphaMatch;\n let alpha: string;\n if (rawAlpha.startsWith('$')) {\n // Custom property: $disabled -> var(--disabled)\n const propName = rawAlpha.slice(1);\n alpha = `var(--${propName})`;\n } else if (rawAlpha === '0') {\n alpha = '0';\n } else {\n alpha = `.${rawAlpha}`;\n }\n return {\n bucket: Bucket.Color,\n processed: `rgb(var(--${base}-color-rgb) / ${alpha})`,\n };\n }\n\n // hyphenated names like #dark-05 should keep full name\n\n const name = token.slice(1);\n // valid hex → treat as hex literal with fallback\n if (RE_HEX.test(name)) {\n return {\n bucket: Bucket.Color,\n processed: `var(--${name}-color, #${name})`,\n };\n }\n // simple color name token → css variable lookup with rgb fallback\n return { bucket: Bucket.Color, processed: `var(--${name}-color)` };\n }\n\n // 4 & 5. Functions\n const openIdx = token.indexOf('(');\n if (openIdx > 0 && token.endsWith(')')) {\n const fname = token.slice(0, openIdx);\n const inner = token.slice(openIdx + 1, -1); // without ()\n\n if (COLOR_FUNCS.has(fname)) {\n // Process inner to expand nested colors or units.\n const argProcessed = recurse(inner).output.replace(/,\\s+/g, ','); // color funcs expect no spaces after commas\n return { bucket: Bucket.Color, processed: `${fname}(${argProcessed})` };\n }\n\n // user function (provided via opts)\n if (opts.funcs && fname in opts.funcs) {\n // split by top-level commas within inner\n const tmp = new StyleParser(opts).process(inner); // fresh parser w/ same opts but no cache share issues\n const funcResult = opts.funcs[fname](tmp.groups);\n // Re-classify the result to determine proper bucket (e.g., if it returns a color)\n // Pass funcs: undefined to prevent infinite recursion if result matches a function pattern\n return classify(funcResult, { ...opts, funcs: undefined }, recurse);\n }\n\n // generic: process inner and rebuild\n const argProcessed = recurse(inner).output;\n return { bucket: Bucket.Value, processed: `${fname}(${argProcessed})` };\n }\n\n // 6. Color fallback syntax: (#name, fallback)\n if (token.startsWith('(') && token.endsWith(')')) {\n const inner = token.slice(1, -1);\n const colorMatch = inner.match(/^#([a-z0-9-]+)\\s*,\\s*(.*)$/i);\n if (colorMatch) {\n const [, name, fallback] = colorMatch;\n const processedFallback = recurse(fallback).output;\n return {\n bucket: Bucket.Color,\n processed: `var(--${name}-color, ${processedFallback})`,\n };\n }\n }\n\n // 7. Custom property with fallback syntax: ($prop, fallback)\n if (token.startsWith('(') && token.endsWith(')')) {\n const inner = token.slice(1, -1);\n const match = inner.match(/^\\$([a-z_][a-z0-9-_]*)\\s*,\\s*(.*)$/);\n if (match) {\n const [, name, fallback] = match;\n const processedFallback = recurse(fallback).output;\n const bucketType = name.endsWith('-color') ? Bucket.Color : Bucket.Value;\n return {\n bucket: bucketType,\n processed: `var(--${name}, ${processedFallback})`,\n };\n }\n }\n\n // 8. Auto-calc group\n if (token[0] === '(' && token[token.length - 1] === ')') {\n const inner = token.slice(1, -1);\n const innerProcessed = recurse(inner).output;\n return { bucket: Bucket.Value, processed: `calc(${innerProcessed})` };\n }\n\n // 9. Unit number\n const um = token.match(RE_UNIT_NUM);\n if (um) {\n const unit = um[1];\n const numericPart = parseFloat(token.slice(0, -unit.length));\n const handler = opts.units && opts.units[unit];\n if (handler) {\n if (typeof handler === 'string') {\n // Check if this is a raw CSS unit (e.g., \"8px\", \"1rem\")\n const rawMatch = handler.match(RE_RAW_UNIT);\n if (rawMatch) {\n // Raw unit: calculate directly instead of using calc()\n const [, baseNum, cssUnit] = rawMatch;\n const result = numericPart * parseFloat(baseNum);\n const processed = `${result}${cssUnit}`;\n // Re-parse to resolve any nested units (e.g., units referencing other units)\n const resolved = resolveUntilStable(processed, opts, recurse);\n return { bucket: Bucket.Value, processed: resolved };\n }\n\n // Non-raw handler (e.g., \"var(--gap)\", \"calc(...)\"): use calc() wrapping\n const base = handler;\n if (numericPart === 1) {\n return { bucket: Bucket.Value, processed: base };\n }\n return {\n bucket: Bucket.Value,\n processed: `calc(${numericPart} * ${base})`,\n };\n } else {\n // Function units return complete CSS expressions, no wrapping needed\n const inner = handler(numericPart);\n return {\n bucket: Bucket.Value,\n processed: inner,\n };\n }\n }\n }\n\n // 9b. Unknown numeric+unit → treat as literal value (e.g., 1fr)\n if (/^[+-]?(?:\\d*\\.\\d+|\\d+)[a-z%]+$/.test(token)) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 9c. Plain unit-less numbers should be treated as value tokens so that\n // code such as `scrollbar={10}` resolves correctly.\n if (RE_NUMBER.test(token)) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 10. Literal value keywords\n if (VALUE_KEYWORDS.has(token)) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 10b. Special keyword colors\n if (token === 'transparent' || token === 'currentcolor') {\n return { bucket: Bucket.Color, processed: token };\n }\n\n // 11. Fallback modifier\n return { bucket: Bucket.Mod, processed: token };\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAS,mBACP,OACA,MACA,SACA,gBAAgB,IACR;CAC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O;AAInD,QAAO;EAAE,QAAQ,OAAO;EAAK,WAAW;EAAO"}
1
+ {"version":3,"file":"classify.js","names":[],"sources":["../../src/parser/classify.ts"],"sourcesContent":["import { getGlobalPredefinedTokens } from '../utils/styles';\n\nimport {\n COLOR_FUNCS,\n RE_HEX,\n RE_NUMBER,\n RE_RAW_UNIT,\n RE_UNIT_NUM,\n VALUE_KEYWORDS,\n} from './const';\nimport { StyleParser } from './parser';\nimport type { ParserOptions, ProcessedStyle } from './types';\nimport { Bucket } from './types';\n\n/**\n * Re-parses a value through the parser until it stabilizes (no changes)\n * or max iterations reached. This allows units to reference other units.\n * Example: { x: '8px', y: '2x' } -> '1y' resolves to '16px'\n */\nfunction resolveUntilStable(\n value: string,\n opts: ParserOptions,\n recurse: (str: string) => ProcessedStyle,\n maxIterations = 10,\n): string {\n let current = value;\n for (let i = 0; i < maxIterations; i++) {\n // Check if the current value contains a custom unit that needs resolution\n const unitMatch = current.match(RE_UNIT_NUM);\n if (!unitMatch) break; // Not a unit number, no resolution needed\n\n const unitName = unitMatch[1];\n // Only recurse if the unit is a custom unit we know about\n // Any unit not in opts.units is assumed to be a native CSS unit\n if (!opts.units || !(unitName in opts.units)) break;\n\n const result = recurse(current);\n if (result.output === current) break; // Stable\n current = result.output;\n }\n return current;\n}\n\nexport function classify(\n raw: string,\n opts: ParserOptions,\n recurse: (str: string) => ProcessedStyle,\n): { bucket: Bucket; processed: string } {\n const token = raw.trim();\n if (!token) return { bucket: Bucket.Mod, processed: '' };\n\n // Early-out: if the token contains unmatched parentheses treat it as invalid\n // and skip it. This avoids cases like `drop-shadow(` that are missing a\n // closing parenthesis (e.g., a user-typo in CSS). We count paren depth while\n // ignoring everything inside string literals to avoid false positives.\n {\n let depth = 0;\n let inQuote: string | 0 = 0;\n for (let i = 0; i < token.length; i++) {\n const ch = token[i];\n\n // track quote context so parentheses inside quotes are ignored\n if (inQuote) {\n if (ch === inQuote && token[i - 1] !== '\\\\') inQuote = 0;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inQuote = ch;\n continue;\n }\n\n if (ch === '(') depth++;\n else if (ch === ')') depth = Math.max(0, depth - 1);\n }\n\n if (depth !== 0) {\n // Unbalanced parens → treat as invalid token (skipped).\n console.warn(\n 'tasty: skipped invalid function token with unmatched parentheses:',\n token,\n );\n return { bucket: Bucket.Mod, processed: '' };\n }\n }\n\n // Quoted string literals should be treated as value tokens (e.g., \"\" for content)\n if (\n (token.startsWith('\"') && token.endsWith('\"')) ||\n (token.startsWith(\"'\") && token.endsWith(\"'\"))\n ) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 0. Double prefix for literal CSS property names ($$name -> --name, ##name -> --name-color)\n // Used in transitions and animations to reference the property name itself, not its value\n if (token.startsWith('$$')) {\n const name = token.slice(2);\n if (/^[a-z_][a-z0-9-_]*$/i.test(name)) {\n return { bucket: Bucket.Value, processed: `--${name}` };\n }\n }\n if (token.startsWith('##')) {\n const name = token.slice(2);\n if (/^[a-z_][a-z0-9-_]*$/i.test(name)) {\n return { bucket: Bucket.Value, processed: `--${name}-color` };\n }\n }\n\n // 0b. Special handling for #current (reserved keyword, cannot be overridden by predefined tokens)\n // #current maps to CSS currentcolor keyword\n if (token === '#current') {\n return { bucket: Bucket.Color, processed: 'currentcolor' };\n }\n\n // #current with opacity: #current.5 or #current.$opacity\n // Uses color-mix since currentcolor doesn't support rgb() alpha syntax\n const currentAlphaMatch = token.match(\n /^#current\\.(\\$[a-z_][a-z0-9-_]*|[0-9]+)$/i,\n );\n if (currentAlphaMatch) {\n const rawAlpha = currentAlphaMatch[1];\n let percentage: string;\n if (rawAlpha.startsWith('$')) {\n // Custom property: $disabled -> calc(var(--disabled) * 100%)\n const propName = rawAlpha.slice(1);\n percentage = `calc(var(--${propName}) * 100%)`;\n } else if (rawAlpha === '0') {\n percentage = '0%';\n } else {\n // Convert .5 -> 50%, .05 -> 5%\n percentage = `${parseFloat('.' + rawAlpha) * 100}%`;\n }\n return {\n bucket: Bucket.Color,\n processed: `color-mix(in oklab, currentcolor ${percentage}, transparent)`,\n };\n }\n\n // 0c. Check for predefined tokens (configured via configure({ tokens: {...} }))\n // Must happen before default $ and # handling to allow overriding\n if (token[0] === '$' || token[0] === '#') {\n const predefinedTokens = getGlobalPredefinedTokens();\n if (predefinedTokens) {\n // Exact match\n if (token in predefinedTokens) {\n const tokenValue = predefinedTokens[token];\n // Lowercase the token value to match parser behavior (parser lowercases input)\n return classify(tokenValue.toLowerCase(), opts, recurse);\n }\n // Check for color token with alpha suffix: #token.alpha or #token.$prop\n if (token[0] === '#') {\n const alphaMatch = token.match(\n /^(#[a-z0-9-]+)\\.(\\$[a-z_][a-z0-9-_]*|[0-9]+)$/i,\n );\n if (alphaMatch) {\n const [, baseToken, rawAlpha] = alphaMatch;\n if (baseToken in predefinedTokens) {\n const resolvedValue = predefinedTokens[baseToken];\n\n // If resolved value starts with # (color token), use standard alpha syntax\n if (resolvedValue.startsWith('#')) {\n // Lowercase to match parser behavior\n return classify(\n `${resolvedValue.toLowerCase()}.${rawAlpha}`,\n opts,\n recurse,\n );\n }\n\n // For color functions like rgb(), rgba(), hsl(), hwb(), etc., inject alpha\n // Includes all standard CSS color functions plus okhsl (plugin)\n const funcMatch = resolvedValue.match(\n /^(rgba?|hsla?|hwb|oklab|oklch|lab|lch|color|okhsl|device-cmyk|gray|color-mix|color-contrast)\\((.+)\\)$/i,\n );\n if (funcMatch) {\n const [, funcName, args] = funcMatch;\n // Handle $prop syntax for custom property alpha\n let alpha: string;\n if (rawAlpha.startsWith('$')) {\n const propName = rawAlpha.slice(1);\n alpha = `var(--${propName})`;\n } else {\n alpha = rawAlpha === '0' ? '0' : `.${rawAlpha}`;\n }\n // Normalize function name: rgba->rgb, hsla->hsl (modern syntax doesn't need 'a' suffix)\n const normalizedFunc = funcName.replace(/a$/i, '').toLowerCase();\n // Normalize to modern syntax: replace top-level commas with spaces\n // Preserves commas inside nested functions like min(), max(), clamp()\n const normalizeArgs = (a: string) => {\n let result = '';\n let depth = 0;\n for (let i = 0; i < a.length; i++) {\n const c = a[i];\n if (c === '(') {\n depth++;\n result += c;\n } else if (c === ')') {\n depth = Math.max(0, depth - 1);\n result += c;\n } else if (c === ',' && depth === 0) {\n // Skip comma and any following whitespace at top level\n while (i + 1 < a.length && /\\s/.test(a[i + 1])) i++;\n result += ' ';\n } else {\n result += c;\n }\n }\n return result;\n };\n // Helper: find last top-level occurrence of a character (ignores parentheses)\n const findLastTopLevel = (str: string, ch: string) => {\n let depth = 0;\n for (let i = str.length - 1; i >= 0; i--) {\n const c = str[i];\n if (c === ')') depth++;\n else if (c === '(') depth = Math.max(0, depth - 1);\n else if (c === ch && depth === 0) return i;\n }\n return -1;\n };\n\n // Check if already has alpha:\n // - Modern syntax: has `/` separator at top level (works with dynamic alpha like var()/calc())\n // - Legacy syntax: function ends with 'a' (rgba, hsla) and has exactly 4 top-level comma-separated values\n const slashIdx = findLastTopLevel(args, '/');\n const hasModernAlpha = slashIdx !== -1;\n\n // Count top-level commas to avoid commas inside nested functions\n let topLevelCommaCount = 0;\n let lastTopLevelComma = -1;\n {\n let depth = 0;\n for (let i = 0; i < args.length; i++) {\n const c = args[i];\n if (c === '(') depth++;\n else if (c === ')') depth = Math.max(0, depth - 1);\n else if (c === ',' && depth === 0) {\n topLevelCommaCount++;\n lastTopLevelComma = i;\n }\n }\n }\n\n const hasLegacyAlpha =\n !hasModernAlpha &&\n /a$/i.test(funcName) &&\n topLevelCommaCount === 3;\n\n const colorArgs =\n hasModernAlpha || hasLegacyAlpha\n ? normalizeArgs(\n hasModernAlpha\n ? args.slice(0, slashIdx).trim()\n : args.slice(0, lastTopLevelComma).trim(),\n )\n : normalizeArgs(args);\n\n const constructed = `${normalizedFunc}(${colorArgs} / ${alpha})`;\n\n // Custom functions (not native CSS) must be re-classified\n // so the function handler can convert them to valid CSS\n if (\n !COLOR_FUNCS.has(normalizedFunc) &&\n opts.funcs &&\n normalizedFunc in opts.funcs\n ) {\n return classify(constructed, opts, recurse);\n }\n\n return { bucket: Bucket.Color, processed: constructed };\n }\n\n // Fallback: try appending .alpha (may not work for all cases)\n return classify(`${resolvedValue}.${rawAlpha}`, opts, recurse);\n }\n }\n }\n }\n }\n\n // 0. Direct var(--*-color) token\n const varColorMatch = token.match(/^var\\(--([a-z0-9-]+)-color\\)$/);\n if (varColorMatch) {\n return { bucket: Bucket.Color, processed: token };\n }\n\n // 1. URL\n if (token.startsWith('url(')) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 2. Custom property\n if (token[0] === '$') {\n const identMatch = token.match(/^\\$([a-z_][a-z0-9-_]*)$/);\n if (identMatch) {\n const name = identMatch[1];\n const processed = `var(--${name})`;\n const bucketType = name.endsWith('-color') ? Bucket.Color : Bucket.Value;\n return {\n bucket: bucketType,\n processed,\n };\n }\n // invalid custom property → modifier\n }\n\n // 3. Hash colors (with optional alpha suffix e.g., #purple.5 or #purple.$disabled)\n if (token[0] === '#' && token.length > 1) {\n // alpha form: #name.alpha or #name.$prop\n const alphaMatch = token.match(\n /^#([a-z0-9-]+)\\.(\\$[a-z_][a-z0-9-_]*|[0-9]+)$/i,\n );\n if (alphaMatch) {\n const [, base, rawAlpha] = alphaMatch;\n let alpha: string;\n if (rawAlpha.startsWith('$')) {\n // Custom property: $disabled -> var(--disabled)\n const propName = rawAlpha.slice(1);\n alpha = `var(--${propName})`;\n } else if (rawAlpha === '0') {\n alpha = '0';\n } else {\n alpha = `.${rawAlpha}`;\n }\n return {\n bucket: Bucket.Color,\n processed: `rgb(var(--${base}-color-rgb) / ${alpha})`,\n };\n }\n\n // hyphenated names like #dark-05 should keep full name\n\n const name = token.slice(1);\n // valid hex → treat as hex literal with fallback\n if (RE_HEX.test(name)) {\n return {\n bucket: Bucket.Color,\n processed: `var(--${name}-color, #${name})`,\n };\n }\n // simple color name token → css variable lookup with rgb fallback\n return { bucket: Bucket.Color, processed: `var(--${name}-color)` };\n }\n\n // 4 & 5. Functions\n const openIdx = token.indexOf('(');\n if (openIdx > 0 && token.endsWith(')')) {\n const fname = token.slice(0, openIdx);\n const inner = token.slice(openIdx + 1, -1); // without ()\n\n if (COLOR_FUNCS.has(fname)) {\n // Process inner to expand nested colors or units.\n const argProcessed = recurse(inner).output.replace(/,\\s+/g, ','); // color funcs expect no spaces after commas\n return { bucket: Bucket.Color, processed: `${fname}(${argProcessed})` };\n }\n\n // user function (provided via opts)\n if (opts.funcs && fname in opts.funcs) {\n // split by top-level commas within inner\n const tmp = new StyleParser(opts).process(inner); // fresh parser w/ same opts but no cache share issues\n const funcResult = opts.funcs[fname](tmp.groups);\n // Re-classify the result to determine proper bucket (e.g., if it returns a color)\n // Pass funcs: undefined to prevent infinite recursion if result matches a function pattern\n return classify(funcResult, { ...opts, funcs: undefined }, recurse);\n }\n\n // generic: process inner and rebuild\n const argProcessed = recurse(inner).output;\n return { bucket: Bucket.Value, processed: `${fname}(${argProcessed})` };\n }\n\n // 6. Color fallback syntax: (#name, fallback)\n if (token.startsWith('(') && token.endsWith(')')) {\n const inner = token.slice(1, -1);\n const colorMatch = inner.match(/^#([a-z0-9-]+)\\s*,\\s*(.*)$/i);\n if (colorMatch) {\n const [, name, fallback] = colorMatch;\n const processedFallback = recurse(fallback).output;\n return {\n bucket: Bucket.Color,\n processed: `var(--${name}-color, ${processedFallback})`,\n };\n }\n }\n\n // 7. Custom property with fallback syntax: ($prop, fallback)\n if (token.startsWith('(') && token.endsWith(')')) {\n const inner = token.slice(1, -1);\n const match = inner.match(/^\\$([a-z_][a-z0-9-_]*)\\s*,\\s*(.*)$/);\n if (match) {\n const [, name, fallback] = match;\n const processedFallback = recurse(fallback).output;\n const bucketType = name.endsWith('-color') ? Bucket.Color : Bucket.Value;\n return {\n bucket: bucketType,\n processed: `var(--${name}, ${processedFallback})`,\n };\n }\n }\n\n // 8. Auto-calc group\n if (token[0] === '(' && token[token.length - 1] === ')') {\n const inner = token.slice(1, -1);\n const innerProcessed = recurse(inner).output;\n return { bucket: Bucket.Value, processed: `calc(${innerProcessed})` };\n }\n\n // 9. Unit number\n const um = token.match(RE_UNIT_NUM);\n if (um) {\n const unit = um[1];\n const numericPart = parseFloat(token.slice(0, -unit.length));\n const handler = opts.units && opts.units[unit];\n if (handler) {\n if (typeof handler === 'string') {\n // Check if this is a raw CSS unit (e.g., \"8px\", \"1rem\")\n const rawMatch = handler.match(RE_RAW_UNIT);\n if (rawMatch) {\n // Raw unit: calculate directly instead of using calc()\n const [, baseNum, cssUnit] = rawMatch;\n const result = numericPart * parseFloat(baseNum);\n const processed = `${result}${cssUnit}`;\n // Re-parse to resolve any nested units (e.g., units referencing other units)\n const resolved = resolveUntilStable(processed, opts, recurse);\n return { bucket: Bucket.Value, processed: resolved };\n }\n\n // Non-raw handler (e.g., \"var(--gap)\", \"calc(...)\"): use calc() wrapping\n const base = handler;\n if (numericPart === 1) {\n return { bucket: Bucket.Value, processed: base };\n }\n return {\n bucket: Bucket.Value,\n processed: `calc(${numericPart} * ${base})`,\n };\n } else {\n // Function units return complete CSS expressions, no wrapping needed\n const inner = handler(numericPart);\n return {\n bucket: Bucket.Value,\n processed: inner,\n };\n }\n }\n }\n\n // 9b. Unknown numeric+unit → treat as literal value (e.g., 1fr)\n if (/^[+-]?(?:\\d*\\.\\d+|\\d+)[a-z%]+$/.test(token)) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 9c. Plain unit-less numbers should be treated as value tokens (e.g.,\n // numeric arguments in custom style handlers).\n if (RE_NUMBER.test(token)) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 10. Literal value keywords\n if (VALUE_KEYWORDS.has(token)) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 10b. Special keyword colors\n if (token === 'transparent' || token === 'currentcolor') {\n return { bucket: Bucket.Color, processed: token };\n }\n\n // 11. Fallback modifier\n return { bucket: Bucket.Mod, processed: token };\n}\n"],"mappings":";;;;;;;;;;;AAmBA,SAAS,mBACP,OACA,MACA,SACA,gBAAgB,IACR;CACR,IAAI,UAAU;AACd,MAAK,IAAI,IA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EAAK,WAAW;EAAO"}
@@ -141,14 +141,31 @@ function pseudoToParsed(state) {
141
141
  };
142
142
  }
143
143
  /**
144
- * Convert parsed pseudo to CSS selector string (for final output)
144
+ * Convert parsed pseudo to CSS selector string (for final output).
145
+ *
146
+ * :not() is normalized to negated :is() at parse time, so pseudo.pseudo
147
+ * never starts with ':not(' here. When negated:
148
+ * - :is(X) → :not(X) (unwrap :is)
149
+ * - :where(X) → :not(X) (unwrap :where)
150
+ * - :has(X) → :not(:has(X))
151
+ * - other → :not(other)
152
+ *
153
+ * When not negated, single-argument :is()/:where() is unwrapped when the
154
+ * inner content is a simple compound selector that can safely append to
155
+ * the base selector (this happens after double-negation of :not()).
145
156
  */
146
157
  function pseudoToCSS(pseudo) {
158
+ const p = pseudo.pseudo;
147
159
  if (pseudo.negated) {
148
- if (pseudo.pseudo.startsWith(":not(")) return pseudo.pseudo.slice(5, -1);
149
- return `:not(${pseudo.pseudo})`;
160
+ if (p.startsWith(":is(") || p.startsWith(":where(")) return `:not(${p.slice(p.indexOf("(") + 1, -1)})`;
161
+ return `:not(${p})`;
162
+ }
163
+ if ((p.startsWith(":is(") || p.startsWith(":where(")) && !p.includes(",")) {
164
+ const inner = p.slice(p.indexOf("(") + 1, -1);
165
+ const ch = inner[0];
166
+ if ((ch === ":" || ch === "." || ch === "[" || ch === "#") && !/\s/.test(inner)) return inner;
150
167
  }
151
- return pseudo.pseudo;
168
+ return p;
152
169
  }
153
170
  /**
154
171
  * Convert media condition to parsed structure(s)
@@ -276,11 +293,12 @@ function innerConditionToVariants(innerCondition, negated, target) {
276
293
  };
277
294
  }
278
295
  /**
279
- * Convert a @parent() inner condition into SelectorVariants with ParentGroups.
296
+ * Convert a @parent() inner condition into a single SelectorVariant with
297
+ * one ParentGroup whose branches represent the inner OR alternatives.
280
298
  *
281
- * Positive: each inner OR branch becomes a separate variant with one :is() group.
282
- * Negated: !(A | B) = !A & !B all branches become :not() groups collected
283
- * into a single variant so they produce :not([a] *):not([b] *) on one element.
299
+ * Both positive and negated cases produce one variant with one group.
300
+ * Negation simply sets the `negated` flag, which swaps :is() for :not()
301
+ * in the final CSS output no structural transformation is needed.
284
302
  */
285
303
  function parentConditionToVariants(innerCondition, negated, direct) {
286
304
  const innerCSS = conditionToCSS(innerCondition);
@@ -288,44 +306,23 @@ function parentConditionToVariants(innerCondition, negated, direct) {
288
306
  variants: [],
289
307
  isImpossible: true
290
308
  };
291
- if (negated) {
292
- const v = emptyVariant();
293
- for (const innerVariant of innerCSS.variants) {
294
- const conditions = collectSelectorConditions(innerVariant);
295
- if (conditions.length > 0) v.parentGroups.push({
296
- conditions,
297
- direct,
298
- negated: true
299
- });
300
- }
301
- if (v.parentGroups.length === 0) return {
302
- variants: [emptyVariant()],
303
- isImpossible: false
304
- };
305
- return {
306
- variants: [v],
307
- isImpossible: false
308
- };
309
- }
310
- const variants = [];
309
+ const branches = [];
311
310
  for (const innerVariant of innerCSS.variants) {
312
311
  const conditions = collectSelectorConditions(innerVariant);
313
- if (conditions.length > 0) {
314
- const v = emptyVariant();
315
- v.parentGroups.push({
316
- conditions,
317
- direct,
318
- negated: false
319
- });
320
- variants.push(v);
321
- }
312
+ if (conditions.length > 0) branches.push(conditions);
322
313
  }
323
- if (variants.length === 0) return {
314
+ if (branches.length === 0) return {
324
315
  variants: [emptyVariant()],
325
316
  isImpossible: false
326
317
  };
318
+ const v = emptyVariant();
319
+ v.parentGroups.push({
320
+ branches,
321
+ direct,
322
+ negated
323
+ });
327
324
  return {
328
- variants,
325
+ variants: [v],
329
326
  isImpossible: false
330
327
  };
331
328
  }
@@ -346,10 +343,13 @@ function parentGroupsToCSS(groups) {
346
343
  let result = "";
347
344
  for (const group of groups) {
348
345
  const combinator = group.direct ? " > *" : " *";
349
- let parts = "";
350
- for (const cond of group.conditions) parts += selectorConditionToCSS(cond);
346
+ const selectorArgs = group.branches.map((branch) => {
347
+ let parts = "";
348
+ for (const cond of branch) parts += selectorConditionToCSS(cond);
349
+ return parts + combinator;
350
+ });
351
351
  const wrapper = group.negated ? ":not" : ":is";
352
- result += `${wrapper}(${parts}${combinator})`;
352
+ result += `${wrapper}(${selectorArgs.join(", ")})`;
353
353
  }
354
354
  return result;
355
355
  }
@@ -459,10 +459,18 @@ function hasSelectorConditionContradiction(conditions) {
459
459
  * with opposite negation. E.g. :not([data-hovered] *) and :is([data-hovered] *)
460
460
  * in the same variant is impossible.
461
461
  */
462
+ function getBranchesKey(branches) {
463
+ if (branches.length === 1) {
464
+ const b = branches[0];
465
+ if (b.length === 1) return getSelectorConditionKey(b[0]);
466
+ return b.map(getSelectorConditionKey).sort().join("+");
467
+ }
468
+ return branches.map((b) => b.map(getSelectorConditionKey).sort().join("+")).sort().join(",");
469
+ }
462
470
  function hasParentGroupContradiction(groups) {
463
471
  const byBaseKey = /* @__PURE__ */ new Map();
464
472
  for (const g of groups) {
465
- const baseKey = `${g.direct ? ">" : ""}(${g.conditions.map(getSelectorConditionKey).sort().join(",")})`;
473
+ const baseKey = `${g.direct ? ">" : ""}(${getBranchesKey(g.branches)})`;
466
474
  const existing = byBaseKey.get(baseKey);
467
475
  if (existing !== void 0 && existing !== !g.negated) return true;
468
476
  byBaseKey.set(baseKey, !g.negated);
@@ -649,6 +657,12 @@ function getVariantKey(v) {
649
657
  return key;
650
658
  }
651
659
  /**
660
+ * Total number of leaf conditions in a variant (for superset / dedup comparisons).
661
+ */
662
+ function variantConditionCount(v) {
663
+ return v.modifierConditions.length + v.pseudoConditions.length + v.ownConditions.length + v.mediaConditions.length + v.containerConditions.length + v.supportsConditions.length + v.rootConditions.length + v.parentGroups.reduce((sum, g) => sum + g.branches.reduce((s, b) => s + b.length, 0), 0);
664
+ }
665
+ /**
652
666
  * Check if variant A is a superset of variant B (A is more restrictive)
653
667
  *
654
668
  * If A has all of B's conditions plus more, then A is redundant
@@ -669,8 +683,7 @@ function isVariantSuperset(a, b) {
669
683
  if (!isPseudoConditionsSuperset(a.pseudoConditions, b.pseudoConditions)) return false;
670
684
  if (!isSelectorConditionsSuperset(a.ownConditions, b.ownConditions)) return false;
671
685
  if (!isParentGroupsSuperset(a.parentGroups, b.parentGroups)) return false;
672
- const parentConditionCount = (groups) => groups.reduce((sum, g) => sum + g.conditions.length, 0);
673
- return a.mediaConditions.length + a.containerConditions.length + a.supportsConditions.length + a.modifierConditions.length + a.pseudoConditions.length + a.rootConditions.length + parentConditionCount(a.parentGroups) + a.ownConditions.length > b.mediaConditions.length + b.containerConditions.length + b.supportsConditions.length + b.modifierConditions.length + b.pseudoConditions.length + b.rootConditions.length + parentConditionCount(b.parentGroups) + b.ownConditions.length;
686
+ return variantConditionCount(a) > variantConditionCount(b);
674
687
  }
675
688
  /**
676
689
  * Generic superset check: true if every item in B has a matching key in A.
@@ -706,7 +719,7 @@ function isParentGroupsSuperset(a, b) {
706
719
  return isConditionsSuperset(a, b, getParentGroupKey);
707
720
  }
708
721
  function getParentGroupKey(g) {
709
- return `${g.negated ? "!" : ""}${g.direct ? ">" : ""}(${g.conditions.map(getSelectorConditionKey).sort().join(",")})`;
722
+ return `${g.negated ? "!" : ""}${g.direct ? ">" : ""}(${getBranchesKey(g.branches)})`;
710
723
  }
711
724
  /**
712
725
  * Deduplicate variants
@@ -725,7 +738,6 @@ function dedupeVariants(variants) {
725
738
  result.push(v);
726
739
  }
727
740
  }
728
- const variantConditionCount = (v) => v.modifierConditions.length + v.pseudoConditions.length + v.ownConditions.length + v.mediaConditions.length + v.containerConditions.length + v.supportsConditions.length + v.rootConditions.length + v.parentGroups.reduce((sum, g) => sum + g.conditions.length, 0);
729
741
  result.sort((a, b) => variantConditionCount(a) - variantConditionCount(b));
730
742
  const filtered = [];
731
743
  for (const candidate of result) {