@tenphi/tasty 0.12.0 → 0.13.1

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.
Files changed (41) hide show
  1. package/dist/chunks/cacheKey.js +16 -8
  2. package/dist/chunks/cacheKey.js.map +1 -1
  3. package/dist/chunks/renderChunk.js +31 -32
  4. package/dist/chunks/renderChunk.js.map +1 -1
  5. package/dist/config.d.ts +1 -1
  6. package/dist/config.js +6 -3
  7. package/dist/config.js.map +1 -1
  8. package/dist/core/index.d.ts +3 -3
  9. package/dist/core/index.js +3 -3
  10. package/dist/hooks/useStyles.js +4 -3
  11. package/dist/hooks/useStyles.js.map +1 -1
  12. package/dist/index.d.ts +3 -3
  13. package/dist/index.js +3 -3
  14. package/dist/pipeline/index.d.ts +1 -1
  15. package/dist/pipeline/index.js +24 -14
  16. package/dist/pipeline/index.js.map +1 -1
  17. package/dist/pipeline/materialize.js +328 -79
  18. package/dist/pipeline/materialize.js.map +1 -1
  19. package/dist/pipeline/parseStateKey.d.ts +1 -1
  20. package/dist/pipeline/parseStateKey.js +2 -6
  21. package/dist/pipeline/parseStateKey.js.map +1 -1
  22. package/dist/states/index.js +10 -257
  23. package/dist/states/index.js.map +1 -1
  24. package/dist/tasty.d.ts +58 -58
  25. package/dist/tasty.js +23 -10
  26. package/dist/tasty.js.map +1 -1
  27. package/dist/utils/cache-wrapper.js +4 -8
  28. package/dist/utils/cache-wrapper.js.map +1 -1
  29. package/dist/utils/has-keys.js +13 -0
  30. package/dist/utils/has-keys.js.map +1 -0
  31. package/dist/utils/mod-attrs.js +1 -1
  32. package/dist/utils/styles.d.ts +1 -64
  33. package/dist/utils/styles.js +7 -319
  34. package/dist/utils/styles.js.map +1 -1
  35. package/dist/zero/babel.d.ts +8 -0
  36. package/dist/zero/babel.js +18 -3
  37. package/dist/zero/babel.js.map +1 -1
  38. package/dist/zero/next.js +14 -1
  39. package/dist/zero/next.js.map +1 -1
  40. package/docs/tasty-static.md +6 -7
  41. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"useStyles.js","names":[],"sources":["../../src/hooks/useStyles.ts"],"sourcesContent":["import { useContext, useInsertionEffect, useMemo, useRef } from 'react';\n\nimport {\n categorizeStyleKeys,\n CHUNK_NAMES,\n generateChunkCacheKey,\n renderStylesForChunk,\n} from '../chunks';\nimport { getConfig, getGlobalKeyframes, hasGlobalKeyframes } from '../config';\nimport { allocateClassName, inject, keyframes, property } from '../injector';\nimport type { KeyframesSteps } from '../injector/types';\nimport {\n extractAnimationNamesFromStyles,\n extractLocalKeyframes,\n filterUsedKeyframes,\n hasLocalKeyframes,\n mergeKeyframes,\n replaceAnimationNames,\n} from '../keyframes';\nimport type { RenderResult } from '../pipeline';\nimport { extractLocalProperties, hasLocalProperties } from '../properties';\nimport { collectAutoInferredProperties } from '../ssr/collect-auto-properties';\nimport type { ServerStyleCollector } from '../ssr/collector';\nimport { TastySSRContext } from '../ssr/context';\nimport { formatKeyframesCSS } from '../ssr/format-keyframes';\nimport { formatPropertyCSS } from '../ssr/format-property';\nimport { getRegisteredSSRCollector } from '../ssr/ssr-collector-ref';\nimport type { Styles } from '../styles/types';\nimport { resolveRecipes } from '../utils/resolve-recipes';\nimport { stringifyStyles } from '../utils/styles';\n\n/**\n * Check if styles contain @starting-style rules.\n *\n * @starting-style CSS cannot be applied via multiple class names because\n * of cascade - later rules override earlier ones. When @starting is detected,\n * we combine top-level styles into a single chunk but keep sub-element styles\n * in their own chunk for better caching.\n */\nfunction containsStartingStyle(styleKey: string): boolean {\n return styleKey.includes('@starting');\n}\n\n/**\n * Tasty styles object to generate CSS classes for.\n * Can be undefined or empty object for no styles.\n */\nexport type UseStylesOptions = Styles | undefined;\n\nexport interface UseStylesResult {\n /**\n * Generated className(s) to apply to the element.\n * Can be empty string if no styles are provided.\n * With chunking enabled, may contain multiple space-separated class names.\n */\n className: string;\n}\n\n/**\n * Information about a processed chunk\n */\ninterface ProcessedChunk {\n name: string;\n styleKeys: string[];\n cacheKey: string;\n renderResult: RenderResult;\n className: string;\n}\n\n/**\n * Render, cache-key, and allocate a className for a single chunk.\n * Returns a ProcessedChunk, or null if the chunk produces no CSS rules.\n *\n * Always runs the pipeline and calls allocateClassName. The inject()\n * call in useInsertionEffect handles all edge cases: placeholders from\n * abandoned concurrent renders, hydration hits (ruleIndex -2), and\n * runtime cache hits (already injected). The pipeline's own LRU cache\n * makes repeated calls for identical styles cheap.\n */\nfunction processChunk(\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n): ProcessedChunk | null {\n if (styleKeys.length === 0) return null;\n\n const renderResult = renderStylesForChunk(styles, chunkName, styleKeys);\n if (renderResult.rules.length === 0) return null;\n\n const cacheKey = generateChunkCacheKey(styles, chunkName, styleKeys);\n const { className } = allocateClassName(cacheKey);\n\n return { name: chunkName, styleKeys, cacheKey, renderResult, className };\n}\n\n/**\n * Merge chunk map entries for @starting-style partial chunking.\n *\n * All non-subcomponent chunks are merged into a single COMBINED entry,\n * while SUBCOMPONENTS stays separate. This preserves CSS cascade for\n * @starting-style while still allowing sub-element styles to cache independently.\n */\nfunction mergeChunksForStartingStyle(\n chunkMap: Map<string, string[]>,\n): Map<string, string[]> {\n const merged = new Map<string, string[]>();\n const combinedKeys: string[] = [];\n\n for (const [chunkName, keys] of chunkMap) {\n if (chunkName === CHUNK_NAMES.SUBCOMPONENTS) {\n merged.set(CHUNK_NAMES.SUBCOMPONENTS, keys);\n } else {\n combinedKeys.push(...keys);\n }\n }\n\n if (combinedKeys.length > 0) {\n // Insert COMBINED first so it appears before SUBCOMPONENTS\n const result = new Map<string, string[]>();\n result.set(CHUNK_NAMES.COMBINED, combinedKeys);\n for (const [k, v] of merged) {\n result.set(k, v);\n }\n return result;\n }\n\n return merged;\n}\n\n/**\n * Get keyframes that are actually used in styles.\n * Returns null if no keyframes are used (fast path for zero overhead).\n *\n * Optimization order:\n * 1. Check if any keyframes are defined (local or global) - if not, return null\n * 2. Extract animation names from styles - if none, return null\n * 3. Merge and filter keyframes to only used ones\n */\nfunction getUsedKeyframes(\n styles: Styles,\n): Record<string, KeyframesSteps> | null {\n // Fast path: no keyframes defined anywhere\n const hasLocal = hasLocalKeyframes(styles);\n const hasGlobal = hasGlobalKeyframes();\n if (!hasLocal && !hasGlobal) return null;\n\n // Extract animation names from styles (not from rendered CSS - faster)\n const usedNames = extractAnimationNamesFromStyles(styles);\n if (usedNames.size === 0) return null;\n\n // Merge local and global keyframes\n const local = hasLocal ? extractLocalKeyframes(styles) : null;\n const global = hasGlobal ? getGlobalKeyframes() : null;\n const allKeyframes = mergeKeyframes(local, global);\n\n // Filter to only used keyframes\n return filterUsedKeyframes(allKeyframes, usedNames);\n}\n\n/**\n * Resolve the SSR collector from React context or AsyncLocalStorage.\n * Returns null on the client (no collector available).\n */\nfunction resolveSSRCollector(\n reactContext: ServerStyleCollector | null,\n): ServerStyleCollector | null {\n if (reactContext) return reactContext;\n\n const alsCollector = getRegisteredSSRCollector();\n if (alsCollector) return alsCollector;\n\n return null;\n}\n\n/**\n * Process a chunk on the SSR path: allocate via collector, render, collect CSS.\n * Returns null if the chunk produces no CSS rules.\n */\nfunction processChunkSSR(\n collector: ServerStyleCollector,\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n): ProcessedChunk | null {\n if (styleKeys.length === 0) return null;\n\n const cacheKey = generateChunkCacheKey(styles, chunkName, styleKeys);\n const { className, isNewAllocation } = collector.allocateClassName(cacheKey);\n\n if (isNewAllocation) {\n const renderResult = renderStylesForChunk(styles, chunkName, styleKeys);\n if (renderResult.rules.length > 0) {\n collector.collectChunk(cacheKey, className, renderResult.rules);\n return {\n name: chunkName,\n styleKeys,\n cacheKey,\n renderResult,\n className,\n };\n }\n return null;\n }\n\n return {\n name: chunkName,\n styleKeys,\n cacheKey,\n renderResult: { rules: [] },\n className,\n };\n}\n\n/**\n * Hook to generate CSS classes from Tasty styles.\n * Handles style rendering, className allocation, and CSS injection.\n *\n * SSR-aware: when a ServerStyleCollector is available (via React context\n * or AsyncLocalStorage), CSS is collected during the render phase instead\n * of being injected into the DOM. useInsertionEffect does not run on the\n * server, so the collector path is the only active path during SSR.\n *\n * Uses chunking to split styles into logical groups for better caching\n * and CSS reuse across components.\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { className } = useStyles({\n * padding: '2x',\n * fill: '#purple',\n * radius: '1r',\n * });\n *\n * return <div className={className}>Styled content</div>;\n * }\n * ```\n */\nexport function useStyles(styles: UseStylesOptions): UseStylesResult {\n const ssrContextValue = useContext(TastySSRContext);\n const ssrCollector = resolveSSRCollector(ssrContextValue);\n\n // Array of dispose functions for each chunk\n const disposeRef = useRef<(() => void)[]>([]);\n\n // Store styles by their stringified key to avoid recomputing when only reference changes\n const stylesRef = useRef<{ key: string; styles: Styles | undefined }>({\n key: '',\n styles: undefined,\n });\n\n // Resolve recipes before any processing (zero overhead if no recipes configured)\n const resolvedStyles = useMemo(() => {\n if (!styles) return styles;\n return resolveRecipes(styles);\n }, [styles]);\n\n // Compute style key - this is a primitive string that captures style content\n const styleKey = useMemo(() => {\n if (!resolvedStyles || Object.keys(resolvedStyles).length === 0) {\n return '';\n }\n return stringifyStyles(resolvedStyles);\n }, [resolvedStyles]);\n\n // Update ref when styleKey changes (content actually changed)\n if (stylesRef.current.key !== styleKey) {\n stylesRef.current = { key: styleKey, styles: resolvedStyles };\n }\n\n // Process chunks: categorize, generate cache keys, render, and allocate classNames\n // Only depends on styleKey (primitive), not styles object reference\n const processedChunks: ProcessedChunk[] = useMemo(() => {\n const currentStyles = stylesRef.current.styles;\n if (!styleKey || !currentStyles) {\n return [];\n }\n\n // Categorize style keys into chunks\n let chunkMap = categorizeStyleKeys(\n currentStyles as Record<string, unknown>,\n );\n\n // Partial chunking for styles containing @starting-style rules.\n // @starting-style CSS cannot work with multiple class names due to cascade,\n // so we merge all top-level chunks into one but keep sub-element styles separate.\n if (containsStartingStyle(styleKey)) {\n chunkMap = mergeChunksForStartingStyle(chunkMap);\n }\n\n const chunks: ProcessedChunk[] = [];\n\n if (ssrCollector) {\n // Ensure internal @property and :root token CSS is included\n ssrCollector.collectInternals();\n\n // SERVER PATH: allocate via collector, collect CSS\n for (const [chunkName, chunkStyleKeys] of chunkMap) {\n const chunk = processChunkSSR(\n ssrCollector,\n currentStyles,\n chunkName,\n chunkStyleKeys,\n );\n if (chunk) chunks.push(chunk);\n }\n\n // Collect keyframes on the server\n const usedKeyframes = getUsedKeyframes(currentStyles);\n if (usedKeyframes) {\n for (const [name, steps] of Object.entries(usedKeyframes)) {\n const css = formatKeyframesCSS(name, steps);\n ssrCollector.collectKeyframes(name, css);\n }\n }\n\n // Collect explicit @property rules on the server\n if (hasLocalProperties(currentStyles)) {\n const localProperties = extractLocalProperties(currentStyles);\n if (localProperties) {\n for (const [token, definition] of Object.entries(localProperties)) {\n const css = formatPropertyCSS(token, definition);\n if (css) {\n ssrCollector.collectProperty(token, css);\n }\n }\n }\n }\n\n // Auto-infer @property types from rendered declarations (SSR).\n // On the client this happens inside StyleInjector.inject(), which\n // runs in useInsertionEffect and therefore never executes on the server.\n if (getConfig().autoPropertyTypes !== false) {\n const allRules = chunks.flatMap((c) => c.renderResult.rules);\n if (allRules.length > 0) {\n collectAutoInferredProperties(allRules, ssrCollector, currentStyles);\n }\n }\n } else {\n // CLIENT PATH: unchanged behavior\n for (const [chunkName, chunkStyleKeys] of chunkMap) {\n const chunk = processChunk(currentStyles, chunkName, chunkStyleKeys);\n if (chunk) chunks.push(chunk);\n }\n }\n\n return chunks;\n }, [styleKey]);\n\n // Inject styles in insertion effect (avoids render phase side effects).\n // Does NOT run on the server — the SSR path above handles collection.\n useInsertionEffect(() => {\n // Cleanup all previous disposals\n disposeRef.current.forEach((dispose) => dispose?.());\n disposeRef.current = [];\n\n // Fast path: no chunks to inject\n if (processedChunks.length === 0) {\n return;\n }\n\n const currentStyles = stylesRef.current.styles;\n\n // Register explicit @properties first so they take precedence over auto-inference\n // that happens during keyframe and style chunk injection.\n // Token formats: $name → --name, #name → --name-color (with auto syntax: '<color>')\n // Note: Global properties are injected once when styles are first generated (see markStylesGenerated)\n if (currentStyles && hasLocalProperties(currentStyles)) {\n const localProperties = extractLocalProperties(currentStyles);\n if (localProperties) {\n for (const [token, definition] of Object.entries(localProperties)) {\n property(token, definition);\n }\n }\n }\n\n // Get keyframes that are actually used (returns null if none - zero overhead)\n const usedKeyframes = currentStyles\n ? getUsedKeyframes(currentStyles)\n : null;\n\n // Inject keyframes and build name map (only if we have keyframes)\n let nameMap: Map<string, string> | null = null;\n\n if (usedKeyframes) {\n nameMap = new Map();\n for (const [name, steps] of Object.entries(usedKeyframes)) {\n const result = keyframes(steps, { name });\n const injectedName = result.toString();\n // Only add to map if name differs (optimization for replacement check)\n if (injectedName !== name) {\n nameMap.set(name, injectedName);\n }\n disposeRef.current.push(result.dispose);\n }\n // Clear map if no replacements needed\n if (nameMap.size === 0) {\n nameMap = null;\n }\n }\n\n // Inject each chunk\n for (const chunk of processedChunks) {\n if (chunk.renderResult.rules.length > 0) {\n // Replace animation names only if needed\n const rulesToInject = nameMap\n ? chunk.renderResult.rules.map((rule) => ({\n ...rule,\n declarations: replaceAnimationNames(rule.declarations, nameMap!),\n }))\n : chunk.renderResult.rules;\n\n const { dispose } = inject(rulesToInject, {\n cacheKey: chunk.cacheKey,\n });\n disposeRef.current.push(dispose);\n }\n }\n\n return () => {\n disposeRef.current.forEach((dispose) => dispose?.());\n disposeRef.current = [];\n };\n }, [processedChunks]);\n\n // Combine all chunk classNames\n const className = useMemo(() => {\n return processedChunks.map((chunk) => chunk.className).join(' ');\n }, [processedChunks]);\n\n return {\n className,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;AAuCA,SAAS,sBAAsB,UAA2B;AACxD,QAAO,SAAS,SAAS,YAAY;;;;;;;;;;;;AAuCvC,SAAS,aACP,QACA,WACA,WACuB;AACvB,KAAI,UAAU,WAAW,EAAG,QAAO;CAEnC,MAAM,eAAe,qBAAqB,QAAQ,WAAW,UAAU;AACvE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CAAC;IACzC,MAAM,eAAe,OAAO,UAAU;AAEtC,QAAI,iBAAiB,KACnB,SAAQ,IAAI,MAAM,aAAa;AAEjC,eAAW,QAAQ,KAAK,OAAO,QAAQ;;AAGzC,OAAI,QAAQ,SAAS,EACnB,WAAU;;AAKd,OAAK,MAAM,SAAS,gBAClB,KAAI,MAAM,aAAa,MAAM,SAAS,GAAG;GASvC,MAAM,EAAE,YAAY,OAPE,UAClB,MAAM,aAAa,MAAM,KAAK,UAAU;IACtC,GAAG;IACH,cAAc,sBAAsB,KAAK,cAAc,QAAS;IACjE,EAAE,GACH,MAAM,aAAa,OAEmB,EACxC,UAAU,MAAM,UACjB,CAAC;AACF,cAAW,QAAQ,KAAK,QAAQ;;AAIpC,eAAa;AACX,cAAW,QAAQ,SAAS,YAAY,WAAW,CAAC;AACpD,cAAW,UAAU,EAAE;;IAExB,CAAC,gBAAgB,CAAC;AAOrB,QAAO,EACL,WALgB,cAAc;AAC9B,SAAO,gBAAgB,KAAK,UAAU,MAAM,UAAU,CAAC,KAAK,IAAI;IAC/D,CAAC,gBAAgB,CAAC,EAIpB"}
