@tenphi/tasty 0.1.2 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"useRawCSS.js","names":[],"sources":["../../src/hooks/useRawCSS.ts"],"sourcesContent":["import { useInsertionEffect, useMemo, useRef } from 'react';\n\nimport { injectRawCSS } from '../injector';\n\ninterface UseRawCSSOptions { root?: Document | ShadowRoot }\n\n/**\n * Hook to inject raw CSS text directly without parsing.\n * This is a low-overhead alternative for injecting global CSS that doesn't need tasty processing.\n *\n * The CSS is inserted into a separate style element (data-tasty-raw) to avoid conflicts\n * with tasty's chunked style sheets.\n *\n * @example Static CSS string\n * ```tsx\n * function GlobalStyles() {\n * useRawCSS(`\n * body {\n * margin: 0;\n * padding: 0;\n * font-family: sans-serif;\n * }\n * `);\n *\n * return null;\n * }\n * ```\n *\n * @example Factory function with dependencies (like useMemo)\n * ```tsx\n * function ThemeStyles({ theme }: { theme: 'light' | 'dark' }) {\n * useRawCSS(() => `\n * :root {\n * --bg-color: ${theme === 'dark' ? '#1a1a1a' : '#ffffff'};\n * --text-color: ${theme === 'dark' ? '#ffffff' : '#1a1a1a'};\n * }\n * `, [theme]);\n *\n * return null;\n * }\n * ```\n *\n * @example With options\n * ```tsx\n * function ShadowStyles({ shadowRoot }) {\n * useRawCSS(() => `.scoped { color: red; }`, [], { root: shadowRoot });\n * return null;\n * }\n * ```\n */\n\n// Overload 1: Static CSS string\nexport function useRawCSS(css: string, options?: UseRawCSSOptions): void;\n\n// Overload 2: Factory function with dependencies\nexport function useRawCSS(\n factory: () => string,\n deps: readonly unknown[],\n options?: UseRawCSSOptions,\n): void;\n\n// Implementation\nexport function useRawCSS(\n cssOrFactory: string | (() => string),\n depsOrOptions?: readonly unknown[] | UseRawCSSOptions,\n options?: UseRawCSSOptions,\n): void {\n // Detect which overload is being used\n const isFactory = typeof cssOrFactory === 'function';\n\n // Parse arguments based on overload\n const deps =\n isFactory && Array.isArray(depsOrOptions) ? depsOrOptions : undefined;\n const opts = isFactory\n ? options\n : (depsOrOptions as UseRawCSSOptions | undefined);\n\n // Memoize CSS - for factory functions, use provided deps; for strings, use the string itself\n const css = useMemo(\n () =>\n isFactory ? (cssOrFactory as () => string)() : (cssOrFactory as string),\n\n isFactory ? deps ?? [] : [cssOrFactory],\n );\n\n const disposeRef = useRef<(() => void) | null>(null);\n\n useInsertionEffect(() => {\n // Dispose previous injection if any\n disposeRef.current?.();\n\n if (!css.trim()) {\n disposeRef.current = null;\n return;\n }\n\n // Inject new CSS\n const { dispose } = injectRawCSS(css, opts);\n disposeRef.current = dispose;\n\n // Cleanup on unmount or when css changes\n return () => {\n disposeRef.current?.();\n disposeRef.current = null;\n };\n }, [css, opts?.root]);\n}\n"],"mappings":";;;;AA8DA,SAAgB,UACd,cACA,eACA,SACM;CAEN,MAAM,YAAY,OAAO,iBAAiB;CAG1C,MAAM,OACJ,aAAa,MAAM,QAAQ,cAAc,GAAG,gBAAgB;CAC9D,MAAM,OAAO,YACT,UACC;CAGL,MAAM,MAAM,cAER,YAAa,cAA+B,GAAI,cAElD,YAAY,QAAQ,EAAE,GAAG,CAAC,aAAa,CACxC;CAED,MAAM,aAAa,OAA4B,KAAK;AAEpD,0BAAyB;AAEvB,aAAW,WAAW;AAEtB,MAAI,CAAC,IAAI,MAAM,EAAE;AACf,cAAW,UAAU;AACrB;;EAIF,MAAM,EAAE,YAAY,aAAa,KAAK,KAAK;AAC3C,aAAW,UAAU;AAGrB,eAAa;AACX,cAAW,WAAW;AACtB,cAAW,UAAU;;IAEtB,CAAC,KAAK,MAAM,KAAK,CAAC"}
1
+ {"version":3,"file":"useRawCSS.js","names":[],"sources":["../../src/hooks/useRawCSS.ts"],"sourcesContent":["import { useInsertionEffect, useMemo, useRef } from 'react';\n\nimport { injectRawCSS } from '../injector';\n\ninterface UseRawCSSOptions {\n root?: Document | ShadowRoot;\n}\n\n/**\n * Hook to inject raw CSS text directly without parsing.\n * This is a low-overhead alternative for injecting global CSS that doesn't need tasty processing.\n *\n * The CSS is inserted into a separate style element (data-tasty-raw) to avoid conflicts\n * with tasty's chunked style sheets.\n *\n * @example Static CSS string\n * ```tsx\n * function GlobalStyles() {\n * useRawCSS(`\n * body {\n * margin: 0;\n * padding: 0;\n * font-family: sans-serif;\n * }\n * `);\n *\n * return null;\n * }\n * ```\n *\n * @example Factory function with dependencies (like useMemo)\n * ```tsx\n * function ThemeStyles({ theme }: { theme: 'light' | 'dark' }) {\n * useRawCSS(() => `\n * :root {\n * --bg-color: ${theme === 'dark' ? '#1a1a1a' : '#ffffff'};\n * --text-color: ${theme === 'dark' ? '#ffffff' : '#1a1a1a'};\n * }\n * `, [theme]);\n *\n * return null;\n * }\n * ```\n *\n * @example With options\n * ```tsx\n * function ShadowStyles({ shadowRoot }) {\n * useRawCSS(() => `.scoped { color: red; }`, [], { root: shadowRoot });\n * return null;\n * }\n * ```\n */\n\n// Overload 1: Static CSS string\nexport function useRawCSS(css: string, options?: UseRawCSSOptions): void;\n\n// Overload 2: Factory function with dependencies\nexport function useRawCSS(\n factory: () => string,\n deps: readonly unknown[],\n options?: UseRawCSSOptions,\n): void;\n\n// Implementation\nexport function useRawCSS(\n cssOrFactory: string | (() => string),\n depsOrOptions?: readonly unknown[] | UseRawCSSOptions,\n options?: UseRawCSSOptions,\n): void {\n // Detect which overload is being used\n const isFactory = typeof cssOrFactory === 'function';\n\n // Parse arguments based on overload\n const deps =\n isFactory && Array.isArray(depsOrOptions) ? depsOrOptions : undefined;\n const opts = isFactory\n ? options\n : (depsOrOptions as UseRawCSSOptions | undefined);\n\n // Memoize CSS - for factory functions, use provided deps; for strings, use the string itself\n const css = useMemo(\n () =>\n isFactory ? (cssOrFactory as () => string)() : (cssOrFactory as string),\n\n isFactory ? (deps ?? []) : [cssOrFactory],\n );\n\n const disposeRef = useRef<(() => void) | null>(null);\n\n useInsertionEffect(() => {\n // Dispose previous injection if any\n disposeRef.current?.();\n\n if (!css.trim()) {\n disposeRef.current = null;\n return;\n }\n\n // Inject new CSS\n const { dispose } = injectRawCSS(css, opts);\n disposeRef.current = dispose;\n\n // Cleanup on unmount or when css changes\n return () => {\n disposeRef.current?.();\n disposeRef.current = null;\n };\n }, [css, opts?.root]);\n}\n"],"mappings":";;;;AAgEA,SAAgB,UACd,cACA,eACA,SACM;CAEN,MAAM,YAAY,OAAO,iBAAiB;CAG1C,MAAM,OACJ,aAAa,MAAM,QAAQ,cAAc,GAAG,gBAAgB;CAC9D,MAAM,OAAO,YACT,UACC;CAGL,MAAM,MAAM,cAER,YAAa,cAA+B,GAAI,cAElD,YAAa,QAAQ,EAAE,GAAI,CAAC,aAAa,CAC1C;CAED,MAAM,aAAa,OAA4B,KAAK;AAEpD,0BAAyB;AAEvB,aAAW,WAAW;AAEtB,MAAI,CAAC,IAAI,MAAM,EAAE;AACf,cAAW,UAAU;AACrB;;EAIF,MAAM,EAAE,YAAY,aAAa,KAAK,KAAK;AAC3C,aAAW,UAAU;AAGrB,eAAa;AACX,cAAW,WAAW;AACtB,cAAW,UAAU;;IAEtB,CAAC,KAAK,MAAM,KAAK,CAAC"}
@@ -1 +1 @@
1
- {"version":3,"file":"injector.js","names":[],"sources":["../../src/injector/injector.ts"],"sourcesContent":["/**\n * Style injector that works with structured style objects\n * Eliminates CSS string parsing for better performance\n */\n\nimport type { StyleResult } from '../pipeline';\nimport {\n colorInitialValueToRgb,\n getEffectiveDefinition,\n normalizePropertyDefinition,\n} from '../properties';\nimport { isDevEnv } from '../utils/is-dev-env';\nimport type { StyleValue } from '../utils/styles';\nimport { parseStyle } from '../utils/styles';\n\nimport { SheetManager } from './sheet-manager';\nimport type {\n CacheMetrics,\n GlobalInjectResult,\n InjectResult,\n KeyframesResult,\n KeyframesSteps,\n PropertyDefinition,\n RawCSSResult,\n RootRegistry,\n StyleInjectorConfig,\n StyleRule,\n} from './types';\n\n/**\n * Generate sequential class name with format t{number}\n */\nfunction generateClassName(counter: number): string {\n return `t${counter}`;\n}\n\nexport class StyleInjector {\n private sheetManager: SheetManager;\n private config: StyleInjectorConfig;\n private cleanupScheduled = false;\n private globalRuleCounter = 0;\n\n /** @internal — exposed for debug utilities only */\n get _sheetManager(): SheetManager {\n return this.sheetManager;\n }\n\n constructor(config: StyleInjectorConfig = {}) {\n this.config = config;\n this.sheetManager = new SheetManager(config);\n }\n\n /**\n * Allocate a className for a cacheKey without injecting styles yet.\n * This allows separating className allocation (render phase) from style injection (insertion phase).\n */\n allocateClassName(\n cacheKey: string,\n options?: { root?: Document | ShadowRoot },\n ): { className: string; isNewAllocation: boolean } {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n // Check if we can reuse existing className for this cache key\n if (registry.cacheKeyToClassName.has(cacheKey)) {\n const className = registry.cacheKeyToClassName.get(cacheKey)!;\n return {\n className,\n isNewAllocation: false,\n };\n }\n\n // Generate new className and reserve it\n const className = generateClassName(registry.classCounter++);\n\n // Create placeholder RuleInfo to reserve the className\n const placeholderRuleInfo = {\n className,\n ruleIndex: -1, // Placeholder - will be set during actual injection\n sheetIndex: -1, // Placeholder - will be set during actual injection\n };\n\n // Store RuleInfo only once by className, and map cacheKey separately\n registry.rules.set(className, placeholderRuleInfo);\n registry.cacheKeyToClassName.set(cacheKey, className);\n\n return {\n className,\n isNewAllocation: true,\n };\n }\n\n /**\n * Inject styles from StyleResult objects\n */\n inject(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot; cacheKey?: string },\n ): InjectResult {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (rules.length === 0) {\n return {\n className: '',\n dispose: () => { /* noop */ },\n };\n }\n\n // Rules are now in StyleRule format directly\n\n // Check if we can reuse based on cache key\n const cacheKey = options?.cacheKey;\n let className: string;\n let isPreAllocated = false;\n\n if (cacheKey && registry.cacheKeyToClassName.has(cacheKey)) {\n // Reuse existing class for this cache key\n className = registry.cacheKeyToClassName.get(cacheKey)!;\n const existingRuleInfo = registry.rules.get(className)!;\n\n // Check if this is a placeholder (pre-allocated but not yet injected)\n isPreAllocated =\n existingRuleInfo.ruleIndex === -1 && existingRuleInfo.sheetIndex === -1;\n\n if (!isPreAllocated) {\n // Already injected - just increment refCount\n const currentRefCount = registry.refCounts.get(className) || 0;\n registry.refCounts.set(className, currentRefCount + 1);\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: () => this.dispose(className, registry),\n };\n }\n } else {\n // Generate new className\n className = generateClassName(registry.classCounter++);\n }\n\n // Process rules: handle needsClassName flag and apply specificity\n const rulesToInsert = rules.map((rule) => {\n let newSelector = rule.selector;\n\n // If rule needs className prepended\n if (rule.needsClassName) {\n // Handle multiple selectors (separated by ||| for OR conditions)\n const selectorParts = newSelector ? newSelector.split('|||') : [''];\n\n const classPrefix = `.${className}.${className}`;\n\n newSelector = selectorParts\n .map((part) => {\n const classSelector = part ? `${classPrefix}${part}` : classPrefix;\n\n // If there's a root prefix, add it before the class selector\n if (rule.rootPrefix) {\n return `${rule.rootPrefix} ${classSelector}`;\n }\n return classSelector;\n })\n .join(', ');\n }\n\n return {\n ...rule,\n selector: newSelector,\n needsClassName: undefined, // Remove the flag after processing\n rootPrefix: undefined, // Remove rootPrefix after processing\n };\n });\n\n // Before inserting, auto-register @property for any color custom properties being defined.\n // Fast parse: split declarations by ';' and match \"--*-color:\"\n // Do this only when we actually insert (i.e., no cache hit above)\n const colorPropRegex = /^\\s*(--[a-z0-9-]+-color)\\s*:/i;\n for (const rule of rulesToInsert) {\n // Skip if no declarations\n if (!rule.declarations) continue;\n const parts = rule.declarations.split(/;+\\s*/);\n for (const part of parts) {\n if (!part) continue;\n const match = colorPropRegex.exec(part);\n if (match) {\n const propName = match[1];\n // Register @property only if not already defined for this root\n if (!this.isPropertyDefined(propName, { root })) {\n this.property(propName, {\n syntax: '<color>',\n initialValue: 'transparent',\n root,\n });\n }\n }\n }\n }\n\n // Insert rules using existing sheet manager\n const ruleInfo = this.sheetManager.insertRule(\n registry,\n rulesToInsert,\n className,\n root,\n );\n\n if (!ruleInfo) {\n // Update metrics\n if (registry.metrics) {\n registry.metrics.misses++;\n }\n\n return {\n className,\n dispose: () => { /* noop */ },\n };\n }\n\n // Store in registry\n registry.refCounts.set(className, 1);\n\n if (isPreAllocated) {\n // Update the existing placeholder entry with real rule info\n registry.rules.set(className, ruleInfo);\n // cacheKey mapping already exists from allocation\n } else {\n // Store new entries\n registry.rules.set(className, ruleInfo);\n if (cacheKey) {\n registry.cacheKeyToClassName.set(cacheKey, className);\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n registry.metrics.misses++;\n }\n\n return {\n className,\n dispose: () => this.dispose(className, registry),\n };\n }\n\n /**\n * Inject global styles (rules without a generated tasty class selector)\n * This ensures we don't reserve a tasty class name (t{number}) for global rules,\n * which could otherwise collide with element-level styles and break lookups.\n */\n injectGlobal(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot },\n ): GlobalInjectResult {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (!rules || rules.length === 0) {\n return { dispose: () => { /* noop */ } };\n }\n\n // Use a non-tasty identifier to avoid any collisions with .t{number} classes\n const key = `global:${this.globalRuleCounter++}`;\n\n const info = this.sheetManager.insertGlobalRule(\n registry,\n rules as unknown as StyleRule[],\n key,\n root,\n );\n\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n }\n\n return {\n dispose: () => {\n if (info) this.sheetManager.deleteGlobalRule(registry, key);\n },\n };\n }\n\n /**\n * Inject raw CSS text directly without parsing\n * This is a low-overhead alternative to createGlobalStyle for raw CSS\n * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking\n */\n injectRawCSS(\n css: string,\n options?: { root?: Document | ShadowRoot },\n ): RawCSSResult {\n const root = options?.root || document;\n return this.sheetManager.injectRawCSS(css, root);\n }\n\n /**\n * Get raw CSS text for SSR\n */\n getRawCSSText(options?: { root?: Document | ShadowRoot }): string {\n const root = options?.root || document;\n return this.sheetManager.getRawCSSText(root);\n }\n\n /**\n * Dispose of a className\n */\n private dispose(className: string, registry: RootRegistry): void {\n const currentRefCount = registry.refCounts.get(className);\n // Guard against stale double-dispose or mismatched lifecycle\n if (currentRefCount == null || currentRefCount <= 0) {\n return;\n }\n\n const newRefCount = currentRefCount - 1;\n registry.refCounts.set(className, newRefCount);\n\n if (newRefCount === 0) {\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalUnused++;\n }\n\n // Check if cleanup should be scheduled\n this.sheetManager.checkCleanupNeeded(registry);\n }\n }\n\n /**\n * Force bulk cleanup of unused styles\n */\n cleanup(root?: Document | ShadowRoot): void {\n const registry = this.sheetManager.getRegistry(root || document);\n // Clean up ALL unused rules regardless of batch ratio\n this.sheetManager.forceCleanup(registry);\n }\n\n /**\n * Get CSS text from all sheets (for SSR)\n */\n getCssText(options?: { root?: Document | ShadowRoot }): string {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n return this.sheetManager.getCssText(registry);\n }\n\n /**\n * Get CSS only for the provided tasty classNames (e.g., [\"t0\",\"t3\"])\n */\n getCssTextForClasses(\n classNames: Iterable<string>,\n options?: { root?: Document | ShadowRoot },\n ): string {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n const cssChunks: string[] = [];\n for (const cls of classNames) {\n const info = registry.rules.get(cls);\n if (info) {\n // Always prefer reading from the live stylesheet, since indices can change\n const sheet = registry.sheets[info.sheetIndex];\n const styleSheet = sheet?.sheet?.sheet;\n if (styleSheet) {\n const start = Math.max(0, info.ruleIndex);\n const end = Math.min(\n styleSheet.cssRules.length - 1,\n (info.endRuleIndex as number) ?? info.ruleIndex,\n );\n // Additional validation: ensure indices are valid and in correct order\n if (\n start >= 0 &&\n end >= start &&\n start < styleSheet.cssRules.length\n ) {\n for (let i = start; i <= end; i++) {\n const rule = styleSheet.cssRules[i] as CSSRule | undefined;\n if (rule) cssChunks.push(rule.cssText);\n }\n }\n } else if (info.cssText && info.cssText.length) {\n // Fallback in environments without CSSOM access\n cssChunks.push(...info.cssText);\n }\n }\n }\n return cssChunks.join('\\n');\n }\n\n /**\n * Get cache performance metrics\n */\n getMetrics(options?: { root?: Document | ShadowRoot }): CacheMetrics | null {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n return this.sheetManager.getMetrics(registry);\n }\n\n /**\n * Reset cache performance metrics\n */\n resetMetrics(options?: { root?: Document | ShadowRoot }): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n this.sheetManager.resetMetrics(registry);\n }\n\n /**\n * Define a CSS @property custom property.\n *\n * Accepts tasty token syntax for the property name:\n * - `$name` → defines `--name`\n * - `#name` → defines `--name-color` (auto-sets syntax: '<color>', defaults initialValue: 'transparent')\n * - `--name` → defines `--name` (legacy format)\n *\n * Example:\n * @property --rotation { syntax: \"<angle>\"; inherits: false; initial-value: 45deg; }\n *\n * Note: No caching or dispose — this defines a global property.\n *\n * If the same property is registered with different options, a warning is emitted\n * but the original definition is preserved (CSS @property cannot be redefined).\n */\n property(\n name: string,\n options?: PropertyDefinition & {\n root?: Document | ShadowRoot;\n },\n ): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n // Parse the token and get effective definition\n // This handles $name, #name, --name formats and auto-sets syntax for colors\n const userDefinition: PropertyDefinition = {\n syntax: options?.syntax,\n inherits: options?.inherits,\n initialValue: options?.initialValue,\n };\n\n const effectiveResult = getEffectiveDefinition(name, userDefinition);\n\n if (!effectiveResult.isValid) {\n if (isDevEnv()) {\n console.warn(\n `[Tasty] property(): ${effectiveResult.error}. Got: \"${name}\"`,\n );\n }\n return;\n }\n\n const cssName = effectiveResult.cssName;\n const definition = effectiveResult.definition;\n\n // Normalize the definition for comparison\n const normalizedDef = normalizePropertyDefinition(definition);\n\n // Check if already defined\n const existingDef = registry.injectedProperties.get(cssName);\n if (existingDef !== undefined) {\n // Property already exists - check if definitions match\n if (existingDef !== normalizedDef) {\n // Different definition - warn but don't replace (CSS @property can't be redefined)\n if (isDevEnv()) {\n console.warn(\n `[Tasty] @property ${cssName} was already defined with a different declaration. ` +\n `The new declaration will be ignored. ` +\n `Original: ${existingDef}, New: ${normalizedDef}`,\n );\n }\n }\n // Either exact match or warned - skip injection\n return;\n }\n\n const parts: string[] = [];\n\n if (definition.syntax != null) {\n let syntax = String(definition.syntax).trim();\n if (!/^['\"]/u.test(syntax)) syntax = `\"${syntax}\"`;\n parts.push(`syntax: ${syntax};`);\n }\n\n // inherits is required by the CSS @property spec - default to true\n const inherits = definition.inherits ?? true;\n parts.push(`inherits: ${inherits ? 'true' : 'false'};`);\n\n if (definition.initialValue != null) {\n let initialValueStr: string;\n if (typeof definition.initialValue === 'number') {\n initialValueStr = String(definition.initialValue);\n } else {\n // Process via tasty parser to resolve custom units/functions\n initialValueStr = parseStyle(definition.initialValue as StyleValue).output;\n }\n parts.push(`initial-value: ${initialValueStr};`);\n }\n\n const declarations = parts.join(' ').trim();\n\n const rule: StyleRule = {\n selector: `@property ${cssName}`,\n declarations,\n } as StyleRule;\n\n // Insert as a global rule; only mark injected when insertion succeeds\n const info = this.sheetManager.insertGlobalRule(\n registry,\n [rule],\n `property:${name}`,\n root,\n );\n\n if (!info) {\n return;\n }\n\n // Track that this property was injected with its normalized definition\n registry.injectedProperties.set(cssName, normalizedDef);\n\n // Auto-register companion -rgb property for color properties.\n // E.g. --white-color gets a companion --white-color-rgb with syntax: '<number>+'\n if (effectiveResult.isColor) {\n const rgbCssName = `${cssName}-rgb`;\n if (!this.isPropertyDefined(rgbCssName, { root })) {\n this.property(rgbCssName, {\n syntax: '<number>+',\n inherits: definition.inherits,\n initialValue: colorInitialValueToRgb(definition.initialValue),\n root,\n });\n }\n }\n }\n\n /**\n * Check whether a given @property name was already injected by this injector.\n *\n * Accepts tasty token syntax:\n * - `$name` → checks `--name`\n * - `#name` → checks `--name-color`\n * - `--name` → checks `--name` (legacy format)\n */\n isPropertyDefined(\n name: string,\n options?: { root?: Document | ShadowRoot },\n ): boolean {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n // Parse the token to get the CSS property name\n const effectiveResult = getEffectiveDefinition(name, {});\n if (!effectiveResult.isValid) {\n return false;\n }\n\n return registry.injectedProperties.has(effectiveResult.cssName);\n }\n\n /**\n * Inject keyframes and return object with toString() and dispose()\n *\n * Keyframes are cached by content (steps). If the same content is injected\n * multiple times with different provided names, the first injected name is reused.\n *\n * If the same name is provided with different content (collision), a unique\n * name is generated to avoid overwriting the existing keyframes.\n */\n keyframes(\n steps: KeyframesSteps,\n nameOrOptions?: string | { root?: Document | ShadowRoot; name?: string },\n ): KeyframesResult {\n // Parse parameters\n const isStringName = typeof nameOrOptions === 'string';\n const providedName = isStringName ? nameOrOptions : nameOrOptions?.name;\n const root = isStringName ? document : nameOrOptions?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (Object.keys(steps).length === 0) {\n return {\n toString: () => '',\n dispose: () => { /* noop */ },\n };\n }\n\n // Generate content-based cache key (independent of provided name)\n const contentHash = JSON.stringify(steps);\n\n // Check if this exact content is already cached\n const existing = registry.keyframesCache.get(contentHash);\n if (existing) {\n existing.refCount++;\n return {\n toString: () => existing.name,\n dispose: () => this.disposeKeyframes(contentHash, registry),\n };\n }\n\n // Determine the actual name to use\n let actualName: string;\n\n if (providedName) {\n // Check if this name is already used with different content\n const existingContentForName =\n registry.keyframesNameToContent.get(providedName);\n\n if (existingContentForName && existingContentForName !== contentHash) {\n // Name collision: same name, different content\n // Generate a unique name to avoid overwriting\n actualName = `${providedName}-k${registry.keyframesCounter++}`;\n } else {\n // Name is available or used with same content\n actualName = providedName;\n // Track this name -> content mapping\n registry.keyframesNameToContent.set(providedName, contentHash);\n }\n } else {\n // No name provided, generate one\n actualName = `k${registry.keyframesCounter++}`;\n }\n\n // Insert keyframes\n const info = this.sheetManager.insertKeyframes(\n registry,\n steps,\n actualName,\n root,\n );\n if (!info) {\n return {\n toString: () => '',\n dispose: () => { /* noop */ },\n };\n }\n\n // Cache the result by content hash\n registry.keyframesCache.set(contentHash, {\n name: actualName,\n refCount: 1,\n info,\n });\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n registry.metrics.misses++;\n }\n\n return {\n toString: () => actualName,\n dispose: () => this.disposeKeyframes(contentHash, registry),\n };\n }\n\n /**\n * Dispose keyframes\n */\n private disposeKeyframes(contentHash: string, registry: RootRegistry): void {\n const entry = registry.keyframesCache.get(contentHash);\n if (!entry) return;\n\n entry.refCount--;\n if (entry.refCount <= 0) {\n // Dispose immediately - keyframes are global and safe to clean up right away\n this.sheetManager.deleteKeyframes(registry, entry.info);\n registry.keyframesCache.delete(contentHash);\n\n // Clean up name-to-content mapping if this name was tracked\n // Find and remove the mapping for this content hash\n for (const [name, hash] of registry.keyframesNameToContent.entries()) {\n if (hash === contentHash) {\n registry.keyframesNameToContent.delete(name);\n break;\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalUnused++;\n registry.metrics.stylesCleanedUp++;\n }\n }\n }\n\n /**\n * Destroy all resources for a root\n */\n destroy(root?: Document | ShadowRoot): void {\n const targetRoot = root || document;\n this.sheetManager.cleanup(targetRoot);\n }\n}\n"],"mappings":";;;;;;;;;AAgCA,SAAS,kBAAkB,SAAyB;AAClD,QAAO,IAAI;;AAGb,IAAa,gBAAb,MAA2B;CACzB,AAAQ;CACR,AAAQ;CACR,AAAQ,mBAAmB;CAC3B,AAAQ,oBAAoB;;CAG5B,IAAI,gBAA8B;AAChC,SAAO,KAAK;;CAGd,YAAY,SAA8B,EAAE,EAAE;AAC5C,OAAK,SAAS;AACd,OAAK,eAAe,IAAI,aAAa,OAAO;;;;;;CAO9C,kBACE,UACA,SACiD;EACjD,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,WAAW,KAAK,aAAa,YAAY,KAAK;AAGpD,MAAI,SAAS,oBAAoB,IAAI,SAAS,CAE5C,QAAO;GACL,WAFgB,SAAS,oBAAoB,IAAI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OAAI,SAAS,SAAS;AACpB,aAAS,QAAQ;AACjB,aAAS,QAAQ;;;;;;;CAQvB,QAAQ,MAAoC;EAC1C,MAAM,aAAa,QAAQ;AAC3B,OAAK,aAAa,QAAQ,WAAW"}
1
+ {"version":3,"file":"injector.js","names":[],"sources":["../../src/injector/injector.ts"],"sourcesContent":["/**\n * Style injector that works with structured style objects\n * Eliminates CSS string parsing for better performance\n */\n\nimport type { StyleResult } from '../pipeline';\nimport {\n colorInitialValueToRgb,\n getEffectiveDefinition,\n normalizePropertyDefinition,\n} from '../properties';\nimport { isDevEnv } from '../utils/is-dev-env';\nimport type { StyleValue } from '../utils/styles';\nimport { parseStyle } from '../utils/styles';\n\nimport { SheetManager } from './sheet-manager';\nimport type {\n CacheMetrics,\n GlobalInjectResult,\n InjectResult,\n KeyframesResult,\n KeyframesSteps,\n PropertyDefinition,\n RawCSSResult,\n RootRegistry,\n StyleInjectorConfig,\n StyleRule,\n} from './types';\n\n/**\n * Generate sequential class name with format t{number}\n */\nfunction generateClassName(counter: number): string {\n return `t${counter}`;\n}\n\nexport class StyleInjector {\n private sheetManager: SheetManager;\n private config: StyleInjectorConfig;\n private cleanupScheduled = false;\n private globalRuleCounter = 0;\n\n /** @internal — exposed for debug utilities only */\n get _sheetManager(): SheetManager {\n return this.sheetManager;\n }\n\n constructor(config: StyleInjectorConfig = {}) {\n this.config = config;\n this.sheetManager = new SheetManager(config);\n }\n\n /**\n * Allocate a className for a cacheKey without injecting styles yet.\n * This allows separating className allocation (render phase) from style injection (insertion phase).\n */\n allocateClassName(\n cacheKey: string,\n options?: { root?: Document | ShadowRoot },\n ): { className: string; isNewAllocation: boolean } {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n // Check if we can reuse existing className for this cache key\n if (registry.cacheKeyToClassName.has(cacheKey)) {\n const className = registry.cacheKeyToClassName.get(cacheKey)!;\n return {\n className,\n isNewAllocation: false,\n };\n }\n\n // Generate new className and reserve it\n const className = generateClassName(registry.classCounter++);\n\n // Create placeholder RuleInfo to reserve the className\n const placeholderRuleInfo = {\n className,\n ruleIndex: -1, // Placeholder - will be set during actual injection\n sheetIndex: -1, // Placeholder - will be set during actual injection\n };\n\n // Store RuleInfo only once by className, and map cacheKey separately\n registry.rules.set(className, placeholderRuleInfo);\n registry.cacheKeyToClassName.set(cacheKey, className);\n\n return {\n className,\n isNewAllocation: true,\n };\n }\n\n /**\n * Inject styles from StyleResult objects\n */\n inject(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot; cacheKey?: string },\n ): InjectResult {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (rules.length === 0) {\n return {\n className: '',\n dispose: () => {\n /* noop */\n },\n };\n }\n\n // Rules are now in StyleRule format directly\n\n // Check if we can reuse based on cache key\n const cacheKey = options?.cacheKey;\n let className: string;\n let isPreAllocated = false;\n\n if (cacheKey && registry.cacheKeyToClassName.has(cacheKey)) {\n // Reuse existing class for this cache key\n className = registry.cacheKeyToClassName.get(cacheKey)!;\n const existingRuleInfo = registry.rules.get(className)!;\n\n // Check if this is a placeholder (pre-allocated but not yet injected)\n isPreAllocated =\n existingRuleInfo.ruleIndex === -1 && existingRuleInfo.sheetIndex === -1;\n\n if (!isPreAllocated) {\n // Already injected - just increment refCount\n const currentRefCount = registry.refCounts.get(className) || 0;\n registry.refCounts.set(className, currentRefCount + 1);\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: () => this.dispose(className, registry),\n };\n }\n } else {\n // Generate new className\n className = generateClassName(registry.classCounter++);\n }\n\n // Process rules: handle needsClassName flag and apply specificity\n const rulesToInsert = rules.map((rule) => {\n let newSelector = rule.selector;\n\n // If rule needs className prepended\n if (rule.needsClassName) {\n // Handle multiple selectors (separated by ||| for OR conditions)\n const selectorParts = newSelector ? newSelector.split('|||') : [''];\n\n const classPrefix = `.${className}.${className}`;\n\n newSelector = selectorParts\n .map((part) => {\n const classSelector = part ? `${classPrefix}${part}` : classPrefix;\n\n // If there's a root prefix, add it before the class selector\n if (rule.rootPrefix) {\n return `${rule.rootPrefix} ${classSelector}`;\n }\n return classSelector;\n })\n .join(', ');\n }\n\n return {\n ...rule,\n selector: newSelector,\n needsClassName: undefined, // Remove the flag after processing\n rootPrefix: undefined, // Remove rootPrefix after processing\n };\n });\n\n // Before inserting, auto-register @property for any color custom properties being defined.\n // Fast parse: split declarations by ';' and match \"--*-color:\"\n // Do this only when we actually insert (i.e., no cache hit above)\n const colorPropRegex = /^\\s*(--[a-z0-9-]+-color)\\s*:/i;\n for (const rule of rulesToInsert) {\n // Skip if no declarations\n if (!rule.declarations) continue;\n const parts = rule.declarations.split(/;+\\s*/);\n for (const part of parts) {\n if (!part) continue;\n const match = colorPropRegex.exec(part);\n if (match) {\n const propName = match[1];\n // Register @property only if not already defined for this root\n if (!this.isPropertyDefined(propName, { root })) {\n this.property(propName, {\n syntax: '<color>',\n initialValue: 'transparent',\n root,\n });\n }\n }\n }\n }\n\n // Insert rules using existing sheet manager\n const ruleInfo = this.sheetManager.insertRule(\n registry,\n rulesToInsert,\n className,\n root,\n );\n\n if (!ruleInfo) {\n // Update metrics\n if (registry.metrics) {\n registry.metrics.misses++;\n }\n\n return {\n className,\n dispose: () => {\n /* noop */\n },\n };\n }\n\n // Store in registry\n registry.refCounts.set(className, 1);\n\n if (isPreAllocated) {\n // Update the existing placeholder entry with real rule info\n registry.rules.set(className, ruleInfo);\n // cacheKey mapping already exists from allocation\n } else {\n // Store new entries\n registry.rules.set(className, ruleInfo);\n if (cacheKey) {\n registry.cacheKeyToClassName.set(cacheKey, className);\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n registry.metrics.misses++;\n }\n\n return {\n className,\n dispose: () => this.dispose(className, registry),\n };\n }\n\n /**\n * Inject global styles (rules without a generated tasty class selector)\n * This ensures we don't reserve a tasty class name (t{number}) for global rules,\n * which could otherwise collide with element-level styles and break lookups.\n */\n injectGlobal(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot },\n ): GlobalInjectResult {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (!rules || rules.length === 0) {\n return {\n dispose: () => {\n /* noop */\n },\n };\n }\n\n // Use a non-tasty identifier to avoid any collisions with .t{number} classes\n const key = `global:${this.globalRuleCounter++}`;\n\n const info = this.sheetManager.insertGlobalRule(\n registry,\n rules as unknown as StyleRule[],\n key,\n root,\n );\n\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n }\n\n return {\n dispose: () => {\n if (info) this.sheetManager.deleteGlobalRule(registry, key);\n },\n };\n }\n\n /**\n * Inject raw CSS text directly without parsing\n * This is a low-overhead alternative to createGlobalStyle for raw CSS\n * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking\n */\n injectRawCSS(\n css: string,\n options?: { root?: Document | ShadowRoot },\n ): RawCSSResult {\n const root = options?.root || document;\n return this.sheetManager.injectRawCSS(css, root);\n }\n\n /**\n * Get raw CSS text for SSR\n */\n getRawCSSText(options?: { root?: Document | ShadowRoot }): string {\n const root = options?.root || document;\n return this.sheetManager.getRawCSSText(root);\n }\n\n /**\n * Dispose of a className\n */\n private dispose(className: string, registry: RootRegistry): void {\n const currentRefCount = registry.refCounts.get(className);\n // Guard against stale double-dispose or mismatched lifecycle\n if (currentRefCount == null || currentRefCount <= 0) {\n return;\n }\n\n const newRefCount = currentRefCount - 1;\n registry.refCounts.set(className, newRefCount);\n\n if (newRefCount === 0) {\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalUnused++;\n }\n\n // Check if cleanup should be scheduled\n this.sheetManager.checkCleanupNeeded(registry);\n }\n }\n\n /**\n * Force bulk cleanup of unused styles\n */\n cleanup(root?: Document | ShadowRoot): void {\n const registry = this.sheetManager.getRegistry(root || document);\n // Clean up ALL unused rules regardless of batch ratio\n this.sheetManager.forceCleanup(registry);\n }\n\n /**\n * Get CSS text from all sheets (for SSR)\n */\n getCssText(options?: { root?: Document | ShadowRoot }): string {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n return this.sheetManager.getCssText(registry);\n }\n\n /**\n * Get CSS only for the provided tasty classNames (e.g., [\"t0\",\"t3\"])\n */\n getCssTextForClasses(\n classNames: Iterable<string>,\n options?: { root?: Document | ShadowRoot },\n ): string {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n const cssChunks: string[] = [];\n for (const cls of classNames) {\n const info = registry.rules.get(cls);\n if (info) {\n // Always prefer reading from the live stylesheet, since indices can change\n const sheet = registry.sheets[info.sheetIndex];\n const styleSheet = sheet?.sheet?.sheet;\n if (styleSheet) {\n const start = Math.max(0, info.ruleIndex);\n const end = Math.min(\n styleSheet.cssRules.length - 1,\n (info.endRuleIndex as number) ?? info.ruleIndex,\n );\n // Additional validation: ensure indices are valid and in correct order\n if (\n start >= 0 &&\n end >= start &&\n start < styleSheet.cssRules.length\n ) {\n for (let i = start; i <= end; i++) {\n const rule = styleSheet.cssRules[i] as CSSRule | undefined;\n if (rule) cssChunks.push(rule.cssText);\n }\n }\n } else if (info.cssText && info.cssText.length) {\n // Fallback in environments without CSSOM access\n cssChunks.push(...info.cssText);\n }\n }\n }\n return cssChunks.join('\\n');\n }\n\n /**\n * Get cache performance metrics\n */\n getMetrics(options?: { root?: Document | ShadowRoot }): CacheMetrics | null {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n return this.sheetManager.getMetrics(registry);\n }\n\n /**\n * Reset cache performance metrics\n */\n resetMetrics(options?: { root?: Document | ShadowRoot }): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n this.sheetManager.resetMetrics(registry);\n }\n\n /**\n * Define a CSS @property custom property.\n *\n * Accepts tasty token syntax for the property name:\n * - `$name` → defines `--name`\n * - `#name` → defines `--name-color` (auto-sets syntax: '<color>', defaults initialValue: 'transparent')\n * - `--name` → defines `--name` (legacy format)\n *\n * Example:\n * @property --rotation { syntax: \"<angle>\"; inherits: false; initial-value: 45deg; }\n *\n * Note: No caching or dispose — this defines a global property.\n *\n * If the same property is registered with different options, a warning is emitted\n * but the original definition is preserved (CSS @property cannot be redefined).\n */\n property(\n name: string,\n options?: PropertyDefinition & {\n root?: Document | ShadowRoot;\n },\n ): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n // Parse the token and get effective definition\n // This handles $name, #name, --name formats and auto-sets syntax for colors\n const userDefinition: PropertyDefinition = {\n syntax: options?.syntax,\n inherits: options?.inherits,\n initialValue: options?.initialValue,\n };\n\n const effectiveResult = getEffectiveDefinition(name, userDefinition);\n\n if (!effectiveResult.isValid) {\n if (isDevEnv()) {\n console.warn(\n `[Tasty] property(): ${effectiveResult.error}. Got: \"${name}\"`,\n );\n }\n return;\n }\n\n const cssName = effectiveResult.cssName;\n const definition = effectiveResult.definition;\n\n // Normalize the definition for comparison\n const normalizedDef = normalizePropertyDefinition(definition);\n\n // Check if already defined\n const existingDef = registry.injectedProperties.get(cssName);\n if (existingDef !== undefined) {\n // Property already exists - check if definitions match\n if (existingDef !== normalizedDef) {\n // Different definition - warn but don't replace (CSS @property can't be redefined)\n if (isDevEnv()) {\n console.warn(\n `[Tasty] @property ${cssName} was already defined with a different declaration. ` +\n `The new declaration will be ignored. ` +\n `Original: ${existingDef}, New: ${normalizedDef}`,\n );\n }\n }\n // Either exact match or warned - skip injection\n return;\n }\n\n const parts: string[] = [];\n\n if (definition.syntax != null) {\n let syntax = String(definition.syntax).trim();\n if (!/^['\"]/u.test(syntax)) syntax = `\"${syntax}\"`;\n parts.push(`syntax: ${syntax};`);\n }\n\n // inherits is required by the CSS @property spec - default to true\n const inherits = definition.inherits ?? true;\n parts.push(`inherits: ${inherits ? 'true' : 'false'};`);\n\n if (definition.initialValue != null) {\n let initialValueStr: string;\n if (typeof definition.initialValue === 'number') {\n initialValueStr = String(definition.initialValue);\n } else {\n // Process via tasty parser to resolve custom units/functions\n initialValueStr = parseStyle(\n definition.initialValue as StyleValue,\n ).output;\n }\n parts.push(`initial-value: ${initialValueStr};`);\n }\n\n const declarations = parts.join(' ').trim();\n\n const rule: StyleRule = {\n selector: `@property ${cssName}`,\n declarations,\n } as StyleRule;\n\n // Insert as a global rule; only mark injected when insertion succeeds\n const info = this.sheetManager.insertGlobalRule(\n registry,\n [rule],\n `property:${name}`,\n root,\n );\n\n if (!info) {\n return;\n }\n\n // Track that this property was injected with its normalized definition\n registry.injectedProperties.set(cssName, normalizedDef);\n\n // Auto-register companion -rgb property for color properties.\n // E.g. --white-color gets a companion --white-color-rgb with syntax: '<number>+'\n if (effectiveResult.isColor) {\n const rgbCssName = `${cssName}-rgb`;\n if (!this.isPropertyDefined(rgbCssName, { root })) {\n this.property(rgbCssName, {\n syntax: '<number>+',\n inherits: definition.inherits,\n initialValue: colorInitialValueToRgb(definition.initialValue),\n root,\n });\n }\n }\n }\n\n /**\n * Check whether a given @property name was already injected by this injector.\n *\n * Accepts tasty token syntax:\n * - `$name` → checks `--name`\n * - `#name` → checks `--name-color`\n * - `--name` → checks `--name` (legacy format)\n */\n isPropertyDefined(\n name: string,\n options?: { root?: Document | ShadowRoot },\n ): boolean {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n // Parse the token to get the CSS property name\n const effectiveResult = getEffectiveDefinition(name, {});\n if (!effectiveResult.isValid) {\n return false;\n }\n\n return registry.injectedProperties.has(effectiveResult.cssName);\n }\n\n /**\n * Inject keyframes and return object with toString() and dispose()\n *\n * Keyframes are cached by content (steps). If the same content is injected\n * multiple times with different provided names, the first injected name is reused.\n *\n * If the same name is provided with different content (collision), a unique\n * name is generated to avoid overwriting the existing keyframes.\n */\n keyframes(\n steps: KeyframesSteps,\n nameOrOptions?: string | { root?: Document | ShadowRoot; name?: string },\n ): KeyframesResult {\n // Parse parameters\n const isStringName = typeof nameOrOptions === 'string';\n const providedName = isStringName ? nameOrOptions : nameOrOptions?.name;\n const root = isStringName ? document : nameOrOptions?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (Object.keys(steps).length === 0) {\n return {\n toString: () => '',\n dispose: () => {\n /* noop */\n },\n };\n }\n\n // Generate content-based cache key (independent of provided name)\n const contentHash = JSON.stringify(steps);\n\n // Check if this exact content is already cached\n const existing = registry.keyframesCache.get(contentHash);\n if (existing) {\n existing.refCount++;\n return {\n toString: () => existing.name,\n dispose: () => this.disposeKeyframes(contentHash, registry),\n };\n }\n\n // Determine the actual name to use\n let actualName: string;\n\n if (providedName) {\n // Check if this name is already used with different content\n const existingContentForName =\n registry.keyframesNameToContent.get(providedName);\n\n if (existingContentForName && existingContentForName !== contentHash) {\n // Name collision: same name, different content\n // Generate a unique name to avoid overwriting\n actualName = `${providedName}-k${registry.keyframesCounter++}`;\n } else {\n // Name is available or used with same content\n actualName = providedName;\n // Track this name -> content mapping\n registry.keyframesNameToContent.set(providedName, contentHash);\n }\n } else {\n // No name provided, generate one\n actualName = `k${registry.keyframesCounter++}`;\n }\n\n // Insert keyframes\n const info = this.sheetManager.insertKeyframes(\n registry,\n steps,\n actualName,\n root,\n );\n if (!info) {\n return {\n toString: () => '',\n dispose: () => {\n /* noop */\n },\n };\n }\n\n // Cache the result by content hash\n registry.keyframesCache.set(contentHash, {\n name: actualName,\n refCount: 1,\n info,\n });\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n registry.metrics.misses++;\n }\n\n return {\n toString: () => actualName,\n dispose: () => this.disposeKeyframes(contentHash, registry),\n };\n }\n\n /**\n * Dispose keyframes\n */\n private disposeKeyframes(contentHash: string, registry: RootRegistry): void {\n const entry = registry.keyframesCache.get(contentHash);\n if (!entry) return;\n\n entry.refCount--;\n if (entry.refCount <= 0) {\n // Dispose immediately - keyframes are global and safe to clean up right away\n this.sheetManager.deleteKeyframes(registry, entry.info);\n registry.keyframesCache.delete(contentHash);\n\n // Clean up name-to-content mapping if this name was tracked\n // Find and remove the mapping for this content hash\n for (const [name, hash] of registry.keyframesNameToContent.entries()) {\n if (hash === contentHash) {\n registry.keyframesNameToContent.delete(name);\n break;\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalUnused++;\n registry.metrics.stylesCleanedUp++;\n }\n }\n }\n\n /**\n * Destroy all resources for a root\n */\n destroy(root?: Document | ShadowRoot): void {\n const targetRoot = root || document;\n this.sheetManager.cleanup(targetRoot);\n }\n}\n"],"mappings":";;;;;;;;;AAgCA,SAAS,kBAAkB,SAAyB;AAClD,QAAO,IAAI;;AAGb,IAAa,gBAAb,MAA2B;CACzB,AAAQ;CACR,AAAQ;CACR,AAAQ,mBAAmB;CAC3B,AAAQ,oBAAoB;;CAG5B,IAAI,gBAA8B;AAChC,SAAO,KAAK;;CAGd,YAAY,SAA8B,EAAE,EAAE;AAC5C,OAAK,SAAS;AACd,OAAK,eAAe,IAAI,aAAa,OAAO;;;;;;CAO9C,kBACE,UACA,SACiD;EACjD,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,WAAW,KAAK,aAAa,YAAY,KAAK;AAGpD,MAAI,SAAS,oBAAoB,IAAI,SAAS,CAE5C,QAAO;GACL,WAFgB,SAAS,oBAAoB,IAAI,SAAS;GAG1D,iBAAiB;GAClB;EAIH,MAAM,YAAY,kBAAkB,SAAS,eAAe;EAG5D,MAAM,sBAAsB;GAC1B;GACA,WAAW;GACX,YAAY;GACb;AAGD,WAAS,MAAM,IAAI,WAAW,oBAAoB;AAClD,WAAS,oBAAoB,IAAI,UAAU,UAAU;AAErD,SAAO;GACL;GACA,iBAAiB;GAClB;;;;;CAMH,OACE,OACA,SACc;EACd,MAAM,OAAO,SAAS,QAAQ;EAC9B,MAAM,WAAW,KAAK,aAAa,YAAY,KAAK;AAEpD,MAAI,MAAM,WAAW,EACnB,QAAO;GACL,WAAW;GACX,eAAe;GAGhB;EAMH,MAAM,WAAW,SAAS;EAC1B,IAAI;EACJ,IAAI,iBAAiB;AAErB,MAAI,YAAY,SAAS,oBAAoB,IAAI,SAAS,EAAE;AAE1D,eAAY,SAAS,oBAAoB,IAAI,SAAS;G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S;EAI5B,MAAM,OAAO,KAAK,aAAa,gBAC7B,UACA,OACA,YACA,KACD;AACD,MAAI,CAAC,KACH,QAAO;GACL,gBAAgB;GAChB,eAAe;GAGhB;AAIH,WAAS,eAAe,IAAI,aAAa;GACvC,MAAM;GACN,UAAU;GACV;GACD,CAAC;AAGF,MAAI,SAAS,SAAS;AACpB,YAAS,QAAQ;AACjB,YAAS,QAAQ;;AAGnB,SAAO;GACL,gBAAgB;GAChB,eAAe,KAAK,iBAAiB,aAAa,SAAS;GAC5D;;;;;CAMH,AAAQ,iBAAiB,aAAqB,UAA8B;EAC1E,MAAM,QAAQ,SAAS,eAAe,IAAI,YAAY;AACtD,MAAI,CAAC,MAAO;AAEZ,QAAM;AACN,MAAI,MAAM,YAAY,GAAG;AAEvB,QAAK,aAAa,gBAAgB,UAAU,MAAM,KAAK;AACvD,YAAS,eAAe,OAAO,YAAY;AAI3C,QAAK,MAAM,CAAC,MAAM,SAAS,SAAS,uBAAuB,SAAS,CAClE,KAAI,SAAS,aAAa;AACxB,aAAS,uBAAuB,OAAO,KAAK;AAC5C;;AAKJ,OAAI,SAAS,SAAS;AACpB,aAAS,QAAQ;AACjB,aAAS,QAAQ;;;;;;;CAQvB,QAAQ,MAAoC;EAC1C,MAAM,aAAa,QAAQ;AAC3B,OAAK,aAAa,QAAQ,WAAW"}
@@ -1 +1 @@
1
- {"version":3,"file":"sheet-manager.js","names":[],"sources":["../../src/injector/sheet-manager.ts"],"sourcesContent":["import { createStyle, STYLE_HANDLER_MAP } from '../styles';\n\nimport type {\n CacheMetrics,\n KeyframesInfo,\n KeyframesSteps,\n RawCSSInfo,\n RawCSSResult,\n RootRegistry,\n RuleInfo,\n SheetInfo,\n StyleInjectorConfig,\n StyleRule,\n} from './types';\n\nimport type {\n CSSMap,\n StyleHandler,\n StyleValueStateMap,\n} from '../utils/styles';\n\nexport class SheetManager {\n private rootRegistries = new WeakMap<Document | ShadowRoot, RootRegistry>();\n private config: StyleInjectorConfig;\n /** Dedicated style elements for raw CSS per root */\n private rawStyleElements = new WeakMap<\n Document | ShadowRoot,\n HTMLStyleElement\n >();\n /** Tracking for raw CSS blocks per root */\n private rawCSSBlocks = new WeakMap<\n Document | ShadowRoot,\n Map<string, RawCSSInfo>\n >();\n /** Counter for generating unique raw CSS IDs */\n private rawCSSCounter = 0;\n\n constructor(config: StyleInjectorConfig) {\n this.config = config;\n }\n\n /**\n * Get or create registry for a root (Document or ShadowRoot)\n */\n getRegistry(root: Document | ShadowRoot): RootRegistry {\n let registry = this.rootRegistries.get(root);\n\n if (!registry) {\n const metrics: CacheMetrics | undefined = this.config.devMode\n ? {\n hits: 0,\n misses: 0,\n bulkCleanups: 0,\n totalInsertions: 0,\n totalUnused: 0,\n stylesCleanedUp: 0,\n cleanupHistory: [],\n startTime: Date.now(),\n }\n : undefined;\n\n registry = {\n sheets: [],\n refCounts: new Map(),\n rules: new Map(),\n cacheKeyToClassName: new Map(),\n ruleTextSet: new Set<string>(),\n bulkCleanupTimeout: null,\n cleanupCheckTimeout: null,\n metrics,\n classCounter: 0,\n keyframesCache: new Map(),\n keyframesNameToContent: new Map(),\n keyframesCounter: 0,\n injectedProperties: new Map<string, string>(),\n globalRules: new Map(),\n } as unknown as RootRegistry;\n\n this.rootRegistries.set(root, registry);\n }\n\n return registry;\n }\n\n /**\n * Create a new stylesheet for the registry\n */\n createSheet(registry: RootRegistry, root: Document | ShadowRoot): SheetInfo {\n const sheet = this.createStyleElement(root);\n\n const sheetInfo: SheetInfo = {\n sheet,\n ruleCount: 0,\n holes: [],\n };\n\n registry.sheets.push(sheetInfo);\n return sheetInfo;\n }\n\n /**\n * Create a style element and append to document\n */\n private createStyleElement(root: Document | ShadowRoot): HTMLStyleElement {\n const style =\n (root as Document).createElement?.('style') ||\n document.createElement('style');\n\n if (this.config.nonce) {\n style.nonce = this.config.nonce;\n }\n\n style.setAttribute('data-tasty', '');\n\n // Append to head or shadow root\n if ('head' in root && root.head) {\n root.head.appendChild(style);\n } else if ('appendChild' in root) {\n root.appendChild(style);\n } else {\n document.head.appendChild(style);\n }\n\n // Verify it was actually added - log only if there's a problem and we're not using forceTextInjection\n if (!style.isConnected && !this.config.forceTextInjection) {\n console.error('SheetManager: Style element failed to connect to DOM!', {\n parentNode: style.parentNode?.nodeName,\n isConnected: style.isConnected,\n });\n }\n\n return style;\n }\n\n /**\n * Insert CSS rules as a single block\n */\n insertRule(\n registry: RootRegistry,\n flattenedRules: StyleRule[],\n className: string,\n root: Document | ShadowRoot,\n ): RuleInfo | null {\n // Find or create a sheet with available space\n let targetSheet = this.findAvailableSheet(registry, root);\n\n if (!targetSheet) {\n targetSheet = this.createSheet(registry, root);\n }\n\n const sheetIndex = registry.sheets.indexOf(targetSheet);\n\n try {\n // Group rules by selector and at-rules to combine declarations\n const groupedRules: StyleRule[] = [];\n const groupMap = new Map<\n string,\n {\n idx: number;\n selector: string;\n atRules?: string[];\n declarations: string;\n }\n >();\n\n const atKey = (at?: string[]) => (at && at.length ? at.join('|') : '');\n\n flattenedRules.forEach((r) => {\n const key = `${atKey(r.atRules)}||${r.selector}`;\n const existing = groupMap.get(key);\n if (existing) {\n // Append declarations, preserving order\n existing.declarations = existing.declarations\n ? `${existing.declarations} ${r.declarations}`\n : r.declarations;\n } else {\n groupMap.set(key, {\n idx: groupedRules.length,\n selector: r.selector,\n atRules: r.atRules,\n declarations: r.declarations,\n });\n groupedRules.push({ ...r });\n }\n });\n\n // Normalize groupedRules from map (with merged declarations)\n groupMap.forEach((val) => {\n groupedRules[val.idx] = {\n selector: val.selector,\n atRules: val.atRules,\n declarations: val.declarations,\n } as StyleRule;\n });\n\n // Insert grouped rules\n const insertedRuleTexts: string[] = [];\n const insertedIndices: number[] = []; // Track exact indices\n // Calculate rule index atomically right before insertion to prevent race conditions\n let currentRuleIndex = this.findAvailableRuleIndex(targetSheet);\n let firstInsertedIndex: number | null = null;\n let lastInsertedIndex: number | null = null;\n\n for (const rule of groupedRules) {\n const declarations = rule.declarations;\n const baseRule = `${rule.selector} { ${declarations} }`;\n\n // Wrap with at-rules if present\n let fullRule = baseRule;\n if (rule.atRules && rule.atRules.length > 0) {\n fullRule = rule.atRules.reduce(\n (css, atRule) => `${atRule} { ${css} }`,\n baseRule,\n );\n }\n\n // Insert individual rule into style element\n const styleElement = targetSheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet && !this.config.forceTextInjection) {\n // Calculate index atomically for each rule to prevent concurrent insertion races\n const maxIndex = styleSheet.cssRules.length;\n const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);\n const safeIndex = Math.min(Math.max(0, atomicRuleIndex), maxIndex);\n\n // Helper: split comma-separated selectors safely (ignores commas inside [] () \" ')\n const splitSelectorsSafely = (selectorList: string): string[] => {\n const parts: string[] = [];\n let buf = '';\n let depthSq = 0; // [] depth\n let depthPar = 0; // () depth\n let inStr: '\"' | \"'\" | '' = '';\n for (let i = 0; i < selectorList.length; i++) {\n const ch = selectorList[i];\n if (inStr) {\n if (ch === inStr && selectorList[i - 1] !== '\\\\') {\n inStr = '';\n }\n buf += ch;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inStr = ch as '\"' | \"'\";\n buf += ch;\n continue;\n }\n if (ch === '[') depthSq++;\n else if (ch === ']') depthSq = Math.max(0, depthSq - 1);\n else if (ch === '(') depthPar++;\n else if (ch === ')') depthPar = Math.max(0, depthPar - 1);\n\n if (ch === ',' && depthSq === 0 && depthPar === 0) {\n const part = buf.trim();\n if (part) parts.push(part);\n buf = '';\n } else {\n buf += ch;\n }\n }\n const tail = buf.trim();\n if (tail) parts.push(tail);\n return parts;\n };\n\n try {\n styleSheet.insertRule(fullRule, safeIndex);\n // Update sheet ruleCount immediately to prevent concurrent race conditions\n targetSheet.ruleCount++;\n insertedIndices.push(safeIndex); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = safeIndex;\n lastInsertedIndex = safeIndex;\n currentRuleIndex = safeIndex + 1;\n } catch (e) {\n // If the browser rejects the combined selector (e.g., vendor pseudo-elements),\n // try to split and insert each selector independently. Skip unsupported ones.\n const selectors = splitSelectorsSafely(rule.selector);\n if (selectors.length > 1) {\n let anyInserted = false;\n for (const sel of selectors) {\n const singleBase = `${sel} { ${declarations} }`;\n let singleRule = singleBase;\n if (rule.atRules && rule.atRules.length > 0) {\n singleRule = rule.atRules.reduce(\n (css, atRule) => `${atRule} { ${css} }`,\n singleBase,\n );\n }\n\n try {\n // Calculate index atomically for each individual selector insertion\n const maxIdx = styleSheet.cssRules.length;\n const atomicIdx = this.findAvailableRuleIndex(targetSheet);\n const idx = Math.min(Math.max(0, atomicIdx), maxIdx);\n styleSheet.insertRule(singleRule, idx);\n // Update sheet ruleCount immediately\n targetSheet.ruleCount++;\n insertedIndices.push(idx); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = idx;\n lastInsertedIndex = idx;\n currentRuleIndex = idx + 1;\n anyInserted = true;\n } catch (singleErr) {\n // Skip unsupported selector in this engine (e.g., ::-moz-selection in Blink)\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n '[tasty] Browser rejected CSS rule:',\n singleRule,\n singleErr,\n );\n }\n }\n }\n // If none inserted, continue without throwing to avoid aborting the whole batch\n if (!anyInserted) {\n // noop: all selectors invalid here; safe to skip\n }\n } else {\n // Single selector failed — skip it silently (likely unsupported in this engine)\n if (process.env.NODE_ENV !== 'production') {\n console.warn('[tasty] Browser rejected CSS rule:', fullRule, e);\n }\n }\n }\n } else {\n // Use textContent (either as fallback or when forceTextInjection is enabled)\n // Calculate index atomically for textContent insertion too\n const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);\n styleElement.textContent =\n (styleElement.textContent || '') + '\\n' + fullRule;\n // Update sheet ruleCount immediately\n targetSheet.ruleCount++;\n insertedIndices.push(atomicRuleIndex); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = atomicRuleIndex;\n lastInsertedIndex = atomicRuleIndex;\n currentRuleIndex = atomicRuleIndex + 1;\n }\n\n // CRITICAL DEBUG: Verify the style element is in DOM only if there are issues and we're not using forceTextInjection\n if (!styleElement.parentNode && !this.config.forceTextInjection) {\n console.error(\n 'SheetManager: Style element is NOT in DOM! This is the problem!',\n {\n className,\n ruleIndex: currentRuleIndex,\n },\n );\n }\n\n // Dev-only: store cssText for debugging tools\n if (this.config.devMode) {\n insertedRuleTexts.push(fullRule);\n try {\n registry.ruleTextSet.add(fullRule);\n } catch {\n // noop: defensive in case ruleTextSet is unavailable\n }\n }\n // currentRuleIndex already adjusted above\n }\n\n // Sheet ruleCount is now updated immediately after each insertion\n // No need for deferred update logic\n\n if (insertedIndices.length === 0) {\n return null;\n }\n\n return {\n className,\n ruleIndex: firstInsertedIndex ?? 0,\n sheetIndex,\n cssText: this.config.devMode ? insertedRuleTexts : undefined,\n endRuleIndex: lastInsertedIndex ?? firstInsertedIndex ?? 0,\n indices: insertedIndices,\n };\n } catch (error) {\n console.warn('Failed to insert CSS rules:', error, {\n flattenedRules,\n className,\n });\n return null;\n }\n }\n\n /**\n * Insert global CSS rules\n */\n insertGlobalRule(\n registry: RootRegistry,\n flattenedRules: StyleRule[],\n globalKey: string,\n root: Document | ShadowRoot,\n ): RuleInfo | null {\n // Insert the rule using the same mechanism as regular rules\n const ruleInfo = this.insertRule(registry, flattenedRules, globalKey, root);\n\n // Track global rules for index adjustment\n if (ruleInfo) {\n registry.globalRules.set(globalKey, ruleInfo);\n }\n\n return ruleInfo;\n }\n\n /**\n * Delete a global CSS rule by key\n */\n public deleteGlobalRule(registry: RootRegistry, globalKey: string): void {\n const ruleInfo = registry.globalRules.get(globalKey);\n if (!ruleInfo) {\n return;\n }\n\n // Delete the rule using the standard deletion mechanism\n this.deleteRule(registry, ruleInfo);\n\n // Remove from global rules tracking\n registry.globalRules.delete(globalKey);\n }\n\n /**\n * Adjust rule indices after deletion to account for shifting\n */\n private adjustIndicesAfterDeletion(\n registry: RootRegistry,\n sheetIndex: number,\n startIdx: number,\n endIdx: number,\n deleteCount: number,\n deletedRuleInfo: RuleInfo,\n deletedIndices?: number[],\n ): void {\n try {\n const sortedDeleted =\n deletedIndices && deletedIndices.length > 0\n ? [...deletedIndices].sort((a, b) => a - b)\n : null;\n const countDeletedBefore = (sorted: number[], idx: number): number => {\n let shift = 0;\n for (const delIdx of sorted) {\n if (delIdx < idx) shift++;\n else break;\n }\n return shift;\n };\n // Helper function to adjust a single RuleInfo\n const adjustRuleInfo = (info: RuleInfo): void => {\n if (info === deletedRuleInfo) return; // Skip the deleted rule\n if (info.sheetIndex !== sheetIndex) return; // Different sheet\n\n if (!info.indices || info.indices.length === 0) {\n return;\n }\n\n if (sortedDeleted) {\n // Adjust each index based on how many deleted indices are before it\n info.indices = info.indices.map((idx) => {\n return idx - countDeletedBefore(sortedDeleted, idx);\n });\n } else {\n // Contiguous deletion: shift indices after the deleted range\n info.indices = info.indices.map((idx) =>\n idx > endIdx ? Math.max(0, idx - deleteCount) : idx,\n );\n }\n\n // Update ruleIndex and endRuleIndex to match adjusted indices\n if (info.indices.length > 0) {\n info.ruleIndex = Math.min(...info.indices);\n info.endRuleIndex = Math.max(...info.indices);\n }\n };\n\n // Adjust active rules\n for (const info of registry.rules.values()) {\n adjustRuleInfo(info);\n }\n\n // Adjust global rules\n for (const info of registry.globalRules.values()) {\n adjustRuleInfo(info);\n }\n\n // No need to separately adjust unused rules since they're part of the rules Map\n\n // Adjust keyframes indices stored in cache\n for (const entry of registry.keyframesCache.values()) {\n const ki = entry.info as KeyframesInfo;\n if (ki.sheetIndex !== sheetIndex) continue;\n if (sortedDeleted) {\n const shift = countDeletedBefore(sortedDeleted, ki.ruleIndex);\n if (shift > 0) {\n ki.ruleIndex = Math.max(0, ki.ruleIndex - shift);\n }\n } else if (ki.ruleIndex > endIdx) {\n ki.ruleIndex = Math.max(0, ki.ruleIndex - deleteCount);\n }\n }\n } catch {\n // Defensive: do not let index adjustments crash cleanup\n }\n }\n\n /**\n * Delete a CSS rule from the sheet\n */\n deleteRule(registry: RootRegistry, ruleInfo: RuleInfo): void {\n const sheet = registry.sheets[ruleInfo.sheetIndex];\n\n if (!sheet) {\n return;\n }\n\n try {\n const texts: string[] =\n this.config.devMode && Array.isArray(ruleInfo.cssText)\n ? ruleInfo.cssText.slice()\n : [];\n\n const styleElement = sheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet) {\n const rules = styleSheet.cssRules;\n\n // Use exact indices if available, otherwise fall back to range\n if (ruleInfo.indices && ruleInfo.indices.length > 0) {\n // NEW: Delete using exact tracked indices\n const sortedIndices = [...ruleInfo.indices].sort((a, b) => b - a); // Sort descending\n const deletedIndices: number[] = [];\n\n for (const idx of sortedIndices) {\n if (idx >= 0 && idx < styleSheet.cssRules.length) {\n try {\n styleSheet.deleteRule(idx);\n deletedIndices.push(idx);\n } catch (e) {\n console.warn(`Failed to delete rule at index ${idx}:`, e);\n }\n }\n }\n\n sheet.ruleCount = Math.max(\n 0,\n sheet.ruleCount - deletedIndices.length,\n );\n\n // Adjust indices for all other rules\n if (deletedIndices.length > 0) {\n this.adjustIndicesAfterDeletion(\n registry,\n ruleInfo.sheetIndex,\n Math.min(...deletedIndices),\n Math.max(...deletedIndices),\n deletedIndices.length,\n ruleInfo,\n deletedIndices,\n );\n }\n } else {\n // FALLBACK: Use old range-based deletion for backwards compatibility\n const startIdx = Math.max(0, ruleInfo.ruleIndex);\n const endIdx = Math.min(\n rules.length - 1,\n Number.isFinite(ruleInfo.endRuleIndex as number)\n ? (ruleInfo.endRuleIndex as number)\n : startIdx,\n );\n\n if (Number.isFinite(startIdx) && endIdx >= startIdx) {\n const deleteCount = endIdx - startIdx + 1;\n for (let idx = endIdx; idx >= startIdx; idx--) {\n if (idx < 0 || idx >= styleSheet.cssRules.length) continue;\n styleSheet.deleteRule(idx);\n }\n sheet.ruleCount = Math.max(0, sheet.ruleCount - deleteCount);\n\n // After deletion, all subsequent rule indices shift left by deleteCount.\n // We must adjust stored indices for all other RuleInfo within the same sheet.\n this.adjustIndicesAfterDeletion(\n registry,\n ruleInfo.sheetIndex,\n startIdx,\n endIdx,\n deleteCount,\n ruleInfo,\n );\n }\n }\n }\n\n // Dev-only: remove cssText entries from validation set\n if (this.config.devMode && texts.length) {\n try {\n for (const text of texts) {\n registry.ruleTextSet.delete(text);\n }\n } catch {\n // noop\n }\n }\n } catch (error) {\n console.warn('Failed to delete CSS rule:', error);\n }\n }\n\n /**\n * Find a sheet with available space or return null\n */\n private findAvailableSheet(\n registry: RootRegistry,\n _root: Document | ShadowRoot,\n ): SheetInfo | null {\n const maxRules = this.config.maxRulesPerSheet;\n\n if (!maxRules) {\n // No limit, use the last sheet if it exists\n const lastSheet = registry.sheets[registry.sheets.length - 1];\n return lastSheet || null;\n }\n\n // Find sheet with space\n for (const sheet of registry.sheets) {\n if (sheet.ruleCount < maxRules) {\n return sheet;\n }\n }\n\n return null; // No available sheet found\n }\n\n /**\n * Find an available rule index in the sheet\n */\n findAvailableRuleIndex(sheet: SheetInfo): number {\n // Always append to the end - CSS doesn't have holes\n return sheet.ruleCount;\n }\n\n /**\n * Schedule bulk cleanup of all unused styles (non-stacking)\n */\n private scheduleBulkCleanup(registry: RootRegistry): void {\n // Clear any existing timeout to prevent stacking\n if (registry.bulkCleanupTimeout) {\n if (\n this.config.idleCleanup &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(registry.bulkCleanupTimeout as unknown as number);\n } else {\n clearTimeout(registry.bulkCleanupTimeout);\n }\n registry.bulkCleanupTimeout = null;\n }\n\n const performCleanup = () => {\n this.performBulkCleanup(registry);\n registry.bulkCleanupTimeout = null;\n };\n\n if (this.config.idleCleanup && typeof requestIdleCallback !== 'undefined') {\n registry.bulkCleanupTimeout = requestIdleCallback(performCleanup);\n } else {\n const delay = this.config.bulkCleanupDelay || 5000;\n registry.bulkCleanupTimeout = setTimeout(performCleanup, delay);\n }\n }\n\n /**\n * Force cleanup of unused styles\n */\n public forceCleanup(registry: RootRegistry): void {\n this.performBulkCleanup(registry, true);\n }\n\n /**\n * Perform bulk cleanup of all unused styles\n */\n private performBulkCleanup(registry: RootRegistry, cleanupAll = false): void {\n const cleanupStartTime = Date.now();\n\n // Calculate unused rules dynamically: rules that have refCount = 0\n const unusedClassNames = Array.from(registry.refCounts.entries())\n .filter(([, refCount]) => refCount === 0)\n .map(([className]) => className);\n\n if (unusedClassNames.length === 0) return;\n\n // Build candidates list - no age filtering needed\n const candidates = unusedClassNames.map((className) => {\n const ruleInfo = registry.rules.get(className)!; // We know it exists\n return {\n className,\n ruleInfo,\n };\n });\n\n if (candidates.length === 0) return;\n\n // Limit deletion scope per run (batch ratio) unless cleanupAll is true\n let selected = candidates;\n if (!cleanupAll) {\n const ratio = this.config.bulkCleanupBatchRatio ?? 0.5;\n const limit = Math.max(\n 1,\n Math.floor(candidates.length * Math.min(1, Math.max(0, ratio))),\n );\n selected = candidates.slice(0, limit);\n }\n\n let cleanedUpCount = 0;\n let totalCssSize = 0;\n let totalRulesDeleted = 0;\n\n // Group by sheet for efficient deletion\n const rulesBySheet = new Map<\n number,\n { className: string; ruleInfo: RuleInfo }[]\n >();\n\n // Calculate CSS size before deletion and group rules\n for (const { className, ruleInfo } of selected) {\n const sheetIndex = ruleInfo.sheetIndex;\n\n // Dev-only metrics: estimate CSS size and rule count if available\n if (this.config.devMode && Array.isArray(ruleInfo.cssText)) {\n const cssSize = ruleInfo.cssText.reduce(\n (total, css) => total + css.length,\n 0,\n );\n totalCssSize += cssSize;\n totalRulesDeleted += ruleInfo.cssText.length;\n }\n\n if (!rulesBySheet.has(sheetIndex)) {\n rulesBySheet.set(sheetIndex, []);\n }\n rulesBySheet.get(sheetIndex)!.push({ className, ruleInfo });\n }\n\n // Delete rules from each sheet (in reverse order to preserve indices)\n for (const [_sheetIndex, rulesInSheet] of rulesBySheet) {\n // Sort by rule index in descending order for safe deletion\n rulesInSheet.sort((a, b) => b.ruleInfo.ruleIndex - a.ruleInfo.ruleIndex);\n\n for (const { className, ruleInfo } of rulesInSheet) {\n // SAFETY 1: Double-check refCount is still 0\n const currentRefCount = registry.refCounts.get(className) || 0;\n if (currentRefCount > 0) {\n // Class became active again; do not delete\n continue;\n }\n\n // SAFETY 2: Ensure rule wasn't replaced\n // Between scheduling and execution a class may have been replaced with a new RuleInfo\n const currentInfo = registry.rules.get(className);\n if (currentInfo !== ruleInfo) {\n // Rule was replaced; skip deletion of the old reference\n continue;\n }\n\n // SAFETY 3: Verify the sheet element is still valid and accessible\n const sheetInfo = registry.sheets[ruleInfo.sheetIndex];\n if (!sheetInfo || !sheetInfo.sheet) {\n // Sheet was removed or corrupted; skip this rule\n continue;\n }\n\n // SAFETY 4: Verify the stylesheet itself is accessible\n const styleSheet = sheetInfo.sheet.sheet;\n if (!styleSheet) {\n // Stylesheet not available; skip this rule\n continue;\n }\n\n // SAFETY 5: Verify rule index is still within valid range\n const maxRuleIndex = styleSheet.cssRules.length - 1;\n const startIdx = ruleInfo.ruleIndex;\n const endIdx = ruleInfo.endRuleIndex ?? ruleInfo.ruleIndex;\n\n if (startIdx < 0 || endIdx > maxRuleIndex || startIdx > endIdx) {\n // Rule indices are out of bounds; skip this rule\n continue;\n }\n\n // All safety checks passed - proceed with deletion\n this.deleteRule(registry, ruleInfo);\n registry.rules.delete(className);\n registry.refCounts.delete(className);\n\n // Clean up cache key mappings that point to this className\n const keysToDelete: string[] = [];\n for (const [\n key,\n mappedClassName,\n ] of registry.cacheKeyToClassName.entries()) {\n if (mappedClassName === className) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n registry.cacheKeyToClassName.delete(key);\n }\n cleanedUpCount++;\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.bulkCleanups++;\n registry.metrics.stylesCleanedUp += cleanedUpCount;\n\n // Add detailed cleanup stats to history\n registry.metrics.cleanupHistory.push({\n timestamp: cleanupStartTime,\n classesDeleted: cleanedUpCount,\n cssSize: totalCssSize,\n rulesDeleted: totalRulesDeleted,\n });\n }\n }\n\n /**\n * Get total number of rules across all sheets\n */\n getTotalRuleCount(registry: RootRegistry): number {\n return registry.sheets.reduce(\n (total, sheet) => total + sheet.ruleCount - sheet.holes.length,\n 0,\n );\n }\n\n /**\n * Get CSS text from all sheets (for SSR)\n */\n getCssText(registry: RootRegistry): string {\n const cssChunks: string[] = [];\n\n for (const sheet of registry.sheets) {\n try {\n const styleElement = sheet.sheet;\n if (styleElement.textContent) {\n cssChunks.push(styleElement.textContent);\n } else if (styleElement.sheet) {\n const rules = Array.from(styleElement.sheet.cssRules);\n cssChunks.push(rules.map((rule) => rule.cssText).join('\\n'));\n }\n } catch (error) {\n console.warn('Failed to read CSS from sheet:', error);\n }\n }\n\n return cssChunks.join('\\n');\n }\n\n /**\n * Get cache performance metrics\n */\n getMetrics(registry: RootRegistry): CacheMetrics | null {\n if (!registry.metrics) return null;\n\n // Calculate unusedHits on demand - only count CSS rules since keyframes are disposed immediately\n const unusedRulesCount = Array.from(registry.refCounts.values()).filter(\n (count) => count === 0,\n ).length;\n\n return {\n ...registry.metrics,\n unusedHits: unusedRulesCount,\n };\n }\n\n /**\n * Reset cache performance metrics\n */\n resetMetrics(registry: RootRegistry): void {\n if (registry.metrics) {\n registry.metrics = {\n hits: 0,\n misses: 0,\n bulkCleanups: 0,\n totalInsertions: 0,\n totalUnused: 0,\n stylesCleanedUp: 0,\n cleanupHistory: [],\n startTime: Date.now(),\n };\n }\n }\n\n /**\n * Convert keyframes steps to CSS string\n */\n private stepsToCSS(steps: KeyframesSteps): string {\n const rules: string[] = [];\n\n for (const [key, value] of Object.entries(steps)) {\n // Support raw CSS strings for backwards compatibility\n if (typeof value === 'string') {\n rules.push(`${key} { ${value.trim()} }`);\n continue;\n }\n\n // Treat value as a style map and process via tasty style handlers\n const styleMap = (value || {}) as StyleValueStateMap;\n\n // Build a deterministic handler queue based on present style keys\n const styleNames = Object.keys(styleMap).sort();\n const handlerQueue: StyleHandler[] = [];\n const seenHandlers = new Set<StyleHandler>();\n\n styleNames.forEach((styleName) => {\n let handlers = STYLE_HANDLER_MAP[styleName];\n if (!handlers) {\n // Create a default handler for unknown styles (maps to kebab-case CSS or custom props)\n handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];\n }\n\n handlers.forEach((handler) => {\n if (!seenHandlers.has(handler)) {\n seenHandlers.add(handler);\n handlerQueue.push(handler);\n }\n });\n });\n\n // Accumulate declarations (ordered). We intentionally ignore `$` selector fan-out\n // and any responsive/state bindings for keyframes.\n const declarationPairs: { prop: string; value: string }[] = [];\n\n handlerQueue.forEach((handler) => {\n const lookup = handler.__lookupStyles;\n const filteredMap = lookup.reduce<StyleValueStateMap>(\n (acc, name) => {\n const v = styleMap[name];\n if (v !== undefined) acc[name] = v;\n return acc;\n },\n {},\n );\n\n const result = handler(filteredMap);\n if (!result) return;\n\n const results = Array.isArray(result) ? result : [result];\n results.forEach((cssMap) => {\n if (!cssMap || typeof cssMap !== 'object') return;\n const { $: _$, ...props } = cssMap as CSSMap;\n\n Object.entries(props).forEach(([prop, val]) => {\n if (val == null || val === '') return;\n\n if (Array.isArray(val)) {\n // Multiple values for the same property -> emit in order\n val.forEach((v) => {\n if (v != null && v !== '') {\n declarationPairs.push({ prop, value: String(v) });\n }\n });\n } else {\n declarationPairs.push({ prop, value: String(val) });\n }\n });\n });\n });\n\n // Fallback: if nothing produced (e.g., empty object), generate empty block\n const declarations = declarationPairs\n .map((d) => `${d.prop}: ${d.value}`)\n .join('; ');\n\n rules.push(`${key} { ${declarations.trim()} }`);\n }\n\n return rules.join(' ');\n }\n\n /**\n * Insert keyframes rule\n */\n insertKeyframes(\n registry: RootRegistry,\n steps: KeyframesSteps,\n name: string,\n root: Document | ShadowRoot,\n ): KeyframesInfo | null {\n let targetSheet = this.findAvailableSheet(registry, root);\n if (!targetSheet) {\n targetSheet = this.createSheet(registry, root);\n }\n\n const ruleIndex = this.findAvailableRuleIndex(targetSheet);\n const sheetIndex = registry.sheets.indexOf(targetSheet);\n\n try {\n const cssSteps = this.stepsToCSS(steps);\n const fullRule = `@keyframes ${name} { ${cssSteps} }`;\n\n const styleElement = targetSheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet && !this.config.forceTextInjection) {\n const safeIndex = Math.min(\n Math.max(0, ruleIndex),\n styleSheet.cssRules.length,\n );\n styleSheet.insertRule(fullRule, safeIndex);\n } else {\n styleElement.textContent =\n (styleElement.textContent || '') + '\\n' + fullRule;\n }\n\n targetSheet.ruleCount++;\n\n return {\n name,\n ruleIndex,\n sheetIndex,\n cssText: this.config.devMode ? fullRule : undefined,\n };\n } catch (error) {\n console.warn('Failed to insert keyframes:', error);\n return null;\n }\n }\n\n /**\n * Delete keyframes rule\n */\n deleteKeyframes(registry: RootRegistry, info: KeyframesInfo): void {\n const sheet = registry.sheets[info.sheetIndex];\n if (!sheet) return;\n\n try {\n const styleElement = sheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet) {\n if (\n info.ruleIndex >= 0 &&\n info.ruleIndex < styleSheet.cssRules.length\n ) {\n styleSheet.deleteRule(info.ruleIndex);\n sheet.ruleCount = Math.max(0, sheet.ruleCount - 1);\n\n // Adjust indices for all other rules in the same sheet\n // This is critical - when a keyframe rule is deleted, all rules\n // with higher indices shift down by 1\n this.adjustIndicesAfterDeletion(\n registry,\n info.sheetIndex,\n info.ruleIndex,\n info.ruleIndex,\n 1,\n // Create a dummy RuleInfo to satisfy the function signature\n {\n className: '',\n ruleIndex: info.ruleIndex,\n sheetIndex: info.sheetIndex,\n } as RuleInfo,\n [info.ruleIndex],\n );\n }\n }\n } catch (error) {\n console.warn('Failed to delete keyframes:', error);\n }\n }\n\n /**\n * Schedule async cleanup check (non-stacking)\n */\n public checkCleanupNeeded(registry: RootRegistry): void {\n // Clear any existing check timeout to prevent stacking\n if (registry.cleanupCheckTimeout) {\n clearTimeout(registry.cleanupCheckTimeout);\n registry.cleanupCheckTimeout = null;\n }\n\n // Schedule the actual check with setTimeout(..., 0)\n registry.cleanupCheckTimeout = setTimeout(() => {\n this.performCleanupCheck(registry);\n registry.cleanupCheckTimeout = null;\n }, 0);\n }\n\n /**\n * Perform the actual cleanup check (called asynchronously)\n */\n private performCleanupCheck(registry: RootRegistry): void {\n // Count unused rules (refCount = 0) - keyframes are disposed immediately\n const unusedRulesCount = Array.from(registry.refCounts.values()).filter(\n (count) => count === 0,\n ).length;\n const threshold = this.config.unusedStylesThreshold || 500;\n\n if (unusedRulesCount >= threshold) {\n this.scheduleBulkCleanup(registry);\n }\n }\n\n /**\n * Clean up resources for a root\n */\n cleanup(root: Document | ShadowRoot): void {\n const registry = this.rootRegistries.get(root);\n\n if (!registry) {\n return;\n }\n\n // Cancel any scheduled bulk cleanup\n if (registry.bulkCleanupTimeout) {\n if (\n this.config.idleCleanup &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(registry.bulkCleanupTimeout as unknown as number);\n } else {\n clearTimeout(registry.bulkCleanupTimeout);\n }\n registry.bulkCleanupTimeout = null;\n }\n\n // Cancel any scheduled cleanup check\n if (registry.cleanupCheckTimeout) {\n clearTimeout(registry.cleanupCheckTimeout);\n registry.cleanupCheckTimeout = null;\n }\n\n // Remove all sheets\n for (const sheet of registry.sheets) {\n try {\n // Remove style element\n const styleElement = sheet.sheet;\n if (styleElement.parentNode) {\n styleElement.parentNode.removeChild(styleElement);\n }\n } catch (error) {\n console.warn('Failed to cleanup sheet:', error);\n }\n }\n\n // Clear registry\n this.rootRegistries.delete(root);\n\n // Clean up raw CSS style element\n const rawStyleElement = this.rawStyleElements.get(root);\n if (rawStyleElement?.parentNode) {\n rawStyleElement.parentNode.removeChild(rawStyleElement);\n }\n this.rawStyleElements.delete(root);\n this.rawCSSBlocks.delete(root);\n }\n\n /**\n * Get or create a dedicated style element for raw CSS\n * Raw CSS is kept separate from tasty-managed sheets to avoid index conflicts\n */\n private getOrCreateRawStyleElement(\n root: Document | ShadowRoot,\n ): HTMLStyleElement {\n let styleElement = this.rawStyleElements.get(root);\n\n if (!styleElement) {\n styleElement =\n (root as Document).createElement?.('style') ||\n document.createElement('style');\n\n if (this.config.nonce) {\n styleElement.nonce = this.config.nonce;\n }\n\n styleElement.setAttribute('data-tasty-raw', '');\n\n // Append to head or shadow root\n if ('head' in root && root.head) {\n root.head.appendChild(styleElement);\n } else if ('appendChild' in root) {\n root.appendChild(styleElement);\n } else {\n document.head.appendChild(styleElement);\n }\n\n this.rawStyleElements.set(root, styleElement);\n this.rawCSSBlocks.set(root, new Map());\n }\n\n return styleElement;\n }\n\n /**\n * Inject raw CSS text directly without parsing\n * Returns a dispose function to remove the injected CSS\n */\n injectRawCSS(css: string, root: Document | ShadowRoot): RawCSSResult {\n if (!css.trim()) {\n return { dispose: () => { /* noop */ } };\n }\n\n const styleElement = this.getOrCreateRawStyleElement(root);\n const blocksMap = this.rawCSSBlocks.get(root)!;\n\n // Generate unique ID for this block\n const id = `raw_${this.rawCSSCounter++}`;\n\n // Calculate offsets\n const currentContent = styleElement.textContent || '';\n const startOffset = currentContent.length;\n const cssWithNewline = (currentContent ? '\\n' : '') + css;\n const endOffset = startOffset + cssWithNewline.length;\n\n // Append CSS\n styleElement.textContent = currentContent + cssWithNewline;\n\n // Track the block\n const info: RawCSSInfo = {\n id,\n css,\n startOffset,\n endOffset,\n };\n blocksMap.set(id, info);\n\n return {\n dispose: () => {\n this.disposeRawCSS(id, root);\n },\n };\n }\n\n /**\n * Remove a raw CSS block by ID\n */\n private disposeRawCSS(id: string, root: Document | ShadowRoot): void {\n const styleElement = this.rawStyleElements.get(root);\n const blocksMap = this.rawCSSBlocks.get(root);\n\n if (!styleElement || !blocksMap) {\n return;\n }\n\n const info = blocksMap.get(id);\n if (!info) {\n return;\n }\n\n // Remove from tracking\n blocksMap.delete(id);\n\n // Rebuild the CSS content from remaining blocks\n // This is simpler and more reliable than trying to splice strings\n const remainingBlocks = Array.from(blocksMap.values());\n\n if (remainingBlocks.length === 0) {\n styleElement.textContent = '';\n } else {\n // Rebuild with remaining CSS blocks in order of their original insertion\n // Sort by original startOffset to maintain order\n remainingBlocks.sort((a, b) => a.startOffset - b.startOffset);\n const newContent = remainingBlocks.map((block) => block.css).join('\\n');\n styleElement.textContent = newContent;\n\n // Update offsets for remaining blocks\n let offset = 0;\n for (const block of remainingBlocks) {\n block.startOffset = offset;\n block.endOffset = offset + block.css.length;\n offset = block.endOffset + 1; // +1 for newline\n }\n }\n }\n\n /**\n * Get the raw CSS content for SSR\n */\n getRawCSSText(root: Document | ShadowRoot): string {\n const styleElement = this.rawStyleElements.get(root);\n return styleElement?.textContent || '';\n }\n}\n"],"mappings":";;;;AAqBA,IAAa,eAAb,MAA0B;CACxB,AAAQ,iCAAiB,IAAI,SAA8C;CAC3E,AAAQ;;CAER,AAAQ,mCAAmB,IAAI,SAG5B;;CAEH,AAAQ,+BAAe,IAAI,SAGxB;;CAEH,AAAQ,gBAAgB;CAExB,YAAY,QAA6B;AACvC,OAAK,SAAS;;;;;CAMhB,YAAY,MAA2C;EACrD,IAAI,WAAW,KAAK,eAAe,IAAI,KAAK;AAE5C,MAAI,CAAC,UAAU;GACb,MAAM,UAAoC,KAAK,OAAO,UAClD;IACE,MAAM;IACN,QAAQ;IACR,cAAc;IACd,iBAAiB;IACjB,aAAa;IACb,iBAAiB;IACjB,gBAAgB,EAAE;IAClB,WAAW,KAAK,KAAK;IACtB,GACD;AAEJ,cAAW;IACT,QAAQ,EAAE;IACV,2BAAW,IAAI,KAAK;IACpB,uBAAO,IAAI,KAAK;IAChB,qCAAqB,IAAI,KAAK;IAC9B,6BAAa,IAAI,KAAa;IAC9B,oBAAoB;IACpB,qBAAqB;IACrB;IACA,cAAc;IACd,gCAAgB,IAAI,KAAK;IACzB,wCAAwB,IAAI,KAAK;IACjC,kBAAkB;IAClB,oCAAoB,IAAI,KAAqB;IAC7C,6BAAa,IAAI,KAAK;IACvB;AAED,QAAK,eAAe,IAAI,MAAM,SAAS;;AAGzC,SAAO;;;;;CAMT,YAAY,UAAwB,MAAwC;EAG1E,MAAM,YAAuB;GAC3B,OAHY,KAAK,mBAAmB,KAAK;GAIzC,WAAW;GACX,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C7B,cAAa,cAAc;OACtB;AAGL,mBAAgB,MAAM,GAAG,MAAM,EAAE,cAAc,EAAE,YAAY;AAE7D,gBAAa,cADM,gBAAgB,KAAK,UAAU,MAAM,IAAI,CAAC,KAAK,KAAK;GAIvE,IAAI,SAAS;AACb,QAAK,MAAM,SAAS,iBAAiB;AACnC,UAAM,cAAc;AACpB,UAAM,YAAY,SAAS,MAAM,IAAI;AACrC,aAAS,MAAM,YAAY;;;;;;;CAQjC,cAAc,MAAqC;AAEjD,SADqB,KAAK,iBAAiB,IAAI,KAAK,EAC/B,eAAe"}
1
+ {"version":3,"file":"sheet-manager.js","names":[],"sources":["../../src/injector/sheet-manager.ts"],"sourcesContent":["import { createStyle, STYLE_HANDLER_MAP } from '../styles';\n\nimport type {\n CacheMetrics,\n KeyframesInfo,\n KeyframesSteps,\n RawCSSInfo,\n RawCSSResult,\n RootRegistry,\n RuleInfo,\n SheetInfo,\n StyleInjectorConfig,\n StyleRule,\n} from './types';\n\nimport type { CSSMap, StyleHandler, StyleValueStateMap } from '../utils/styles';\n\nexport class SheetManager {\n private rootRegistries = new WeakMap<Document | ShadowRoot, RootRegistry>();\n private config: StyleInjectorConfig;\n /** Dedicated style elements for raw CSS per root */\n private rawStyleElements = new WeakMap<\n Document | ShadowRoot,\n HTMLStyleElement\n >();\n /** Tracking for raw CSS blocks per root */\n private rawCSSBlocks = new WeakMap<\n Document | ShadowRoot,\n Map<string, RawCSSInfo>\n >();\n /** Counter for generating unique raw CSS IDs */\n private rawCSSCounter = 0;\n\n constructor(config: StyleInjectorConfig) {\n this.config = config;\n }\n\n /**\n * Get or create registry for a root (Document or ShadowRoot)\n */\n getRegistry(root: Document | ShadowRoot): RootRegistry {\n let registry = this.rootRegistries.get(root);\n\n if (!registry) {\n const metrics: CacheMetrics | undefined = this.config.devMode\n ? {\n hits: 0,\n misses: 0,\n bulkCleanups: 0,\n totalInsertions: 0,\n totalUnused: 0,\n stylesCleanedUp: 0,\n cleanupHistory: [],\n startTime: Date.now(),\n }\n : undefined;\n\n registry = {\n sheets: [],\n refCounts: new Map(),\n rules: new Map(),\n cacheKeyToClassName: new Map(),\n ruleTextSet: new Set<string>(),\n bulkCleanupTimeout: null,\n cleanupCheckTimeout: null,\n metrics,\n classCounter: 0,\n keyframesCache: new Map(),\n keyframesNameToContent: new Map(),\n keyframesCounter: 0,\n injectedProperties: new Map<string, string>(),\n globalRules: new Map(),\n } as unknown as RootRegistry;\n\n this.rootRegistries.set(root, registry);\n }\n\n return registry;\n }\n\n /**\n * Create a new stylesheet for the registry\n */\n createSheet(registry: RootRegistry, root: Document | ShadowRoot): SheetInfo {\n const sheet = this.createStyleElement(root);\n\n const sheetInfo: SheetInfo = {\n sheet,\n ruleCount: 0,\n holes: [],\n };\n\n registry.sheets.push(sheetInfo);\n return sheetInfo;\n }\n\n /**\n * Create a style element and append to document\n */\n private createStyleElement(root: Document | ShadowRoot): HTMLStyleElement {\n const style =\n (root as Document).createElement?.('style') ||\n document.createElement('style');\n\n if (this.config.nonce) {\n style.nonce = this.config.nonce;\n }\n\n style.setAttribute('data-tasty', '');\n\n // Append to head or shadow root\n if ('head' in root && root.head) {\n root.head.appendChild(style);\n } else if ('appendChild' in root) {\n root.appendChild(style);\n } else {\n document.head.appendChild(style);\n }\n\n // Verify it was actually added - log only if there's a problem and we're not using forceTextInjection\n if (!style.isConnected && !this.config.forceTextInjection) {\n console.error('SheetManager: Style element failed to connect to DOM!', {\n parentNode: style.parentNode?.nodeName,\n isConnected: style.isConnected,\n });\n }\n\n return style;\n }\n\n /**\n * Insert CSS rules as a single block\n */\n insertRule(\n registry: RootRegistry,\n flattenedRules: StyleRule[],\n className: string,\n root: Document | ShadowRoot,\n ): RuleInfo | null {\n // Find or create a sheet with available space\n let targetSheet = this.findAvailableSheet(registry, root);\n\n if (!targetSheet) {\n targetSheet = this.createSheet(registry, root);\n }\n\n const sheetIndex = registry.sheets.indexOf(targetSheet);\n\n try {\n // Group rules by selector and at-rules to combine declarations\n const groupedRules: StyleRule[] = [];\n const groupMap = new Map<\n string,\n {\n idx: number;\n selector: string;\n atRules?: string[];\n declarations: string;\n }\n >();\n\n const atKey = (at?: string[]) => (at && at.length ? at.join('|') : '');\n\n flattenedRules.forEach((r) => {\n const key = `${atKey(r.atRules)}||${r.selector}`;\n const existing = groupMap.get(key);\n if (existing) {\n // Append declarations, preserving order\n existing.declarations = existing.declarations\n ? `${existing.declarations} ${r.declarations}`\n : r.declarations;\n } else {\n groupMap.set(key, {\n idx: groupedRules.length,\n selector: r.selector,\n atRules: r.atRules,\n declarations: r.declarations,\n });\n groupedRules.push({ ...r });\n }\n });\n\n // Normalize groupedRules from map (with merged declarations)\n groupMap.forEach((val) => {\n groupedRules[val.idx] = {\n selector: val.selector,\n atRules: val.atRules,\n declarations: val.declarations,\n } as StyleRule;\n });\n\n // Insert grouped rules\n const insertedRuleTexts: string[] = [];\n const insertedIndices: number[] = []; // Track exact indices\n // Calculate rule index atomically right before insertion to prevent race conditions\n let currentRuleIndex = this.findAvailableRuleIndex(targetSheet);\n let firstInsertedIndex: number | null = null;\n let lastInsertedIndex: number | null = null;\n\n for (const rule of groupedRules) {\n const declarations = rule.declarations;\n const baseRule = `${rule.selector} { ${declarations} }`;\n\n // Wrap with at-rules if present\n let fullRule = baseRule;\n if (rule.atRules && rule.atRules.length > 0) {\n fullRule = rule.atRules.reduce(\n (css, atRule) => `${atRule} { ${css} }`,\n baseRule,\n );\n }\n\n // Insert individual rule into style element\n const styleElement = targetSheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet && !this.config.forceTextInjection) {\n // Calculate index atomically for each rule to prevent concurrent insertion races\n const maxIndex = styleSheet.cssRules.length;\n const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);\n const safeIndex = Math.min(Math.max(0, atomicRuleIndex), maxIndex);\n\n // Helper: split comma-separated selectors safely (ignores commas inside [] () \" ')\n const splitSelectorsSafely = (selectorList: string): string[] => {\n const parts: string[] = [];\n let buf = '';\n let depthSq = 0; // [] depth\n let depthPar = 0; // () depth\n let inStr: '\"' | \"'\" | '' = '';\n for (let i = 0; i < selectorList.length; i++) {\n const ch = selectorList[i];\n if (inStr) {\n if (ch === inStr && selectorList[i - 1] !== '\\\\') {\n inStr = '';\n }\n buf += ch;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inStr = ch as '\"' | \"'\";\n buf += ch;\n continue;\n }\n if (ch === '[') depthSq++;\n else if (ch === ']') depthSq = Math.max(0, depthSq - 1);\n else if (ch === '(') depthPar++;\n else if (ch === ')') depthPar = Math.max(0, depthPar - 1);\n\n if (ch === ',' && depthSq === 0 && depthPar === 0) {\n const part = buf.trim();\n if (part) parts.push(part);\n buf = '';\n } else {\n buf += ch;\n }\n }\n const tail = buf.trim();\n if (tail) parts.push(tail);\n return parts;\n };\n\n try {\n styleSheet.insertRule(fullRule, safeIndex);\n // Update sheet ruleCount immediately to prevent concurrent race conditions\n targetSheet.ruleCount++;\n insertedIndices.push(safeIndex); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = safeIndex;\n lastInsertedIndex = safeIndex;\n currentRuleIndex = safeIndex + 1;\n } catch (e) {\n // If the browser rejects the combined selector (e.g., vendor pseudo-elements),\n // try to split and insert each selector independently. Skip unsupported ones.\n const selectors = splitSelectorsSafely(rule.selector);\n if (selectors.length > 1) {\n let anyInserted = false;\n for (const sel of selectors) {\n const singleBase = `${sel} { ${declarations} }`;\n let singleRule = singleBase;\n if (rule.atRules && rule.atRules.length > 0) {\n singleRule = rule.atRules.reduce(\n (css, atRule) => `${atRule} { ${css} }`,\n singleBase,\n );\n }\n\n try {\n // Calculate index atomically for each individual selector insertion\n const maxIdx = styleSheet.cssRules.length;\n const atomicIdx = this.findAvailableRuleIndex(targetSheet);\n const idx = Math.min(Math.max(0, atomicIdx), maxIdx);\n styleSheet.insertRule(singleRule, idx);\n // Update sheet ruleCount immediately\n targetSheet.ruleCount++;\n insertedIndices.push(idx); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = idx;\n lastInsertedIndex = idx;\n currentRuleIndex = idx + 1;\n anyInserted = true;\n } catch (singleErr) {\n // Skip unsupported selector in this engine (e.g., ::-moz-selection in Blink)\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n '[tasty] Browser rejected CSS rule:',\n singleRule,\n singleErr,\n );\n }\n }\n }\n // If none inserted, continue without throwing to avoid aborting the whole batch\n if (!anyInserted) {\n // noop: all selectors invalid here; safe to skip\n }\n } else {\n // Single selector failed — skip it silently (likely unsupported in this engine)\n if (process.env.NODE_ENV !== 'production') {\n console.warn('[tasty] Browser rejected CSS rule:', fullRule, e);\n }\n }\n }\n } else {\n // Use textContent (either as fallback or when forceTextInjection is enabled)\n // Calculate index atomically for textContent insertion too\n const atomicRuleIndex = this.findAvailableRuleIndex(targetSheet);\n styleElement.textContent =\n (styleElement.textContent || '') + '\\n' + fullRule;\n // Update sheet ruleCount immediately\n targetSheet.ruleCount++;\n insertedIndices.push(atomicRuleIndex); // Track this index\n if (firstInsertedIndex == null) firstInsertedIndex = atomicRuleIndex;\n lastInsertedIndex = atomicRuleIndex;\n currentRuleIndex = atomicRuleIndex + 1;\n }\n\n // CRITICAL DEBUG: Verify the style element is in DOM only if there are issues and we're not using forceTextInjection\n if (!styleElement.parentNode && !this.config.forceTextInjection) {\n console.error(\n 'SheetManager: Style element is NOT in DOM! This is the problem!',\n {\n className,\n ruleIndex: currentRuleIndex,\n },\n );\n }\n\n // Dev-only: store cssText for debugging tools\n if (this.config.devMode) {\n insertedRuleTexts.push(fullRule);\n try {\n registry.ruleTextSet.add(fullRule);\n } catch {\n // noop: defensive in case ruleTextSet is unavailable\n }\n }\n // currentRuleIndex already adjusted above\n }\n\n // Sheet ruleCount is now updated immediately after each insertion\n // No need for deferred update logic\n\n if (insertedIndices.length === 0) {\n return null;\n }\n\n return {\n className,\n ruleIndex: firstInsertedIndex ?? 0,\n sheetIndex,\n cssText: this.config.devMode ? insertedRuleTexts : undefined,\n endRuleIndex: lastInsertedIndex ?? firstInsertedIndex ?? 0,\n indices: insertedIndices,\n };\n } catch (error) {\n console.warn('Failed to insert CSS rules:', error, {\n flattenedRules,\n className,\n });\n return null;\n }\n }\n\n /**\n * Insert global CSS rules\n */\n insertGlobalRule(\n registry: RootRegistry,\n flattenedRules: StyleRule[],\n globalKey: string,\n root: Document | ShadowRoot,\n ): RuleInfo | null {\n // Insert the rule using the same mechanism as regular rules\n const ruleInfo = this.insertRule(registry, flattenedRules, globalKey, root);\n\n // Track global rules for index adjustment\n if (ruleInfo) {\n registry.globalRules.set(globalKey, ruleInfo);\n }\n\n return ruleInfo;\n }\n\n /**\n * Delete a global CSS rule by key\n */\n public deleteGlobalRule(registry: RootRegistry, globalKey: string): void {\n const ruleInfo = registry.globalRules.get(globalKey);\n if (!ruleInfo) {\n return;\n }\n\n // Delete the rule using the standard deletion mechanism\n this.deleteRule(registry, ruleInfo);\n\n // Remove from global rules tracking\n registry.globalRules.delete(globalKey);\n }\n\n /**\n * Adjust rule indices after deletion to account for shifting\n */\n private adjustIndicesAfterDeletion(\n registry: RootRegistry,\n sheetIndex: number,\n startIdx: number,\n endIdx: number,\n deleteCount: number,\n deletedRuleInfo: RuleInfo,\n deletedIndices?: number[],\n ): void {\n try {\n const sortedDeleted =\n deletedIndices && deletedIndices.length > 0\n ? [...deletedIndices].sort((a, b) => a - b)\n : null;\n const countDeletedBefore = (sorted: number[], idx: number): number => {\n let shift = 0;\n for (const delIdx of sorted) {\n if (delIdx < idx) shift++;\n else break;\n }\n return shift;\n };\n // Helper function to adjust a single RuleInfo\n const adjustRuleInfo = (info: RuleInfo): void => {\n if (info === deletedRuleInfo) return; // Skip the deleted rule\n if (info.sheetIndex !== sheetIndex) return; // Different sheet\n\n if (!info.indices || info.indices.length === 0) {\n return;\n }\n\n if (sortedDeleted) {\n // Adjust each index based on how many deleted indices are before it\n info.indices = info.indices.map((idx) => {\n return idx - countDeletedBefore(sortedDeleted, idx);\n });\n } else {\n // Contiguous deletion: shift indices after the deleted range\n info.indices = info.indices.map((idx) =>\n idx > endIdx ? Math.max(0, idx - deleteCount) : idx,\n );\n }\n\n // Update ruleIndex and endRuleIndex to match adjusted indices\n if (info.indices.length > 0) {\n info.ruleIndex = Math.min(...info.indices);\n info.endRuleIndex = Math.max(...info.indices);\n }\n };\n\n // Adjust active rules\n for (const info of registry.rules.values()) {\n adjustRuleInfo(info);\n }\n\n // Adjust global rules\n for (const info of registry.globalRules.values()) {\n adjustRuleInfo(info);\n }\n\n // No need to separately adjust unused rules since they're part of the rules Map\n\n // Adjust keyframes indices stored in cache\n for (const entry of registry.keyframesCache.values()) {\n const ki = entry.info as KeyframesInfo;\n if (ki.sheetIndex !== sheetIndex) continue;\n if (sortedDeleted) {\n const shift = countDeletedBefore(sortedDeleted, ki.ruleIndex);\n if (shift > 0) {\n ki.ruleIndex = Math.max(0, ki.ruleIndex - shift);\n }\n } else if (ki.ruleIndex > endIdx) {\n ki.ruleIndex = Math.max(0, ki.ruleIndex - deleteCount);\n }\n }\n } catch {\n // Defensive: do not let index adjustments crash cleanup\n }\n }\n\n /**\n * Delete a CSS rule from the sheet\n */\n deleteRule(registry: RootRegistry, ruleInfo: RuleInfo): void {\n const sheet = registry.sheets[ruleInfo.sheetIndex];\n\n if (!sheet) {\n return;\n }\n\n try {\n const texts: string[] =\n this.config.devMode && Array.isArray(ruleInfo.cssText)\n ? ruleInfo.cssText.slice()\n : [];\n\n const styleElement = sheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet) {\n const rules = styleSheet.cssRules;\n\n // Use exact indices if available, otherwise fall back to range\n if (ruleInfo.indices && ruleInfo.indices.length > 0) {\n // NEW: Delete using exact tracked indices\n const sortedIndices = [...ruleInfo.indices].sort((a, b) => b - a); // Sort descending\n const deletedIndices: number[] = [];\n\n for (const idx of sortedIndices) {\n if (idx >= 0 && idx < styleSheet.cssRules.length) {\n try {\n styleSheet.deleteRule(idx);\n deletedIndices.push(idx);\n } catch (e) {\n console.warn(`Failed to delete rule at index ${idx}:`, e);\n }\n }\n }\n\n sheet.ruleCount = Math.max(\n 0,\n sheet.ruleCount - deletedIndices.length,\n );\n\n // Adjust indices for all other rules\n if (deletedIndices.length > 0) {\n this.adjustIndicesAfterDeletion(\n registry,\n ruleInfo.sheetIndex,\n Math.min(...deletedIndices),\n Math.max(...deletedIndices),\n deletedIndices.length,\n ruleInfo,\n deletedIndices,\n );\n }\n } else {\n // FALLBACK: Use old range-based deletion for backwards compatibility\n const startIdx = Math.max(0, ruleInfo.ruleIndex);\n const endIdx = Math.min(\n rules.length - 1,\n Number.isFinite(ruleInfo.endRuleIndex as number)\n ? (ruleInfo.endRuleIndex as number)\n : startIdx,\n );\n\n if (Number.isFinite(startIdx) && endIdx >= startIdx) {\n const deleteCount = endIdx - startIdx + 1;\n for (let idx = endIdx; idx >= startIdx; idx--) {\n if (idx < 0 || idx >= styleSheet.cssRules.length) continue;\n styleSheet.deleteRule(idx);\n }\n sheet.ruleCount = Math.max(0, sheet.ruleCount - deleteCount);\n\n // After deletion, all subsequent rule indices shift left by deleteCount.\n // We must adjust stored indices for all other RuleInfo within the same sheet.\n this.adjustIndicesAfterDeletion(\n registry,\n ruleInfo.sheetIndex,\n startIdx,\n endIdx,\n deleteCount,\n ruleInfo,\n );\n }\n }\n }\n\n // Dev-only: remove cssText entries from validation set\n if (this.config.devMode && texts.length) {\n try {\n for (const text of texts) {\n registry.ruleTextSet.delete(text);\n }\n } catch {\n // noop\n }\n }\n } catch (error) {\n console.warn('Failed to delete CSS rule:', error);\n }\n }\n\n /**\n * Find a sheet with available space or return null\n */\n private findAvailableSheet(\n registry: RootRegistry,\n _root: Document | ShadowRoot,\n ): SheetInfo | null {\n const maxRules = this.config.maxRulesPerSheet;\n\n if (!maxRules) {\n // No limit, use the last sheet if it exists\n const lastSheet = registry.sheets[registry.sheets.length - 1];\n return lastSheet || null;\n }\n\n // Find sheet with space\n for (const sheet of registry.sheets) {\n if (sheet.ruleCount < maxRules) {\n return sheet;\n }\n }\n\n return null; // No available sheet found\n }\n\n /**\n * Find an available rule index in the sheet\n */\n findAvailableRuleIndex(sheet: SheetInfo): number {\n // Always append to the end - CSS doesn't have holes\n return sheet.ruleCount;\n }\n\n /**\n * Schedule bulk cleanup of all unused styles (non-stacking)\n */\n private scheduleBulkCleanup(registry: RootRegistry): void {\n // Clear any existing timeout to prevent stacking\n if (registry.bulkCleanupTimeout) {\n if (\n this.config.idleCleanup &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(registry.bulkCleanupTimeout as unknown as number);\n } else {\n clearTimeout(registry.bulkCleanupTimeout);\n }\n registry.bulkCleanupTimeout = null;\n }\n\n const performCleanup = () => {\n this.performBulkCleanup(registry);\n registry.bulkCleanupTimeout = null;\n };\n\n if (this.config.idleCleanup && typeof requestIdleCallback !== 'undefined') {\n registry.bulkCleanupTimeout = requestIdleCallback(performCleanup);\n } else {\n const delay = this.config.bulkCleanupDelay || 5000;\n registry.bulkCleanupTimeout = setTimeout(performCleanup, delay);\n }\n }\n\n /**\n * Force cleanup of unused styles\n */\n public forceCleanup(registry: RootRegistry): void {\n this.performBulkCleanup(registry, true);\n }\n\n /**\n * Perform bulk cleanup of all unused styles\n */\n private performBulkCleanup(registry: RootRegistry, cleanupAll = false): void {\n const cleanupStartTime = Date.now();\n\n // Calculate unused rules dynamically: rules that have refCount = 0\n const unusedClassNames = Array.from(registry.refCounts.entries())\n .filter(([, refCount]) => refCount === 0)\n .map(([className]) => className);\n\n if (unusedClassNames.length === 0) return;\n\n // Build candidates list - no age filtering needed\n const candidates = unusedClassNames.map((className) => {\n const ruleInfo = registry.rules.get(className)!; // We know it exists\n return {\n className,\n ruleInfo,\n };\n });\n\n if (candidates.length === 0) return;\n\n // Limit deletion scope per run (batch ratio) unless cleanupAll is true\n let selected = candidates;\n if (!cleanupAll) {\n const ratio = this.config.bulkCleanupBatchRatio ?? 0.5;\n const limit = Math.max(\n 1,\n Math.floor(candidates.length * Math.min(1, Math.max(0, ratio))),\n );\n selected = candidates.slice(0, limit);\n }\n\n let cleanedUpCount = 0;\n let totalCssSize = 0;\n let totalRulesDeleted = 0;\n\n // Group by sheet for efficient deletion\n const rulesBySheet = new Map<\n number,\n { className: string; ruleInfo: RuleInfo }[]\n >();\n\n // Calculate CSS size before deletion and group rules\n for (const { className, ruleInfo } of selected) {\n const sheetIndex = ruleInfo.sheetIndex;\n\n // Dev-only metrics: estimate CSS size and rule count if available\n if (this.config.devMode && Array.isArray(ruleInfo.cssText)) {\n const cssSize = ruleInfo.cssText.reduce(\n (total, css) => total + css.length,\n 0,\n );\n totalCssSize += cssSize;\n totalRulesDeleted += ruleInfo.cssText.length;\n }\n\n if (!rulesBySheet.has(sheetIndex)) {\n rulesBySheet.set(sheetIndex, []);\n }\n rulesBySheet.get(sheetIndex)!.push({ className, ruleInfo });\n }\n\n // Delete rules from each sheet (in reverse order to preserve indices)\n for (const [_sheetIndex, rulesInSheet] of rulesBySheet) {\n // Sort by rule index in descending order for safe deletion\n rulesInSheet.sort((a, b) => b.ruleInfo.ruleIndex - a.ruleInfo.ruleIndex);\n\n for (const { className, ruleInfo } of rulesInSheet) {\n // SAFETY 1: Double-check refCount is still 0\n const currentRefCount = registry.refCounts.get(className) || 0;\n if (currentRefCount > 0) {\n // Class became active again; do not delete\n continue;\n }\n\n // SAFETY 2: Ensure rule wasn't replaced\n // Between scheduling and execution a class may have been replaced with a new RuleInfo\n const currentInfo = registry.rules.get(className);\n if (currentInfo !== ruleInfo) {\n // Rule was replaced; skip deletion of the old reference\n continue;\n }\n\n // SAFETY 3: Verify the sheet element is still valid and accessible\n const sheetInfo = registry.sheets[ruleInfo.sheetIndex];\n if (!sheetInfo || !sheetInfo.sheet) {\n // Sheet was removed or corrupted; skip this rule\n continue;\n }\n\n // SAFETY 4: Verify the stylesheet itself is accessible\n const styleSheet = sheetInfo.sheet.sheet;\n if (!styleSheet) {\n // Stylesheet not available; skip this rule\n continue;\n }\n\n // SAFETY 5: Verify rule index is still within valid range\n const maxRuleIndex = styleSheet.cssRules.length - 1;\n const startIdx = ruleInfo.ruleIndex;\n const endIdx = ruleInfo.endRuleIndex ?? ruleInfo.ruleIndex;\n\n if (startIdx < 0 || endIdx > maxRuleIndex || startIdx > endIdx) {\n // Rule indices are out of bounds; skip this rule\n continue;\n }\n\n // All safety checks passed - proceed with deletion\n this.deleteRule(registry, ruleInfo);\n registry.rules.delete(className);\n registry.refCounts.delete(className);\n\n // Clean up cache key mappings that point to this className\n const keysToDelete: string[] = [];\n for (const [\n key,\n mappedClassName,\n ] of registry.cacheKeyToClassName.entries()) {\n if (mappedClassName === className) {\n keysToDelete.push(key);\n }\n }\n for (const key of keysToDelete) {\n registry.cacheKeyToClassName.delete(key);\n }\n cleanedUpCount++;\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.bulkCleanups++;\n registry.metrics.stylesCleanedUp += cleanedUpCount;\n\n // Add detailed cleanup stats to history\n registry.metrics.cleanupHistory.push({\n timestamp: cleanupStartTime,\n classesDeleted: cleanedUpCount,\n cssSize: totalCssSize,\n rulesDeleted: totalRulesDeleted,\n });\n }\n }\n\n /**\n * Get total number of rules across all sheets\n */\n getTotalRuleCount(registry: RootRegistry): number {\n return registry.sheets.reduce(\n (total, sheet) => total + sheet.ruleCount - sheet.holes.length,\n 0,\n );\n }\n\n /**\n * Get CSS text from all sheets (for SSR)\n */\n getCssText(registry: RootRegistry): string {\n const cssChunks: string[] = [];\n\n for (const sheet of registry.sheets) {\n try {\n const styleElement = sheet.sheet;\n if (styleElement.textContent) {\n cssChunks.push(styleElement.textContent);\n } else if (styleElement.sheet) {\n const rules = Array.from(styleElement.sheet.cssRules);\n cssChunks.push(rules.map((rule) => rule.cssText).join('\\n'));\n }\n } catch (error) {\n console.warn('Failed to read CSS from sheet:', error);\n }\n }\n\n return cssChunks.join('\\n');\n }\n\n /**\n * Get cache performance metrics\n */\n getMetrics(registry: RootRegistry): CacheMetrics | null {\n if (!registry.metrics) return null;\n\n // Calculate unusedHits on demand - only count CSS rules since keyframes are disposed immediately\n const unusedRulesCount = Array.from(registry.refCounts.values()).filter(\n (count) => count === 0,\n ).length;\n\n return {\n ...registry.metrics,\n unusedHits: unusedRulesCount,\n };\n }\n\n /**\n * Reset cache performance metrics\n */\n resetMetrics(registry: RootRegistry): void {\n if (registry.metrics) {\n registry.metrics = {\n hits: 0,\n misses: 0,\n bulkCleanups: 0,\n totalInsertions: 0,\n totalUnused: 0,\n stylesCleanedUp: 0,\n cleanupHistory: [],\n startTime: Date.now(),\n };\n }\n }\n\n /**\n * Convert keyframes steps to CSS string\n */\n private stepsToCSS(steps: KeyframesSteps): string {\n const rules: string[] = [];\n\n for (const [key, value] of Object.entries(steps)) {\n // Support raw CSS strings for backwards compatibility\n if (typeof value === 'string') {\n rules.push(`${key} { ${value.trim()} }`);\n continue;\n }\n\n // Treat value as a style map and process via tasty style handlers\n const styleMap = (value || {}) as StyleValueStateMap;\n\n // Build a deterministic handler queue based on present style keys\n const styleNames = Object.keys(styleMap).sort();\n const handlerQueue: StyleHandler[] = [];\n const seenHandlers = new Set<StyleHandler>();\n\n styleNames.forEach((styleName) => {\n let handlers = STYLE_HANDLER_MAP[styleName];\n if (!handlers) {\n // Create a default handler for unknown styles (maps to kebab-case CSS or custom props)\n handlers = STYLE_HANDLER_MAP[styleName] = [createStyle(styleName)];\n }\n\n handlers.forEach((handler) => {\n if (!seenHandlers.has(handler)) {\n seenHandlers.add(handler);\n handlerQueue.push(handler);\n }\n });\n });\n\n // Accumulate declarations (ordered). We intentionally ignore `$` selector fan-out\n // and any responsive/state bindings for keyframes.\n const declarationPairs: { prop: string; value: string }[] = [];\n\n handlerQueue.forEach((handler) => {\n const lookup = handler.__lookupStyles;\n const filteredMap = lookup.reduce<StyleValueStateMap>((acc, name) => {\n const v = styleMap[name];\n if (v !== undefined) acc[name] = v;\n return acc;\n }, {});\n\n const result = handler(filteredMap);\n if (!result) return;\n\n const results = Array.isArray(result) ? result : [result];\n results.forEach((cssMap) => {\n if (!cssMap || typeof cssMap !== 'object') return;\n const { $: _$, ...props } = cssMap as CSSMap;\n\n Object.entries(props).forEach(([prop, val]) => {\n if (val == null || val === '') return;\n\n if (Array.isArray(val)) {\n // Multiple values for the same property -> emit in order\n val.forEach((v) => {\n if (v != null && v !== '') {\n declarationPairs.push({ prop, value: String(v) });\n }\n });\n } else {\n declarationPairs.push({ prop, value: String(val) });\n }\n });\n });\n });\n\n // Fallback: if nothing produced (e.g., empty object), generate empty block\n const declarations = declarationPairs\n .map((d) => `${d.prop}: ${d.value}`)\n .join('; ');\n\n rules.push(`${key} { ${declarations.trim()} }`);\n }\n\n return rules.join(' ');\n }\n\n /**\n * Insert keyframes rule\n */\n insertKeyframes(\n registry: RootRegistry,\n steps: KeyframesSteps,\n name: string,\n root: Document | ShadowRoot,\n ): KeyframesInfo | null {\n let targetSheet = this.findAvailableSheet(registry, root);\n if (!targetSheet) {\n targetSheet = this.createSheet(registry, root);\n }\n\n const ruleIndex = this.findAvailableRuleIndex(targetSheet);\n const sheetIndex = registry.sheets.indexOf(targetSheet);\n\n try {\n const cssSteps = this.stepsToCSS(steps);\n const fullRule = `@keyframes ${name} { ${cssSteps} }`;\n\n const styleElement = targetSheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet && !this.config.forceTextInjection) {\n const safeIndex = Math.min(\n Math.max(0, ruleIndex),\n styleSheet.cssRules.length,\n );\n styleSheet.insertRule(fullRule, safeIndex);\n } else {\n styleElement.textContent =\n (styleElement.textContent || '') + '\\n' + fullRule;\n }\n\n targetSheet.ruleCount++;\n\n return {\n name,\n ruleIndex,\n sheetIndex,\n cssText: this.config.devMode ? fullRule : undefined,\n };\n } catch (error) {\n console.warn('Failed to insert keyframes:', error);\n return null;\n }\n }\n\n /**\n * Delete keyframes rule\n */\n deleteKeyframes(registry: RootRegistry, info: KeyframesInfo): void {\n const sheet = registry.sheets[info.sheetIndex];\n if (!sheet) return;\n\n try {\n const styleElement = sheet.sheet;\n const styleSheet = styleElement.sheet;\n\n if (styleSheet) {\n if (\n info.ruleIndex >= 0 &&\n info.ruleIndex < styleSheet.cssRules.length\n ) {\n styleSheet.deleteRule(info.ruleIndex);\n sheet.ruleCount = Math.max(0, sheet.ruleCount - 1);\n\n // Adjust indices for all other rules in the same sheet\n // This is critical - when a keyframe rule is deleted, all rules\n // with higher indices shift down by 1\n this.adjustIndicesAfterDeletion(\n registry,\n info.sheetIndex,\n info.ruleIndex,\n info.ruleIndex,\n 1,\n // Create a dummy RuleInfo to satisfy the function signature\n {\n className: '',\n ruleIndex: info.ruleIndex,\n sheetIndex: info.sheetIndex,\n } as RuleInfo,\n [info.ruleIndex],\n );\n }\n }\n } catch (error) {\n console.warn('Failed to delete keyframes:', error);\n }\n }\n\n /**\n * Schedule async cleanup check (non-stacking)\n */\n public checkCleanupNeeded(registry: RootRegistry): void {\n // Clear any existing check timeout to prevent stacking\n if (registry.cleanupCheckTimeout) {\n clearTimeout(registry.cleanupCheckTimeout);\n registry.cleanupCheckTimeout = null;\n }\n\n // Schedule the actual check with setTimeout(..., 0)\n registry.cleanupCheckTimeout = setTimeout(() => {\n this.performCleanupCheck(registry);\n registry.cleanupCheckTimeout = null;\n }, 0);\n }\n\n /**\n * Perform the actual cleanup check (called asynchronously)\n */\n private performCleanupCheck(registry: RootRegistry): void {\n // Count unused rules (refCount = 0) - keyframes are disposed immediately\n const unusedRulesCount = Array.from(registry.refCounts.values()).filter(\n (count) => count === 0,\n ).length;\n const threshold = this.config.unusedStylesThreshold || 500;\n\n if (unusedRulesCount >= threshold) {\n this.scheduleBulkCleanup(registry);\n }\n }\n\n /**\n * Clean up resources for a root\n */\n cleanup(root: Document | ShadowRoot): void {\n const registry = this.rootRegistries.get(root);\n\n if (!registry) {\n return;\n }\n\n // Cancel any scheduled bulk cleanup\n if (registry.bulkCleanupTimeout) {\n if (\n this.config.idleCleanup &&\n typeof cancelIdleCallback !== 'undefined'\n ) {\n cancelIdleCallback(registry.bulkCleanupTimeout as unknown as number);\n } else {\n clearTimeout(registry.bulkCleanupTimeout);\n }\n registry.bulkCleanupTimeout = null;\n }\n\n // Cancel any scheduled cleanup check\n if (registry.cleanupCheckTimeout) {\n clearTimeout(registry.cleanupCheckTimeout);\n registry.cleanupCheckTimeout = null;\n }\n\n // Remove all sheets\n for (const sheet of registry.sheets) {\n try {\n // Remove style element\n const styleElement = sheet.sheet;\n if (styleElement.parentNode) {\n styleElement.parentNode.removeChild(styleElement);\n }\n } catch (error) {\n console.warn('Failed to cleanup sheet:', error);\n }\n }\n\n // Clear registry\n this.rootRegistries.delete(root);\n\n // Clean up raw CSS style element\n const rawStyleElement = this.rawStyleElements.get(root);\n if (rawStyleElement?.parentNode) {\n rawStyleElement.parentNode.removeChild(rawStyleElement);\n }\n this.rawStyleElements.delete(root);\n this.rawCSSBlocks.delete(root);\n }\n\n /**\n * Get or create a dedicated style element for raw CSS\n * Raw CSS is kept separate from tasty-managed sheets to avoid index conflicts\n */\n private getOrCreateRawStyleElement(\n root: Document | ShadowRoot,\n ): HTMLStyleElement {\n let styleElement = this.rawStyleElements.get(root);\n\n if (!styleElement) {\n styleElement =\n (root as Document).createElement?.('style') ||\n document.createElement('style');\n\n if (this.config.nonce) {\n styleElement.nonce = this.config.nonce;\n }\n\n styleElement.setAttribute('data-tasty-raw', '');\n\n // Append to head or shadow root\n if ('head' in root && root.head) {\n root.head.appendChild(styleElement);\n } else if ('appendChild' in root) {\n root.appendChild(styleElement);\n } else {\n document.head.appendChild(styleElement);\n }\n\n this.rawStyleElements.set(root, styleElement);\n this.rawCSSBlocks.set(root, new Map());\n }\n\n return styleElement;\n }\n\n /**\n * Inject raw CSS text directly without parsing\n * Returns a dispose function to remove the injected CSS\n */\n injectRawCSS(css: string, root: Document | ShadowRoot): RawCSSResult {\n if (!css.trim()) {\n return {\n dispose: () => {\n /* noop */\n },\n };\n }\n\n const styleElement = this.getOrCreateRawStyleElement(root);\n const blocksMap = this.rawCSSBlocks.get(root)!;\n\n // Generate unique ID for this block\n const id = `raw_${this.rawCSSCounter++}`;\n\n // Calculate offsets\n const currentContent = styleElement.textContent || '';\n const startOffset = currentContent.length;\n const cssWithNewline = (currentContent ? '\\n' : '') + css;\n const endOffset = startOffset + cssWithNewline.length;\n\n // Append CSS\n styleElement.textContent = currentContent + cssWithNewline;\n\n // Track the block\n const info: RawCSSInfo = {\n id,\n css,\n startOffset,\n endOffset,\n };\n blocksMap.set(id, info);\n\n return {\n dispose: () => {\n this.disposeRawCSS(id, root);\n },\n };\n }\n\n /**\n * Remove a raw CSS block by ID\n */\n private disposeRawCSS(id: string, root: Document | ShadowRoot): void {\n const styleElement = this.rawStyleElements.get(root);\n const blocksMap = this.rawCSSBlocks.get(root);\n\n if (!styleElement || !blocksMap) {\n return;\n }\n\n const info = blocksMap.get(id);\n if (!info) {\n return;\n }\n\n // Remove from tracking\n blocksMap.delete(id);\n\n // Rebuild the CSS content from remaining blocks\n // This is simpler and more reliable than trying to splice strings\n const remainingBlocks = Array.from(blocksMap.values());\n\n if (remainingBlocks.length === 0) {\n styleElement.textContent = '';\n } else {\n // Rebuild with remaining CSS blocks in order of their original insertion\n // Sort by original startOffset to maintain order\n remainingBlocks.sort((a, b) => a.startOffset - b.startOffset);\n const newContent = remainingBlocks.map((block) => block.css).join('\\n');\n styleElement.textContent = newContent;\n\n // Update offsets for remaining blocks\n let offset = 0;\n for (const block of remainingBlocks) {\n block.startOffset = offset;\n block.endOffset = offset + block.css.length;\n offset = block.endOffset + 1; // +1 for newline\n }\n }\n }\n\n /**\n * Get the raw CSS content for SSR\n */\n getRawCSSText(root: Document | ShadowRoot): string {\n const styleElement = this.rawStyleElements.get(root);\n return styleElement?.textContent || '';\n }\n}\n"],"mappings":";;;;AAiBA,IAAa,eAAb,MAA0B;CACxB,AAAQ,iCAAiB,IAAI,SAA8C;CAC3E,AAAQ;;CAER,AAAQ,mCAAmB,IAAI,SAG5B;;CAEH,AAAQ,+BAAe,IAAI,SAGxB;;CAEH,AAAQ,gBAAgB;CAExB,YAAY,QA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AAO,EACL,eAAe,IAGhB;EAGH,MAAM,eAAe,KAAK,2BAA2B,KAAK;EAC1D,MAAM,YAAY,KAAK,aAAa,IAAI,KAAK;EAG7C,MAAM,KAAK,OAAO,KAAK;EAGvB,MAAM,iBAAiB,aAAa,eAAe;EACnD,MAAM,cAAc,eAAe;EACnC,MAAM,kBAAkB,iBAAiB,OAAO,MAAM;EACtD,MAAM,YAAY,cAAc,eAAe;AAG/C,eAAa,cAAc,iBAAiB;EAG5C,MAAM,OAAmB;GACvB;GACA;GACA;GACA;GACD;AACD,YAAU,IAAI,IAAI,KAAK;AAEvB,SAAO,EACL,eAAe;AACb,QAAK,cAAc,IAAI,KAAK;KAE/B;;;;;CAMH,AAAQ,cAAc,IAAY,MAAmC;EACnE,MAAM,eAAe,KAAK,iBAAiB,IAAI,KAAK;EACpD,MAAM,YAAY,KAAK,aAAa,IAAI,KAAK;AAE7C,MAAI,CAAC,gBAAgB,CAAC,UACpB;AAIF,MAAI,CADS,UAAU,IAAI,GAAG,CAE5B;AAIF,YAAU,OAAO,GAAG;EAIpB,MAAM,kBAAkB,MAAM,KAAK,UAAU,QAAQ,CAAC;AAEtD,MAAI,gBAAgB,WAAW,EAC7B,cAAa,cAAc;OACtB;AAGL,mBAAgB,MAAM,GAAG,MAAM,EAAE,cAAc,EAAE,YAAY;AAE7D,gBAAa,cADM,gBAAgB,KAAK,UAAU,MAAM,IAAI,CAAC,KAAK,KAAK;GAIvE,IAAI,SAAS;AACb,QAAK,MAAM,SAAS,iBAAiB;AACnC,UAAM,cAAc;AACpB,UAAM,YAAY,SAAS,MAAM,IAAI;AACrC,aAAS,MAAM,YAAY;;;;;;;CAQjC,cAAc,MAAqC;AAEjD,SADqB,KAAK,iBAAiB,IAAI,KAAK,EAC/B,eAAe"}
@@ -0,0 +1,3 @@
1
+ import { Bucket, ParserOptions, ProcessedStyle, StyleDetails, StyleDetailsPart, UnitHandler } from "./types.js";
2
+ import { StyleParser } from "./parser.js";
3
+ export { Bucket, type ParserOptions, type ProcessedStyle, type StyleDetails, type StyleDetailsPart, StyleParser, type UnitHandler };
@@ -0,0 +1,4 @@
1
+ import { Bucket } from "./types.js";
2
+ import { StyleParser } from "./parser.js";
3
+
4
+ export { Bucket, StyleParser };
@@ -1 +1 @@
1
- {"version":3,"file":"parser.js","names":[],"sources":["../../src/parser/parser.ts"],"sourcesContent":["import { classify } from './classify';\nimport { Lru } from './lru';\nimport { scan } from './tokenizer';\nimport type {\n ParserOptions,\n ProcessedStyle,\n StyleDetails,\n StyleDetailsPart} from './types';\nimport {\n Bucket,\n finalizeGroup,\n finalizePart,\n makeEmptyDetails,\n makeEmptyPart\n} from './types';\n\nexport class StyleParser {\n private cache: Lru<string, ProcessedStyle>;\n constructor(private opts: ParserOptions = {}) {\n this.cache = new Lru<string, ProcessedStyle>(this.opts.cacheSize ?? 1000);\n }\n\n /* ---------------- Public API ---------------- */\n process(src: string): ProcessedStyle {\n const key = String(src);\n const hit = this.cache.get(key);\n if (hit) return hit;\n\n // strip comments & lower-case once\n const stripped = src\n .replace(/\\/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*\\//g, '')\n .toLowerCase();\n\n const groups: StyleDetails[] = [];\n let currentGroup = makeEmptyDetails();\n let currentPart = makeEmptyPart();\n let parts: StyleDetailsPart[] = [];\n\n const pushToken = (bucket: Bucket, processed: string) => {\n if (!processed) return;\n\n // If the previous token was a url(...) value, merge this token into it so that\n // background layer segments like \"url(img) no-repeat center/cover\" are kept\n // as a single value entry.\n const mergeIntoPrevUrl = () => {\n const lastIdx = currentPart.values.length - 1;\n currentPart.values[lastIdx] += ` ${processed}`;\n const lastAllIdx = currentPart.all.length - 1;\n currentPart.all[lastAllIdx] += ` ${processed}`;\n };\n\n const prevIsUrlValue =\n currentPart.values.length > 0 &&\n currentPart.values[currentPart.values.length - 1].startsWith('url(');\n\n if (prevIsUrlValue) {\n // Extend the existing url(...) value regardless of current bucket.\n mergeIntoPrevUrl();\n // Additionally, for non-value buckets we need to remove their own storage.\n // So early return.\n return;\n }\n\n switch (bucket) {\n case Bucket.Color:\n currentPart.colors.push(processed);\n break;\n case Bucket.Value:\n currentPart.values.push(processed);\n break;\n case Bucket.Mod:\n currentPart.mods.push(processed);\n break;\n }\n currentPart.all.push(processed);\n };\n\n const endPart = () => {\n // Only add non-empty parts\n if (currentPart.all.length > 0) {\n finalizePart(currentPart);\n parts.push(currentPart);\n }\n currentPart = makeEmptyPart();\n };\n\n const endGroup = () => {\n endPart(); // finalize last part\n\n // Ensure at least one part exists (even if empty) for backward compat\n if (parts.length === 0) {\n parts.push(makeEmptyPart());\n finalizePart(parts[0]);\n }\n\n finalizeGroup(currentGroup, parts);\n groups.push(currentGroup);\n\n // Reset for next group\n currentGroup = makeEmptyDetails();\n parts = [];\n currentPart = makeEmptyPart();\n };\n\n scan(stripped, (tok, isComma, isSlash, _prevChar) => {\n if (tok) {\n // Accumulate raw token into currentGroup.input\n if (currentGroup.input) {\n currentGroup.input += ` ${tok}`;\n } else {\n currentGroup.input = tok;\n }\n\n const { bucket, processed } = classify(tok, this.opts, (sub) =>\n this.process(sub),\n );\n pushToken(bucket, processed);\n }\n if (isSlash) endPart();\n if (isComma) endGroup();\n });\n\n // push final group if not already\n if (currentPart.all.length || parts.length || !groups.length) endGroup();\n\n const output = groups.map((g) => g.output).join(', ');\n const result: ProcessedStyle = { output, groups };\n Object.freeze(result);\n this.cache.set(key, result);\n return result;\n }\n\n setFuncs(funcs: Required<ParserOptions>['funcs']): void {\n this.opts.funcs = funcs;\n this.cache.clear();\n }\n\n setUnits(units: Required<ParserOptions>['units']): void {\n this.opts.units = units;\n this.cache.clear();\n }\n\n updateOptions(patch: Partial<ParserOptions>): void {\n Object.assign(this.opts, patch);\n if (patch.cacheSize)\n this.cache = new Lru<string, ProcessedStyle>(patch.cacheSize);\n else this.cache.clear();\n }\n\n /**\n * Clear the parser cache.\n * Call this when external state that affects parsing results has changed\n * (e.g., predefined tokens).\n */\n clearCache(): void {\n this.cache.clear();\n }\n\n /**\n * Get the current units configuration.\n */\n getUnits(): ParserOptions['units'] {\n return this.opts.units;\n }\n}\n\n// Re-export\nexport type { StyleDetails, ProcessedStyle } from './types';\n"],"mappings":";;;;;;AAgBA,IAAa,cAAb,MAAyB;CACvB,AAAQ;CACR,YAAY,AAAQ,OAAsB,EAAE,EAAE;EAA1B;AAClB,OAAK,QAAQ,IAAI,IAA4B,KAAK,KAAK,aAAa,IAAK;;CAI3E,QAAQ,KAA6B;EACnC,MAAM,MAAM,OAAO,IAAI;EACvB,MAAM,MAAM,KAAK,MAAM,IAAI,IAAI;AAC/B,MAAI,IAAK,QAAO;EAGhB,MAAM,WAAW,IACd,QAAQ,qCAAqC,GAAG,CAChD,aAAa;EAEhB,MAAM,SAAyB,EAAE;EACjC,IAAI,eAAe,kBAAkB;EACrC,IAAI,cAAc,eAAe;EACjC,IAAI,QAA4B,EAAE;EAElC,MAAM,aAAa,QAAgB,cAAsB;AACvD,OAAI,CAAC,UAAW;GAKhB,MAAM,yBAAyB;IAC7B,MAAM,UAAU,YAAY,OAAO,SAAS;AAC5C,gBAAY,OAAO,YAAY,IAAI;IACnC,MAAM,aAAa,YAAY,IAAI,SAAS;AAC5C,gBAAY,IAAI,eAAe,IAAI;;AAOrC,OAHE,YAAY,OAAO,SAAS,KAC5B,YAAY,OAAO,YAAY,OAAO,SAAS,GAAG,WAAW,OAAO,EAElD;AAElB,sBAAkB;AAGlB;;AAGF,WAAQ,QAAR;IACE,KAAK,OAAO;AACV,iBAAY,OAAO,KAAK,UAAU;AAClC;IACF,KAAK,OAAO;AACV,iBAAY,OAAO,KAAK,UAAU;AAClC;IACF,KAAK,OAAO;AACV,iBAAY,KAAK,KAAK,UAAU;AAChC;;AAEJ,eAAY,IAAI,KAAK,UAAU;;EAGjC,MAAM,gBAAgB;AAEpB,OAAI,YAAY,IAAI,SAAS,GAAG;AAC9B,iBAAa,YAAY;AACzB,UAAM,KAAK,YAAY;;AAEzB,iBAAc,eAAe;;EAG/B,MAAM,iBAAiB;AACrB,YAAS;AAGT,OAAI,MAAM,WAAW,GAAG;AACtB,UAAM,KAAK,eAAe,CAAC;AAC3B,iBAAa,MAAM,GAAG;;AAGxB,iBAAc,cAAc,MAAM;AAClC,UAAO,KAAK,aAAa;AAGzB,kBAAe,kBAAkB;AACjC,WAAQ,EAAE;AACV,iBAAc,eAAe;;AAG/B,OAAK,WAAW,KAAK,SAAS,SAAS,cAAc;AACnD,OAAI,KAAK;AAEP,QAAI,aAAa,MACf,cAAa,SAAS,IAAI;QAE1B,cAAa,QAAQ;IAGvB,MAAM,EAAE,QAAQ,cAAc,SAAS,KAAK,KAAK,OAAO,QACtD,KAAK,QAAQ,IAAI,CAClB;AACD,cAAU,QAAQ,UAAU;;AAE9B,OAAI,QAAS,UAAS;AACtB,OAAI,QAAS,WAAU;IACvB;AAGF,MAAI,YAAY,IAAI,UAAU,MAAM,UAAU,CAAC,OAAO,OAAQ,WAAU;EAGxE,MAAM,SAAyB;GAAE,QADlB,OAAO,KAAK,MAAM,EAAE,OAAO,CAAC,KAAK,KAAK;GACZ;GAAQ;AACjD,SAAO,OAAO,OAAO;AACrB,OAAK,MAAM,IAAI,KAAK,OAAO;AAC3B,SAAO;;CAGT,SAAS,OAA+C;AACtD,OAAK,KAAK,QAAQ;AAClB,OAAK,MAAM,OAAO;;CAGpB,SAAS,OAA+C;AACtD,OAAK,KAAK,QAAQ;AAClB,OAAK,MAAM,OAAO;;CAGpB,cAAc,OAAqC;AACjD,SAAO,OAAO,KAAK,MAAM,MAAM;AAC/B,MAAI,MAAM,UACR,MAAK,QAAQ,IAAI,IAA4B,MAAM,UAAU;MAC1D,MAAK,MAAM,OAAO;;;;;;;CAQzB,aAAmB;AACjB,OAAK,MAAM,OAAO;;;;;CAMpB,WAAmC;AACjC,SAAO,KAAK,KAAK"}
1
+ {"version":3,"file":"parser.js","names":[],"sources":["../../src/parser/parser.ts"],"sourcesContent":["import { classify } from './classify';\nimport { Lru } from './lru';\nimport { scan } from './tokenizer';\nimport type {\n ParserOptions,\n ProcessedStyle,\n StyleDetails,\n StyleDetailsPart,\n} from './types';\nimport {\n Bucket,\n finalizeGroup,\n finalizePart,\n makeEmptyDetails,\n makeEmptyPart,\n} from './types';\n\nexport class StyleParser {\n private cache: Lru<string, ProcessedStyle>;\n constructor(private opts: ParserOptions = {}) {\n this.cache = new Lru<string, ProcessedStyle>(this.opts.cacheSize ?? 1000);\n }\n\n /* ---------------- Public API ---------------- */\n process(src: string): ProcessedStyle {\n const key = String(src);\n const hit = this.cache.get(key);\n if (hit) return hit;\n\n // strip comments & lower-case once\n const stripped = src\n .replace(/\\/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*\\//g, '')\n .toLowerCase();\n\n const groups: StyleDetails[] = [];\n let currentGroup = makeEmptyDetails();\n let currentPart = makeEmptyPart();\n let parts: StyleDetailsPart[] = [];\n\n const pushToken = (bucket: Bucket, processed: string) => {\n if (!processed) return;\n\n // If the previous token was a url(...) value, merge this token into it so that\n // background layer segments like \"url(img) no-repeat center/cover\" are kept\n // as a single value entry.\n const mergeIntoPrevUrl = () => {\n const lastIdx = currentPart.values.length - 1;\n currentPart.values[lastIdx] += ` ${processed}`;\n const lastAllIdx = currentPart.all.length - 1;\n currentPart.all[lastAllIdx] += ` ${processed}`;\n };\n\n const prevIsUrlValue =\n currentPart.values.length > 0 &&\n currentPart.values[currentPart.values.length - 1].startsWith('url(');\n\n if (prevIsUrlValue) {\n // Extend the existing url(...) value regardless of current bucket.\n mergeIntoPrevUrl();\n // Additionally, for non-value buckets we need to remove their own storage.\n // So early return.\n return;\n }\n\n switch (bucket) {\n case Bucket.Color:\n currentPart.colors.push(processed);\n break;\n case Bucket.Value:\n currentPart.values.push(processed);\n break;\n case Bucket.Mod:\n currentPart.mods.push(processed);\n break;\n }\n currentPart.all.push(processed);\n };\n\n const endPart = () => {\n // Only add non-empty parts\n if (currentPart.all.length > 0) {\n finalizePart(currentPart);\n parts.push(currentPart);\n }\n currentPart = makeEmptyPart();\n };\n\n const endGroup = () => {\n endPart(); // finalize last part\n\n // Ensure at least one part exists (even if empty) for backward compat\n if (parts.length === 0) {\n parts.push(makeEmptyPart());\n finalizePart(parts[0]);\n }\n\n finalizeGroup(currentGroup, parts);\n groups.push(currentGroup);\n\n // Reset for next group\n currentGroup = makeEmptyDetails();\n parts = [];\n currentPart = makeEmptyPart();\n };\n\n scan(stripped, (tok, isComma, isSlash, _prevChar) => {\n if (tok) {\n // Accumulate raw token into currentGroup.input\n if (currentGroup.input) {\n currentGroup.input += ` ${tok}`;\n } else {\n currentGroup.input = tok;\n }\n\n const { bucket, processed } = classify(tok, this.opts, (sub) =>\n this.process(sub),\n );\n pushToken(bucket, processed);\n }\n if (isSlash) endPart();\n if (isComma) endGroup();\n });\n\n // push final group if not already\n if (currentPart.all.length || parts.length || !groups.length) endGroup();\n\n const output = groups.map((g) => g.output).join(', ');\n const result: ProcessedStyle = { output, groups };\n Object.freeze(result);\n this.cache.set(key, result);\n return result;\n }\n\n setFuncs(funcs: Required<ParserOptions>['funcs']): void {\n this.opts.funcs = funcs;\n this.cache.clear();\n }\n\n setUnits(units: Required<ParserOptions>['units']): void {\n this.opts.units = units;\n this.cache.clear();\n }\n\n updateOptions(patch: Partial<ParserOptions>): void {\n Object.assign(this.opts, patch);\n if (patch.cacheSize)\n this.cache = new Lru<string, ProcessedStyle>(patch.cacheSize);\n else this.cache.clear();\n }\n\n /**\n * Clear the parser cache.\n * Call this when external state that affects parsing results has changed\n * (e.g., predefined tokens).\n */\n clearCache(): void {\n this.cache.clear();\n }\n\n /**\n * Get the current units configuration.\n */\n getUnits(): ParserOptions['units'] {\n return this.opts.units;\n }\n}\n\n// Re-export\nexport type { StyleDetails, ProcessedStyle } from './types';\n"],"mappings":";;;;;;AAiBA,IAAa,cAAb,MAAyB;CACvB,AAAQ;CACR,YAAY,AAAQ,OAAsB,EAAE,EAAE;EAA1B;AAClB,OAAK,QAAQ,IAAI,IAA4B,KAAK,KAAK,aAAa,IAAK;;CA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AAI,KAAK;AAEP,QAAI,aAAa,MACf,cAAa,SAAS,IAAI;QAE1B,cAAa,QAAQ;IAGvB,MAAM,EAAE,QAAQ,cAAc,SAAS,KAAK,KAAK,OAAO,QACtD,KAAK,QAAQ,IAAI,CAClB;AACD,cAAU,QAAQ,UAAU;;AAE9B,OAAI,QAAS,UAAS;AACtB,OAAI,QAAS,WAAU;IACvB;AAGF,MAAI,YAAY,IAAI,UAAU,MAAM,UAAU,CAAC,OAAO,OAAQ,WAAU;EAGxE,MAAM,SAAyB;GAAE,QADlB,OAAO,KAAK,MAAM,EAAE,OAAO,CAAC,KAAK,KAAK;GACZ;GAAQ;AACjD,SAAO,OAAO,OAAO;AACrB,OAAK,MAAM,IAAI,KAAK,OAAO;AAC3B,SAAO;;CAGT,SAAS,OAA+C;AACtD,OAAK,KAAK,QAAQ;AAClB,OAAK,MAAM,OAAO;;CAGpB,SAAS,OAA+C;AACtD,OAAK,KAAK,QAAQ;AAClB,OAAK,MAAM,OAAO;;CAGpB,cAAc,OAAqC;AACjD,SAAO,OAAO,KAAK,MAAM,MAAM;AAC/B,MAAI,MAAM,UACR,MAAK,QAAQ,IAAI,IAA4B,MAAM,UAAU;MAC1D,MAAK,MAAM,OAAO;;;;;;;CAQzB,aAAmB;AACjB,OAAK,MAAM,OAAO;;;;;CAMpB,WAAmC;AACjC,SAAO,KAAK,KAAK"}
@@ -1,4 +1,9 @@
1
1
  //#region src/parser/types.d.ts