1
+ {"version":3,"file":"useStyles.js","names":[],"sources":["../../src/hooks/useStyles.ts"],"sourcesContent":["import { useContext, useInsertionEffect, useMemo, useRef } from 'react';\n\nimport {\n categorizeStyleKeys,\n CHUNK_NAMES,\n generateChunkCacheKey,\n renderStylesForChunk,\n} from '../chunks';\nimport { getConfig, getGlobalKeyframes, hasGlobalKeyframes } from '../config';\nimport { allocateClassName, inject, keyframes, property } from '../injector';\nimport type { KeyframesSteps } from '../injector/types';\nimport {\n extractAnimationNamesFromStyles,\n extractLocalKeyframes,\n filterUsedKeyframes,\n hasLocalKeyframes,\n mergeKeyframes,\n replaceAnimationNames,\n} from '../keyframes';\nimport type { RenderResult } from '../pipeline';\nimport { extractLocalProperties, hasLocalProperties } from '../properties';\nimport { collectAutoInferredProperties } from '../ssr/collect-auto-properties';\nimport type { ServerStyleCollector } from '../ssr/collector';\nimport { TastySSRContext } from '../ssr/context';\nimport { formatKeyframesCSS } from '../ssr/format-keyframes';\nimport { formatPropertyCSS } from '../ssr/format-property';\nimport { getRegisteredSSRCollector } from '../ssr/ssr-collector-ref';\nimport type { Styles } from '../styles/types';\nimport { hasKeys } from '../utils/has-keys';\nimport { resolveRecipes } from '../utils/resolve-recipes';\nimport { stringifyStyles } from '../utils/styles';\n\n/**\n * Check if styles contain @starting-style rules.\n *\n * @starting-style CSS cannot be applied via multiple class names because\n * of cascade - later rules override earlier ones. When @starting is detected,\n * we combine top-level styles into a single chunk but keep sub-element styles\n * in their own chunk for better caching.\n */\nfunction containsStartingStyle(styleKey: string): boolean {\n return styleKey.includes('@starting');\n}\n\n/**\n * Tasty styles object to generate CSS classes for.\n * Can be undefined or empty object for no styles.\n */\nexport type UseStylesOptions = Styles | undefined;\n\nexport interface UseStylesResult {\n /**\n * Generated className(s) to apply to the element.\n * Can be empty string if no styles are provided.\n * With chunking enabled, may contain multiple space-separated class names.\n */\n className: string;\n}\n\n/**\n * Information about a processed chunk\n */\ninterface ProcessedChunk {\n name: string;\n styleKeys: string[];\n cacheKey: string;\n renderResult: RenderResult;\n className: string;\n}\n\n/**\n * Render, cache-key, and allocate a className for a single chunk.\n * Returns a ProcessedChunk, or null if the chunk produces no CSS rules.\n *\n * Always runs the pipeline and calls allocateClassName. The inject()\n * call in useInsertionEffect handles all edge cases: placeholders from\n * abandoned concurrent renders, hydration hits (ruleIndex -2), and\n * runtime cache hits (already injected). The pipeline's own LRU cache\n * makes repeated calls for identical styles cheap.\n */\nfunction processChunk(\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n): ProcessedChunk | null {\n if (styleKeys.length === 0) return null;\n\n const cacheKey = generateChunkCacheKey(styles, chunkName, styleKeys);\n const renderResult = renderStylesForChunk(\n styles,\n chunkName,\n styleKeys,\n cacheKey,\n );\n if (renderResult.rules.length === 0) return null;\n\n const { className } = allocateClassName(cacheKey);\n\n return { name: chunkName, styleKeys, cacheKey, renderResult, className };\n}\n\n/**\n * Merge chunk map entries for @starting-style partial chunking.\n *\n * All non-subcomponent chunks are merged into a single COMBINED entry,\n * while SUBCOMPONENTS stays separate. This preserves CSS cascade for\n * @starting-style while still allowing sub-element styles to cache independently.\n */\nfunction mergeChunksForStartingStyle(\n chunkMap: Map<string, string[]>,\n): Map<string, string[]> {\n const merged = new Map<string, string[]>();\n const combinedKeys: string[] = [];\n\n for (const [chunkName, keys] of chunkMap) {\n if (chunkName === CHUNK_NAMES.SUBCOMPONENTS) {\n merged.set(CHUNK_NAMES.SUBCOMPONENTS, keys);\n } else {\n combinedKeys.push(...keys);\n }\n }\n\n if (combinedKeys.length > 0) {\n // Insert COMBINED first so it appears before SUBCOMPONENTS\n const result = new Map<string, string[]>();\n result.set(CHUNK_NAMES.COMBINED, combinedKeys);\n for (const [k, v] of merged) {\n result.set(k, v);\n }\n return result;\n }\n\n return merged;\n}\n\n/**\n * Get keyframes that are actually used in styles.\n * Returns null if no keyframes are used (fast path for zero overhead).\n *\n * Optimization order:\n * 1. Check if any keyframes are defined (local or global) - if not, return null\n * 2. Extract animation names from styles - if none, return null\n * 3. Merge and filter keyframes to only used ones\n */\nfunction getUsedKeyframes(\n styles: Styles,\n): Record<string, KeyframesSteps> | null {\n // Fast path: no keyframes defined anywhere\n const hasLocal = hasLocalKeyframes(styles);\n const hasGlobal = hasGlobalKeyframes();\n if (!hasLocal && !hasGlobal) return null;\n\n // Extract animation names from styles (not from rendered CSS - faster)\n const usedNames = extractAnimationNamesFromStyles(styles);\n if (usedNames.size === 0) return null;\n\n // Merge local and global keyframes\n const local = hasLocal ? extractLocalKeyframes(styles) : null;\n const global = hasGlobal ? getGlobalKeyframes() : null;\n const allKeyframes = mergeKeyframes(local, global);\n\n // Filter to only used keyframes\n return filterUsedKeyframes(allKeyframes, usedNames);\n}\n\n/**\n * Resolve the SSR collector from React context or AsyncLocalStorage.\n * Returns null on the client (no collector available).\n */\nfunction resolveSSRCollector(\n reactContext: ServerStyleCollector | null,\n): ServerStyleCollector | null {\n if (reactContext) return reactContext;\n\n const alsCollector = getRegisteredSSRCollector();\n if (alsCollector) return alsCollector;\n\n return null;\n}\n\n/**\n * Process a chunk on the SSR path: allocate via collector, render, collect CSS.\n * Returns null if the chunk produces no CSS rules.\n */\nfunction processChunkSSR(\n collector: ServerStyleCollector,\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n): ProcessedChunk | null {\n if (styleKeys.length === 0) return null;\n\n const cacheKey = generateChunkCacheKey(styles, chunkName, styleKeys);\n const { className, isNewAllocation } = collector.allocateClassName(cacheKey);\n\n if (isNewAllocation) {\n const renderResult = renderStylesForChunk(styles, chunkName, styleKeys);\n if (renderResult.rules.length > 0) {\n collector.collectChunk(cacheKey, className, renderResult.rules);\n return {\n name: chunkName,\n styleKeys,\n cacheKey,\n renderResult,\n className,\n };\n }\n return null;\n }\n\n return {\n name: chunkName,\n styleKeys,\n cacheKey,\n renderResult: { rules: [] },\n className,\n };\n}\n\n/**\n * Hook to generate CSS classes from Tasty styles.\n * Handles style rendering, className allocation, and CSS injection.\n *\n * SSR-aware: when a ServerStyleCollector is available (via React context\n * or AsyncLocalStorage), CSS is collected during the render phase instead\n * of being injected into the DOM. useInsertionEffect does not run on the\n * server, so the collector path is the only active path during SSR.\n *\n * Uses chunking to split styles into logical groups for better caching\n * and CSS reuse across components.\n *\n * @example\n * ```tsx\n * function MyComponent() {\n * const { className } = useStyles({\n * padding: '2x',\n * fill: '#purple',\n * radius: '1r',\n * });\n *\n * return <div className={className}>Styled content</div>;\n * }\n * ```\n */\nexport function useStyles(styles: UseStylesOptions): UseStylesResult {\n const ssrContextValue = useContext(TastySSRContext);\n const ssrCollector = resolveSSRCollector(ssrContextValue);\n\n // Array of dispose functions for each chunk\n const disposeRef = useRef<(() => void)[]>([]);\n\n // Store styles by their stringified key to avoid recomputing when only reference changes\n const stylesRef = useRef<{ key: string; styles: Styles | undefined }>({\n key: '',\n styles: undefined,\n });\n\n // Resolve recipes before any processing (zero overhead if no recipes configured)\n const resolvedStyles = useMemo(() => {\n if (!styles) return styles;\n return resolveRecipes(styles);\n }, [styles]);\n\n // Compute style key - this is a primitive string that captures style content\n const styleKey = useMemo(() => {\n if (!resolvedStyles || !hasKeys(resolvedStyles)) {\n return '';\n }\n return stringifyStyles(resolvedStyles);\n }, [resolvedStyles]);\n\n // Update ref when styleKey changes (content actually changed)\n if (stylesRef.current.key !== styleKey) {\n stylesRef.current = { key: styleKey, styles: resolvedStyles };\n }\n\n // Process chunks: categorize, generate cache keys, render, and allocate classNames\n // Only depends on styleKey (primitive), not styles object reference\n const processedChunks: ProcessedChunk[] = useMemo(() => {\n const currentStyles = stylesRef.current.styles;\n if (!styleKey || !currentStyles) {\n return [];\n }\n\n // Categorize style keys into chunks\n let chunkMap = categorizeStyleKeys(\n currentStyles as Record<string, unknown>,\n );\n\n // Partial chunking for styles containing @starting-style rules.\n // @starting-style CSS cannot work with multiple class names due to cascade,\n // so we merge all top-level chunks into one but keep sub-element styles separate.\n if (containsStartingStyle(styleKey)) {\n chunkMap = mergeChunksForStartingStyle(chunkMap);\n }\n\n const chunks: ProcessedChunk[] = [];\n\n if (ssrCollector) {\n // Ensure internal @property and :root token CSS is included\n ssrCollector.collectInternals();\n\n // SERVER PATH: allocate via collector, collect CSS\n for (const [chunkName, chunkStyleKeys] of chunkMap) {\n const chunk = processChunkSSR(\n ssrCollector,\n currentStyles,\n chunkName,\n chunkStyleKeys,\n );\n if (chunk) chunks.push(chunk);\n }\n\n // Collect keyframes on the server\n const usedKeyframes = getUsedKeyframes(currentStyles);\n if (usedKeyframes) {\n for (const [name, steps] of Object.entries(usedKeyframes)) {\n const css = formatKeyframesCSS(name, steps);\n ssrCollector.collectKeyframes(name, css);\n }\n }\n\n // Collect explicit @property rules on the server\n if (hasLocalProperties(currentStyles)) {\n const localProperties = extractLocalProperties(currentStyles);\n if (localProperties) {\n for (const [token, definition] of Object.entries(localProperties)) {\n const css = formatPropertyCSS(token, definition);\n if (css) {\n ssrCollector.collectProperty(token, css);\n }\n }\n }\n }\n\n // Auto-infer @property types from rendered declarations (SSR).\n // On the client this happens inside StyleInjector.inject(), which\n // runs in useInsertionEffect and therefore never executes on the server.\n if (getConfig().autoPropertyTypes !== false) {\n const allRules = chunks.flatMap((c) => c.renderResult.rules);\n if (allRules.length > 0) {\n collectAutoInferredProperties(allRules, ssrCollector, currentStyles);\n }\n }\n } else {\n // CLIENT PATH: unchanged behavior\n for (const [chunkName, chunkStyleKeys] of chunkMap) {\n const chunk = processChunk(currentStyles, chunkName, chunkStyleKeys);\n if (chunk) chunks.push(chunk);\n }\n }\n\n return chunks;\n }, [styleKey]);\n\n // Inject styles in insertion effect (avoids render phase side effects).\n // Does NOT run on the server — the SSR path above handles collection.\n useInsertionEffect(() => {\n // Cleanup all previous disposals\n disposeRef.current.forEach((dispose) => dispose?.());\n disposeRef.current = [];\n\n // Fast path: no chunks to inject\n if (processedChunks.length === 0) {\n return;\n }\n\n const currentStyles = stylesRef.current.styles;\n\n // Register explicit @properties first so they take precedence over auto-inference\n // that happens during keyframe and style chunk injection.\n // Token formats: $name → --name, #name → --name-color (with auto syntax: '<color>')\n // Note: Global properties are injected once when styles are first generated (see markStylesGenerated)\n if (currentStyles && hasLocalProperties(currentStyles)) {\n const localProperties = extractLocalProperties(currentStyles);\n if (localProperties) {\n for (const [token, definition] of Object.entries(localProperties)) {\n property(token, definition);\n }\n }\n }\n\n // Get keyframes that are actually used (returns null if none - zero overhead)\n const usedKeyframes = currentStyles\n ? getUsedKeyframes(currentStyles)\n : null;\n\n // Inject keyframes and build name map (only if we have keyframes)\n let nameMap: Map<string, string> | null = null;\n\n if (usedKeyframes) {\n nameMap = new Map();\n for (const [name, steps] of Object.entries(usedKeyframes)) {\n const result = keyframes(steps, { name });\n const injectedName = result.toString();\n // Only add to map if name differs (optimization for replacement check)\n if (injectedName !== name) {\n nameMap.set(name, injectedName);\n }\n disposeRef.current.push(result.dispose);\n }\n // Clear map if no replacements needed\n if (nameMap.size === 0) {\n nameMap = null;\n }\n }\n\n // Inject each chunk\n for (const chunk of processedChunks) {\n if (chunk.renderResult.rules.length > 0) {\n // Replace animation names only if needed\n const rulesToInject = nameMap\n ? chunk.renderResult.rules.map((rule) => ({\n ...rule,\n declarations: replaceAnimationNames(rule.declarations, nameMap!),\n }))\n : chunk.renderResult.rules;\n\n const { dispose } = inject(rulesToInject, {\n cacheKey: chunk.cacheKey,\n });\n disposeRef.current.push(dispose);\n }\n }\n\n return () => {\n disposeRef.current.forEach((dispose) => dispose?.());\n disposeRef.current = [];\n };\n }, [processedChunks]);\n\n // Combine all chunk classNames\n const className = useMemo(() => {\n return processedChunks.map((chunk) => chunk.className).join(' ');\n }, [processedChunks]);\n\n return {\n className,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,SAAS,sBAAsB,UAA2B;AACxD,QAAO,SAAS,SAAS,YAAY;;;;;;;;;;;;AAuCvC,SAAS,aACP,QACA,WACA,WACuB;AACvB,KAAI,UAAU,WAAW,EAAG,QAAO;CAEnC,MAAM,WAAW,sBAAsB,QAAQ,WAAW,UAAU;CACpE,MAAM,eAAe,qBACnB,QACA,WACA,WACA,SACD;AACD,KAAI,aAAa,MAAM,WAAW,EAAG,QAAO;CAE5C,MAAM,EAAE,cAAc,kBAAkB,SAAS;AAEjD,QAAO;EAAE,MAAM;EAAW;EAAW;EAAU;EAAc;EAAW;;;;;;;;;AAU1E,SAAS,4BACP,UACuB;CACvB,MAAM,yBAAS,IAAI,KAAuB;CAC1C,MAAM,eAAyB,EAAE;AAEjC,MAAK,MAAM,CAAC,WAAW,SAAS,SAC9B,KAAI,cAAc,YAAY,cAC5B,QAAO,IAAI,YAAY,eAAe,KAAK;KAE3C,cAAa,KAAK,GAAG,KAAK;AAI9B,KAAI,aAAa,SAAS,GAAG;EAE3B,MAAM,yBAAS,IAAI,KAAuB;AAC1C,SAAO,IAAI,YAAY,UAAU,aAAa;AAC9C,OAAK,MAAM,CAAC,GAA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BAAgB,CAAC;AAOrB,QAAO,EACL,WALgB,cAAc;AAC9B,SAAO,gBAAgB,KAAK,UAAU,MAAM,UAAU,CAAC,KAAK,IAAI;IAC/D,CAAC,gBAAgB,CAAC,EAIpB"}
package/dist/index.d.ts CHANGED
@@ -2,10 +2,10 @@ import { CacheMetrics, DisposeFunction, InjectResult, KeyframesCacheEntry, Keyfr
2
2
  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
- 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, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "./utils/styles.js";
5
+ import { CSSMap, CUSTOM_UNITS, DIRECTIONS, ParsedColor, RawStyleHandler, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleMap, StylePropValue, StyleValue, StyleValueStateMap, customFunc, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getRgbValuesFromRgbaString, hexToRgb, normalizeColorTokenValue, parseColor, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles } from "./utils/styles.js";
7
6
  import { ConfigTokenValue, ConfigTokens, NoType, NotSelector, RecipeStyles, Selector, Styles, StylesInterface, StylesWithoutSelectors, SuffixForSelector, TastyNamedColors, TastyPresetNames } from "./styles/types.js";
8
7
  import { ConditionNode } from "./pipeline/conditions.js";
8
+ import { AtRuleContext, ParsedAdvancedState, StateParserContext, createStateParserContext, getGlobalPredefinedStates, setGlobalPredefinedStates } from "./states/index.js";
9
9
  import { ParseStateKeyOptions, parseStateKey } from "./pipeline/parseStateKey.js";
10
10
  import { RenderResult, StyleResult, isSelector, renderStyles } from "./pipeline/index.js";
11
11
  import { SheetManager } from "./injector/sheet-manager.js";
@@ -43,5 +43,5 @@ declare module './utils/css-types' {
43
43
  interface CSSProperties extends CSSProperties$1 {}
44
44
  }
45
45
  //#endregion
46
- 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, ConfigTokenValue, ConfigTokens, 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, trackRef, useGlobalStyles, useKeyframes, useProperty, useRawCSS, useStyles, warn };
46
+ 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, CONTAINER_STYLES, CSSMap, CSSProperties, CUSTOM_UNITS, CacheMetrics, ChunkInfo, ChunkName, ColorStyleProps, ConditionNode, ConfigTokenValue, ConfigTokens, 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, STYLE_TO_CHUNK, Selector, SheetInfo, SheetManager, ShortGridStyles, StateParserContext, StyleDetails, StyleDetailsPart, StyleHandler, StyleHandlerDefinition, StyleHandlerResult, StyleInjector, StyleInjectorConfig, StyleMap, StyleParser, StylePropValue, StyleResult, StyleRule, 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, categorizeStyleKeys, cleanup, color, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, 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, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, tasty, tastyDebug, trackRef, useGlobalStyles, useKeyframes, useProperty, useRawCSS, useStyles, warn };
47
47
  //# sourceMappingURL=index.d.ts.map
package/dist/index.js CHANGED
@@ -1,13 +1,13 @@
1
1
  import { Bucket } from "./parser/types.js";
2
2
  import { StyleParser } from "./parser/parser.js";
3
3
  import { okhslFunc, okhslPlugin } from "./plugins/okhsl-plugin.js";
4
- import { createStateParserContext, getGlobalPredefinedStates, setGlobalPredefinedStates } from "./states/index.js";
5
4
  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, getRgbValuesFromRgbaString, hexToRgb, isAdvancedStateToken, normalizeColorTokenValue, parseColor, parseStateNotation, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles, styleStateMapToStyleStateDataList } from "./utils/styles.js";
5
+ import { CUSTOM_UNITS, DIRECTIONS, customFunc, filterMods, getGlobalFuncs, getGlobalParser, getGlobalPredefinedTokens, getRgbValuesFromRgbaString, hexToRgb, normalizeColorTokenValue, parseColor, parseStyle, resetGlobalPredefinedTokens, setGlobalPredefinedTokens, strToRgb, stringifyStyles } from "./utils/styles.js";
7
6
  import { deprecationWarning, warn } from "./utils/warnings.js";
8
7
  import { styleHandlers } from "./styles/predefined.js";
9
8
  import { SheetManager } from "./injector/sheet-manager.js";
10
9
  import { StyleInjector } from "./injector/injector.js";
10
+ import { createStateParserContext, getGlobalPredefinedStates, setGlobalPredefinedStates } from "./states/index.js";
11
11
  import { parseStateKey } from "./pipeline/parseStateKey.js";
12
12
  import { isSelector, renderStyles } from "./pipeline/index.js";
13
13
  import { configure, getConfig, getGlobalKeyframes, getGlobalRecipes, hasGlobalKeyframes, hasGlobalRecipes, hasStylesGenerated, isConfigLocked, isTestEnvironment, resetConfig } from "./config.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, 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, trackRef, useGlobalStyles, useKeyframes, useProperty, useRawCSS, useStyles, warn };