2
+ declare enum Bucket {
3
+ Color = 0,
4
+ Value = 1,
5
+ Mod = 2
6
+ }
2
7
  /**
3
8
  * A part within a group, representing a slash-separated segment.
4
9
  * For example, in `'2px solid #red / 4px'`, there are two parts:
@@ -42,5 +47,5 @@ interface ParserOptions {
42
47
  cacheSize?: number;
43
48
  }
44
49
  //#endregion
45
- export { ParserOptions, ProcessedStyle, StyleDetails, UnitHandler };
50
+ export { Bucket, ParserOptions, ProcessedStyle, StyleDetails, StyleDetailsPart, UnitHandler };
46
51
  //# sourceMappingURL=types.d.ts.map
@@ -142,6 +142,13 @@ function rootUniqueId(selector, negated = false) {
142
142
  return negated ? `!${base}` : base;
143
143
  }
144
144
  /**
145
+ * Generate a normalized unique ID for a parent condition
146
+ */
147
+ function parentUniqueId(selector, direct, negated = false) {
148
+ const base = `parent:${direct ? ">" : ""}${selector}`;
149
+ return negated ? `!${base}` : base;
150
+ }
151
+ /**
145
152
  * Generate a normalized unique ID for an own condition
146
153
  */
147
154
  function ownUniqueId(innerUniqueId, negated = false) {
@@ -316,6 +323,20 @@ function createRootCondition(selector, negated = false, raw) {
316
323
  };
317
324
  }