33
+ export { BASE_STYLES, BLOCK_INNER_STYLES, BLOCK_OUTER_STYLES, BLOCK_STYLES, Bucket, CHUNK_NAMES, COLOR_STYLES, CONTAINER_STYLES, CUSTOM_UNITS, DIMENSION_STYLES, DIRECTIONS, Element, FLOW_STYLES, INNER_STYLES, OUTER_STYLES, POSITION_STYLES, STYLE_TO_CHUNK, SheetManager, StyleInjector, StyleParser, TEXT_STYLES, allocateClassName, categorizeStyleKeys, cleanup, color, configure, createInjector, createStateParserContext, customFunc, deprecationWarning, destroy, dotize, 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, isConfigLocked, isPropertyDefined, isSelector, isTestEnvironment, keyframes, mergeStyles, _modAttrs as modAttrs, normalizeColorTokenValue, okhslFunc, okhslPlugin, parseColor, parseStateKey, parseStyle, processTokens, property, renderStyles, resetConfig, resetGlobalPredefinedTokens, resolveRecipes, setGlobalPredefinedStates, setGlobalPredefinedTokens, strToRgb, stringifyStyles, stringifyTokens, styleHandlers, tasty, tastyDebug, trackRef, useGlobalStyles, useKeyframes, useProperty, useRawCSS, useStyles, warn };
@@ -46,7 +46,7 @@ interface RenderStylesOptions {
46
46
  * When called without classNameOrSelector, returns RenderResult with needsClassName=true.
47
47
  * When called with a selector/className string, returns StyleResult[] for direct injection.
48
48
  */
49
- declare function renderStyles(styles?: Styles): RenderResult;
49
+ declare function renderStyles(styles?: Styles, classNameOrSelector?: undefined, options?: undefined, pipelineCacheKey?: string): RenderResult;
50
50
  declare function renderStyles(styles: Styles | undefined, classNameOrSelector: string, options?: RenderStylesOptions): StyleResult[];
51
51
  //#endregion
52
52
  export { RenderResult, StyleResult, isSelector, renderStyles };
@@ -1,12 +1,12 @@
1
1
  import { Lru } from "../parser/lru.js";
2
- import { createStateParserContext, extractLocalPredefinedStates } from "../states/index.js";
3
2
  import { stringifyStyles } from "../utils/styles.js";
4
3
  import { createStyle } from "../styles/createStyle.js";
5
4
  import { STYLE_HANDLER_MAP } from "../styles/index.js";
5
+ import { createStateParserContext, extractLocalPredefinedStates } from "../states/index.js";
6
6
  import { and, falseCondition, not, or, trueCondition } from "./conditions.js";
7
7
  import { simplifyCondition } from "./simplify.js";
8
8
  import { buildExclusiveConditions, expandExclusiveOrs, expandOrConditions, isValueMapping, parseStyleEntries } from "./exclusive.js";
9
- import { buildAtRulesFromVariant, conditionToCSS, modifierToCSS, parentGroupsToCSS, pseudoToCSS, rootConditionsToCSS, selectorConditionToCSS } from "./materialize.js";
9
+ import { branchToCSS, buildAtRulesFromVariant, conditionToCSS, mergeVariantsIntoSelectorGroups, optimizeGroups, parentGroupsToCSS, rootGroupsToCSS, selectorGroupToCSS } from "./materialize.js";
10
10
  import { emitWarning } from "./warnings.js";
11
11
  import { parseStateKey } from "./parseStateKey.js";
12
12
 
@@ -28,6 +28,13 @@ import { parseStateKey } from "./parseStateKey.js";
28
28
  */
29
29
  const pipelineCache = new Lru(5e3);
30
30
  /**
31
+ * Check if a cache key exists in the pipeline cache.
32
+ * Used by renderStylesForChunk to avoid building filtered styles on cache hit.
33
+ */
34
+ function hasPipelineCacheEntry(cacheKey) {
35
+ return pipelineCache.get(cacheKey) !== void 0;
36
+ }
37
+ /**
31
38
  * Clear the pipeline cache (for testing)
32
39
  */
33
40
  function clearPipelineCache() {
@@ -38,7 +45,7 @@ function runPipeline(styles, parserContext) {
38
45
  processStyles(styles, "", parserContext, allRules);
39
46
  const seen = /* @__PURE__ */ new Set();
40
47
  return allRules.filter((rule) => {
41
- const key = `${rule.selector}|${rule.declarations}|${JSON.stringify(rule.atRules || [])}|${rule.rootPrefix || ""}`;
48
+ const key = `${rule.selector}|${rule.declarations}|${rule.atRules?.join("|") ?? ""}|${rule.rootPrefix || ""}`;
42
49
  if (seen.has(key)) return false;
43
50
  seen.add(key);
44
51
  return true;
@@ -573,11 +580,12 @@ function mergeByValue(rules) {
573
580
  */
574
581
  function buildSelectorFromVariant(variant, selectorSuffix) {
575
582
  let selector = "";
576
- for (const mod of variant.modifierConditions) selector += modifierToCSS(mod);
577
- for (const pseudo of variant.pseudoConditions) selector += pseudoToCSS(pseudo);
583
+ selector += branchToCSS([...variant.modifierConditions, ...variant.pseudoConditions]);
584
+ for (const group of variant.selectorGroups) selector += selectorGroupToCSS(group);
578
585
  if (variant.parentGroups.length > 0) selector += parentGroupsToCSS(variant.parentGroups);
579
586
  selector += selectorSuffix;
580
- for (const own of variant.ownConditions) selector += selectorConditionToCSS(own);
587
+ const ownOptimized = optimizeGroups(variant.ownGroups);
588
+ for (const group of ownOptimized) selector += selectorGroupToCSS(group);
581
589
  return selector;
582
590
  }
583
591
  /**
@@ -591,7 +599,7 @@ function materializeComputedRule(rule) {
591
599
  if (components.isImpossible || components.variants.length === 0) return [];
592
600
  const declarations = Object.entries(rule.declarations).map(([prop, value]) => `${prop}: ${value};`).join(" ");
593
601
  const getRootPrefixKey = (variant) => {
594
- return variant.rootConditions.map((r) => selectorConditionToCSS(r)).sort().join("|");
602
+ return rootGroupsToCSS(variant.rootGroups) || "";
595
603
  };
596
604
  const byAtRules = /* @__PURE__ */ new Map();
597
605
  for (const variant of components.variants) {
@@ -602,12 +610,12 @@ function materializeComputedRule(rule) {
602
610
  else byAtRules.set(key, {
603
611
  variants: [variant],
604
612
  atRules,
605
- rootPrefix: rootConditionsToCSS(variant.rootConditions)
613
+ rootPrefix: rootGroupsToCSS(variant.rootGroups)
606
614
  });
607
615
  }
608
616
  const rules = [];
609
617
  for (const [, group] of byAtRules) {
610
- const selectorFragments = group.variants.map((v) => buildSelectorFromVariant(v, rule.selectorSuffix));
618
+ const selectorFragments = mergeVariantsIntoSelectorGroups(group.variants).map((v) => buildSelectorFromVariant(v, rule.selectorSuffix));
611
619
  const cssRule = {
612
620
  selector: selectorFragments.length === 1 ? selectorFragments[0] : selectorFragments,
613
621
  declarations
@@ -618,11 +626,13 @@ function materializeComputedRule(rule) {
618
626
  }
619
627
  return rules;
620
628
  }
621
- function renderStyles(styles, classNameOrSelector, options) {
629
+ function renderStyles(styles, classNameOrSelector, options, pipelineCacheKey) {
622
630
  const directSelector = !!classNameOrSelector;
623
- if (!styles) return directSelector ? [] : { rules: [] };
624
- const cacheKey = stringifyStyles(styles);
625
- let rules = pipelineCache.get(cacheKey);
631
+ let rules;
632
+ if (pipelineCacheKey) rules = pipelineCache.get(pipelineCacheKey);
633
+ if (!rules && !styles) return directSelector ? [] : { rules: [] };
634
+ const cacheKey = pipelineCacheKey || stringifyStyles(styles);
635
+ if (!rules) rules = pipelineCache.get(cacheKey);
626
636
  if (!rules) {
627
637
  rules = runPipeline(styles, createStateParserContext(styles));
628
638
  pipelineCache.set(cacheKey, rules);
@@ -656,5 +666,5 @@ function renderStyles(styles, classNameOrSelector, options) {
656
666
  }
657
667
 
658
668
  //#endregion
659
- export { clearPipelineCache, isSelector, renderStyles };
669
+ export { clearPipelineCache, hasPipelineCacheEntry, isSelector, renderStyles };
660
670
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","names":[],"sources":["../../src/pipeline/index.ts"],"sourcesContent":["/**\n * Tasty Style Rendering Pipeline\n *\n * This is the main entrypoint for the new pipeline implementation.\n * It implements the complete flow from style objects to CSS rules.\n *\n * Pipeline stages:\n * 1. PARSE CONDITIONS - Parse state keys into ConditionNode trees\n * 2. BUILD EXCLUSIVE CONDITIONS - AND with negation of higher-priority conditions\n * 3. SIMPLIFY CONDITIONS - Apply boolean algebra, detect contradictions\n * 4. GROUP BY HANDLER - Collect styles per handler, compute combinations\n * 5. COMPUTE CSS VALUES - Call handlers to get CSS declarations\n * 6. MERGE BY VALUE - Merge rules with identical CSS output\n * 7. MATERIALIZE CSS - Convert conditions to CSS selectors + at-rules\n */\n\nimport { Lru } from '../parser/lru';\nimport type { StateParserContext } from '../states';\nimport {\n createStateParserContext,\n extractLocalPredefinedStates,\n} from '../states';\nimport { createStyle, STYLE_HANDLER_MAP } from '../styles';\nimport type { Styles } from '../styles/types';\nimport type {\n StyleHandler,\n StyleMap,\n StyleValue,\n StyleValueStateMap,\n} from '../utils/styles';\nimport { stringifyStyles } from '../utils/styles';\n\nimport type { ConditionNode } from './conditions';\nimport { and, or, trueCondition } from './conditions';\nimport type { ExclusiveStyleEntry } from './exclusive';\nimport {\n buildExclusiveConditions,\n expandExclusiveOrs,\n expandOrConditions,\n isValueMapping,\n parseStyleEntries,\n} from './exclusive';\nimport type { CSSRule, SelectorVariant } from './materialize';\nimport {\n buildAtRulesFromVariant,\n conditionToCSS,\n modifierToCSS,\n parentGroupsToCSS,\n pseudoToCSS,\n rootConditionsToCSS,\n selectorConditionToCSS,\n} from './materialize';\nimport { parseStateKey } from './parseStateKey';\nimport { simplifyCondition } from './simplify';\nimport { emitWarning } from './warnings';\n\n// ============================================================================\n// Types (compatible with old renderStyles API)\n// ============================================================================\n\n/**\n * Matches the old StyleResult interface for backward compatibility\n */\nexport interface StyleResult {\n selector: string;\n declarations: string;\n atRules?: string[];\n needsClassName?: boolean;\n rootPrefix?: string;\n}\n\n/**\n * Matches the old RenderResult interface for backward compatibility\n */\nexport interface RenderResult {\n rules: StyleResult[];\n className?: string;\n}\n\nexport interface PipelineResult {\n rules: CSSRule[];\n className?: string;\n}\n\ninterface ComputedRule {\n condition: ConditionNode;\n declarations: Record<string, string>;\n selectorSuffix: string;\n}\n\n// ============================================================================\n// Caching\n// ============================================================================\n\nconst pipelineCache = new Lru<string, CSSRule[]>(5000);\n\n// ============================================================================\n// Main Pipeline Function\n// ============================================================================\n\n/**\n * Render styles using the new pipeline.\n *\n * This is the main entrypoint that implements the complete flow.\n */\nexport function renderStylesPipeline(\n styles?: Styles,\n className?: string,\n): PipelineResult {\n if (!styles) {\n return { rules: [], className };\n }\n\n // Check cache\n const cacheKey = stringifyStyles(styles);\n let rules = pipelineCache.get(cacheKey);\n\n if (!rules) {\n // Create parser context\n const parserContext = createStateParserContext(styles);\n\n // Run pipeline\n rules = runPipeline(styles, parserContext);\n\n // Cache result\n pipelineCache.set(cacheKey, rules);\n }\n\n // If no className, rules need it to be prepended later\n if (!className) {\n return {\n rules: rules.map((r) => ({\n ...r,\n needsClassName: true,\n })),\n };\n }\n\n // Prepend className to selectors\n const finalRules = rules.map((rule) => {\n // Parse the selector to find where to insert className\n let selector = rule.selector;\n\n // If selector starts with :root, insert className after the :root part\n if (rule.rootPrefix) {\n selector = `${rule.rootPrefix} .${className}.${className}${selector}`;\n } else {\n selector = `.${className}.${className}${selector}`;\n }\n\n return {\n ...rule,\n selector,\n };\n });\n\n return {\n rules: finalRules,\n className,\n };\n}\n\n/**\n * Clear the pipeline cache (for testing)\n */\nexport function clearPipelineCache(): void {\n pipelineCache.clear();\n}\n\n// ============================================================================\n// Pipeline Implementation\n// ============================================================================\n\nfunction runPipeline(\n styles: Styles,\n parserContext: StateParserContext,\n): CSSRule[] {\n const allRules: CSSRule[] = [];\n\n // Process styles recursively (including nested selectors)\n processStyles(styles, '', parserContext, allRules);\n\n // Deduplicate rules\n const seen = new Set<string>();\n const dedupedRules = allRules.filter((rule) => {\n // Include rootPrefix in dedup key - rules with different root prefixes are distinct\n const key = `${rule.selector}|${rule.declarations}|${JSON.stringify(rule.atRules || [])}|${rule.rootPrefix || ''}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n\n return dedupedRules;\n}\n\n/**\n * Process styles at a given nesting level\n */\nfunction processStyles(\n styles: Styles,\n selectorSuffix: string,\n parserContext: StateParserContext,\n allRules: CSSRule[],\n): void {\n const keys = Object.keys(styles);\n\n // Separate selector keys from style keys\n // Skip @keyframes (processed separately) and other @ prefixed keys (predefined states)\n const selectorKeys = keys.filter((key) => isSelector(key));\n const styleKeys = keys.filter(\n (key) => !isSelector(key) && !key.startsWith('@'),\n );\n\n // Process nested selectors first\n for (const key of selectorKeys) {\n const nestedStyles = styles[key] as Styles;\n if (!nestedStyles || typeof nestedStyles !== 'object') continue;\n\n // Get all selectors (handles comma-separated patterns)\n const suffixes = getAllSelectors(key, nestedStyles);\n if (!suffixes) continue; // Invalid selector, skip\n\n // Remove $ from nested styles\n const { $: _$, ...cleanedStyles } = nestedStyles;\n\n // Extract local predefined states scoped to this sub-element\n const subLocalStates = extractLocalPredefinedStates(cleanedStyles);\n const hasSubStates = Object.keys(subLocalStates).length > 0;\n const subContext: StateParserContext = {\n ...parserContext,\n isSubElement: true,\n localPredefinedStates: hasSubStates\n ? { ...parserContext.localPredefinedStates, ...subLocalStates }\n : parserContext.localPredefinedStates,\n };\n\n // Process for each selector (multiple selectors = same styles applied to each)\n for (const suffix of suffixes) {\n processStyles(\n cleanedStyles,\n selectorSuffix + suffix,\n subContext,\n allRules,\n );\n }\n }\n\n // Build handler queue\n const handlerQueue = buildHandlerQueue(styleKeys, styles);\n\n // Process each handler\n for (const { handler, styleMap } of handlerQueue) {\n const lookupStyles = handler.__lookupStyles;\n\n // Stage 1 & 2: Parse and build exclusive conditions for each style\n // Exclusive conditions ensure each CSS rule applies to exactly one state.\n // OR conditions in exclusives are properly expanded to DNF (multiple CSS selectors).\n const exclusiveByStyle = new Map<string, ExclusiveStyleEntry[]>();\n\n for (const styleName of lookupStyles) {\n const value = styleMap[styleName];\n if (value === undefined) continue;\n\n if (isValueMapping(value)) {\n // Parse entries from value mapping\n const parsed = parseStyleEntries(styleName, value, (stateKey) =>\n parseStateKey(stateKey, { context: parserContext }),\n );\n\n // Expand OR conditions into exclusive branches\n // This ensures OR branches like `A | B | C` become:\n // A, B & !A, C & !A & !B\n const expanded = expandOrConditions(parsed);\n\n // Build exclusive conditions across all entries\n const exclusive = buildExclusiveConditions(expanded);\n\n // Expand ORs from De Morgan negation into exclusive branches\n // This transforms: !A | !B → !A, (A & !B)\n // Ensures each CSS rule has proper at-rule context\n const fullyExpanded = expandExclusiveOrs(exclusive);\n exclusiveByStyle.set(styleName, fullyExpanded);\n } else {\n // Simple value - single entry with TRUE condition\n exclusiveByStyle.set(styleName, [\n {\n styleKey: styleName,\n stateKey: '',\n value,\n condition: trueCondition(),\n priority: 0,\n exclusiveCondition: trueCondition(),\n },\n ]);\n }\n }\n\n // Stage 4: Compute all valid state combinations\n const stateSnapshots = computeStateCombinations(\n exclusiveByStyle,\n lookupStyles,\n );\n\n // Stage 5: Call handler for each snapshot\n const computedRules: ComputedRule[] = [];\n\n for (const snapshot of stateSnapshots) {\n const result = handler(snapshot.values as StyleValueStateMap);\n if (!result) continue;\n\n // Handler may return single or array\n const results = Array.isArray(result) ? result : [result];\n\n for (const r of results) {\n if (!r || typeof r !== 'object') continue;\n\n const { $, ...styleProps } = r;\n const declarations: Record<string, string> = {};\n\n for (const [prop, val] of Object.entries(styleProps)) {\n if (val != null && val !== '') {\n declarations[prop] = String(val);\n }\n }\n\n if (Object.keys(declarations).length === 0) continue;\n\n // Handle $ suffixes\n const suffixes = $\n ? (Array.isArray($) ? $ : [$]).map(\n (s) => selectorSuffix + normalizeSelectorSuffix(String(s)),\n )\n : [selectorSuffix];\n\n for (const suffix of suffixes) {\n computedRules.push({\n condition: snapshot.condition,\n declarations,\n selectorSuffix: suffix,\n });\n }\n }\n }\n\n // Stage 6: Merge rules with identical CSS output\n const mergedRules = mergeByValue(computedRules);\n\n // Stage 7: Materialize to CSS\n for (const rule of mergedRules) {\n const cssRules = materializeComputedRule(rule);\n allRules.push(...cssRules);\n }\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if a key is a CSS selector\n */\nexport function isSelector(key: string): boolean {\n return key.startsWith('&') || key.startsWith('.') || /^[A-Z]/.test(key);\n}\n\n/**\n * Result of processing a selector affix ($) pattern.\n *\n * @example\n * // Valid result with multiple selectors\n * { valid: true, selectors: ['> [data-element=\"Cell\"]', ' [data-element=\"Body\"] > [data-element=\"Cell\"]'] }\n *\n * // Invalid result with error message\n * { valid: false, reason: 'Selector affix \"+\" targets elements outside the root scope.' }\n */\ntype AffixResult =\n | { valid: true; selectors: string[] }\n | { valid: false; reason: string };\n\n/**\n * Get all selector suffixes for a sub-element key.\n *\n * Handles three types of selector keys:\n * - `&` prefix: Raw selector suffix (e.g., `&:hover` → `:hover`)\n * - `.` prefix: Class selector (e.g., `.active` → ` .active`)\n * - Uppercase: Sub-element with optional `$` affix pattern\n *\n * @param key - The sub-element key (e.g., 'Label', '&:hover', '.active')\n * @param styles - The styles object, may contain `$` property for selector affix\n * @returns Array of selector suffixes, or null if invalid (with console warning)\n *\n * @example\n * getAllSelectors('Label', {})\n * // → [' [data-element=\"Label\"]']\n *\n * getAllSelectors('Cell', { $: '>, >Body>' })\n * // → ['> [data-element=\"Cell\"]', ' [data-element=\"Body\"] > [data-element=\"Cell\"]']\n */\nfunction getAllSelectors(key: string, styles?: Styles): string[] | null {\n if (key.startsWith('&')) {\n return [key.slice(1)];\n }\n\n if (key.startsWith('.')) {\n return [` ${key}`];\n }\n\n if (/^[A-Z]/.test(key)) {\n const affix = styles?.$;\n if (affix !== undefined) {\n const result = processAffix(String(affix), key);\n if (!result.valid) {\n emitWarning('INVALID_SELECTOR_AFFIX', result.reason);\n return null;\n }\n return result.selectors;\n }\n return [` [data-element=\"${key}\"]`];\n }\n\n return null;\n}\n\n/**\n * Process selector affix pattern and return selector(s)\n *\n * Supports:\n * - Direct child: '>'\n * - Chained elements: '>Body>Row>'\n * - HTML tags: 'a', '>ul>li', 'button:hover'\n * - Pseudo-elements on root: '::before'\n * - Pseudo on sub-element: '@::before', '>@:hover'\n * - Classes: '.active', '>@.active'\n * - Multiple selectors: '>, >Body>'\n * - Sibling combinators (after element): '>Item+', '>Item~'\n */\nfunction processAffix(affix: string, key: string): AffixResult {\n const trimmed = affix.trim();\n\n // Empty = default behavior (descendant selector with key)\n if (!trimmed) {\n return { valid: true, selectors: [` [data-element=\"${key}\"]`] };\n }\n\n // Split by comma for multiple selectors\n const patterns = trimmed.split(',').map((p) => p.trim());\n const selectors: string[] = [];\n\n for (const pattern of patterns) {\n const validation = validatePattern(pattern);\n if (!validation.valid) {\n return validation;\n }\n\n const selector = processSinglePattern(pattern, key);\n selectors.push(selector);\n }\n\n return { valid: true, selectors };\n}\n\n/**\n * Recognized token patterns for selector affix validation.\n *\n * These patterns are used to tokenize and validate `$` affix strings.\n * Order matters: more specific patterns must come first to avoid\n * partial matches (e.g., `::before` must match before `:` alone).\n *\n * Unrecognized tokens (like `#id`, `*`, or numbers) will cause validation to fail.\n */\nconst VALID_TOKEN_PATTERNS = [\n /^[>+~]/, // Combinators: >, +, ~\n /^[A-Z][a-zA-Z0-9]*/, // Uppercase element names → [data-element=\"...\"]\n /^@/, // @ placeholder for key injection position\n /^::?[a-z][a-z0-9-]*(?:\\([^)]*\\))?/, // Pseudo-elements/classes (:hover, ::before, :not(.x))\n /^\\.[a-zA-Z_-][a-zA-Z0-9_-]*/, // Class selectors (.active, .is-open)\n /^\\[[^\\]]+\\]/, // Attribute selectors ([type=\"text\"], [role])\n /^[a-z][a-z0-9-]*/, // HTML tag names (a, div, button, my-component)\n /^\\s+/, // Whitespace (ignored during parsing)\n /^&/, // Root reference (stripped, kept for backward compat)\n];\n\n/**\n * Scan a pattern for unrecognized tokens.\n *\n * Iterates through the pattern, consuming recognized tokens until\n * either the pattern is fully consumed (valid) or an unrecognized\n * character sequence is found (invalid).\n *\n * @param pattern - The selector pattern to validate\n * @returns The first unrecognized token found, or null if all tokens are valid\n *\n * @example\n * findUnrecognizedTokens('>Body>Row>') // → null (valid)\n * findUnrecognizedTokens('123') // → '123' (invalid)\n * findUnrecognizedTokens('#myId') // → '#' (invalid)\n */\nfunction findUnrecognizedTokens(pattern: string): string | null {\n let remaining = pattern;\n\n while (remaining.length > 0) {\n let matched = false;\n\n for (const regex of VALID_TOKEN_PATTERNS) {\n const match = remaining.match(regex);\n if (match) {\n remaining = remaining.slice(match[0].length);\n matched = true;\n break;\n }\n }\n\n if (!matched) {\n // Found unrecognized content - extract the problematic part\n const unrecognized = remaining.match(/^[^\\s>+~@.:[\\]A-Z]+/);\n return unrecognized ? unrecognized[0] : remaining[0];\n }\n }\n\n return null;\n}\n\n/**\n * Validate a selector pattern for structural correctness.\n *\n * Checks for:\n * 1. Out-of-scope selectors: Patterns starting with `+` or `~` target siblings\n * of the root element, which is outside the component's DOM scope.\n * 2. Consecutive combinators: Patterns like `>>` or `>+` are malformed CSS.\n * 3. Unrecognized tokens: Characters/sequences not matching valid CSS selectors.\n *\n * @param pattern - A single selector pattern (already split by comma)\n * @returns AffixResult indicating validity and error reason if invalid\n *\n * @example\n * validatePattern('>Body>Row>') // → { valid: true, selectors: [] }\n * validatePattern('+') // → { valid: false, reason: '...outside root scope...' }\n * validatePattern('>>') // → { valid: false, reason: '...consecutive combinators...' }\n */\nfunction validatePattern(pattern: string): AffixResult {\n const trimmed = pattern.trim();\n\n // Patterns starting with + or ~ target siblings of the root element,\n // which is outside the component's scope. Valid sibling patterns must\n // be preceded by an element: \">Item+\", \">Item~\"\n if (/^[+~]/.test(trimmed)) {\n return {\n valid: false,\n reason:\n `Selector affix \"${pattern}\" targets elements outside the root scope. ` +\n `Sibling selectors (+, ~) must be preceded by an element inside the root. ` +\n `Use \">Element+\" or \">Element~\" instead.`,\n };\n }\n\n // Check for consecutive combinators\n if (/[>+~]{2,}/.test(trimmed.replace(/\\s+/g, ''))) {\n return {\n valid: false,\n reason: `Selector affix \"${pattern}\" contains consecutive combinators.`,\n };\n }\n\n // Check for unrecognized tokens (e.g., lowercase text like \"foo\")\n const unrecognized = findUnrecognizedTokens(trimmed);\n if (unrecognized) {\n return {\n valid: false,\n reason:\n `Selector affix \"${pattern}\" contains unrecognized token \"${unrecognized}\". ` +\n `Valid tokens: combinators (>, +, ~), element names (Uppercase), ` +\n `@ placeholder, pseudo (:hover, ::before), class (.name), attribute ([attr]).`,\n };\n }\n\n return { valid: true, selectors: [] };\n}\n\n/**\n * Process a single selector pattern into a CSS selector suffix.\n *\n * This is the main transformation function that converts a `$` affix pattern\n * into a valid CSS selector suffix. It handles:\n *\n * 1. `@` placeholder replacement with `[data-element=\"key\"]`\n * 2. Key injection based on pattern ending (see `shouldInjectKey`)\n * 3. Proper spacing for descendant vs direct child selectors\n *\n * @param pattern - A single validated selector pattern\n * @param key - The sub-element key to inject (e.g., 'Label', 'Cell')\n * @returns CSS selector suffix ready to append to the root selector\n *\n * @example\n * processSinglePattern('>', 'Row')\n * // → '> [data-element=\"Row\"]'\n *\n * processSinglePattern('>Body>Row>', 'Cell')\n * // → '> [data-element=\"Body\"] > [data-element=\"Row\"] > [data-element=\"Cell\"]'\n *\n * processSinglePattern('::before', 'Before')\n * // → '::before' (no key injection for pseudo on root)\n *\n * processSinglePattern('>@:hover', 'Item')\n * // → '> [data-element=\"Item\"]:hover'\n */\nfunction processSinglePattern(pattern: string, key: string): string {\n // Strip leading & if present (implicit root reference, kept for compat)\n const normalized = pattern.replace(/^&/, '').trim();\n\n if (!normalized) {\n return ` [data-element=\"${key}\"]`;\n }\n\n // Pseudo-elements/classes at start apply directly to root (no space prefix)\n const startsWithPseudo = /^::?[a-z]/.test(normalized);\n\n // Transform the pattern: convert element names and normalize spacing\n let result = transformPattern(normalized);\n\n // Handle @ placeholder: explicit key injection position\n if (result.includes('@')) {\n // Remove space between @ and following class/pseudo for proper attachment\n // e.g., \"@ .active\" → \"[el].active\", but \"@ > span\" → \"[el] > span\"\n result = result.replace(/@ (?=[.:])/g, '@');\n result = result.replace(/@/g, `[data-element=\"${key}\"]`);\n\n if (!startsWithPseudo && !result.startsWith(' ')) {\n result = ' ' + result;\n }\n return result;\n }\n\n // Auto-inject key based on pattern ending (see shouldInjectKey for rules)\n if (shouldInjectKey(normalized)) {\n result = result + ' ' + `[data-element=\"${key}\"]`;\n }\n\n // Add space prefix for selectors targeting inside root (not pseudo on root)\n if (!startsWithPseudo && !result.startsWith(' ')) {\n result = ' ' + result;\n }\n\n return result;\n}\n\n/**\n * Transform a selector pattern by converting element names and normalizing spacing.\n *\n * This is a character-by-character tokenizer that:\n * - Converts uppercase names to `[data-element=\"Name\"]` selectors\n * - Adds proper spacing around combinators (>, +, ~)\n * - Preserves lowercase tags, classes, pseudos, and attributes as-is\n * - Keeps @ placeholder for later replacement\n *\n * The tokenizer handles these token types in order:\n * 1. Whitespace (skipped)\n * 2. Combinators: >, +, ~ (add surrounding spaces)\n * 3. Uppercase names: Body, Row (convert to [data-element=\"...\"])\n * 4. @ placeholder (keep for later replacement)\n * 5. Pseudo: :hover, ::before (attach to previous token)\n * 6. Tags: a, div, button (keep as-is with spacing)\n * 7. Classes: .active (attach to previous element/tag/placeholder)\n * 8. Attributes: [type=\"text\"] (keep as-is)\n *\n * @param pattern - The raw selector pattern to transform\n * @returns Transformed pattern with proper CSS selector syntax\n *\n * @example\n * transformPattern('>Body>Row>')\n * // → '> [data-element=\"Body\"] > [data-element=\"Row\"] >'\n *\n * transformPattern('button.primary:hover')\n * // → 'button.primary:hover'\n */\nfunction transformPattern(pattern: string): string {\n let result = '';\n let lastCh = '';\n let i = 0;\n\n while (i < pattern.length) {\n const char = pattern[i];\n\n if (/\\s/.test(char)) {\n i++;\n continue;\n }\n\n if (/[>+~]/.test(char)) {\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n result += char;\n lastCh = char;\n i++;\n continue;\n }\n\n if (/[A-Z]/.test(char)) {\n const nameStart = i;\n while (i < pattern.length && /[a-zA-Z0-9]/.test(pattern[i])) {\n i++;\n }\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n const segment = `[data-element=\"${pattern.slice(nameStart, i)}\"]`;\n result += segment;\n lastCh = ']';\n continue;\n }\n\n if (char === '@') {\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n result += '@';\n lastCh = '@';\n i++;\n continue;\n }\n\n if (char === ':') {\n const pseudoStart = i;\n while (\n i < pattern.length &&\n !/[\\s>+~,@]/.test(pattern[i]) &&\n !/[A-Z]/.test(pattern[i])\n ) {\n i++;\n }\n const segment = pattern.slice(pseudoStart, i);\n result += segment;\n lastCh = segment[segment.length - 1] || lastCh;\n continue;\n }\n\n if (/[a-z]/.test(char)) {\n const tagStart = i;\n while (i < pattern.length && /[a-z0-9-]/.test(pattern[i])) {\n i++;\n }\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n const segment = pattern.slice(tagStart, i);\n result += segment;\n lastCh = segment[segment.length - 1] || lastCh;\n continue;\n }\n\n if (char === '.') {\n const attachToLast =\n lastCh === ']' || lastCh === '@' || /[a-zA-Z0-9-]/.test(lastCh);\n if (result && !attachToLast && lastCh !== ' ') {\n result += ' ';\n }\n const clsStart = i;\n i++;\n while (i < pattern.length && /[a-zA-Z0-9_-]/.test(pattern[i])) {\n i++;\n }\n const segment = pattern.slice(clsStart, i);\n result += segment;\n lastCh = segment[segment.length - 1] || lastCh;\n continue;\n }\n\n if (char === '[') {\n const attachToLast =\n lastCh === ']' || lastCh === '@' || /[a-zA-Z0-9-]/.test(lastCh);\n if (result && !attachToLast && lastCh !== ' ') {\n result += ' ';\n }\n const attrStart = i;\n let depth = 0;\n while (i < pattern.length) {\n if (pattern[i] === '[') depth++;\n if (pattern[i] === ']') depth--;\n i++;\n if (depth === 0) break;\n }\n result += pattern.slice(attrStart, i);\n lastCh = ']';\n continue;\n }\n\n result += char;\n lastCh = char;\n i++;\n }\n\n return result;\n}\n\n/**\n * Determine if the sub-element key should be auto-injected based on pattern ending.\n *\n * Key injection rules (when no @ placeholder is present):\n *\n * | Pattern Ending | Inject Key? | Example | Result |\n * |----------------|-------------|---------|--------|\n * | Combinator (>, +, ~) | Yes | `'>Body>'` | `> [data-element=\"Body\"] > [el]` |\n * | Uppercase element | Yes | `'>Body>Row'` | `> [el1] > [el2] [key]` |\n * | Lowercase tag | Yes | `'>ul>li'` | `> ul > li [key]` |\n * | Pseudo (:hover, ::before) | No | `'::before'` | `::before` |\n * | Class (.active) | No | `'.active'` | `.active` |\n * | Attribute ([type]) | No | `'[type=\"text\"]'` | `[type=\"text\"]` |\n *\n * @param pattern - The normalized pattern (after stripping &)\n * @returns true if key should be injected, false otherwise\n *\n * @example\n * shouldInjectKey('>') // → true (trailing combinator)\n * shouldInjectKey('>Body>Row') // → true (ends with element)\n * shouldInjectKey('>ul>li') // → true (ends with tag)\n * shouldInjectKey('::before') // → false (ends with pseudo)\n * shouldInjectKey('.active') // → false (ends with class)\n * shouldInjectKey('a:hover') // → false (ends with pseudo)\n * shouldInjectKey('button.primary') // → false (ends with class)\n */\nfunction shouldInjectKey(pattern: string): boolean {\n const trimmed = pattern.trim();\n\n // Rule 1: Ends with combinator → inject key after it\n // e.g., '>' → '> [data-element=\"Key\"]'\n if (/[>+~]$/.test(trimmed)) {\n return true;\n }\n\n // Rule 2: Ends with uppercase element name → inject key as descendant\n // The lookbehind ensures we're matching a standalone element name, not\n // part of a class like .myClass (where C is preceded by lowercase)\n // e.g., '>Body' → '> [data-element=\"Body\"] [data-element=\"Key\"]'\n if (/(?:^|[\\s>+~\\]:])[A-Z][a-zA-Z0-9]*$/.test(trimmed)) {\n return true;\n }\n\n // Rule 3: Ends with lowercase tag name → inject key as descendant\n // The negative lookbehind (?<![:.]) ensures we don't match:\n // - ':hover' (pseudo ending)\n // - '.primary' (class ending)\n // e.g., '>ul>li' → '> ul > li [data-element=\"Key\"]'\n if (/(?<![:.])(?:^|[\\s>+~])[a-z][a-z0-9-]*$/.test(trimmed)) {\n return true;\n }\n\n // Rule 4: Otherwise (pseudo, class, attribute) → no injection\n // The pattern is complete as-is, applying to root or a specific selector\n return false;\n}\n\n/**\n * Normalize selector suffix from $ property\n */\nfunction normalizeSelectorSuffix(suffix: string): string {\n if (!suffix) return '';\n return suffix.startsWith('&') ? suffix.slice(1) : suffix;\n}\n\n/**\n * Build handler queue from style keys\n */\nfunction buildHandlerQueue(\n styleKeys: string[],\n styles: Styles,\n): { handler: StyleHandler; styleMap: StyleMap }[] {\n const queue: { handler: StyleHandler; styleMap: StyleMap }[] = [];\n const seenHandlers = new Set<StyleHandler>();\n\n for (const styleName of styleKeys) {\n let handlers: StyleHandler[] = STYLE_HANDLER_MAP[styleName];\n\n if (!handlers) {\n handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];\n }\n\n for (const handler of handlers) {\n if (seenHandlers.has(handler)) continue;\n seenHandlers.add(handler);\n\n const lookupStyles = handler.__lookupStyles;\n const styleMap: StyleMap = {};\n\n for (const name of lookupStyles) {\n const val = styles[name];\n if (val !== undefined) {\n styleMap[name] = val as StyleValue | StyleValueStateMap;\n }\n }\n\n queue.push({ handler, styleMap });\n }\n }\n\n return queue;\n}\n\n/**\n * Compute all valid state combinations for a handler's lookup styles\n */\nfunction computeStateCombinations(\n exclusiveByStyle: Map<string, ExclusiveStyleEntry[]>,\n lookupStyles: string[],\n): { condition: ConditionNode; values: Record<string, StyleValue> }[] {\n // Get entries for each style\n const entriesPerStyle = lookupStyles.map(\n (style) => exclusiveByStyle.get(style) || [],\n );\n\n // Cartesian product of all combinations\n const combinations = cartesianProduct(entriesPerStyle);\n\n // Build snapshots, simplifying and filtering impossible combinations\n const snapshots: {\n condition: ConditionNode;\n values: Record<string, StyleValue>;\n }[] = [];\n\n for (const combo of combinations) {\n // Combine all exclusive conditions with AND\n const conditions = combo.map((e) => e.exclusiveCondition);\n const combined = and(...conditions);\n const simplified = simplifyCondition(combined);\n\n // Skip impossible combinations\n if (simplified.kind === 'false') continue;\n\n // Build values map\n const values: Record<string, StyleValue> = {};\n for (const entry of combo) {\n values[entry.styleKey] = entry.value;\n }\n\n snapshots.push({\n condition: simplified,\n values,\n });\n }\n\n return snapshots;\n}\n\n/**\n * Cartesian product of arrays\n */\nfunction cartesianProduct<T>(arrays: T[][]): T[][] {\n if (arrays.length === 0) return [[]];\n\n const nonEmpty = arrays.filter((a) => a.length > 0);\n if (nonEmpty.length === 0) return [[]];\n\n let result: T[][] = [[]];\n for (const arr of nonEmpty) {\n const next: T[][] = [];\n for (const combo of result) {\n for (const item of arr) {\n const newCombo = new Array<T>(combo.length + 1);\n for (let i = 0; i < combo.length; i++) newCombo[i] = combo[i];\n newCombo[combo.length] = item;\n next.push(newCombo);\n }\n }\n result = next;\n }\n return result;\n}\n\nconst declStringCache = new WeakMap<Record<string, string>, string>();\n\nfunction stringifyDeclarations(decl: Record<string, string>): string {\n let cached = declStringCache.get(decl);\n if (cached === undefined) {\n cached = JSON.stringify(decl);\n declStringCache.set(decl, cached);\n }\n return cached;\n}\n\n/**\n * Merge rules with identical CSS output\n */\nfunction mergeByValue(rules: ComputedRule[]): ComputedRule[] {\n const groups = new Map<string, ComputedRule[]>();\n\n for (const rule of rules) {\n const key = `${rule.selectorSuffix}|${stringifyDeclarations(rule.declarations)}`;\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key)!.push(rule);\n }\n\n // Merge conditions with OR for each group\n const merged: ComputedRule[] = [];\n\n for (const [, groupRules] of groups) {\n if (groupRules.length === 1) {\n merged.push(groupRules[0]);\n } else {\n // Merge conditions with OR\n const mergedCondition = simplifyCondition(\n or(...groupRules.map((r) => r.condition)),\n );\n merged.push({\n condition: mergedCondition,\n declarations: groupRules[0].declarations,\n selectorSuffix: groupRules[0].selectorSuffix,\n });\n }\n }\n\n return merged;\n}\n\n/**\n * Build selector fragment from a variant (without className prefix)\n */\nfunction buildSelectorFromVariant(\n variant: SelectorVariant,\n selectorSuffix: string,\n): string {\n let selector = '';\n\n // Add modifier selectors\n for (const mod of variant.modifierConditions) {\n selector += modifierToCSS(mod);\n }\n\n // Add pseudo selectors\n for (const pseudo of variant.pseudoConditions) {\n selector += pseudoToCSS(pseudo);\n }\n\n // Add parent selectors (before sub-element suffix)\n if (variant.parentGroups.length > 0) {\n selector += parentGroupsToCSS(variant.parentGroups);\n }\n\n selector += selectorSuffix;\n\n // Add own selectors (after sub-element)\n for (const own of variant.ownConditions) {\n selector += selectorConditionToCSS(own);\n }\n\n return selector;\n}\n\n/**\n * Materialize a computed rule to final CSS format\n *\n * Returns an array because OR conditions may generate multiple CSS rules\n * (when different branches have different at-rules)\n */\nfunction materializeComputedRule(rule: ComputedRule): CSSRule[] {\n const components = conditionToCSS(rule.condition);\n\n if (components.isImpossible || components.variants.length === 0) {\n return [];\n }\n\n const declarations = Object.entries(rule.declarations)\n .map(([prop, value]) => `${prop}: ${value};`)\n .join(' ');\n\n // Helper to get root prefix key for grouping\n const getRootPrefixKey = (variant: SelectorVariant): string => {\n return variant.rootConditions\n .map((r) => selectorConditionToCSS(r))\n .sort()\n .join('|');\n };\n\n // Group variants by their at-rules (variants with same at-rules can be combined with commas)\n const byAtRules = new Map<\n string,\n { variants: SelectorVariant[]; atRules: string[]; rootPrefix?: string }\n >();\n\n for (const variant of components.variants) {\n const atRules = buildAtRulesFromVariant(variant);\n const key = atRules.sort().join('|||') + '###' + getRootPrefixKey(variant);\n\n const group = byAtRules.get(key);\n if (group) {\n group.variants.push(variant);\n } else {\n byAtRules.set(key, {\n variants: [variant],\n atRules,\n rootPrefix: rootConditionsToCSS(variant.rootConditions),\n });\n }\n }\n\n // Generate one CSSRule per at-rules group\n const rules: CSSRule[] = [];\n for (const [, group] of byAtRules) {\n // Build selector fragments for each variant (will be joined with className later)\n const selectorFragments = group.variants.map((v) =>\n buildSelectorFromVariant(v, rule.selectorSuffix),\n );\n\n // Store as array if multiple, string if single\n const selector =\n selectorFragments.length === 1 ? selectorFragments[0] : selectorFragments;\n\n const cssRule: CSSRule = {\n selector,\n declarations,\n };\n\n if (group.atRules.length > 0) {\n cssRule.atRules = group.atRules;\n }\n\n if (group.rootPrefix) {\n cssRule.rootPrefix = group.rootPrefix;\n }\n\n rules.push(cssRule);\n }\n\n return rules;\n}\n\n// ============================================================================\n// Public API: renderStyles (compatible with old API)\n// ============================================================================\n\n/**\n * Options for renderStyles when using direct selector mode.\n */\nexport interface RenderStylesOptions {\n /**\n * Whether to double the class selector for increased specificity.\n * When true, `.myClass` becomes `.myClass.myClass` for higher specificity.\n *\n * @default false - User-provided selectors are not doubled.\n *\n * Note: This only applies when a classNameOrSelector is provided.\n * When renderStyles returns RenderResult with needsClassName=true,\n * the injector handles doubling automatically.\n */\n doubleSelector?: boolean;\n}\n\n/**\n * Render styles to CSS rules.\n *\n * When called without classNameOrSelector, returns RenderResult with needsClassName=true.\n * When called with a selector/className string, returns StyleResult[] for direct injection.\n */\nexport function renderStyles(styles?: Styles): RenderResult;\nexport function renderStyles(\n styles: Styles | undefined,\n classNameOrSelector: string,\n options?: RenderStylesOptions,\n): StyleResult[];\nexport function renderStyles(\n styles?: Styles,\n classNameOrSelector?: string,\n options?: RenderStylesOptions,\n): RenderResult | StyleResult[] {\n // Check if we have a direct selector/className\n const directSelector = !!classNameOrSelector;\n\n if (!styles) {\n return directSelector ? [] : { rules: [] };\n }\n\n // Check cache\n const cacheKey = stringifyStyles(styles);\n let rules = pipelineCache.get(cacheKey);\n\n if (!rules) {\n // Create parser context\n const parserContext = createStateParserContext(styles);\n\n // Run pipeline\n rules = runPipeline(styles, parserContext);\n\n // Cache result\n pipelineCache.set(cacheKey, rules);\n }\n\n // Direct selector/className mode: return StyleResult[] directly\n if (directSelector) {\n const shouldDouble = options?.doubleSelector ?? false;\n\n return rules.map((rule): StyleResult => {\n // Handle selector as array (OR conditions) or string\n const selectorParts = Array.isArray(rule.selector)\n ? rule.selector\n : rule.selector\n ? [rule.selector]\n : [''];\n\n const finalSelector = selectorParts\n .map((part) => {\n let sel = part\n ? `${classNameOrSelector}${part}`\n : classNameOrSelector;\n\n // Double class selector for increased specificity if requested\n // This is used when the caller explicitly wants higher specificity\n if (shouldDouble && sel.startsWith('.')) {\n const classMatch = sel.match(/^\\.[a-zA-Z_-][a-zA-Z0-9_-]*/);\n if (classMatch) {\n const baseClass = classMatch[0];\n sel = baseClass + sel;\n }\n }\n\n // Handle root prefix for this selector\n if (rule.rootPrefix) {\n sel = `${rule.rootPrefix} ${sel}`;\n }\n\n return sel;\n })\n .join(', ');\n\n const result: StyleResult = {\n selector: finalSelector,\n declarations: rule.declarations,\n };\n\n if (rule.atRules && rule.atRules.length > 0) {\n result.atRules = rule.atRules;\n }\n\n return result;\n });\n }\n\n // No className mode: return RenderResult with needsClassName flag\n // Normalize selector to string (join array with placeholder that injector will handle)\n return {\n rules: rules.map(\n (r): StyleResult => ({\n selector: Array.isArray(r.selector)\n ? r.selector.join('|||')\n : r.selector,\n declarations: r.declarations,\n atRules: r.atRules,\n needsClassName: true,\n rootPrefix: r.rootPrefix,\n }),\n ),\n };\n}\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport type { ConditionNode } from './conditions';\nexport { and, or, not, trueCondition, falseCondition } from './conditions';\nexport { parseStateKey } from './parseStateKey';\nexport { simplifyCondition } from './simplify';\nexport { buildExclusiveConditions } from './exclusive';\nexport { conditionToCSS } from './materialize';\nexport type { CSSRule } from './materialize';\nexport { setWarningHandler, emitWarning } from './warnings';\nexport type {\n TastyWarning,\n TastyWarningCode,\n TastyWarningHandler,\n} from './warnings';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA8FA,MAAM,gBAAgB,IAAI,IAAuB,IAAK;;;;AAuEtD,SAAgB,qBAA2B;AACzC,eAAc,OAAO;;AAOvB,SAAS,YACP,QACA,eACW;CACX,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MAAM,iBAAiB,CAAC,CAAC;AAEzB,KAAI,CAAC,OACH,QAAO,iBAAiB,EAAE,GAAG,EAAE,OAAO,EAAE,EAAE;CAI5C,MAAM,WAAW,gBAAgB,OAAO;CACxC,IAAI,QAAQ,cAAc,IAAI,SAAS;AAEvC,KAAI,CAAC,OAAO;AAKV,UAAQ,YAAY,QAHE,yBAAyB,OAAO,CAGZ;AAG1C,gBAAc,IAAI,UAAU,MAAM;;AAIpC,KAAI,gBAAgB;EAClB,MAAM,eAAe,SAAS,kBAAkB;AAEhD,SAAO,MAAM,KAAK,SAAsB;GAiCtC,MAAM,SAAsB;IAC1B,WAhCoB,MAAM,QAAQ,KAAK,SAAS,GAC9C,KAAK,WACL,KAAK,WACH,CAAC,KAAK,SAAS,GACf,CAAC,GAAG,EAGP,KAAK,SAAS;KACb,IAAI,MAAM,OACN,GAAG,sBAAsB,SACzB;AAIJ,SAAI,gBAAgB,IAAI,WAAW,IAAI,EAAE;MACvC,MAAM,aAAa,IAAI,MAAM,8BAA8B;AAC3D,UAAI,WAEF,OADkB,WAAW,KACX;;AAKtB,SAAI,KAAK,WACP,OAAM,GAAG,KAAK,WAAW,GAAG;AAG9B,YAAO;MACP,CACD,KAAK,KAAK;IAIX,cAAc,KAAK;IACpB;AAED,OAAI,KAAK,WAAW,KAAK,QAAQ,SAAS,EACxC,QAAO,UAAU,KAAK;AAGxB,UAAO;IACP;;AAKJ,QAAO,EACL,OAAO,MAAM,KACV,OAAoB;EACnB,UAAU,MAAM,QAAQ,EAAE,SAAS,GAC/B,EAAE,SAAS,KAAK,MAAM,GACtB,EAAE;EACN,cAAc,EAAE;EAChB,SAAS,EAAE;EACX,gBAAgB;EAChB,YAAY,EAAE;EACf,EACF,EACF"}
1
+ {"version":3,"file":"index.js","names":[],"sources":["../../src/pipeline/index.ts"],"sourcesContent":["/**\n * Tasty Style Rendering Pipeline\n *\n * This is the main entrypoint for the new pipeline implementation.\n * It implements the complete flow from style objects to CSS rules.\n *\n * Pipeline stages:\n * 1. PARSE CONDITIONS - Parse state keys into ConditionNode trees\n * 2. BUILD EXCLUSIVE CONDITIONS - AND with negation of higher-priority conditions\n * 3. SIMPLIFY CONDITIONS - Apply boolean algebra, detect contradictions\n * 4. GROUP BY HANDLER - Collect styles per handler, compute combinations\n * 5. COMPUTE CSS VALUES - Call handlers to get CSS declarations\n * 6. MERGE BY VALUE - Merge rules with identical CSS output\n * 7. MATERIALIZE CSS - Convert conditions to CSS selectors + at-rules\n */\n\nimport { Lru } from '../parser/lru';\nimport type { StateParserContext } from '../states';\nimport {\n createStateParserContext,\n extractLocalPredefinedStates,\n} from '../states';\nimport { createStyle, STYLE_HANDLER_MAP } from '../styles';\nimport type { Styles } from '../styles/types';\nimport type {\n StyleHandler,\n StyleMap,\n StyleValue,\n StyleValueStateMap,\n} from '../utils/styles';\nimport { stringifyStyles } from '../utils/styles';\n\nimport type { ConditionNode } from './conditions';\nimport { and, or, trueCondition } from './conditions';\nimport type { ExclusiveStyleEntry } from './exclusive';\nimport {\n buildExclusiveConditions,\n expandExclusiveOrs,\n expandOrConditions,\n isValueMapping,\n parseStyleEntries,\n} from './exclusive';\nimport type { CSSRule, SelectorVariant } from './materialize';\nimport {\n branchToCSS,\n buildAtRulesFromVariant,\n conditionToCSS,\n mergeVariantsIntoSelectorGroups,\n optimizeGroups,\n parentGroupsToCSS,\n rootGroupsToCSS,\n selectorGroupToCSS,\n} from './materialize';\nimport { parseStateKey } from './parseStateKey';\nimport { simplifyCondition } from './simplify';\nimport { emitWarning } from './warnings';\n\n// ============================================================================\n// Types (compatible with old renderStyles API)\n// ============================================================================\n\n/**\n * Matches the old StyleResult interface for backward compatibility\n */\nexport interface StyleResult {\n selector: string;\n declarations: string;\n atRules?: string[];\n needsClassName?: boolean;\n rootPrefix?: string;\n}\n\n/**\n * Matches the old RenderResult interface for backward compatibility\n */\nexport interface RenderResult {\n rules: StyleResult[];\n className?: string;\n}\n\nexport interface PipelineResult {\n rules: CSSRule[];\n className?: string;\n}\n\ninterface ComputedRule {\n condition: ConditionNode;\n declarations: Record<string, string>;\n selectorSuffix: string;\n}\n\n// ============================================================================\n// Caching\n// ============================================================================\n\nconst pipelineCache = new Lru<string, CSSRule[]>(5000);\n\n// ============================================================================\n// Main Pipeline Function\n// ============================================================================\n\n/**\n * Render styles using the new pipeline.\n *\n * This is the main entrypoint that implements the complete flow.\n */\nexport function renderStylesPipeline(\n styles?: Styles,\n className?: string,\n pipelineCacheKey?: string,\n): PipelineResult {\n if (!styles) {\n return { rules: [], className };\n }\n\n // Use pre-computed cache key when available, falling back to stringifyStyles\n const cacheKey = pipelineCacheKey || stringifyStyles(styles);\n let rules = pipelineCache.get(cacheKey);\n\n if (!rules) {\n // Create parser context\n const parserContext = createStateParserContext(styles);\n\n // Run pipeline\n rules = runPipeline(styles, parserContext);\n\n // Cache result\n pipelineCache.set(cacheKey, rules);\n }\n\n // If no className, rules need it to be prepended later\n if (!className) {\n return {\n rules: rules.map((r) => ({\n ...r,\n needsClassName: true,\n })),\n };\n }\n\n // Prepend className to selectors\n const finalRules = rules.map((rule) => {\n // Parse the selector to find where to insert className\n let selector = rule.selector;\n\n // If selector starts with :root, insert className after the :root part\n if (rule.rootPrefix) {\n selector = `${rule.rootPrefix} .${className}.${className}${selector}`;\n } else {\n selector = `.${className}.${className}${selector}`;\n }\n\n return {\n ...rule,\n selector,\n };\n });\n\n return {\n rules: finalRules,\n className,\n };\n}\n\n/**\n * Check if a cache key exists in the pipeline cache.\n * Used by renderStylesForChunk to avoid building filtered styles on cache hit.\n */\nexport function hasPipelineCacheEntry(cacheKey: string): boolean {\n return pipelineCache.get(cacheKey) !== undefined;\n}\n\n/**\n * Clear the pipeline cache (for testing)\n */\nexport function clearPipelineCache(): void {\n pipelineCache.clear();\n}\n\n// ============================================================================\n// Pipeline Implementation\n// ============================================================================\n\nfunction runPipeline(\n styles: Styles,\n parserContext: StateParserContext,\n): CSSRule[] {\n const allRules: CSSRule[] = [];\n\n // Process styles recursively (including nested selectors)\n processStyles(styles, '', parserContext, allRules);\n\n // Deduplicate rules\n const seen = new Set<string>();\n const dedupedRules = allRules.filter((rule) => {\n // Include rootPrefix in dedup key - rules with different root prefixes are distinct\n const key = `${rule.selector}|${rule.declarations}|${rule.atRules?.join('|') ?? ''}|${rule.rootPrefix || ''}`;\n if (seen.has(key)) return false;\n seen.add(key);\n return true;\n });\n\n return dedupedRules;\n}\n\n/**\n * Process styles at a given nesting level\n */\nfunction processStyles(\n styles: Styles,\n selectorSuffix: string,\n parserContext: StateParserContext,\n allRules: CSSRule[],\n): void {\n const keys = Object.keys(styles);\n\n // Separate selector keys from style keys\n // Skip @keyframes (processed separately) and other @ prefixed keys (predefined states)\n const selectorKeys = keys.filter((key) => isSelector(key));\n const styleKeys = keys.filter(\n (key) => !isSelector(key) && !key.startsWith('@'),\n );\n\n // Process nested selectors first\n for (const key of selectorKeys) {\n const nestedStyles = styles[key] as Styles;\n if (!nestedStyles || typeof nestedStyles !== 'object') continue;\n\n // Get all selectors (handles comma-separated patterns)\n const suffixes = getAllSelectors(key, nestedStyles);\n if (!suffixes) continue; // Invalid selector, skip\n\n // Remove $ from nested styles\n const { $: _$, ...cleanedStyles } = nestedStyles;\n\n // Extract local predefined states scoped to this sub-element\n const subLocalStates = extractLocalPredefinedStates(cleanedStyles);\n const hasSubStates = Object.keys(subLocalStates).length > 0;\n const subContext: StateParserContext = {\n ...parserContext,\n isSubElement: true,\n localPredefinedStates: hasSubStates\n ? { ...parserContext.localPredefinedStates, ...subLocalStates }\n : parserContext.localPredefinedStates,\n };\n\n // Process for each selector (multiple selectors = same styles applied to each)\n for (const suffix of suffixes) {\n processStyles(\n cleanedStyles,\n selectorSuffix + suffix,\n subContext,\n allRules,\n );\n }\n }\n\n // Build handler queue\n const handlerQueue = buildHandlerQueue(styleKeys, styles);\n\n // Process each handler\n for (const { handler, styleMap } of handlerQueue) {\n const lookupStyles = handler.__lookupStyles;\n\n // Stage 1 & 2: Parse and build exclusive conditions for each style\n // Exclusive conditions ensure each CSS rule applies to exactly one state.\n // OR conditions in exclusives are properly expanded to DNF (multiple CSS selectors).\n const exclusiveByStyle = new Map<string, ExclusiveStyleEntry[]>();\n\n for (const styleName of lookupStyles) {\n const value = styleMap[styleName];\n if (value === undefined) continue;\n\n if (isValueMapping(value)) {\n // Parse entries from value mapping\n const parsed = parseStyleEntries(styleName, value, (stateKey) =>\n parseStateKey(stateKey, { context: parserContext }),\n );\n\n // Expand OR conditions into exclusive branches\n // This ensures OR branches like `A | B | C` become:\n // A, B & !A, C & !A & !B\n const expanded = expandOrConditions(parsed);\n\n // Build exclusive conditions across all entries\n const exclusive = buildExclusiveConditions(expanded);\n\n // Expand ORs from De Morgan negation into exclusive branches\n // This transforms: !A | !B → !A, (A & !B)\n // Ensures each CSS rule has proper at-rule context\n const fullyExpanded = expandExclusiveOrs(exclusive);\n exclusiveByStyle.set(styleName, fullyExpanded);\n } else {\n // Simple value - single entry with TRUE condition\n exclusiveByStyle.set(styleName, [\n {\n styleKey: styleName,\n stateKey: '',\n value,\n condition: trueCondition(),\n priority: 0,\n exclusiveCondition: trueCondition(),\n },\n ]);\n }\n }\n\n // Stage 4: Compute all valid state combinations\n const stateSnapshots = computeStateCombinations(\n exclusiveByStyle,\n lookupStyles,\n );\n\n // Stage 5: Call handler for each snapshot\n const computedRules: ComputedRule[] = [];\n\n for (const snapshot of stateSnapshots) {\n const result = handler(snapshot.values as StyleValueStateMap);\n if (!result) continue;\n\n // Handler may return single or array\n const results = Array.isArray(result) ? result : [result];\n\n for (const r of results) {\n if (!r || typeof r !== 'object') continue;\n\n const { $, ...styleProps } = r;\n const declarations: Record<string, string> = {};\n\n for (const [prop, val] of Object.entries(styleProps)) {\n if (val != null && val !== '') {\n declarations[prop] = String(val);\n }\n }\n\n if (Object.keys(declarations).length === 0) continue;\n\n // Handle $ suffixes\n const suffixes = $\n ? (Array.isArray($) ? $ : [$]).map(\n (s) => selectorSuffix + normalizeSelectorSuffix(String(s)),\n )\n : [selectorSuffix];\n\n for (const suffix of suffixes) {\n computedRules.push({\n condition: snapshot.condition,\n declarations,\n selectorSuffix: suffix,\n });\n }\n }\n }\n\n // Stage 6: Merge rules with identical CSS output\n const mergedRules = mergeByValue(computedRules);\n\n // Stage 7: Materialize to CSS\n for (const rule of mergedRules) {\n const cssRules = materializeComputedRule(rule);\n allRules.push(...cssRules);\n }\n }\n}\n\n// ============================================================================\n// Helper Functions\n// ============================================================================\n\n/**\n * Check if a key is a CSS selector\n */\nexport function isSelector(key: string): boolean {\n return key.startsWith('&') || key.startsWith('.') || /^[A-Z]/.test(key);\n}\n\n/**\n * Result of processing a selector affix ($) pattern.\n *\n * @example\n * // Valid result with multiple selectors\n * { valid: true, selectors: ['> [data-element=\"Cell\"]', ' [data-element=\"Body\"] > [data-element=\"Cell\"]'] }\n *\n * // Invalid result with error message\n * { valid: false, reason: 'Selector affix \"+\" targets elements outside the root scope.' }\n */\ntype AffixResult =\n | { valid: true; selectors: string[] }\n | { valid: false; reason: string };\n\n/**\n * Get all selector suffixes for a sub-element key.\n *\n * Handles three types of selector keys:\n * - `&` prefix: Raw selector suffix (e.g., `&:hover` → `:hover`)\n * - `.` prefix: Class selector (e.g., `.active` → ` .active`)\n * - Uppercase: Sub-element with optional `$` affix pattern\n *\n * @param key - The sub-element key (e.g., 'Label', '&:hover', '.active')\n * @param styles - The styles object, may contain `$` property for selector affix\n * @returns Array of selector suffixes, or null if invalid (with console warning)\n *\n * @example\n * getAllSelectors('Label', {})\n * // → [' [data-element=\"Label\"]']\n *\n * getAllSelectors('Cell', { $: '>, >Body>' })\n * // → ['> [data-element=\"Cell\"]', ' [data-element=\"Body\"] > [data-element=\"Cell\"]']\n */\nfunction getAllSelectors(key: string, styles?: Styles): string[] | null {\n if (key.startsWith('&')) {\n return [key.slice(1)];\n }\n\n if (key.startsWith('.')) {\n return [` ${key}`];\n }\n\n if (/^[A-Z]/.test(key)) {\n const affix = styles?.$;\n if (affix !== undefined) {\n const result = processAffix(String(affix), key);\n if (!result.valid) {\n emitWarning('INVALID_SELECTOR_AFFIX', result.reason);\n return null;\n }\n return result.selectors;\n }\n return [` [data-element=\"${key}\"]`];\n }\n\n return null;\n}\n\n/**\n * Process selector affix pattern and return selector(s)\n *\n * Supports:\n * - Direct child: '>'\n * - Chained elements: '>Body>Row>'\n * - HTML tags: 'a', '>ul>li', 'button:hover'\n * - Pseudo-elements on root: '::before'\n * - Pseudo on sub-element: '@::before', '>@:hover'\n * - Classes: '.active', '>@.active'\n * - Multiple selectors: '>, >Body>'\n * - Sibling combinators (after element): '>Item+', '>Item~'\n */\nfunction processAffix(affix: string, key: string): AffixResult {\n const trimmed = affix.trim();\n\n // Empty = default behavior (descendant selector with key)\n if (!trimmed) {\n return { valid: true, selectors: [` [data-element=\"${key}\"]`] };\n }\n\n // Split by comma for multiple selectors\n const patterns = trimmed.split(',').map((p) => p.trim());\n const selectors: string[] = [];\n\n for (const pattern of patterns) {\n const validation = validatePattern(pattern);\n if (!validation.valid) {\n return validation;\n }\n\n const selector = processSinglePattern(pattern, key);\n selectors.push(selector);\n }\n\n return { valid: true, selectors };\n}\n\n/**\n * Recognized token patterns for selector affix validation.\n *\n * These patterns are used to tokenize and validate `$` affix strings.\n * Order matters: more specific patterns must come first to avoid\n * partial matches (e.g., `::before` must match before `:` alone).\n *\n * Unrecognized tokens (like `#id`, `*`, or numbers) will cause validation to fail.\n */\nconst VALID_TOKEN_PATTERNS = [\n /^[>+~]/, // Combinators: >, +, ~\n /^[A-Z][a-zA-Z0-9]*/, // Uppercase element names → [data-element=\"...\"]\n /^@/, // @ placeholder for key injection position\n /^::?[a-z][a-z0-9-]*(?:\\([^)]*\\))?/, // Pseudo-elements/classes (:hover, ::before, :not(.x))\n /^\\.[a-zA-Z_-][a-zA-Z0-9_-]*/, // Class selectors (.active, .is-open)\n /^\\[[^\\]]+\\]/, // Attribute selectors ([type=\"text\"], [role])\n /^[a-z][a-z0-9-]*/, // HTML tag names (a, div, button, my-component)\n /^\\s+/, // Whitespace (ignored during parsing)\n /^&/, // Root reference (stripped, kept for backward compat)\n];\n\n/**\n * Scan a pattern for unrecognized tokens.\n *\n * Iterates through the pattern, consuming recognized tokens until\n * either the pattern is fully consumed (valid) or an unrecognized\n * character sequence is found (invalid).\n *\n * @param pattern - The selector pattern to validate\n * @returns The first unrecognized token found, or null if all tokens are valid\n *\n * @example\n * findUnrecognizedTokens('>Body>Row>') // → null (valid)\n * findUnrecognizedTokens('123') // → '123' (invalid)\n * findUnrecognizedTokens('#myId') // → '#' (invalid)\n */\nfunction findUnrecognizedTokens(pattern: string): string | null {\n let remaining = pattern;\n\n while (remaining.length > 0) {\n let matched = false;\n\n for (const regex of VALID_TOKEN_PATTERNS) {\n const match = remaining.match(regex);\n if (match) {\n remaining = remaining.slice(match[0].length);\n matched = true;\n break;\n }\n }\n\n if (!matched) {\n // Found unrecognized content - extract the problematic part\n const unrecognized = remaining.match(/^[^\\s>+~@.:[\\]A-Z]+/);\n return unrecognized ? unrecognized[0] : remaining[0];\n }\n }\n\n return null;\n}\n\n/**\n * Validate a selector pattern for structural correctness.\n *\n * Checks for:\n * 1. Out-of-scope selectors: Patterns starting with `+` or `~` target siblings\n * of the root element, which is outside the component's DOM scope.\n * 2. Consecutive combinators: Patterns like `>>` or `>+` are malformed CSS.\n * 3. Unrecognized tokens: Characters/sequences not matching valid CSS selectors.\n *\n * @param pattern - A single selector pattern (already split by comma)\n * @returns AffixResult indicating validity and error reason if invalid\n *\n * @example\n * validatePattern('>Body>Row>') // → { valid: true, selectors: [] }\n * validatePattern('+') // → { valid: false, reason: '...outside root scope...' }\n * validatePattern('>>') // → { valid: false, reason: '...consecutive combinators...' }\n */\nfunction validatePattern(pattern: string): AffixResult {\n const trimmed = pattern.trim();\n\n // Patterns starting with + or ~ target siblings of the root element,\n // which is outside the component's scope. Valid sibling patterns must\n // be preceded by an element: \">Item+\", \">Item~\"\n if (/^[+~]/.test(trimmed)) {\n return {\n valid: false,\n reason:\n `Selector affix \"${pattern}\" targets elements outside the root scope. ` +\n `Sibling selectors (+, ~) must be preceded by an element inside the root. ` +\n `Use \">Element+\" or \">Element~\" instead.`,\n };\n }\n\n // Check for consecutive combinators\n if (/[>+~]{2,}/.test(trimmed.replace(/\\s+/g, ''))) {\n return {\n valid: false,\n reason: `Selector affix \"${pattern}\" contains consecutive combinators.`,\n };\n }\n\n // Check for unrecognized tokens (e.g., lowercase text like \"foo\")\n const unrecognized = findUnrecognizedTokens(trimmed);\n if (unrecognized) {\n return {\n valid: false,\n reason:\n `Selector affix \"${pattern}\" contains unrecognized token \"${unrecognized}\". ` +\n `Valid tokens: combinators (>, +, ~), element names (Uppercase), ` +\n `@ placeholder, pseudo (:hover, ::before), class (.name), attribute ([attr]).`,\n };\n }\n\n return { valid: true, selectors: [] };\n}\n\n/**\n * Process a single selector pattern into a CSS selector suffix.\n *\n * This is the main transformation function that converts a `$` affix pattern\n * into a valid CSS selector suffix. It handles:\n *\n * 1. `@` placeholder replacement with `[data-element=\"key\"]`\n * 2. Key injection based on pattern ending (see `shouldInjectKey`)\n * 3. Proper spacing for descendant vs direct child selectors\n *\n * @param pattern - A single validated selector pattern\n * @param key - The sub-element key to inject (e.g., 'Label', 'Cell')\n * @returns CSS selector suffix ready to append to the root selector\n *\n * @example\n * processSinglePattern('>', 'Row')\n * // → '> [data-element=\"Row\"]'\n *\n * processSinglePattern('>Body>Row>', 'Cell')\n * // → '> [data-element=\"Body\"] > [data-element=\"Row\"] > [data-element=\"Cell\"]'\n *\n * processSinglePattern('::before', 'Before')\n * // → '::before' (no key injection for pseudo on root)\n *\n * processSinglePattern('>@:hover', 'Item')\n * // → '> [data-element=\"Item\"]:hover'\n */\nfunction processSinglePattern(pattern: string, key: string): string {\n // Strip leading & if present (implicit root reference, kept for compat)\n const normalized = pattern.replace(/^&/, '').trim();\n\n if (!normalized) {\n return ` [data-element=\"${key}\"]`;\n }\n\n // Pseudo-elements/classes at start apply directly to root (no space prefix)\n const startsWithPseudo = /^::?[a-z]/.test(normalized);\n\n // Transform the pattern: convert element names and normalize spacing\n let result = transformPattern(normalized);\n\n // Handle @ placeholder: explicit key injection position\n if (result.includes('@')) {\n // Remove space between @ and following class/pseudo for proper attachment\n // e.g., \"@ .active\" → \"[el].active\", but \"@ > span\" → \"[el] > span\"\n result = result.replace(/@ (?=[.:])/g, '@');\n result = result.replace(/@/g, `[data-element=\"${key}\"]`);\n\n if (!startsWithPseudo && !result.startsWith(' ')) {\n result = ' ' + result;\n }\n return result;\n }\n\n // Auto-inject key based on pattern ending (see shouldInjectKey for rules)\n if (shouldInjectKey(normalized)) {\n result = result + ' ' + `[data-element=\"${key}\"]`;\n }\n\n // Add space prefix for selectors targeting inside root (not pseudo on root)\n if (!startsWithPseudo && !result.startsWith(' ')) {\n result = ' ' + result;\n }\n\n return result;\n}\n\n/**\n * Transform a selector pattern by converting element names and normalizing spacing.\n *\n * This is a character-by-character tokenizer that:\n * - Converts uppercase names to `[data-element=\"Name\"]` selectors\n * - Adds proper spacing around combinators (>, +, ~)\n * - Preserves lowercase tags, classes, pseudos, and attributes as-is\n * - Keeps @ placeholder for later replacement\n *\n * The tokenizer handles these token types in order:\n * 1. Whitespace (skipped)\n * 2. Combinators: >, +, ~ (add surrounding spaces)\n * 3. Uppercase names: Body, Row (convert to [data-element=\"...\"])\n * 4. @ placeholder (keep for later replacement)\n * 5. Pseudo: :hover, ::before (attach to previous token)\n * 6. Tags: a, div, button (keep as-is with spacing)\n * 7. Classes: .active (attach to previous element/tag/placeholder)\n * 8. Attributes: [type=\"text\"] (keep as-is)\n *\n * @param pattern - The raw selector pattern to transform\n * @returns Transformed pattern with proper CSS selector syntax\n *\n * @example\n * transformPattern('>Body>Row>')\n * // → '> [data-element=\"Body\"] > [data-element=\"Row\"] >'\n *\n * transformPattern('button.primary:hover')\n * // → 'button.primary:hover'\n */\nfunction transformPattern(pattern: string): string {\n let result = '';\n let lastCh = '';\n let i = 0;\n\n while (i < pattern.length) {\n const char = pattern[i];\n\n if (/\\s/.test(char)) {\n i++;\n continue;\n }\n\n if (/[>+~]/.test(char)) {\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n result += char;\n lastCh = char;\n i++;\n continue;\n }\n\n if (/[A-Z]/.test(char)) {\n const nameStart = i;\n while (i < pattern.length && /[a-zA-Z0-9]/.test(pattern[i])) {\n i++;\n }\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n const segment = `[data-element=\"${pattern.slice(nameStart, i)}\"]`;\n result += segment;\n lastCh = ']';\n continue;\n }\n\n if (char === '@') {\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n result += '@';\n lastCh = '@';\n i++;\n continue;\n }\n\n if (char === ':') {\n const pseudoStart = i;\n while (\n i < pattern.length &&\n !/[\\s>+~,@]/.test(pattern[i]) &&\n !/[A-Z]/.test(pattern[i])\n ) {\n i++;\n }\n const segment = pattern.slice(pseudoStart, i);\n result += segment;\n lastCh = segment[segment.length - 1] || lastCh;\n continue;\n }\n\n if (/[a-z]/.test(char)) {\n const tagStart = i;\n while (i < pattern.length && /[a-z0-9-]/.test(pattern[i])) {\n i++;\n }\n if (result && lastCh !== ' ') {\n result += ' ';\n }\n const segment = pattern.slice(tagStart, i);\n result += segment;\n lastCh = segment[segment.length - 1] || lastCh;\n continue;\n }\n\n if (char === '.') {\n const attachToLast =\n lastCh === ']' || lastCh === '@' || /[a-zA-Z0-9-]/.test(lastCh);\n if (result && !attachToLast && lastCh !== ' ') {\n result += ' ';\n }\n const clsStart = i;\n i++;\n while (i < pattern.length && /[a-zA-Z0-9_-]/.test(pattern[i])) {\n i++;\n }\n const segment = pattern.slice(clsStart, i);\n result += segment;\n lastCh = segment[segment.length - 1] || lastCh;\n continue;\n }\n\n if (char === '[') {\n const attachToLast =\n lastCh === ']' || lastCh === '@' || /[a-zA-Z0-9-]/.test(lastCh);\n if (result && !attachToLast && lastCh !== ' ') {\n result += ' ';\n }\n const attrStart = i;\n let depth = 0;\n while (i < pattern.length) {\n if (pattern[i] === '[') depth++;\n if (pattern[i] === ']') depth--;\n i++;\n if (depth === 0) break;\n }\n result += pattern.slice(attrStart, i);\n lastCh = ']';\n continue;\n }\n\n result += char;\n lastCh = char;\n i++;\n }\n\n return result;\n}\n\n/**\n * Determine if the sub-element key should be auto-injected based on pattern ending.\n *\n * Key injection rules (when no @ placeholder is present):\n *\n * | Pattern Ending | Inject Key? | Example | Result |\n * |----------------|-------------|---------|--------|\n * | Combinator (>, +, ~) | Yes | `'>Body>'` | `> [data-element=\"Body\"] > [el]` |\n * | Uppercase element | Yes | `'>Body>Row'` | `> [el1] > [el2] [key]` |\n * | Lowercase tag | Yes | `'>ul>li'` | `> ul > li [key]` |\n * | Pseudo (:hover, ::before) | No | `'::before'` | `::before` |\n * | Class (.active) | No | `'.active'` | `.active` |\n * | Attribute ([type]) | No | `'[type=\"text\"]'` | `[type=\"text\"]` |\n *\n * @param pattern - The normalized pattern (after stripping &)\n * @returns true if key should be injected, false otherwise\n *\n * @example\n * shouldInjectKey('>') // → true (trailing combinator)\n * shouldInjectKey('>Body>Row') // → true (ends with element)\n * shouldInjectKey('>ul>li') // → true (ends with tag)\n * shouldInjectKey('::before') // → false (ends with pseudo)\n * shouldInjectKey('.active') // → false (ends with class)\n * shouldInjectKey('a:hover') // → false (ends with pseudo)\n * shouldInjectKey('button.primary') // → false (ends with class)\n */\nfunction shouldInjectKey(pattern: string): boolean {\n const trimmed = pattern.trim();\n\n // Rule 1: Ends with combinator → inject key after it\n // e.g., '>' → '> [data-element=\"Key\"]'\n if (/[>+~]$/.test(trimmed)) {\n return true;\n }\n\n // Rule 2: Ends with uppercase element name → inject key as descendant\n // The lookbehind ensures we're matching a standalone element name, not\n // part of a class like .myClass (where C is preceded by lowercase)\n // e.g., '>Body' → '> [data-element=\"Body\"] [data-element=\"Key\"]'\n if (/(?:^|[\\s>+~\\]:])[A-Z][a-zA-Z0-9]*$/.test(trimmed)) {\n return true;\n }\n\n // Rule 3: Ends with lowercase tag name → inject key as descendant\n // The negative lookbehind (?<![:.]) ensures we don't match:\n // - ':hover' (pseudo ending)\n // - '.primary' (class ending)\n // e.g., '>ul>li' → '> ul > li [data-element=\"Key\"]'\n if (/(?<![:.])(?:^|[\\s>+~])[a-z][a-z0-9-]*$/.test(trimmed)) {\n return true;\n }\n\n // Rule 4: Otherwise (pseudo, class, attribute) → no injection\n // The pattern is complete as-is, applying to root or a specific selector\n return false;\n}\n\n/**\n * Normalize selector suffix from $ property\n */\nfunction normalizeSelectorSuffix(suffix: string): string {\n if (!suffix) return '';\n return suffix.startsWith('&') ? suffix.slice(1) : suffix;\n}\n\n/**\n * Build handler queue from style keys\n */\nfunction buildHandlerQueue(\n styleKeys: string[],\n styles: Styles,\n): { handler: StyleHandler; styleMap: StyleMap }[] {\n const queue: { handler: StyleHandler; styleMap: StyleMap }[] = [];\n const seenHandlers = new Set<StyleHandler>();\n\n for (const styleName of styleKeys) {\n let handlers: StyleHandler[] = STYLE_HANDLER_MAP[styleName];\n\n if (!handlers) {\n handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];\n }\n\n for (const handler of handlers) {\n if (seenHandlers.has(handler)) continue;\n seenHandlers.add(handler);\n\n const lookupStyles = handler.__lookupStyles;\n const styleMap: StyleMap = {};\n\n for (const name of lookupStyles) {\n const val = styles[name];\n if (val !== undefined) {\n styleMap[name] = val as StyleValue | StyleValueStateMap;\n }\n }\n\n queue.push({ handler, styleMap });\n }\n }\n\n return queue;\n}\n\n/**\n * Compute all valid state combinations for a handler's lookup styles\n */\nfunction computeStateCombinations(\n exclusiveByStyle: Map<string, ExclusiveStyleEntry[]>,\n lookupStyles: string[],\n): { condition: ConditionNode; values: Record<string, StyleValue> }[] {\n // Get entries for each style\n const entriesPerStyle = lookupStyles.map(\n (style) => exclusiveByStyle.get(style) || [],\n );\n\n // Cartesian product of all combinations\n const combinations = cartesianProduct(entriesPerStyle);\n\n // Build snapshots, simplifying and filtering impossible combinations\n const snapshots: {\n condition: ConditionNode;\n values: Record<string, StyleValue>;\n }[] = [];\n\n for (const combo of combinations) {\n // Combine all exclusive conditions with AND\n const conditions = combo.map((e) => e.exclusiveCondition);\n const combined = and(...conditions);\n const simplified = simplifyCondition(combined);\n\n // Skip impossible combinations\n if (simplified.kind === 'false') continue;\n\n // Build values map\n const values: Record<string, StyleValue> = {};\n for (const entry of combo) {\n values[entry.styleKey] = entry.value;\n }\n\n snapshots.push({\n condition: simplified,\n values,\n });\n }\n\n return snapshots;\n}\n\n/**\n * Cartesian product of arrays\n */\nfunction cartesianProduct<T>(arrays: T[][]): T[][] {\n if (arrays.length === 0) return [[]];\n\n const nonEmpty = arrays.filter((a) => a.length > 0);\n if (nonEmpty.length === 0) return [[]];\n\n let result: T[][] = [[]];\n for (const arr of nonEmpty) {\n const next: T[][] = [];\n for (const combo of result) {\n for (const item of arr) {\n const newCombo = new Array<T>(combo.length + 1);\n for (let i = 0; i < combo.length; i++) newCombo[i] = combo[i];\n newCombo[combo.length] = item;\n next.push(newCombo);\n }\n }\n result = next;\n }\n return result;\n}\n\nconst declStringCache = new WeakMap<Record<string, string>, string>();\n\nfunction stringifyDeclarations(decl: Record<string, string>): string {\n let cached = declStringCache.get(decl);\n if (cached === undefined) {\n cached = JSON.stringify(decl);\n declStringCache.set(decl, cached);\n }\n return cached;\n}\n\n/**\n * Merge rules with identical CSS output\n */\nfunction mergeByValue(rules: ComputedRule[]): ComputedRule[] {\n const groups = new Map<string, ComputedRule[]>();\n\n for (const rule of rules) {\n const key = `${rule.selectorSuffix}|${stringifyDeclarations(rule.declarations)}`;\n if (!groups.has(key)) {\n groups.set(key, []);\n }\n groups.get(key)!.push(rule);\n }\n\n // Merge conditions with OR for each group\n const merged: ComputedRule[] = [];\n\n for (const [, groupRules] of groups) {\n if (groupRules.length === 1) {\n merged.push(groupRules[0]);\n } else {\n // Merge conditions with OR\n const mergedCondition = simplifyCondition(\n or(...groupRules.map((r) => r.condition)),\n );\n merged.push({\n condition: mergedCondition,\n declarations: groupRules[0].declarations,\n selectorSuffix: groupRules[0].selectorSuffix,\n });\n }\n }\n\n return merged;\n}\n\n/**\n * Build selector fragment from a variant (without className prefix)\n */\nfunction buildSelectorFromVariant(\n variant: SelectorVariant,\n selectorSuffix: string,\n): string {\n let selector = '';\n\n // Add flat modifier + pseudo selectors (sorted for canonical output)\n selector += branchToCSS([\n ...variant.modifierConditions,\n ...variant.pseudoConditions,\n ]);\n\n // Add selector groups (:is()/:not() on element)\n for (const group of variant.selectorGroups) {\n selector += selectorGroupToCSS(group);\n }\n\n // Add parent selectors (before sub-element suffix)\n if (variant.parentGroups.length > 0) {\n selector += parentGroupsToCSS(variant.parentGroups);\n }\n\n selector += selectorSuffix;\n\n // Add own groups (:is()/:not() on sub-element)\n const ownOptimized = optimizeGroups(variant.ownGroups);\n for (const group of ownOptimized) {\n selector += selectorGroupToCSS(group);\n }\n\n return selector;\n}\n\n/**\n * Materialize a computed rule to final CSS format\n *\n * Returns an array because OR conditions may generate multiple CSS rules\n * (when different branches have different at-rules)\n */\nfunction materializeComputedRule(rule: ComputedRule): CSSRule[] {\n const components = conditionToCSS(rule.condition);\n\n if (components.isImpossible || components.variants.length === 0) {\n return [];\n }\n\n const declarations = Object.entries(rule.declarations)\n .map(([prop, value]) => `${prop}: ${value};`)\n .join(' ');\n\n // Helper to get root prefix key for grouping\n const getRootPrefixKey = (variant: SelectorVariant): string => {\n return rootGroupsToCSS(variant.rootGroups) || '';\n };\n\n // Group variants by their at-rules (variants with same at-rules can be combined with commas)\n const byAtRules = new Map<\n string,\n { variants: SelectorVariant[]; atRules: string[]; rootPrefix?: string }\n >();\n\n for (const variant of components.variants) {\n const atRules = buildAtRulesFromVariant(variant);\n const key = atRules.sort().join('|||') + '###' + getRootPrefixKey(variant);\n\n const group = byAtRules.get(key);\n if (group) {\n group.variants.push(variant);\n } else {\n byAtRules.set(key, {\n variants: [variant],\n atRules,\n rootPrefix: rootGroupsToCSS(variant.rootGroups),\n });\n }\n }\n\n // Generate one CSSRule per at-rules group\n const rules: CSSRule[] = [];\n for (const [, group] of byAtRules) {\n // Merge variants that differ only in flat modifier/pseudo conditions\n // into :is() groups before building selector strings\n const mergedVariants = mergeVariantsIntoSelectorGroups(group.variants);\n\n // Build selector fragments for each variant (will be joined with className later)\n const selectorFragments = mergedVariants.map((v) =>\n buildSelectorFromVariant(v, rule.selectorSuffix),\n );\n\n // Store as array if multiple, string if single\n const selector =\n selectorFragments.length === 1 ? selectorFragments[0] : selectorFragments;\n\n const cssRule: CSSRule = {\n selector,\n declarations,\n };\n\n if (group.atRules.length > 0) {\n cssRule.atRules = group.atRules;\n }\n\n if (group.rootPrefix) {\n cssRule.rootPrefix = group.rootPrefix;\n }\n\n rules.push(cssRule);\n }\n\n return rules;\n}\n\n// ============================================================================\n// Public API: renderStyles (compatible with old API)\n// ============================================================================\n\n/**\n * Options for renderStyles when using direct selector mode.\n */\nexport interface RenderStylesOptions {\n /**\n * Whether to double the class selector for increased specificity.\n * When true, `.myClass` becomes `.myClass.myClass` for higher specificity.\n *\n * @default false - User-provided selectors are not doubled.\n *\n * Note: This only applies when a classNameOrSelector is provided.\n * When renderStyles returns RenderResult with needsClassName=true,\n * the injector handles doubling automatically.\n */\n doubleSelector?: boolean;\n}\n\n/**\n * Render styles to CSS rules.\n *\n * When called without classNameOrSelector, returns RenderResult with needsClassName=true.\n * When called with a selector/className string, returns StyleResult[] for direct injection.\n */\nexport function renderStyles(\n styles?: Styles,\n classNameOrSelector?: undefined,\n options?: undefined,\n pipelineCacheKey?: string,\n): RenderResult;\nexport function renderStyles(\n styles: Styles | undefined,\n classNameOrSelector: string,\n options?: RenderStylesOptions,\n): StyleResult[];\nexport function renderStyles(\n styles?: Styles,\n classNameOrSelector?: string,\n options?: RenderStylesOptions,\n pipelineCacheKey?: string,\n): RenderResult | StyleResult[] {\n // Check if we have a direct selector/className\n const directSelector = !!classNameOrSelector;\n\n // Check cache first when a pre-computed key is available.\n // This allows callers to skip building the styles object on cache hit.\n let rules: CSSRule[] | undefined;\n if (pipelineCacheKey) {\n rules = pipelineCache.get(pipelineCacheKey);\n }\n\n if (!rules && !styles) {\n return directSelector ? [] : { rules: [] };\n }\n\n // Use pre-computed cache key when available (from chunk path),\n // falling back to stringifyStyles for direct renderStyles() calls\n const cacheKey = pipelineCacheKey || stringifyStyles(styles!);\n if (!rules) {\n rules = pipelineCache.get(cacheKey);\n }\n\n if (!rules) {\n // styles is guaranteed non-null here: early return above handles (!rules && !styles)\n const parserContext = createStateParserContext(styles!);\n rules = runPipeline(styles!, parserContext);\n pipelineCache.set(cacheKey, rules);\n }\n\n // Direct selector/className mode: return StyleResult[] directly\n if (directSelector) {\n const shouldDouble = options?.doubleSelector ?? false;\n\n return rules.map((rule): StyleResult => {\n // Handle selector as array (OR conditions) or string\n const selectorParts = Array.isArray(rule.selector)\n ? rule.selector\n : rule.selector\n ? [rule.selector]\n : [''];\n\n const finalSelector = selectorParts\n .map((part) => {\n let sel = part\n ? `${classNameOrSelector}${part}`\n : classNameOrSelector;\n\n // Double class selector for increased specificity if requested\n // This is used when the caller explicitly wants higher specificity\n if (shouldDouble && sel.startsWith('.')) {\n const classMatch = sel.match(/^\\.[a-zA-Z_-][a-zA-Z0-9_-]*/);\n if (classMatch) {\n const baseClass = classMatch[0];\n sel = baseClass + sel;\n }\n }\n\n // Handle root prefix for this selector\n if (rule.rootPrefix) {\n sel = `${rule.rootPrefix} ${sel}`;\n }\n\n return sel;\n })\n .join(', ');\n\n const result: StyleResult = {\n selector: finalSelector,\n declarations: rule.declarations,\n };\n\n if (rule.atRules && rule.atRules.length > 0) {\n result.atRules = rule.atRules;\n }\n\n return result;\n });\n }\n\n // No className mode: return RenderResult with needsClassName flag\n // Normalize selector to string (join array with placeholder that injector will handle)\n return {\n rules: rules.map(\n (r): StyleResult => ({\n selector: Array.isArray(r.selector)\n ? r.selector.join('|||')\n : r.selector,\n declarations: r.declarations,\n atRules: r.atRules,\n needsClassName: true,\n rootPrefix: r.rootPrefix,\n }),\n ),\n };\n}\n\n// ============================================================================\n// Exports\n// ============================================================================\n\nexport type { ConditionNode } from './conditions';\nexport { and, or, not, trueCondition, falseCondition } from './conditions';\nexport { parseStateKey } from './parseStateKey';\nexport { simplifyCondition } from './simplify';\nexport { buildExclusiveConditions } from './exclusive';\nexport { conditionToCSS } from './materialize';\nexport type { CSSRule } from './materialize';\nexport { setWarningHandler, emitWarning } from './warnings';\nexport type {\n TastyWarning,\n TastyWarningCode,\n TastyWarningHandler,\n} from './warnings';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+FA,MAAM,gBAAgB,IAAI,IAAuB,IAAK;;;;;AAyEtD,SAAgB,sBAAsB,UAA2B;AAC/D,QAAO,cAAc,IAAI,SAAS,KAAK;;;;;AAMzC,SAAgB,qBAA2B;AACzC,eAAc,OAAO;;AAOvB,SAAS,YACP,QACA,eACW;CACX,MAAM,WAAsB,EAAE;AAG9B,eAAc,QAAQ,IAAI,eAAe,SAAS;CAGlD,MAAM,uBAAO,IAAI,KAAa;AAS9B,QARqB,SAAS,QAAQ,SAAS;EAE7C,MAAM,MAAM,GAAG,KAAK,SAAS,GAAG,KAAK,aAAa,GAAG,KAAK,SAAS,KAAK,IAAI,IAAI,GAAG,GAAG,KAAK,cAAc;AACzG,MAAI,KAAK,IAAI,IAAI,CAAE,QAAO;AAC1B,OAAK,IAAI,IAAI;AACb,SAAO;GACP;;;;;AAQJ,SAAS,cACP,QACA,gBACA,eACA,UACM;CACN,MAAM,OAAO,OAAO,KAAK,OAAO;CAIhC,MAAM,eAAe,KAAK,QAAQ,QAAQ,WAAW,IAAI,CAAC;CAC1D,MAAM,YAAY,KAAK,QACpB,QAAQ,CAAC,WAAW,IAAI,IAAI,CAAC,IAAI,WAAW,IAAI,CAClD;AAGD,MAAK,MAAM,OAAO,cAAc;EAC9B,MAAM,eAAe,OAAO;AAC5B,MAAI,CAAC,gBAAgB,OAAO,iBAAiB,SAAU;EAGvD,MAAM,WAAW,gBAAgB,KAAK,aAAa;AACnD,MAAI,CAAC,SAAU;EAGf,MAAM,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