318
325
  /**
326
+ * Create a parent condition
327
+ */
328
+ function createParentCondition(selector, direct, negated = false, raw) {
329
+ return {
330
+ kind: "state",
331
+ type: "parent",
332
+ negated,
333
+ raw: raw || `@parent(${selector}${direct ? " >" : ""})`,
334
+ uniqueId: parentUniqueId(selector, direct, negated),
335
+ selector,
336
+ direct
337
+ };
338
+ }
339
+ /**
319
340
  * Create an own condition
320
341
  */
321
342
  function createOwnCondition(innerCondition, negated = false, raw) {
@@ -373,5 +394,5 @@ function getConditionUniqueId(node) {
373
394
  }
374
395
 
375
396
  //#endregion
376
- export { and, createContainerDimensionCondition, createContainerRawCondition, createContainerStyleCondition, createMediaDimensionCondition, createMediaFeatureCondition, createMediaTypeCondition, createModifierCondition, createOwnCondition, createPseudoCondition, createRootCondition, createStartingCondition, createSupportsCondition, falseCondition, getConditionUniqueId, isCompoundCondition, not, or, trueCondition };
397
+ export { and, createContainerDimensionCondition, createContainerRawCondition, createContainerStyleCondition, createMediaDimensionCondition, createMediaFeatureCondition, createMediaTypeCondition, createModifierCondition, createOwnCondition, createParentCondition, createPseudoCondition, createRootCondition, createStartingCondition, createSupportsCondition, falseCondition, getConditionUniqueId, isCompoundCondition, not, or, trueCondition };
377
398
  //# sourceMappingURL=conditions.js.map