@tenphi/tasty 3.9.0 → 3.9.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +6 -6
- package/dist/chunks/{debug-C9LeNVoJ.js → debug-CiiHDgmR.js} +2 -2
- package/dist/chunks/{debug-C9LeNVoJ.js.map → debug-CiiHDgmR.js.map} +1 -1
- package/dist/chunks/{react-runtime-O-OUrKLH.js → react-runtime-sH6r6Ajr.js} +2 -2
- package/dist/chunks/{react-runtime-O-OUrKLH.js.map → react-runtime-sH6r6Ajr.js.map} +1 -1
- package/dist/chunks/{runtime-engine-DvnE2g-E.js → runtime-engine-BrRcOZwD.js} +8 -7
- package/dist/chunks/runtime-engine-BrRcOZwD.js.map +1 -0
- package/dist/core/index.js +2 -2
- package/dist/index.js +3 -3
- package/dist/ssr/next.js +1 -1
- package/docs/runtime-benchmarks.md +1 -1
- package/docs/ssr.md +1 -1
- package/package.json +2 -1
- package/dist/chunks/runtime-engine-DvnE2g-E.js.map +0 -1
|
@@ -1 +0,0 @@
|
|
|
1
|
-
{"version":3,"file":"runtime-engine-DvnE2g-E.js","names":["cache"],"sources":["../../src/prop-handlers.ts","../../src/injector/batch.ts","../../src/injector/sheet-manager.ts","../../src/injector/injector.ts","../../src/config.ts","../../src/injector/chunk-sheet-registry.ts","../../src/injector/index.ts","../../src/rsc-cache.ts","../../src/ssr/collect-auto-properties.ts","../../src/utils/has-keys.ts","../../src/utils/resolve-recipes.ts","../../src/compute-styles.ts","../../src/utils/filter-base-props.ts","../../src/utils/mod-attrs.ts","../../src/utils/process-tokens.ts","../../src/utils/client-state.ts","../../src/utils/deps-equal.ts"],"sourcesContent":["/**\n * Props middleware for tasty components.\n *\n * A prop handler receives a component's props and returns them, changed or not.\n * That makes it the extension point for props that are *not* style properties:\n * it can read a custom prop, strip it so it never reaches the DOM, and fold its\n * meaning into `styles`, `mods`, `tokens`, `variant`, or `as`.\n *\n * ```ts\n * configure({\n * propHandlers: {\n * glaze: (props) => {\n * const { glaze, ...rest } = props;\n * if (!glaze) return rest;\n * return { ...rest, styles: mergeStyles(glazeStyles(glaze), rest.styles) };\n * },\n * },\n * });\n * ```\n *\n * Handlers run on every render of every tasty component, so the registry is a\n * pre-composed chain that is `null` while nothing is registered — the cost when\n * unused is one property load and one branch.\n */\n\nimport { isDevEnv } from './utils/is-dev-env';\n\n/** Props object handed to a prop handler. Deliberately untyped: handlers see everything. */\nexport type PropHandlerProps = Record<string, unknown>;\n\n/**\n * Props middleware: props in, props out. Returning nothing means \"unchanged\".\n *\n * Must be a **pure function** and must not mutate its input. Style values are\n * cached by object identity, so mutating a value object in place produces a stale\n * class name and stale CSS. Return fresh (ideally frozen, ideally memoized)\n * objects instead.\n */\nexport type PropHandler = (\n props: PropHandlerProps,\n) => PropHandlerProps | void | null;\n\n/**\n * How a prop handler is declared. The map key is both its name and, by default,\n * the prop that triggers it.\n *\n * - `fn` — triggered when a prop matching the key is present\n * - `['glaze', fn]` — triggered by the named prop\n * - `[['glaze', 'tone'], fn]` — triggered by any of them\n * - `['*', fn]` — unconditional; runs on every render of every component\n */\nexport type PropHandlerDefinition =\n PropHandler | [string, PropHandler] | [string[], PropHandler];\n\ninterface NormalizedPropHandler {\n key: string;\n /** Props that trigger this handler, or `null` for unconditional. */\n triggers: string[] | null;\n fn: PropHandler;\n source: string;\n}\n\ntype PropHandlerChain = (props: PropHandlerProps) => PropHandlerProps;\n\ninterface PropHandlerRegistry {\n /** Pre-composed chain, or `null` while nothing is registered. */\n apply: PropHandlerChain | null;\n list: NormalizedPropHandler[];\n}\n\n// Held on globalThis so a duplicated module graph (Astro's server/client split)\n// shares one registry, matching how the rest of the global config is stored.\nconst GTKEY = '__tasty_prop_handlers__';\n\nconst globalStore = globalThis as unknown as Record<string, unknown>;\n\nexport const propHandlerRegistry: PropHandlerRegistry =\n (globalStore[GTKEY] as PropHandlerRegistry | undefined) ??\n ((globalStore[GTKEY] = { apply: null, list: [] }) as PropHandlerRegistry);\n\nexport interface RegisterPropHandlerOptions {\n /** Where the handler came from — a plugin name, or `'configure()'`. */\n source?: string;\n}\n\nfunction normalize(\n key: string,\n definition: PropHandlerDefinition,\n options?: RegisterPropHandlerOptions,\n): NormalizedPropHandler {\n const source = options?.source ?? 'configure()';\n\n if (typeof definition === 'function') {\n return { key, triggers: [key], fn: definition, source };\n }\n\n if (Array.isArray(definition)) {\n const [first, fn] = definition;\n\n if (typeof fn !== 'function') {\n throw new Error(\n `[Tasty] Invalid prop handler definition for \"${key}\". ` +\n 'Tuple must have a function as the second element: [string, function] or [string[], function].',\n );\n }\n\n if (first === '*') {\n return { key, triggers: null, fn, source };\n }\n\n if (typeof first === 'string') {\n return { key, triggers: [first], fn, source };\n }\n\n if (Array.isArray(first)) {\n return {\n key,\n triggers: first.includes('*') ? null : first,\n fn,\n source,\n };\n }\n\n throw new Error(\n `[Tasty] Invalid prop handler definition for \"${key}\". ` +\n 'First element must be a string or string array.',\n );\n }\n\n throw new Error(\n `[Tasty] Invalid prop handler definition for \"${key}\". ` +\n 'Expected function, [string, function], or [string[], function].',\n );\n}\n\n/**\n * Run one handler, treating a nothing/non-object return as \"unchanged\".\n *\n * `isDevEnv()` is called lazily rather than captured at module load so the\n * warnings are assertable in tests; it is only reached on the misuse path.\n */\nfunction runOne(\n handler: NormalizedPropHandler,\n props: PropHandlerProps,\n): PropHandlerProps {\n const next = handler.fn(props);\n\n if (next != null && typeof next === 'object' && !Array.isArray(next)) {\n return next;\n }\n\n if (isDevEnv()) {\n console.warn(\n next == null\n ? `[Tasty] propHandlers[\"${handler.key}\"] (from ${handler.source}) returned ` +\n `${String(next)}. Props are treated as unchanged — did you forget to ` +\n `\\`return props\\`?`\n : `[Tasty] propHandlers[\"${handler.key}\"] (from ${handler.source}) returned ` +\n `${Array.isArray(next) ? 'an array' : typeof next}. A prop handler must ` +\n `return a props object. The result was ignored.`,\n );\n }\n\n return props;\n}\n\nfunction compose(list: NormalizedPropHandler[]): PropHandlerChain | null {\n if (list.length === 0) return null;\n\n // Specialize the overwhelmingly common single-handler case.\n if (list.length === 1) {\n const only = list[0];\n\n if (only.triggers === null) {\n return (props) => runOne(only, props);\n }\n\n if (only.triggers.length === 1) {\n const trigger = only.triggers[0];\n\n return (props) => (trigger in props ? runOne(only, props) : props);\n }\n }\n\n return (props) => {\n for (const handler of list) {\n const triggers = handler.triggers;\n\n if (triggers !== null) {\n let triggered = false;\n\n for (const trigger of triggers) {\n if (trigger in props) {\n triggered = true;\n break;\n }\n }\n\n if (!triggered) continue;\n }\n\n props = runOne(handler, props);\n }\n\n return props;\n };\n}\n\n/**\n * Register a props middleware under `key`, replacing any handler already\n * registered under the same key while keeping its position in the chain.\n */\nexport function registerPropHandler(\n key: string,\n definition: PropHandlerDefinition,\n options?: RegisterPropHandlerOptions,\n): void {\n const normalized = normalize(key, definition, options);\n const { list } = propHandlerRegistry;\n const existing = list.findIndex((handler) => handler.key === key);\n\n if (existing === -1) {\n list.push(normalized);\n } else {\n list[existing] = normalized;\n }\n\n propHandlerRegistry.apply = compose(list);\n}\n\n/** Drop every registered props middleware. Called by `resetConfig()`. */\nexport function resetPropHandlers(): void {\n if (propHandlerRegistry.list.length === 0) return;\n\n // Mutate the holder rather than replacing it: other modules captured this\n // object reference at import time.\n propHandlerRegistry.list.length = 0;\n propHandlerRegistry.apply = null;\n}\n","/**\n * Deferred CSSOM writes (\"batched injection\").\n *\n * Every `insertRule()` on a live stylesheet invalidates style for the sheet's\n * scope, so Blink recalculates style the next time anything reads layout or\n * computed style. When components inject during React's render phase and other\n * components read layout in the same pass, the two interleave:\n *\n * inject -> read (forced recalc) -> inject -> read (forced recalc) -> ...\n *\n * Batching moves every sheet write out from between those reads. Writes are\n * queued in FIFO order and drained in one go, so the tree is invalidated once\n * per flush instead of once per component.\n *\n * ## Ordering\n *\n * A single queue holds *all* writes — component rules, global rules, keyframes,\n * `@property`, `@font-face`, `@counter-style`, `@function` and raw CSS. Draining\n * it in insertion order keeps the sheet byte-identical to unbatched output,\n * which matters because equal-specificity rules resolve by document order.\n *\n * ## Batch windows — why queuing is safe\n *\n * Deferring a write past React's layout phase would let a `useLayoutEffect`\n * measure an element whose rules are not in the sheet yet, reading the unstyled\n * box. `<TastyBatchProvider>` closes that hole by opening a *window* during its\n * render and closing it — flushing — in its `useInsertionEffect`, which React\n * runs in the mutation phase, before any layout effect:\n *\n * provider renders -> window OPEN\n * children render -> injections queued\n * provider insertionEffect -> FLUSH, window CLOSED\n * layout effects run -> rules are in the sheet\n *\n * So in the default (`batchInjection: true`) mode a write is only ever queued\n * inside a commit whose flush is already guaranteed by that same commit. Every\n * injection outside a window — a deep update the provider did not re-render\n * for, a `useLayoutEffect` that injects, an event handler, an async callback —\n * is written straight through, exactly as with batching off.\n *\n * `batchInjection: 'always'` opts out of the gate and queues unconditionally.\n * That wins on more commits, at the cost of the measurement hazard above.\n *\n * ## Flush points (earliest wins)\n *\n * 1. `<TastyBatchProvider>`'s `useInsertionEffect` — closes the window.\n * 2. A microtask — a backstop for a render that was aborted or suspended and\n * therefore never reached its insertion effect. An aborted render mounts\n * nothing, so nothing can measure what it queued. Microtasks also always\n * drain before paint, so styles are never visually missing.\n * 3. `flushStyles()` — explicit, and called internally by every injector read\n * API (`getCSSText`, `cleanup`, `gc`, `destroy`, ...).\n */\n\nimport { isDevEnv } from '../utils/is-dev-env';\nimport { warn } from '../utils/warnings';\n\nexport interface QueuedWrite {\n /** Perform the deferred sheet write. */\n run: () => void;\n /** Set when the owner disposed before the write happened. */\n cancelled: boolean;\n /** Set once the write has been applied (or skipped as cancelled). */\n done: boolean;\n}\n\n/**\n * FIFO of pending writes. Drained with a moving `head` index rather than\n * `shift()` so a large batch stays O(n) instead of O(n²).\n */\nlet queue: QueuedWrite[] = [];\nlet head = 0;\nlet microtaskScheduled = false;\nlet flushing = false;\n\n/**\n * Whether a `<TastyBatchProvider>` has rendered in the current commit and will\n * therefore flush in its insertion effect, making it safe to queue a write.\n *\n * A flag rather than a depth count, because renders and insertion effects do\n * not pair up one-to-one. StrictMode double-invokes render but runs the\n * insertion effect once, so a counter ends the commit stuck above zero — and a\n * window that stays open past its commit turns the next provider-less commit\n * into `'always'` mode behind the user's back, which is exactly the measurement\n * hazard `true` exists to avoid.\n *\n * Clearing on the first close is safe with nested or sibling providers: React\n * finishes every render in a commit before running any insertion effect, so once\n * one closes, no further render-phase injection can arrive in that commit.\n */\nlet windowOpen = false;\n/** Whether any window has ever been opened, i.e. a provider is in the tree. */\nlet everOpened = false;\n/** Dev-only: warn at most once that batching is on with no provider mounted. */\nlet warnedNoProvider = false;\n\n/**\n * Queue a sheet write.\n *\n * Returns a handle whose `cancel()` drops the write if the caller disposes\n * before the flush. The handle is intentionally tiny — one is allocated per\n * injected class, on the cache-miss path only.\n */\nexport function enqueueStyleWrite(run: () => void): QueuedWrite {\n // A write triggered by the write currently being drained — an `@property`\n // rule inferred from declarations that are going into the sheet right now —\n // has to land at the position the drain is at, not behind everything already\n // queued after it. Appending would reorder the sheet against unbatched\n // output, so run it in place and hand back an already-done handle.\n if (flushing) {\n run();\n return { run, cancelled: false, done: true };\n }\n\n const entry: QueuedWrite = { run, cancelled: false, done: false };\n queue.push(entry);\n scheduleMicrotaskFlush();\n return entry;\n}\n\n/** Whether any write is still waiting to hit a stylesheet. */\nexport function hasPendingStyleWrites(): boolean {\n return head < queue.length;\n}\n\n/**\n * Open a batch window. Called from `<TastyBatchProvider>`'s render, so every\n * descendant injection in this commit is covered by the provider's insertion\n * effect.\n *\n * Called during render on purpose: the window must be open before children\n * render. It is idempotent — so StrictMode's double render costs nothing — and\n * carries no other side effect. A render that is thrown away is recovered by the\n * microtask backstop.\n *\n * A no-op without a `document`. On the server there is no sheet to batch\n * against, and `useInsertionEffect` never runs, so nothing would ever close a\n * window this opened. Skipping it keeps the provider inert during SSR and RSC\n * instead of merely harmless.\n */\nexport function openBatchWindow(): void {\n if (typeof document === 'undefined') return;\n windowOpen = true;\n everOpened = true;\n}\n\n/**\n * Close a batch window and flush. Called from the provider's\n * `useInsertionEffect`, i.e. after every render in the commit and before any\n * layout effect.\n */\nexport function closeBatchWindow(): void {\n windowOpen = false;\n flushStyles();\n}\n\n/** Whether a batch window is currently open. */\nexport function isBatchWindowOpen(): boolean {\n return windowOpen;\n}\n\nfunction scheduleMicrotaskFlush(): void {\n if (microtaskScheduled || flushing) return;\n microtaskScheduled = true;\n queueMicrotask(() => {\n microtaskScheduled = false;\n // Normally a no-op: the provider's insertion effect has already drained the\n // queue. This only does work when a render was aborted or suspended before\n // reaching that effect, or when running in `'always'` mode.\n windowOpen = false;\n flushStyles();\n });\n}\n\n/**\n * Drain every pending sheet write, in insertion order.\n *\n * Safe to call when the queue is empty (the common case, so the guard comes\n * first) and safe to call re-entrantly: a nested `flushStyles()` is a no-op,\n * and work a draining write triggers is written in place by\n * `enqueueStyleWrite` rather than queued behind the rest of the batch.\n */\nexport function flushStyles(): void {\n if (head >= queue.length) return;\n if (flushing) return;\n\n flushing = true;\n try {\n // `queue.length` is re-read every iteration so a write appended by anything\n // reachable from `run()` that does not go through `enqueueStyleWrite` still\n // gets drained by this loop instead of waiting for the next flush.\n while (head < queue.length) {\n const entry = queue[head++];\n if (entry.cancelled) {\n entry.done = true;\n continue;\n }\n entry.run();\n entry.done = true;\n }\n } finally {\n queue = [];\n head = 0;\n flushing = false;\n }\n}\n\n/**\n * Dev-only: `batchInjection: true` batches nothing unless a window opens, and no\n * window has ever opened, so no provider is in the tree. Called by the injector\n * the first time it declines to batch.\n */\nexport function warnBatchProviderMissing(): void {\n if (everOpened || warnedNoProvider || !isDevEnv()) return;\n warnedNoProvider = true;\n warn('[Tasty] batchInjection needs <TastyBatchProvider> mounted to batch.');\n}\n\n/**\n * Drop every pending write without applying it. Test helper — production code\n * should call `flushStyles()` instead.\n */\nexport function resetStyleBatch(): void {\n queue = [];\n head = 0;\n microtaskScheduled = false;\n flushing = false;\n windowOpen = false;\n everOpened = false;\n warnedNoProvider = false;\n}\n","import { PropertyTypeResolver } from '../properties/property-type-resolver';\nimport { createStyle, STYLE_HANDLER_MAP } from '../styles';\n\nimport type {\n CacheMetrics,\n InjectionMode,\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\nconst supportsConstructableSheets =\n typeof CSSStyleSheet !== 'undefined' &&\n (() => {\n try {\n new CSSStyleSheet();\n return true;\n } catch {\n return false;\n }\n })();\n\nfunction wrapAtRules(css: string, atRules?: string[]): string {\n return (\n atRules?.reduce((wrapped, atRule) => `${atRule} { ${wrapped} }`, css) ?? css\n );\n}\n\n/** Split a selector list without treating commas inside [] / () / strings as separators. */\nfunction splitSelectorsSafely(selectorList: string): string[] {\n const parts: string[] = [];\n let buffer = '';\n let squareDepth = 0;\n let parenDepth = 0;\n let quote: '\"' | \"'\" | '' = '';\n\n for (let i = 0; i < selectorList.length; i++) {\n const char = selectorList[i];\n\n if (quote) {\n if (char === quote && selectorList[i - 1] !== '\\\\') quote = '';\n buffer += char;\n continue;\n }\n if (char === '\"' || char === \"'\") {\n quote = char as '\"' | \"'\";\n buffer += char;\n continue;\n }\n if (char === '[') squareDepth++;\n else if (char === ']') squareDepth = Math.max(0, squareDepth - 1);\n else if (char === '(') parenDepth++;\n else if (char === ')') parenDepth = Math.max(0, parenDepth - 1);\n\n if (char === ',' && squareDepth === 0 && parenDepth === 0) {\n const part = buffer.trim();\n if (part) parts.push(part);\n buffer = '';\n } else {\n buffer += char;\n }\n }\n\n const tail = buffer.trim();\n if (tail) parts.push(tail);\n return parts;\n}\n\nfunction rulesToCSS(sheet: CSSStyleSheet): string {\n return Array.from(sheet.cssRules, (rule) => rule.cssText).join('\\n');\n}\n\nfunction rawBlocksToCSS(blocks: Map<string, RawCSSInfo>): string {\n return [...blocks.values()]\n .sort((a, b) => a.startOffset - b.startOffset)\n .map((block) => block.css)\n .join('\\n');\n}\n\nexport class SheetManager {\n private rootRegistries = new WeakMap<Document | ShadowRoot, RootRegistry>();\n /** Strong set of active roots so background GC can iterate them all */\n private activeRoots = new Set<Document | ShadowRoot>();\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 /** Constructable sheets for raw CSS in adopted mode */\n private rawConstructableSheets = new WeakMap<ShadowRoot, CSSStyleSheet>();\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 * Resolve the underlying CSSStyleSheet from a SheetInfo,\n * abstracting away adopted vs style-element modes.\n */\n getCSSSheet(sheetInfo: SheetInfo): CSSStyleSheet | null {\n if (sheetInfo.constructableSheet) return sheetInfo.constructableSheet;\n return sheetInfo.sheet?.sheet ?? null;\n }\n\n /**\n * Record an inserted rule text at its rule index (text mode only).\n *\n * `textRules` mirrors the sheet's rule order. `textContent` cannot be edited\n * rule-by-rule the way CSSOM can, so keeping the texts is what makes\n * deletion possible at all in this mode.\n */\n private trackTextRule(\n sheet: SheetInfo,\n ruleIndex: number,\n ruleText: string,\n ): void {\n if (!sheet.textMode) return;\n\n const rules = (sheet.textRules ??= []);\n // Defensive: keep the array dense so indices stay meaningful\n while (rules.length < ruleIndex) rules.push('');\n rules[ruleIndex] = ruleText;\n }\n\n /**\n * Remove rule indices from a text-mode sheet and rewrite the element's text.\n * Returns the indices that were actually removed.\n */\n private deleteTextRules(sheet: SheetInfo, indices: number[]): number[] {\n const rules = sheet.textRules;\n if (!rules) return [];\n\n const removed = [...new Set(indices)]\n .filter((idx) => idx >= 0 && idx < rules.length)\n .sort((a, b) => b - a);\n\n for (const idx of removed) {\n rules.splice(idx, 1);\n }\n\n if (removed.length > 0 && sheet.sheet) {\n sheet.sheet.textContent = rules.length ? '\\n' + rules.join('\\n') : '';\n }\n\n return removed;\n }\n\n /**\n * Determine the injection mode for a root.\n * ShadowRoot uses adopted stylesheets when supported; Document uses <style> elements.\n */\n private detectInjectionMode(root: Document | ShadowRoot): InjectionMode {\n if (\n root instanceof ShadowRoot &&\n supportsConstructableSheets &&\n !this.config.forceTextInjection\n ) {\n return 'adopted';\n }\n return 'style-element';\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 pinCounts: new Map(),\n rules: new Map(),\n cacheKeyToClassName: new Map(),\n ruleTextSet: new Set<string>(),\n metrics,\n keyframesCache: new Map(),\n keyframesNameToContent: new Map(),\n keyframesCounter: 0,\n injectedProperties: new Map<string, string>(),\n injectedFontFaces: new Set<string>(),\n injectedCounterStyles: new Map<string, boolean>(),\n injectedFunctions: new Map<string, boolean>(),\n globalRules: new Map(),\n propertyTypeResolver: new PropertyTypeResolver(),\n unusedSince: new Map(),\n localKeyframes: new Map(),\n touchCount: 0,\n serverClassSyncIndex: 0,\n rscStylesScanned: false,\n injectionMode: this.detectInjectionMode(root),\n } as unknown as RootRegistry;\n\n this.rootRegistries.set(root, registry);\n this.activeRoots.add(root);\n }\n\n return registry;\n }\n\n /** Return all roots with active registries (for background GC sweep). */\n getActiveRoots(): Iterable<Document | ShadowRoot> {\n return this.activeRoots;\n }\n\n /** Check whether any roots have active registries. */\n hasActiveRoots(): boolean {\n return this.activeRoots.size > 0;\n }\n\n /** Remove registries for ShadowRoots whose host has been detached from the DOM. */\n pruneDisconnectedRoots(): void {\n for (const root of this.activeRoots) {\n if (root !== document && !(root as ShadowRoot).host?.isConnected) {\n this.cleanup(root);\n }\n }\n }\n\n /**\n * Create a new stylesheet for the registry.\n * In adopted mode (ShadowRoot), creates a constructable CSSStyleSheet and\n * pushes it to adoptedStyleSheets. Otherwise creates a <style> element.\n */\n createSheet(registry: RootRegistry, root: Document | ShadowRoot): SheetInfo {\n if (registry.injectionMode === 'adopted') {\n const constructableSheet = new CSSStyleSheet();\n\n // Append after any existing raw CSS sheet\n (root as ShadowRoot).adoptedStyleSheets = [\n ...(root as ShadowRoot).adoptedStyleSheets,\n constructableSheet,\n ];\n\n const sheetInfo: SheetInfo = {\n sheet: null,\n constructableSheet,\n ruleCount: 0,\n holes: [],\n };\n\n registry.sheets.push(sheetInfo);\n return sheetInfo;\n }\n\n const sheet = this.createStyleElement(root);\n\n // Pin the write mode now: `insertRule` and `deleteRule` must agree on it for\n // the lifetime of the sheet, otherwise tracked rule indices desync from\n // whichever representation is actually applied.\n const textMode =\n this.config.forceTextInjection === true || sheet.sheet == null;\n\n const sheetInfo: SheetInfo = {\n sheet,\n ruleCount: 0,\n holes: [],\n textMode,\n ...(textMode ? { textRules: [] } : {}),\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(\n root: Document | ShadowRoot,\n attribute = 'data-tasty',\n ): 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(attribute, '');\n\n // Documents inject into their head; shadow roots accept the style directly.\n ('head' in root && root.head ? root.head : root).appendChild(style);\n\n // Verify it was actually added - log only if there's a problem and we're not using forceTextInjection\n if (\n attribute === 'data-tasty' &&\n !style.isConnected &&\n !this.config.forceTextInjection\n ) {\n console.error(\n '[Tasty] SheetManager: style element failed to connect to the DOM.',\n {\n parentNode: style.parentNode?.nodeName,\n isConnected: style.isConnected,\n },\n );\n }\n\n return style;\n }\n\n /** Append a rule to a text-mode sheet while preserving its index mirror. */\n private appendTextRule(\n sheet: SheetInfo,\n ruleIndex: number,\n ruleText: string,\n ): void {\n this.trackTextRule(sheet, ruleIndex, ruleText);\n const style = sheet.sheet!;\n style.textContent = (style.textContent || '') + '\\n' + ruleText;\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);\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, at-rules, and startingStyle to combine declarations\n const groupedRules = new Map<string, StyleRule>();\n\n for (const rule of flattenedRules) {\n const key = `${rule.atRules?.join('|') ?? ''}||${rule.selector}||${rule.startingStyle ? '1' : '0'}`;\n const existing = groupedRules.get(key);\n if (existing) {\n // Append declarations, preserving order\n existing.declarations = existing.declarations\n ? `${existing.declarations} ${rule.declarations}`\n : rule.declarations;\n } else {\n groupedRules.set(key, {\n selector: rule.selector,\n atRules: rule.atRules,\n startingStyle: rule.startingStyle,\n declarations: rule.declarations,\n });\n }\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 const recordInsertion = (index: number): void => {\n targetSheet.ruleCount++;\n insertedIndices.push(index);\n if (firstInsertedIndex == null) firstInsertedIndex = index;\n lastInsertedIndex = index;\n currentRuleIndex = index + 1;\n };\n\n for (const rule of groupedRules.values()) {\n const declarations = rule.declarations;\n const innerContent = rule.startingStyle\n ? `@starting-style { ${declarations} }`\n : declarations;\n const baseRule = `${rule.selector} { ${innerContent} }`;\n const fullRule = wrapAtRules(baseRule, rule.atRules);\n\n // Insert individual rule\n const styleElement = targetSheet.sheet;\n const styleSheet = this.getCSSSheet(targetSheet);\n\n if (!targetSheet.textMode && styleSheet) {\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 try {\n styleSheet.insertRule(fullRule, safeIndex);\n recordInsertion(safeIndex);\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 for (const sel of selectors) {\n const singleBase = `${sel} { ${declarations} }`;\n const singleRule = wrapAtRules(singleBase, rule.atRules);\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 recordInsertion(idx);\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 } else {\n // Single selector failed — skip it silently (likely unsupported in this engine).\n // For @property rules specifically, probe once per registry to distinguish\n // \"engine doesn't support @property at all\" (e.g., jsdom) from\n // \"engine supports @property but this specific rule is invalid\"\n // (a real user bug worth warning about).\n if (process.env.NODE_ENV !== 'production') {\n const isAtProperty = fullRule.startsWith('@property ');\n const shouldSuppress =\n isAtProperty &&\n !this.engineSupportsAtProperty(registry, styleSheet);\n if (!shouldSuppress) {\n console.warn(\n '[Tasty] Browser rejected CSS rule:',\n fullRule,\n e,\n );\n }\n }\n }\n }\n } else if (styleElement) {\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 // Record the text so `deleteRule` can rebuild the element without it\n this.appendTextRule(targetSheet, atomicRuleIndex, fullRule);\n recordInsertion(atomicRuleIndex);\n }\n\n // Report a detached style element only if there are issues and we're not using forceTextInjection\n if (\n styleElement &&\n !styleElement.parentNode &&\n !this.config.forceTextInjection\n ) {\n console.error(\n '[Tasty] SheetManager: style element is not attached to the DOM; rules will not apply.',\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('[Tasty] 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 | null,\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 styleSheet = this.getCSSSheet(sheet);\n const indices = ruleInfo.indices;\n\n if (sheet.textMode) {\n // Text mode: splice the rules out of the tracked texts and rewrite the\n // element. Never also touch CSSOM here — assigning textContent\n // reparses the sheet, so a CSSOM delete would be undone anyway.\n let targetIndices: number[];\n\n if (indices?.length) {\n targetIndices = indices;\n } else {\n // FALLBACK: range-based deletion, mirroring the CSSOM path below\n const startIdx = Math.max(0, ruleInfo.ruleIndex);\n const endIdx = Math.min(\n (sheet.textRules?.length ?? 0) - 1,\n Number.isFinite(ruleInfo.endRuleIndex as number)\n ? (ruleInfo.endRuleIndex as number)\n : startIdx,\n );\n\n targetIndices = [];\n for (let idx = startIdx; idx <= endIdx; idx++) {\n targetIndices.push(idx);\n }\n }\n\n const deletedIndices = this.deleteTextRules(sheet, targetIndices);\n\n if (deletedIndices.length > 0) {\n sheet.ruleCount = Math.max(\n 0,\n sheet.ruleCount - deletedIndices.length,\n );\n\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 if (styleSheet) {\n const rules = styleSheet.cssRules;\n\n // Use exact indices if available, otherwise fall back to range\n if (indices?.length) {\n // NEW: Delete using exact tracked indices\n const sortedIndices = [...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(\n `[Tasty] Failed to delete rule at index ${idx}:`,\n e,\n );\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('[Tasty] Failed to delete CSS rule:', error);\n }\n }\n\n /**\n * Find a sheet with available space or return null\n */\n private findAvailableSheet(registry: RootRegistry): 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 * Probe whether the underlying CSS engine supports `@property` at-rules.\n * Result is cached per registry on `registry.atPropertySupported`.\n *\n * The probe inserts and immediately deletes a minimal known-valid rule\n * (`@property --__tasty_probe__ { syntax: \"*\"; inherits: true; }`).\n * Engines that lack `@property` support (jsdom, happy-dom) reject any\n * `@property` rule including this one, so a probe failure is a reliable\n * signal that further `@property` rejections are environmental noise and\n * not user-authored bugs.\n *\n * The probe is intentionally a separate operation from the user's failing\n * insertion: we don't want to leak `--__tasty_probe__` into the sheet, so\n * on success we delete the probe rule immediately, leaving `ruleCount`\n * and `cssRules.length` unchanged.\n */\n private engineSupportsAtProperty(\n registry: RootRegistry,\n styleSheet: CSSStyleSheet,\n ): boolean {\n if (registry.atPropertySupported !== undefined) {\n return registry.atPropertySupported;\n }\n\n const probeRule =\n '@property --__tasty_probe__ { syntax: \"*\"; inherits: true; }';\n\n try {\n const probeIdx = styleSheet.cssRules.length;\n styleSheet.insertRule(probeRule, probeIdx);\n try {\n styleSheet.deleteRule(probeIdx);\n } catch {\n // noop: unable to delete the probe; leaving it in is harmless\n // (declares an unused CSS custom property scoped to documentElement)\n }\n registry.atPropertySupported = true;\n } catch {\n registry.atPropertySupported = false;\n }\n\n return registry.atPropertySupported;\n }\n\n /**\n * Delete the given classes: their rules leave the sheets and every registry\n * entry pointing at them is dropped.\n *\n * Deciding *what* is unused belongs to `StyleInjector.gc()`, which owns the\n * DOM scan and the capacity policy. This only re-checks that each class is\n * still safe to delete, and reports how many were.\n *\n * @returns Number of classes actually deleted.\n */\n public deleteClasses(\n registry: RootRegistry,\n classNames: Iterable<string>,\n ): number {\n const cleanupStartTime = Date.now();\n\n const selected = Array.from(classNames)\n .map((className) => {\n const ruleInfo = registry.rules.get(className);\n return ruleInfo ? { className, ruleInfo } : null;\n })\n .filter((entry): entry is NonNullable<typeof entry> => entry != null);\n\n if (selected.length === 0) return 0;\n\n const deleted = new Set<string>();\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 const rules = rulesBySheet.get(sheetIndex);\n if (rules) rules.push({ className, ruleInfo });\n else rulesBySheet.set(sheetIndex, [{ className, ruleInfo }]);\n }\n\n // Delete rules from each sheet (in reverse order to preserve indices)\n for (const rulesInSheet of rulesBySheet.values()) {\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: Never delete a class someone pinned\n if ((registry.pinCounts.get(className) ?? 0) > 0) {\n // Class was pinned again between collection and deletion\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 entry is still valid and accessible\n const sheetInfo = registry.sheets[ruleInfo.sheetIndex];\n if (!sheetInfo || (!sheetInfo.sheet && !sheetInfo.constructableSheet)) {\n // Sheet was removed or corrupted; skip this rule\n continue;\n }\n\n // SAFETY 4: Verify the rule storage itself is accessible.\n // Text-mode sheets are backed by `textRules`, not CSSOM, so a missing\n // CSSStyleSheet is expected there and must not block cleanup.\n const styleSheet = this.getCSSSheet(sheetInfo);\n if (!sheetInfo.textMode && !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 =\n (sheetInfo.textMode\n ? (sheetInfo.textRules?.length ?? 0)\n : (styleSheet?.cssRules.length ?? 0)) - 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.pinCounts.delete(className);\n registry.unusedSince.delete(className);\n\n // Last class animating these keyframes: nothing refers to them now.\n for (const [key, entry] of registry.localKeyframes) {\n if (!entry.owners.delete(className)) continue;\n if (entry.owners.size === 0) {\n entry.dispose();\n registry.localKeyframes.delete(key);\n }\n }\n deleted.add(className);\n }\n }\n\n // Cache keys are indexed by key, not by className, so finding the ones that\n // point at a deleted class means scanning the map — once for the whole\n // batch rather than once per class.\n if (deleted.size > 0) {\n for (const [key, mappedClassName] of registry.cacheKeyToClassName) {\n if (deleted.has(mappedClassName)) {\n registry.cacheKeyToClassName.delete(key);\n }\n }\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.bulkCleanups++;\n registry.metrics.stylesCleanedUp += deleted.size;\n\n // Add detailed cleanup stats to history\n registry.metrics.cleanupHistory.push({\n timestamp: cleanupStartTime,\n classesDeleted: deleted.size,\n cssSize: totalCssSize,\n rulesDeleted: totalRulesDeleted,\n });\n }\n\n return deleted.size;\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 * The CSS of one managed sheet, or `null` when it holds none this can read —\n * an empty style element, or a sheet the engine refuses to hand over.\n */\n private readSheetCSS(sheetInfo: SheetInfo): string | null {\n try {\n if (sheetInfo.sheet?.textContent) return sheetInfo.sheet.textContent;\n const sheet = this.getCSSSheet(sheetInfo);\n if (sheet) return rulesToCSS(sheet);\n } catch (error) {\n console.warn('[Tasty] Failed to read CSS from sheet:', error);\n }\n\n return null;\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 sheetInfo of registry.sheets) {\n const css = this.readSheetCSS(sheetInfo);\n if (css !== null) cssChunks.push(css);\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 // `unusedHits` needs a DOM scan to be meaningful, so `StyleInjector.getMetrics()`\n // fills it in; a registry on its own cannot tell which classes are still rendered.\n return {\n ...registry.metrics,\n unusedHits: 0,\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 * Public so the SSR collector can format keyframes without DOM access.\n * Returns both the CSS text and a combined declarations string for property type scanning.\n */\n stepsToCSS(steps: KeyframesSteps): {\n css: string;\n declarations: string;\n } {\n const rules: string[] = [];\n const allDeclarations: 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 allDeclarations.push(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 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 allDeclarations.push(declarations);\n }\n\n return { css: rules.join(' '), declarations: allDeclarations.join('; ') };\n }\n\n /**\n * Insert keyframes rule.\n * Returns the KeyframesInfo and the raw declarations string for property type scanning.\n */\n insertKeyframes(\n registry: RootRegistry,\n steps: KeyframesSteps,\n name: string,\n root: Document | ShadowRoot,\n ): { info: KeyframesInfo; declarations: string } | null {\n let targetSheet = this.findAvailableSheet(registry);\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 { css: cssSteps, declarations } = this.stepsToCSS(steps);\n const fullRule = `@keyframes ${name} { ${cssSteps} }`;\n\n const styleSheet = this.getCSSSheet(targetSheet);\n\n if (!targetSheet.textMode && styleSheet) {\n const safeIndex = Math.min(\n Math.max(0, ruleIndex),\n styleSheet.cssRules.length,\n );\n styleSheet.insertRule(fullRule, safeIndex);\n } else if (targetSheet.sheet) {\n // Keyframes share the sheet's rule-index sequence, so their text has to\n // be tracked too or every later index desyncs\n this.appendTextRule(targetSheet, ruleIndex, fullRule);\n }\n\n targetSheet.ruleCount++;\n\n return {\n info: {\n name,\n ruleIndex,\n sheetIndex,\n cssText: this.config.devMode ? fullRule : undefined,\n },\n declarations,\n };\n } catch (error) {\n console.warn('[Tasty] 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 styleSheet = this.getCSSSheet(sheet);\n\n if (sheet.textMode) {\n if (!this.deleteTextRules(sheet, [info.ruleIndex]).length) return;\n } else {\n if (\n !styleSheet ||\n info.ruleIndex < 0 ||\n info.ruleIndex >= styleSheet.cssRules.length\n ) {\n return;\n }\n styleSheet.deleteRule(info.ruleIndex);\n }\n\n sheet.ruleCount = Math.max(0, sheet.ruleCount - 1);\n // Deleting one keyframe shifts every later rule index down by one.\n this.adjustIndicesAfterDeletion(\n registry,\n info.sheetIndex,\n info.ruleIndex,\n info.ruleIndex,\n 1,\n null,\n [info.ruleIndex],\n );\n } catch (error) {\n console.warn('[Tasty] Failed to delete keyframes:', error);\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 if (registry.injectionMode === 'adopted') {\n // Remove all adopted stylesheets from the shadow root\n const shadowRoot = root as ShadowRoot;\n\n // Collect all constructable sheets owned by this registry\n const ownedSheets = new Set<CSSStyleSheet>();\n for (const sheetInfo of registry.sheets) {\n if (sheetInfo.constructableSheet) {\n ownedSheets.add(sheetInfo.constructableSheet);\n }\n }\n\n // Also include the raw CSS constructable sheet\n const rawSheet = this.rawConstructableSheets.get(shadowRoot);\n if (rawSheet) {\n ownedSheets.add(rawSheet);\n this.rawConstructableSheets.delete(shadowRoot);\n }\n\n // Remove owned sheets from adoptedStyleSheets\n if (ownedSheets.size > 0) {\n shadowRoot.adoptedStyleSheets = shadowRoot.adoptedStyleSheets.filter(\n (s) => !ownedSheets.has(s),\n );\n }\n } else {\n // Remove all <style> elements\n for (const sheet of registry.sheets) {\n try {\n const styleElement = sheet.sheet;\n if (styleElement?.parentNode) {\n styleElement.parentNode.removeChild(styleElement);\n }\n } catch (error) {\n console.warn('[Tasty] Failed to cleanup sheet:', error);\n }\n }\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 }\n\n // Clear registry\n this.rootRegistries.delete(root);\n this.activeRoots.delete(root);\n this.rawCSSBlocks.delete(root);\n }\n\n /**\n * Check if a root uses adopted injection mode.\n */\n private isAdoptedMode(root: Document | ShadowRoot): boolean {\n const registry = this.rootRegistries.get(root);\n if (registry) return registry.injectionMode === 'adopted';\n return this.detectInjectionMode(root) === 'adopted';\n }\n\n /**\n * Get or create a constructable CSSStyleSheet for raw CSS in adopted mode.\n * The raw sheet is prepended to adoptedStyleSheets so it precedes tasty rules.\n */\n private getOrCreateRawAdoptedSheet(root: ShadowRoot): CSSStyleSheet {\n let sheet = this.rawConstructableSheets.get(root);\n\n if (!sheet) {\n sheet = new CSSStyleSheet();\n // Prepend raw sheet before any tasty-managed sheets for cascade ordering\n root.adoptedStyleSheets = [sheet, ...root.adoptedStyleSheets];\n this.rawConstructableSheets.set(root, sheet);\n if (!this.rawCSSBlocks.has(root)) {\n this.rawCSSBlocks.set(root, new Map());\n }\n }\n\n return sheet;\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 = this.createStyleElement(root, 'data-tasty-raw');\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 // Generate unique ID for this block\n const id = `raw_${this.rawCSSCounter++}`;\n\n if (this.isAdoptedMode(root)) {\n this.getOrCreateRawAdoptedSheet(root as ShadowRoot);\n const blocksMap = this.rawCSSBlocks.get(root)!;\n\n const info: RawCSSInfo = {\n id,\n css,\n startOffset: 0,\n endOffset: css.length,\n };\n blocksMap.set(id, info);\n\n // Rebuild full text and apply via replaceSync\n this.rebuildRawAdoptedSheet(root as ShadowRoot);\n } else {\n const styleElement = this.getOrCreateRawStyleElement(root);\n const blocksMap = this.rawCSSBlocks.get(root)!;\n const currentContent = styleElement.textContent || '';\n const cssWithNewline = (currentContent ? '\\n' : '') + css;\n\n styleElement.textContent = currentContent + cssWithNewline;\n blocksMap.set(id, {\n id,\n css,\n startOffset: currentContent.length,\n endOffset: currentContent.length + cssWithNewline.length,\n });\n }\n\n return {\n dispose: () => {\n this.disposeRawCSS(id, root);\n },\n };\n }\n\n /**\n * Rebuild the raw CSS constructable sheet from all tracked blocks.\n */\n private rebuildRawAdoptedSheet(root: ShadowRoot): void {\n const sheet = this.rawConstructableSheets.get(root);\n const blocksMap = this.rawCSSBlocks.get(root);\n if (!sheet || !blocksMap) return;\n\n sheet.replaceSync(rawBlocksToCSS(blocksMap));\n }\n\n /**\n * Remove a raw CSS block by ID\n */\n private disposeRawCSS(id: string, root: Document | ShadowRoot): void {\n const blocksMap = this.rawCSSBlocks.get(root);\n if (!blocksMap?.delete(id)) return;\n\n // Adopted mode: rebuild via replaceSync\n if (this.isAdoptedMode(root)) {\n this.rebuildRawAdoptedSheet(root as ShadowRoot);\n return;\n }\n\n // Style-element mode: rebuild textContent\n const styleElement = this.rawStyleElements.get(root);\n if (!styleElement) return;\n\n const remainingBlocks = Array.from(blocksMap.values());\n\n if (remainingBlocks.length === 0) {\n styleElement.textContent = '';\n } else {\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\n */\n /**\n * The CSS this injector owns in `root`, one entry per sheet, in the order the\n * engine applies them.\n *\n * `getCSSText()` walks the managed sheets only, and raw CSS has its own —\n * which sits before, after, or *between* them depending on how it got there:\n * prepended to `adoptedStyleSheets`, or wherever in `<head>` the first raw\n * injection happened to land, with every managed sheet opened afterwards\n * following it. Reporting a fixed order would describe the opposite winner\n * from the live page whenever two rules of equal specificity meet, so the raw\n * sheet is spliced in at the position the DOM actually gives it.\n */\n getOwnedCSSInOrder(\n registry: RootRegistry,\n root: Document | ShadowRoot,\n ): string[] {\n const raw = this.getRawCSSText(root);\n // Adopted mode prepends the raw sheet to `adoptedStyleSheets`, always, so\n // there is nothing to compare positions against.\n const rawElement = this.isAdoptedMode(root)\n ? null\n : this.rawStyleElements.get(root);\n\n let rawIndex = raw && !rawElement ? 0 : -1;\n const chunks: string[] = [];\n\n for (const sheetInfo of registry.sheets) {\n const css = this.readSheetCSS(sheetInfo);\n if (css === null) continue;\n\n if (\n rawIndex < 0 &&\n rawElement &&\n sheetInfo.sheet &&\n // DOCUMENT_POSITION_FOLLOWING: this managed sheet comes after the raw\n // one, so the raw CSS belongs in front of it.\n rawElement.compareDocumentPosition(sheetInfo.sheet) &\n Node.DOCUMENT_POSITION_FOLLOWING\n ) {\n rawIndex = chunks.length;\n }\n\n chunks.push(css);\n }\n\n if (!raw) return chunks;\n\n // No managed sheet follows it: the raw CSS is last.\n chunks.splice(rawIndex < 0 ? chunks.length : rawIndex, 0, raw);\n\n return chunks;\n }\n\n /**\n * Top-level rules in the raw sheet.\n *\n * Read from the sheet the engine parsed, not from the text: a raw block is\n * one string but any number of rules, and one rule — `@keyframes`, `@media` —\n * can contain any number of blocks, so counting braces answers neither\n * question.\n */\n getRawRuleCount(root: Document | ShadowRoot): number {\n const sheet = this.isAdoptedMode(root)\n ? this.rawConstructableSheets.get(root as ShadowRoot)\n : this.rawStyleElements.get(root)?.sheet;\n\n try {\n return sheet?.cssRules.length ?? 0;\n } catch {\n // Sheet not readable (not yet attached, or cross-origin).\n return 0;\n }\n }\n\n getRawCSSText(root: Document | ShadowRoot): string {\n // In adopted mode, read from the blocks map (source of truth)\n if (this.isAdoptedMode(root)) {\n const blocksMap = this.rawCSSBlocks.get(root);\n if (!blocksMap || blocksMap.size === 0) return '';\n return rawBlocksToCSS(blocksMap);\n }\n\n const styleElement = this.rawStyleElements.get(root);\n return styleElement?.textContent || '';\n }\n}\n","/**\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 getEffectiveDefinition,\n normalizePropertyDefinition,\n} from '../properties';\nimport { hashString } from '../utils/hash';\nimport { isDevEnv } from '../utils/is-dev-env';\nimport {\n DEFAULT_NAME_PREFIX,\n makeClassName,\n makeKeyframeName,\n rscClassRegexGlobal,\n tastyClassRegex,\n validateNamePrefix,\n} from '../utils/name-prefix';\nimport type { StyleValue } from '../utils/styles';\nimport { parseStyle } from '../utils/styles';\n\nimport {\n enqueueStyleWrite,\n flushStyles,\n isBatchWindowOpen,\n warnBatchProviderMissing,\n} from './batch';\nimport type { QueuedWrite } from './batch';\nimport { SheetManager } from './sheet-manager';\nimport { fontFaceContentHash, formatFontFaceDeclarations } from '../font-face';\nimport { formatCounterStyleDeclarations } from '../counter-style';\nimport {\n formatFunctionDeclarations,\n formatFunctionPrelude,\n parseFunctionName,\n} from '../functions';\nimport {\n HYDRATED_RULE_INDEX,\n PENDING_RULE_INDEX,\n PLACEHOLDER_RULE_INDEX,\n} from './types';\nimport type {\n CacheMetrics,\n CounterStyleDescriptors,\n FontFaceDescriptors,\n FunctionDefinition,\n GCOptions,\n GlobalInjectResult,\n InjectOptions,\n InjectResult,\n KeyframesCacheEntry,\n KeyframesInfo,\n KeyframesResult,\n KeyframesSteps,\n PropertyDefinition,\n RawCSSResult,\n RootRegistry,\n RuleInfo,\n StyleInjectorConfig,\n StyleRule,\n} from './types';\n\n/**\n * How long a class is left alone after it was last known to be wanted.\n * Long enough that a render cannot plausibly still be waiting to commit one.\n */\nconst DEFAULT_GC_GRACE = 10_000;\n\n/** Dispose handle handed back for injections that took no pin. */\nconst noop = () => {\n /* nothing to release */\n};\n\n/**\n * Placeholder `KeyframesInfo` for a cache entry reserved by a batched write and\n * not yet backed by a real rule. Only ever read through `entry.pending`, which\n * is checked before the info is used.\n */\nconst EMPTY_KEYFRAMES_INFO = {\n name: '',\n ruleIndex: PENDING_RULE_INDEX,\n sheetIndex: PENDING_RULE_INDEX,\n} as unknown as KeyframesInfo;\n\n/**\n * Extract class names from `<style data-tasty-rsc>` tags.\n * The doubled-specificity pattern `.tXXX.tXXX` makes extraction reliable.\n */\nfunction extractRSCClassNames(rscClassRegex: RegExp): string[] {\n if (typeof document === 'undefined') return [];\n const styles = document.querySelectorAll('style[data-tasty-rsc]');\n if (styles.length === 0) return [];\n\n const classSet = new Set<string>();\n for (const style of styles) {\n const text = style.textContent;\n if (!text) continue;\n let match: RegExpExecArray | null;\n rscClassRegex.lastIndex = 0;\n while ((match = rscClassRegex.exec(text)) !== null) {\n classSet.add(match[1]);\n }\n }\n return Array.from(classSet);\n}\n\n/**\n * Lazily sync server-rendered class names into the client registry.\n *\n * Sources:\n * 1. `window.__TASTY__` — pushed by SSR/RSC streaming scripts\n * 2. `<style data-tasty-rsc>` tags — inline CSS emitted by RSC components\n *\n * Called inside `inject()` / `allocateClassName()` to pick up\n * class names rendered on the server (including during SPA navigation).\n */\nfunction syncServerClasses(\n registry: RootRegistry,\n rscClassRegex: RegExp,\n): void {\n if (typeof window === 'undefined') return;\n\n // Source 1: window.__TASTY__ (SSR streaming scripts)\n const classes = window.__TASTY__;\n if (classes && classes.length > registry.serverClassSyncIndex) {\n for (let i = registry.serverClassSyncIndex; i < classes.length; i++) {\n registerHydratedClass(registry, classes[i]);\n }\n registry.serverClassSyncIndex = classes.length;\n }\n\n // Source 2: <style data-tasty-rsc> tags (RSC inline styles)\n if (!registry.rscStylesScanned) {\n registry.rscStylesScanned = true;\n for (const cls of extractRSCClassNames(rscClassRegex)) {\n registerHydratedClass(registry, cls);\n }\n }\n}\n\nfunction registerHydratedClass(\n registry: RootRegistry,\n className: string,\n): void {\n if (registry.rules.has(className)) return;\n registry.rules.set(className, {\n className,\n ruleIndex: HYDRATED_RULE_INDEX,\n sheetIndex: HYDRATED_RULE_INDEX,\n });\n registry.pinCounts.set(className, 0);\n}\n\nexport class StyleInjector {\n private sheetManager: SheetManager;\n private config: StyleInjectorConfig;\n private globalRuleCounter = 0;\n /** Cancels the scheduled sweep, whichever timer scheduled it. */\n private cancelPendingGC: (() => void) | null = null;\n private namePrefix: string;\n private classRegex: RegExp;\n private rscClassRegex: RegExp;\n\n /** @internal — exposed for debug utilities only */\n get _sheetManager(): SheetManager {\n return this.sheetManager;\n }\n\n /** Register inferable custom properties used by a set of declarations. */\n private inferProperties(\n registry: RootRegistry,\n rules: readonly { declarations?: string }[],\n root: Document | ShadowRoot,\n ): void {\n if (this.config.autoPropertyTypes === false) return;\n\n const resolver = registry.propertyTypeResolver;\n const defined = registry.injectedProperties;\n\n for (const rule of rules) {\n if (!rule.declarations) continue;\n resolver.scanDeclarations(\n rule.declarations,\n (name) => defined.has(name),\n (name, syntax, initialValue) => {\n this.property(name, {\n syntax,\n inherits: true,\n initialValue,\n root,\n });\n },\n );\n }\n }\n\n /**\n * Whether sheet writes should be queued instead of applied immediately.\n *\n * Only ever true on the client: SSR collects CSS as text and the RSC path\n * returns it as strings, so neither has a live sheet to batch writes against.\n *\n * In the default `true` mode a write is only queued inside an open batch\n * window — a commit in which `<TastyBatchProvider>` rendered and will\n * therefore flush in its insertion effect, before any layout effect can\n * measure. Everything else falls through to a synchronous write, so enabling\n * the flag cannot make a `useLayoutEffect` read an unstyled element.\n * `'always'` drops the gate and accepts that trade for wider coverage.\n */\n private get batching(): boolean {\n const mode = this.config.batchInjection;\n if (!mode || typeof document === 'undefined') return false;\n if (mode === 'always') return true;\n if (isBatchWindowOpen()) return true;\n warnBatchProviderMissing();\n return false;\n }\n\n /**\n * Apply a sheet write now, or queue it when batching is on.\n * Returns the queue handle when deferred, so the caller can cancel it if it\n * disposes before the flush.\n */\n private writeSheet(task: () => void): QueuedWrite | null {\n if (this.batching) return enqueueStyleWrite(task);\n task();\n return null;\n }\n\n /**\n * Insert a global (non-class) rule, honouring batching.\n *\n * `onApplied` records the caller's dedupe bookkeeping. When the write is\n * queued it runs eagerly, so a repeat call before the flush bails out instead\n * of queueing the same rule twice — the same reasoning as\n * `insertPropertyRule`'s eager marking. When written synchronously it runs\n * only on success, preserving the existing retry-on-failure behaviour.\n */\n private writeGlobalRule(\n registry: RootRegistry,\n rules: StyleRule[],\n key: string,\n root: Document | ShadowRoot,\n onApplied?: () => void,\n ): void {\n if (this.batching) {\n onApplied?.();\n enqueueStyleWrite(() => {\n this.sheetManager.insertGlobalRule(registry, rules, key, root);\n });\n return;\n }\n const info = this.sheetManager.insertGlobalRule(registry, rules, key, root);\n if (info) onApplied?.();\n }\n\n constructor(config: StyleInjectorConfig = {}) {\n if (config.namePrefix !== undefined) {\n validateNamePrefix(config.namePrefix);\n }\n this.config = config;\n this.sheetManager = new SheetManager(config);\n this.namePrefix = config.namePrefix ?? DEFAULT_NAME_PREFIX;\n this.classRegex = tastyClassRegex(this.namePrefix);\n this.rscClassRegex = rscClassRegexGlobal(this.namePrefix);\n }\n\n /**\n * Generate a deterministic class name from a cache key using content hash.\n * The same cache key always produces the same class name across environments\n * with the same `namePrefix`.\n */\n private generateClassName(cacheKey: string): string {\n return makeClassName(this.namePrefix, hashString(cacheKey));\n }\n\n /**\n * Check if `className` was hydrated from server-rendered styles and,\n * if so, wire the cacheKey mapping. Returns true on hit.\n */\n private tryHydratedHit(\n registry: RootRegistry,\n cacheKey: string,\n className: string,\n ): boolean {\n syncServerClasses(registry, this.rscClassRegex);\n const rule = registry.rules.get(className);\n if (\n rule &&\n rule.ruleIndex === HYDRATED_RULE_INDEX &&\n rule.sheetIndex === HYDRATED_RULE_INDEX\n ) {\n registry.cacheKeyToClassName.set(cacheKey, className);\n return true;\n }\n return false;\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 deterministic className from cache key\n const className = this.generateClassName(cacheKey);\n\n // Check if this className was hydrated from server-rendered styles\n if (this.tryHydratedHit(registry, cacheKey, className)) {\n return { className, isNewAllocation: false };\n }\n\n // Hash collision guard: another cache key already owns this class name\n const existingRule = registry.rules.get(className);\n if (existingRule) {\n if (isDevEnv()) {\n console.warn(\n `[Tasty] Hash collision: cache keys produce the same class \"${className}\". Styles may be incorrect.`,\n );\n }\n // Treat as already allocated to avoid overwriting\n registry.cacheKeyToClassName.set(cacheKey, className);\n return { className, isNewAllocation: false };\n }\n\n // Create placeholder RuleInfo to reserve the className\n const placeholderRuleInfo = {\n className,\n ruleIndex: PLACEHOLDER_RULE_INDEX,\n sheetIndex: PLACEHOLDER_RULE_INDEX,\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(rules: StyleResult[], options?: InjectOptions): InjectResult {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n // `pin: false` injects without holding the class: the caller keeps no handle\n // and lets the DOM decide when the class is done (see `gc()`).\n const pin = options?.pin ?? true;\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\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 // Rules are already queued for a batched write. Record the pin and let\n // the queued write land — injecting again would duplicate every rule.\n if (existingRuleInfo.ruleIndex === PENDING_RULE_INDEX) {\n registry.unusedSince.delete(className);\n if (pin) {\n registry.pinCounts.set(\n className,\n (registry.pinCounts.get(className) || 0) + 1,\n );\n }\n\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: pin ? () => this.unpin(className, registry) : noop,\n };\n }\n\n // A placeholder means the class name was pre-allocated but its CSS was\n // never injected, so fall through and inject it now. Anything else is\n // already in a sheet.\n const isPreAllocated =\n existingRuleInfo.ruleIndex === PLACEHOLDER_RULE_INDEX &&\n existingRuleInfo.sheetIndex === PLACEHOLDER_RULE_INDEX;\n\n if (!isPreAllocated) {\n // Handing the class to a render makes it wanted again: clearing the\n // cold mark puts it back in band 1/3, so a sweep cannot take it out\n // from under a render that has not committed yet. A `delete` that\n // misses is what the live case costs, which is nothing.\n registry.unusedSince.delete(className);\n\n // Already injected — nothing to write, only the reference to record.\n if (pin) {\n const pins = registry.pinCounts.get(className) || 0;\n registry.pinCounts.set(className, pins + 1);\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: pin ? () => this.unpin(className, registry) : noop,\n };\n }\n } else if (cacheKey) {\n // Generate deterministic className from cache key\n className = this.generateClassName(cacheKey);\n\n // Check if this className was hydrated from server-rendered styles\n if (this.tryHydratedHit(registry, cacheKey, className)) {\n if (pin) {\n registry.pinCounts.set(\n className,\n (registry.pinCounts.get(className) || 0) + 1,\n );\n }\n\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: pin ? () => this.unpin(className, registry) : noop,\n };\n }\n } else {\n // No cache key — generate from rules content\n const parts = rules.map((r) => `${r.selector}\\0${r.declarations}`);\n className = makeClassName(this.namePrefix, hashString(parts.join('\\n')));\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 // The sheet write, plus the `@property` auto-registration that the rules'\n // declarations may trigger. Kept together in one closure so batching moves\n // them as a unit and the sheet ends up in the same order either way.\n const applySheetWrite = (): RuleInfo | null => {\n // Auto-register @property for custom properties with inferable types.\n // Colors are detected by --*-color name pattern, numeric types by value.\n this.inferProperties(registry, rulesToInsert, root);\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 return null;\n }\n\n // Store in registry. Setting the cacheKey mapping is idempotent when the\n // class was pre-allocated, so both paths can share one branch.\n registry.rules.set(className, ruleInfo);\n if (cacheKey) {\n registry.cacheKeyToClassName.set(cacheKey, className);\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n registry.metrics.misses++;\n }\n\n return ruleInfo;\n };\n\n if (this.batching) {\n // Reserve the class name before returning so a repeat inject() with the\n // same cacheKey — very common, one per sibling component — takes the\n // PENDING short-circuit above instead of queueing the same rules again.\n registry.rules.set(className, {\n className,\n ruleIndex: PENDING_RULE_INDEX,\n sheetIndex: PENDING_RULE_INDEX,\n });\n if (cacheKey) {\n registry.cacheKeyToClassName.set(cacheKey, className);\n }\n if (pin) {\n registry.pinCounts.set(className, 1);\n }\n registry.unusedSince.set(className, Date.now());\n\n const queued = enqueueStyleWrite(() => {\n if (applySheetWrite()) return;\n // Insertion failed. Fall back to the \"allocated but not injected\"\n // state so a later render retries, matching the unbatched path.\n registry.rules.set(className, {\n className,\n ruleIndex: PLACEHOLDER_RULE_INDEX,\n sheetIndex: PLACEHOLDER_RULE_INDEX,\n });\n });\n\n return {\n className,\n dispose: pin\n ? () => {\n // Still queued and this was the only owner: drop the write and the\n // reservation rather than leaving an orphan rule for GC to find.\n if (\n !queued.done &&\n registry.pinCounts.get(className) === 1 &&\n registry.rules.get(className)?.ruleIndex === PENDING_RULE_INDEX\n ) {\n queued.cancelled = true;\n registry.rules.delete(className);\n if (cacheKey) {\n registry.cacheKeyToClassName.delete(cacheKey);\n }\n registry.pinCounts.set(className, 0);\n return;\n }\n this.unpin(className, registry);\n }\n : noop,\n };\n }\n\n if (!applySheetWrite()) {\n return {\n className,\n dispose: () => {\n /* noop */\n },\n };\n }\n\n if (pin) {\n registry.pinCounts.set(className, 1);\n }\n registry.unusedSince.set(className, Date.now());\n\n return {\n className,\n dispose: pin ? () => this.unpin(className, registry) : noop,\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 // The `@property` auto-registration inserts rules of its own, so it stays in\n // the same queue slot as the rules that triggered it. Global rules are style\n // rules and do take part in the cascade, so they share the one FIFO with\n // component rules — that is what keeps sheet order identical to unbatched\n // output, and equal-specificity rules resolve by document order.\n const applyWrite = (): RuleInfo | null => {\n // Auto-register @property for custom properties in global rules\n this.inferProperties(registry, rules, root);\n\n const inserted = 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 inserted;\n };\n\n if (this.batching) {\n let info: RuleInfo | null = null;\n const queued = enqueueStyleWrite(() => {\n info = applyWrite();\n });\n\n return {\n dispose: () => {\n // Cancel instead of deleting a rule that never made it into a sheet.\n if (!queued.done) {\n queued.cancelled = true;\n return;\n }\n if (info) this.sheetManager.deleteGlobalRule(registry, key);\n },\n };\n }\n\n const info = applyWrite();\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\n if (!this.batching) {\n return this.sheetManager.injectRawCSS(css, root);\n }\n\n // Raw CSS is arbitrary and does take part in the cascade, so it goes through\n // the same FIFO as component and global rules.\n let result: RawCSSResult | null = null;\n const queued = enqueueStyleWrite(() => {\n result = this.sheetManager.injectRawCSS(css, root);\n });\n\n return {\n dispose: () => {\n if (!queued.done) {\n queued.cancelled = true;\n return;\n }\n result?.dispose();\n },\n };\n }\n\n /**\n * Get raw CSS text for SSR\n */\n getRawCSSText(options?: { root?: Document | ShadowRoot }): string {\n flushStyles();\n const root = options?.root || document;\n return this.sheetManager.getRawCSSText(root);\n }\n\n /**\n * Take a reference on local `@keyframes`, under the deterministic names the\n * caller resolved.\n *\n * One reference per distinct set of steps, shared by every class that ends up\n * animating it, so a repeat render takes nothing further. Ownership is\n * assigned by `ownKeyframes()` once the rules exist to be inspected.\n */\n holdKeyframes(\n steps: Record<string, KeyframesSteps>,\n names: Map<string, string>,\n options?: { root?: Document | ShadowRoot },\n ): Map<string, string> {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n // Authored name -> the entry key holding it, so a chunk that runs the\n // animation can be recorded as an owner.\n const keys = new Map<string, string>();\n\n for (const [authored, definition] of Object.entries(steps)) {\n const resolved = names.get(authored) ?? authored;\n let entry = registry.localKeyframes.get(resolved);\n\n if (!entry) {\n // `distinctByName`: the rules rewritten to this name need a rule under\n // it. Two authored animations can share steps — `fade` and `spin` with\n // the same from/to — and would otherwise collapse onto whichever name\n // was injected first, leaving the other animating nothing.\n const injected = this.keyframes(definition, {\n name: resolved,\n root,\n distinctByName: true,\n });\n entry = {\n name: injected.toString(),\n dispose: injected.dispose,\n owners: new Set(),\n };\n registry.localKeyframes.set(resolved, entry);\n }\n\n keys.set(authored, resolved);\n }\n\n return keys;\n }\n\n /**\n * Record that `className` animates these keyframes, so the reference is\n * released when the last such class is collected.\n *\n * Only classes whose rules actually reference the animation should be here:\n * a class that merely rendered alongside one would otherwise keep the\n * keyframes alive for as long as it lives.\n */\n ownKeyframes(\n key: string,\n className: string,\n options?: { root?: Document | ShadowRoot },\n ): void {\n const registry = this.sheetManager.getRegistry(options?.root || document);\n registry.localKeyframes.get(key)?.owners.add(className);\n }\n\n /**\n * Pin an already-injected cacheKey and return the handle that releases it.\n * For callers that skipped the pipeline on a cache hit but still need the\n * class held. Returns null if the cacheKey is not found.\n */\n trackRef(\n cacheKey: string,\n options?: { root?: Document | ShadowRoot },\n ): InjectResult | null {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n if (!registry.cacheKeyToClassName.has(cacheKey)) return null;\n\n const className = registry.cacheKeyToClassName.get(cacheKey)!;\n const pins = registry.pinCounts.get(className) || 0;\n registry.pinCounts.set(className, pins + 1);\n\n if (registry.metrics) {\n registry.metrics.hits++;\n }\n\n return {\n className,\n dispose: () => this.unpin(className, registry),\n };\n }\n\n /**\n * Release one pin on a className. At zero pins the class is not deleted — it\n * stays cached and collectible, and `gc()` decides when it actually goes.\n */\n private unpin(className: string, registry: RootRegistry): void {\n const pins = registry.pinCounts.get(className);\n if (pins == null || pins <= 0) {\n return;\n }\n\n const remaining = pins - 1;\n registry.pinCounts.set(className, remaining);\n\n if (remaining === 0 && registry.metrics) {\n registry.metrics.totalUnused++;\n }\n }\n\n /**\n * Remove every style that is neither in the DOM nor referenced by an\n * outstanding `inject()` handle, ignoring the GC capacity threshold.\n */\n cleanup(root?: Document | ShadowRoot): void {\n this.gc({ root, force: true });\n }\n\n /**\n * Get CSS text from all sheets (for SSR)\n */\n getCSSText(options?: { root?: Document | ShadowRoot }): string {\n flushStyles();\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 flushStyles();\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 ? this.sheetManager.getCSSSheet(sheet) : null;\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 // Batched insertions only count themselves once they reach a sheet, so a read\n // taken mid-window would report a torn picture: `hits` already advanced,\n // `totalInsertions` not yet.\n flushStyles();\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n const metrics = this.sheetManager.getMetrics(registry);\n\n if (metrics && typeof document !== 'undefined') {\n metrics.unusedHits = this.collectUnused(registry, root).length;\n }\n\n return metrics;\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 this.insertPropertyRule(registry, root, cssName, definition, name);\n }\n\n /**\n * Build and insert a single `@property` rule into the given registry.\n * No-op if the property was already injected.\n */\n private insertPropertyRule(\n registry: RootRegistry,\n root: Document | ShadowRoot,\n cssName: string,\n definition: PropertyDefinition,\n cacheKey: string,\n ): void {\n if (registry.injectedProperties.has(cssName)) {\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 // Mark as attempted BEFORE inserting so repeated calls bail early even\n // when the insertion ultimately fails (e.g., engines like jsdom that\n // don't support @property reject every @property rule unconditionally).\n // Without this, every render's auto-property scan would re-attempt the\n // same rejected rules and flood the console with warnings.\n registry.injectedProperties.set(\n cssName,\n normalizePropertyDefinition(definition),\n );\n\n this.writeGlobalRule(registry, [rule], `property:${cacheKey}`, root);\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 flushStyles();\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 a CSS @font-face rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by content hash (family + descriptors).\n */\n fontFace(\n family: string,\n descriptors: FontFaceDescriptors,\n options?: { root?: Document | ShadowRoot },\n ): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n const hash = fontFaceContentHash(family, descriptors);\n\n if (registry.injectedFontFaces.has(hash)) {\n return;\n }\n\n const rule: StyleRule = {\n selector: '@font-face',\n declarations: formatFontFaceDeclarations(family, descriptors),\n } as StyleRule;\n\n this.writeGlobalRule(registry, [rule], `fontface:${hash}`, root, () => {\n registry.injectedFontFaces.add(hash);\n });\n }\n\n /**\n * Inject a CSS @counter-style rule.\n *\n * Permanent and global — no dispose or ref-counting. Deduplicates by name.\n * By default a definition overrides a previously injected one of the same\n * name. Pass `weak: true` for global `configure()` definitions, which must\n * never clobber an existing rule (so component-local definitions win\n * regardless of injection order).\n */\n counterStyle(\n name: string,\n descriptors: CounterStyleDescriptors,\n options?: { root?: Document | ShadowRoot; weak?: boolean },\n ): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n const isWeak = options?.weak === true;\n\n const existingIsStrong = registry.injectedCounterStyles.get(name);\n if (existingIsStrong !== undefined) {\n // A weak (global) definition never overrides; a strong one keeps the\n // first definition. Only a strong definition replacing a weak one wins.\n if (isWeak || existingIsStrong === true) {\n return;\n }\n this.writeSheet(() => {\n this.sheetManager.deleteGlobalRule(registry, `counterstyle:${name}`);\n });\n }\n\n const rule: StyleRule = {\n selector: `@counter-style ${name}`,\n declarations: formatCounterStyleDeclarations(descriptors),\n } as StyleRule;\n\n this.writeGlobalRule(registry, [rule], `counterstyle:${name}`, root, () => {\n registry.injectedCounterStyles.set(name, !isWeak);\n });\n }\n\n /**\n * Inject a CSS @function rule (custom function).\n *\n * Permanent and global — no dispose or ref-counting. Deduplicates by function\n * name. By default a definition overrides a previously injected one of the\n * same name. Pass `weak: true` for global `configure()` definitions, which\n * must never clobber an existing rule (so component-local definitions win\n * regardless of injection order).\n */\n func(\n name: string,\n definition: FunctionDefinition,\n options?: { root?: Document | ShadowRoot; weak?: boolean },\n ): void {\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n const isWeak = options?.weak === true;\n\n const cssName = parseFunctionName(name);\n\n const existingIsStrong = registry.injectedFunctions.get(cssName);\n if (existingIsStrong !== undefined) {\n // A weak (global) definition never overrides; a strong one keeps the\n // first definition. Only a strong definition replacing a weak one wins.\n if (isWeak || existingIsStrong === true) {\n return;\n }\n this.writeSheet(() => {\n this.sheetManager.deleteGlobalRule(registry, `function:${cssName}`);\n });\n }\n\n const rule: StyleRule = {\n selector: formatFunctionPrelude(\n name,\n definition.args,\n definition.returns,\n ),\n declarations: formatFunctionDeclarations(definition),\n } as StyleRule;\n\n this.writeGlobalRule(registry, [rule], `function:${cssName}`, root, () => {\n registry.injectedFunctions.set(cssName, !isWeak);\n });\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?:\n | string\n | {\n root?: Document | ShadowRoot;\n name?: string;\n /**\n * Give this name its own rule even if another name already carries\n * the same steps. Without it two names with identical steps share\n * one rule under whichever name arrived first — fine when the caller\n * only wants the animation, wrong when the name has to be the one it\n * asked for.\n */\n distinctByName?: boolean;\n },\n ): KeyframesResult {\n // Parse parameters\n const isStringName = typeof nameOrOptions === 'string';\n const providedName = isStringName ? nameOrOptions : nameOrOptions?.name;\n const distinctByName = isStringName\n ? false\n : (nameOrOptions?.distinctByName ?? false);\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 // Content-based cache key, scoped to the name when the caller needs that\n // exact name to exist.\n const contentHash =\n distinctByName && providedName\n ? `${providedName}\\u0000${JSON.stringify(steps)}`\n : 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}-${makeKeyframeName(\n this.namePrefix,\n String(registry.keyframesCounter++),\n )}`;\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 = makeKeyframeName(\n this.namePrefix,\n String(registry.keyframesCounter++),\n );\n }\n\n // The insertion plus the `@property` scan over the resulting declarations.\n // Returns false when the sheet rejected the rule, so the caller can leave\n // the cache untouched and let a later call retry.\n const applyWrite = (): boolean => {\n const result = this.sheetManager.insertKeyframes(\n registry,\n steps,\n actualName,\n root,\n );\n if (!result) return false;\n\n const { info, declarations } = result;\n\n // Auto-register @property for custom properties found in keyframe declarations\n if (this.config.autoPropertyTypes !== false && declarations) {\n const resolver = registry.propertyTypeResolver;\n resolver.scanDeclarations(\n declarations,\n (name) => registry.injectedProperties.has(name),\n (name, syntax, initialValue) => {\n this.property(name, {\n syntax,\n inherits: true,\n initialValue,\n root,\n });\n },\n );\n }\n\n const entry = registry.keyframesCache.get(contentHash);\n if (entry) {\n // Batched path: the entry was reserved up front, fill in the real info.\n entry.info = info;\n entry.pending = undefined;\n } else {\n registry.keyframesCache.set(contentHash, {\n name: actualName,\n refCount: 1,\n info,\n });\n }\n\n // Update metrics\n if (registry.metrics) {\n registry.metrics.totalInsertions++;\n registry.metrics.misses++;\n }\n\n return true;\n };\n\n if (this.batching) {\n // Reserve the cache entry now so a second keyframes() call with the same\n // content before the flush reuses the name instead of queueing again.\n // `info` is a placeholder until the write lands; `pending` marks that, and\n // disposeKeyframes() cancels rather than deleting a non-existent rule.\n const entry: KeyframesCacheEntry = {\n name: actualName,\n refCount: 1,\n info: EMPTY_KEYFRAMES_INFO,\n };\n registry.keyframesCache.set(contentHash, entry);\n\n entry.pending = enqueueStyleWrite(() => {\n if (applyWrite()) return;\n // Rejected: drop the reservation so a later call can retry, mirroring\n // the unbatched path which never caches a failed insertion.\n if (registry.keyframesCache.get(contentHash) === entry) {\n registry.keyframesCache.delete(contentHash);\n }\n });\n\n return {\n toString: () => actualName,\n dispose: () => this.disposeKeyframes(contentHash, registry),\n };\n }\n\n if (!applyWrite()) {\n return {\n toString: () => '',\n dispose: () => {\n /* noop */\n },\n };\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 // Queued but not yet written: cancel the write instead of deleting a rule\n // that was never inserted.\n if (entry.pending && !entry.pending.done) {\n entry.pending.cancelled = true;\n } else {\n // Dispose immediately - keyframes are global and safe to clean up right away\n this.sheetManager.deleteKeyframes(registry, entry.info);\n }\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 // GC: touch-count-driven garbage collection with DOM safety guard\n // =========================================================================\n\n /**\n * Count a render, and schedule a collection pass every `touchInterval` of\n * them. Nothing else: what a class is worth keeping is decided by the sweep's\n * own DOM scan, so rendering does not track usage at all.\n *\n * @deprecated The class name is ignored — pass anything, or stop calling it.\n * Collection no longer records per-class usage, and scheduling does not need\n * to know which class was rendered. A class handed back by `inject()` is\n * marked wanted there, which is what reuse actually goes through.\n */\n touch(_className: string, options?: { root?: Document | ShadowRoot }): void {\n if (typeof document === 'undefined') return;\n if (!this.config.gc) return;\n\n const registry = this.sheetManager.getRegistry(options?.root || document);\n\n if (++registry.touchCount >= (this.config.gc.touchInterval ?? 1000)) {\n registry.touchCount = 0;\n this.scheduleGC();\n }\n }\n\n /**\n * Schedule a GC in idle time. Runs GC on all active roots, and avoids\n * double-scheduling.\n *\n * Idle only. Without `requestIdleCallback` nothing is collected\n * automatically: running the sweep inline here would put it inside the render\n * that touched the class, and collection is never urgent enough for that.\n */\n private scheduleGC(): void {\n if (this.cancelPendingGC) return;\n\n const runGC = () => {\n this.cancelPendingGC = null;\n this.sheetManager.pruneDisconnectedRoots();\n for (const root of this.sheetManager.getActiveRoots()) {\n this.gc({ root });\n }\n };\n\n if (typeof requestIdleCallback !== 'undefined') {\n const handle = requestIdleCallback(() => runGC());\n this.cancelPendingGC = () => cancelIdleCallback(handle);\n }\n }\n\n /**\n * The one definition of \"unused\": this injector owns the class's rules, no\n * element in `root` carries it, and nobody pinned it.\n *\n * `gc()` evicts from this set, `getMetrics()` counts it, and `tastyDebug`\n * reports it — all through here, so the three can never disagree about what\n * \"unused\" means. Entries carry their last `touch()` so callers can drop the\n * oldest first; a class that was never touched sorts as oldest.\n */\n /**\n * Everything the injector holds falls into one of five bands, and only the\n * last of them is ever deleted:\n *\n * 1. rendered — some element carries the class right now\n * 2. not ours — queued for a batched write, pre-allocated, or server-rendered\n * 3. hot — nothing carries it, but that was noticed less than `grace` ago\n * 4. cached — cold, but within `capacity` when ordered by when it went cold\n * 5. the rest\n *\n * This returns bands 4 and 5 together, most recently cold first; `gc()` draws\n * the capacity line through them. Band 3 is what makes collection safe\n * without a commit signal: a render can resolve a class and commit it a\n * little later, and during that gap nothing on the page carries it.\n */\n private collectUnused(\n registry: RootRegistry,\n root: Document | ShadowRoot,\n ): string[] {\n const now = Date.now();\n const grace = this.config.gc?.grace ?? DEFAULT_GC_GRACE;\n\n // Scan the DOM for live classes (classList handles SVG elements too)\n const liveClasses = new Set<string>();\n for (const el of root.querySelectorAll('[class]')) {\n for (const token of el.classList) {\n if (this.classRegex.test(token)) liveClasses.add(token);\n }\n }\n\n const unused: string[] = [];\n\n for (const [className, ruleInfo] of registry.rules) {\n // Band 2: a negative sheet index marks a rule this injector does not own\n // — server rendered (hydrated), pre-allocated, or still queued.\n if (ruleInfo.sheetIndex < 0) continue;\n\n // Band 1.\n if (liveClasses.has(className)) {\n registry.unusedSince.delete(className);\n continue;\n }\n\n // Someone still holds the dispose handle `inject()` returned.\n if ((registry.pinCounts.get(className) ?? 0) > 0) continue;\n\n // Band 3. The clock starts at the sighting, not at whatever moment the\n // element actually left — nothing was watching for that — so every class\n // gets the same full window however long ago it went.\n let since = registry.unusedSince.get(className);\n if (since === undefined) {\n since = now;\n registry.unusedSince.set(className, now);\n }\n if (now - since < grace) continue;\n\n unused.push(className);\n }\n\n // Most recently cold first, so `gc()` can keep that many and drop the tail.\n unused.sort(\n (a, b) =>\n (registry.unusedSince.get(b) ?? 0) - (registry.unusedSince.get(a) ?? 0),\n );\n\n return unused;\n }\n\n /**\n * Class names this injector holds CSS for that nothing renders and nobody\n * pinned — exactly what `gc({ force: true })` would delete. Unordered.\n */\n getUnusedClasses(options?: { root?: Document | ShadowRoot }): string[] {\n flushStyles();\n if (typeof document === 'undefined') return [];\n\n const root = options?.root || document;\n const registry = this.sheetManager.getRegistry(root);\n\n return this.collectUnused(registry, root);\n }\n\n /**\n * Synchronous garbage collection.\n *\n * 1. Quick upper-bound check: skip if the registry is smaller than capacity.\n * 2. Scans the DOM for live tasty classNames — the DOM, not a ref count, is\n * what says a class rendered by a component is still in use.\n * 3. With `force: true`: deletes every unused class.\n * Without `force`: keeps the `capacity` most recently touched and deletes\n * the rest, oldest first.\n *\n * @returns Number of styles evicted.\n */\n gc(options?: GCOptions): number {\n // Pending writes still carry PENDING sentinels in `registry.rules`; sweeping\n // those would corrupt sheet indices, so land every write first.\n flushStyles();\n if (typeof document === 'undefined') return 0;\n\n // Cancel any pending scheduled GC to prevent double runs\n this.cancelPendingGC?.();\n this.cancelPendingGC = null;\n\n const root = options?.root || document;\n const force = options?.force;\n const registry = this.sheetManager.getRegistry(root);\n const capacity = this.config.gc?.capacity ?? 1000;\n\n // Quick upper-bound check: not even every class being unused would exceed\n // capacity, so skip the DOM scan.\n if (!force && registry.rules.size <= capacity) return 0;\n\n const unused = this.collectUnused(registry, root);\n\n let doomed: string[];\n\n if (force) {\n // Bands 4 and 5. Band 3 is spared even here: an explicit cleanup is still\n // no reason to take rules from a render that has not committed yet.\n doomed = unused;\n } else if (unused.length > capacity) {\n // Band 4 is the `capacity` classes that went cold most recently; band 5\n // is everything behind them, and only band 5 goes.\n doomed = unused.slice(capacity);\n } else {\n return 0;\n }\n\n if (doomed.length === 0) return 0;\n\n return this.sheetManager.deleteClasses(registry, doomed);\n }\n\n /**\n * Destroy all resources for a root\n */\n destroy(root?: Document | ShadowRoot): void {\n flushStyles();\n const targetRoot = root || document;\n this.sheetManager.cleanup(targetRoot);\n\n // Clear pending GC when no active roots remain\n if (this.cancelPendingGC && !this.sheetManager.hasActiveRoots()) {\n this.cancelPendingGC();\n this.cancelPendingGC = null;\n }\n }\n}\n","/**\n * Tasty Configuration Module\n *\n * Centralizes all tasty configuration, including:\n * - Style injector settings (nonce, cleanup thresholds, etc.)\n * - Global predefined states for advanced state mapping\n * - stylesGenerated flag that locks configuration after first style generation\n *\n * Configuration must be done BEFORE any styles are generated.\n * After the first `inject()` call, configuration is locked and attempts to\n * reconfigure will emit a warning and be ignored.\n */\n\nimport { resetFunctionPolyfills } from './functions';\nimport { applyStyleConfig, normalizeConfig } from './config-normalize';\nimport {\n getEffectiveProperties,\n getGlobalConfigTokens,\n getGlobalCounterStyles,\n getGlobalFontFaces,\n getGlobalFunctions,\n getGlobalStyles,\n mergeGlobalConfigTokens,\n mergeGlobalCounterStyles,\n mergeGlobalFontFaces,\n mergeGlobalFunctions,\n mergeGlobalProperties,\n mergeGlobalStyles,\n resetConfigResources,\n setRuntimeConfigState,\n} from './config-resources';\nimport {\n hasStylesGenerated,\n isFunctionsPolyfillEnabled,\n markStylesGeneratedState,\n resetGlobalPolyfillsState,\n resetStylesGeneratedState,\n} from './config-state';\nimport { resetStyleChunks } from './chunks/style-chunk-map';\nimport type { PropHandlerDefinition } from './prop-handlers';\nimport { registerPropHandler, resetPropHandlers } from './prop-handlers';\nimport { StyleInjector } from './injector/injector';\nimport { clearPipelineCache, renderStyles } from './pipeline';\nimport { resetHandlers } from './styles/predefined';\nimport {\n registerBaseStyleProps,\n resetBaseStyleProps,\n} from './styles/base-props';\nimport { isDevEnv } from './utils/is-dev-env';\nimport { isSelector } from './utils/is-selector';\nimport { DEFAULT_NAME_PREFIX, validateNamePrefix } from './utils/name-prefix';\nimport { resetStyleWarnings } from './utils/warnings';\nimport {\n resetGlobalParseFunctions,\n resetGlobalPredefinedTokens,\n} from './utils/styles';\n\nimport type { FunctionsConfig } from './functions';\nimport type { ColorSpace } from './utils/color-space';\n\nimport type {\n CounterStyleDescriptors,\n FontFaceInput,\n FunctionDefinition,\n GCConfig,\n KeyframesSteps,\n PropertyDefinition,\n} from './injector/types';\nimport type { UnitHandler } from './parser/types';\nimport type { StyleResult } from './pipeline';\nimport type { TastyPlugin } from './plugins/types';\nimport type { RecipeStyles, ConfigTokens } from './styles/types';\nimport type { Styles } from './styles/types';\nimport type { StyleHandlerDefinition } from './utils/styles';\nimport type { TypographyPreset } from './utils/typography';\n\nexport {\n getEffectiveProperties,\n getGlobalConfigTokens,\n getGlobalCounterStyles,\n getGlobalFontFaces,\n getGlobalFunctions,\n getGlobalStyles,\n};\n\n/**\n * Configuration options for the Tasty style system\n */\nexport interface TastyConfig {\n /** CSP nonce for style elements */\n nonce?: string;\n /** Maximum rules per stylesheet (default: 8192) */\n maxRulesPerSheet?: number;\n /** Force text injection mode, auto-detected in test environments (default: auto) */\n forceTextInjection?: boolean;\n /** Enable development mode features: performance metrics and debug info (default: auto) */\n devMode?: boolean;\n /**\n * Global predefined states for advanced state mapping.\n * These are state aliases that can be used in any component.\n * Example: { '@mobile': '@media(w < 920px)', '@dark': '@root(theme=dark)' }\n */\n states?: Record<string, string>;\n /**\n * Parser LRU cache size (default: 1000).\n * Larger values improve performance for apps with many unique style values.\n */\n parserCacheSize?: number;\n /**\n * Custom units for the style parser (merged with built-in units).\n * Units transform numeric values like `2x` → `calc(2 * var(--gap))`.\n * @example { em: 'em', vw: 'vw', custom: (n) => `${n * 10}px` }\n */\n units?: Record<string, string | UnitHandler>;\n /**\n * Custom functions (merged with existing). A single map holds both flavors,\n * discriminated by value type:\n *\n * - **Bare key + function value** — a parse-time function that processes the\n * parsed argument groups and returns a CSS value. Called as `name(...)`.\n * - **`$$name` key + object value** — a declarative CSS `@function`\n * definition. Called as `$$name(...)` (→ native `--name(...)`).\n *\n * A key whose prefix does not match its value type (object under a bare key,\n * or function under a `$$` key) is ignored with a dev warning.\n *\n * @example\n * ```ts\n * configure({\n * functions: {\n * double: (groups) => `calc(2 * ${groups[0].output})`, // parse function\n * $$negative: { args: ['$value'], result: '(-1 * $value)' }, // CSS function\n * },\n * });\n * ```\n */\n functions?: FunctionsConfig;\n /**\n * @deprecated No longer has any effect; will be removed in the next major.\n * Setting it warns in development.\n *\n * A `#name` token's value used to be rewritten into this color space so an\n * opacity suffix had numeric channels to write an alpha into. Opacity now uses\n * relative color syntax — `oklch(from var(--name-color) l c h / .5)` — which\n * has the browser read the channels, so a color is emitted exactly as\n * authored and there is nothing left for the setting to decide.\n *\n * To address a token's channels yourself, write relative color syntax against\n * the token: `oklch(from var(--brand-color) calc(l * 1.2) c h)`. It works on\n * every `<color>`, including the ones no conversion could evaluate.\n */\n colorSpace?: ColorSpace;\n /**\n * Automatically infer and register CSS @property declarations\n * from custom property values found in styles, keyframes, and global config.\n * Covers all types: \\<color\\>, \\<number\\>, \\<length\\>, \\<angle\\>, \\<percentage\\>, \\<time\\>.\n * When false, only explicitly declared @property are registered.\n * @default true\n */\n autoPropertyTypes?: boolean;\n /**\n * Defer stylesheet writes and apply them in one batch instead of performing\n * one `insertRule()` per component during render.\n *\n * Each `insertRule()` on a live sheet invalidates style for that sheet's\n * scope. When components inject during React's render phase while other\n * components read layout in the same pass, the two interleave and the browser\n * is forced to recalculate style between every injection. Batching collapses\n * that into one invalidation per flush.\n *\n * - `false` (default) — inject synchronously, one write per component.\n * - `true` — batch, but only inside a *batch window*: a commit in which\n * `<TastyBatchProvider>` rendered and will therefore flush in its\n * `useInsertionEffect`, before any `useLayoutEffect` runs. Any injection\n * outside a window — a deep update the provider did not re-render for, an\n * injection from a layout effect, an event handler, an async callback — is\n * written straight through. Enabling this can never make a layout effect\n * measure an unstyled element. Requires `<TastyBatchProvider>`; without it\n * nothing is batched (and dev mode says so once).\n * - `'always'` — batch every injection, flushing on a microtask when no\n * window is open. Wins on more commits, but a `useLayoutEffect` that\n * measures a freshly mounted element can read its unstyled box, because\n * microtasks run after the layout phase. Paint is unaffected: microtasks\n * always drain before the browser paints.\n *\n * No effect during SSR or RSC: styles are collected as text there, the\n * runtime injector never runs, and the provider is inert without a\n * `document`. No effect on zero-runtime `tastyStatic` styles either — those\n * are extracted at build time and never reach the injector.\n *\n * @default false\n * @example\n * ```tsx\n * configure({ batchInjection: true });\n *\n * <TastyBatchProvider>\n * <App />\n * </TastyBatchProvider>\n * ```\n */\n batchInjection?: boolean | 'always';\n /**\n * Garbage collection configuration for unused styles.\n * GC is triggered by touch count: every `touchInterval` touches, the\n * oldest unused styles are evicted when their count exceeds `capacity`.\n * @example\n * ```ts\n * configure({\n * gc: { touchInterval: 1000, capacity: 1000 },\n * });\n * ```\n */\n gc?: GCConfig;\n /**\n * Prefix prepended to every generated identifier (class names,\n * keyframe names, counter-style names). The hash is appended verbatim,\n * so include any separator inside the prefix itself (e.g. `'myapp-'`).\n *\n * Discriminator letters are inserted between the prefix and the hash\n * for non-class names so the three kinds stay visually distinct:\n * - class: `${namePrefix}${hash}` — e.g. `t1a2b3`\n * - keyframe: `${namePrefix}k${hash}` — e.g. `tk1a2b3`\n * - counter-style: `${namePrefix}c${hash}` — e.g. `tc1a2b3`\n *\n * The runtime, SSR, and RSC paths must agree on this value or\n * hydration will mismatch. The zero-runtime build path defaults to\n * `'ts'` (overridable via the same option) so its classes can't\n * collide with runtime classes when both are loaded on the same page.\n *\n * Must match `^[a-zA-Z_][a-zA-Z0-9_-]{0,31}$`. Locked once styles\n * have been generated.\n *\n * @default 't'\n */\n namePrefix?: string;\n /**\n * Plugins that extend tasty with custom functions, units, or states.\n * Plugins are processed in order, with later plugins overriding earlier ones.\n * @example\n * ```ts\n * import { okhslPlugin } from '@tenphi/tasty';\n *\n * configure({\n * plugins: [okhslPlugin()],\n * });\n * ```\n */\n plugins?: TastyPlugin[];\n /**\n * Global keyframes definitions that can be referenced by animation names in styles.\n * Keys are animation names, values are keyframes step definitions.\n * Keyframes are only injected when actually used in styles.\n * @example\n * ```ts\n * configure({\n * keyframes: {\n * fadeIn: { from: { opacity: 0 }, to: { opacity: 1 } },\n * pulse: { '0%, 100%': { transform: 'scale(1)' }, '50%': { transform: 'scale(1.05)' } },\n * },\n * });\n * ```\n */\n keyframes?: Record<string, KeyframesSteps>;\n /**\n * Global CSS @property definitions for custom properties.\n * Keys use tasty token syntax ($name for properties, #name for colors).\n *\n * Tasty ships with `DEFAULT_PROPERTIES` (e.g. `$gap`, `$radius`, `#white`,\n * `#black`, `#clear`, `#border`, etc.) that are always included.\n * Properties you specify here are merged on top, so you can override any\n * default by using the same key.\n *\n * For color tokens (#name), `syntax: '<color>'` is auto-set and\n * `initialValue` defaults to `'transparent'` if not specified.\n *\n * @example\n * ```ts\n * configure({\n * properties: {\n * '$rotation': { syntax: '<angle>', initialValue: '0deg' },\n * '$scale': { syntax: '<number>', inherits: false, initialValue: 1 },\n * '#accent': { initialValue: 'purple' }, // syntax: '<color>' auto-set\n * // Override a default property:\n * '$gap': { syntax: '<length>', inherits: true, initialValue: '8px' },\n * },\n * });\n *\n * // Now use in styles - properties are registered when component renders:\n * const Spinner = tasty({\n * styles: {\n * transform: 'rotate($rotation)',\n * transition: '$$rotation 0.3s', // outputs: --rotation 0.3s\n * },\n * });\n * ```\n */\n properties?: Record<string, PropertyDefinition>;\n /**\n * Global @font-face definitions.\n * Keys are font-family names, values are descriptors or arrays of descriptors\n * (for multiple weights/styles of the same family).\n * Injected eagerly when styles are first generated.\n * @example\n * ```ts\n * configure({\n * fontFaces: {\n * 'Brand Sans': [\n * { src: 'url(\"/fonts/brand-regular.woff2\") format(\"woff2\")', fontWeight: 400, fontDisplay: 'swap' },\n * { src: 'url(\"/fonts/brand-bold.woff2\") format(\"woff2\")', fontWeight: 700, fontDisplay: 'swap' },\n * ],\n * Icons: { src: 'url(\"/fonts/icons.woff2\") format(\"woff2\")', fontDisplay: 'block' },\n * },\n * });\n * ```\n */\n fontFaces?: Record<string, FontFaceInput>;\n /**\n * Global @counter-style definitions.\n * Keys are counter-style names, values are descriptor objects.\n * Injected eagerly when styles are first generated.\n * @example\n * ```ts\n * configure({\n * counterStyles: {\n * thumbs: { system: 'cyclic', symbols: '\"👍\"', suffix: '\" \"' },\n * },\n * });\n * ```\n */\n counterStyles?: Record<string, CounterStyleDescriptors>;\n /**\n * Opt-in polyfills for not-yet-baseline CSS features. Each key toggles a\n * feature polyfill; all default to `false`.\n *\n * - `functions` — polyfill CSS `@function` by inlining every `$$name(...)`\n * call into plain CSS (calc/var/color-mix) at parse time instead of\n * emitting the native `@function` at-rule. Enables `@function` usage in\n * browsers that don't support it yet (Firefox/Safari). Note this is the\n * `functions` *feature toggle*, distinct from the top-level `functions`\n * definitions map.\n *\n * @example\n * ```ts\n * configure({ polyfills: { functions: true } });\n * ```\n */\n polyfills?: { functions?: boolean };\n /**\n * Custom style handlers that transform style properties into CSS declarations.\n * Handlers replace built-in handlers for the same style name.\n * @example\n * ```ts\n * import { styleHandlers } from '@tenphi/tasty';\n *\n * configure({\n * handlers: {\n * // Override fill with custom behavior\n * fill: ({ fill }) => {\n * if (fill?.startsWith('gradient:')) {\n * return { background: fill.slice(9) };\n * }\n * return styleHandlers.fill({ fill });\n * },\n * // Add new custom style\n * elevation: ({ elevation }) => {\n * const level = parseInt(elevation) || 1;\n * return {\n * 'box-shadow': `0 ${level * 2}px ${level * 4}px rgba(0,0,0,0.1)`,\n * 'z-index': String(level * 100),\n * };\n * },\n * },\n * });\n * ```\n */\n handlers?: Record<string, StyleHandlerDefinition>;\n /**\n * Props middleware for every tasty component. A prop handler receives the\n * component's props and returns them, changed or not — the extension point for\n * props that are not style properties.\n *\n * The map key is the handler's name and, by default, the prop that triggers it.\n * Use `['*', fn]` for an unconditional handler, or `[['a', 'b'], fn]` to trigger\n * on any of several props.\n *\n * Handlers must be pure and must not mutate their input: style values are cached\n * by object identity, so mutating one in place yields stale CSS. Memoize the\n * styles you build per input value.\n *\n * Not applicable to zero-runtime mode — `tastyStatic()` takes styles objects, not\n * props, so there is nothing for middleware to run on. Components rendered\n * through `tasty()` are unaffected and keep the runtime injector.\n *\n * @example\n * ```ts\n * configure({\n * propHandlers: {\n * glaze: (props) => {\n * const { glaze, ...rest } = props;\n * if (!glaze) return rest;\n * return { ...rest, styles: mergeStyles(glazeStyles(glaze), rest.styles) };\n * },\n * },\n * });\n *\n * <Element glaze=\"purple\" />\n * ```\n */\n propHandlers?: Record<string, PropHandlerDefinition>;\n /**\n * Style properties exposed as top-level props on **every** tasty component, in\n * addition to the built-in base styles, without each component listing them in\n * `styleProps`.\n *\n * Augment `TastyBaseStylePropNames` to type them. Each name costs one property\n * check per render of every component, so keep the list short; the effect is\n * app-global and cannot be scoped to a subtree.\n *\n * @example\n * ```ts\n * configure({ baseStyleProps: ['radius', 'shadow'] });\n *\n * <Card radius=\"1r\" shadow />\n * ```\n */\n baseStyleProps?: readonly string[];\n /**\n * Design tokens injected as CSS custom properties on `:root`.\n * Values are parsed through the Tasty DSL. Supports state maps\n * for responsive/theme-aware tokens.\n *\n * - `$name` keys become `--name` CSS custom properties\n * - `#name` keys become `--name-color` properties\n *\n * Tokens are injected once when the first style is rendered.\n *\n * @example\n * ```ts\n * configure({\n * tokens: {\n * '$gap': '4px',\n * '#primary': {\n * '': '#purple',\n * '@dark': '#light-purple',\n * },\n * },\n * });\n * ```\n */\n tokens?: ConfigTokens;\n /**\n * Predefined tokens that are replaced during style parsing (parse-time substitution).\n * Use `$name` for custom properties and `#name` for color tokens.\n * Values are substituted inline before CSS generation, unlike `tokens` which\n * inject CSS custom properties on `:root`.\n *\n * For color tokens (#name), boolean `true` is converted to `transparent`.\n *\n * @example\n * ```ts\n * configure({\n * replaceTokens: {\n * $spacing: '2x',\n * '#accent': '#purple',\n * '#overlay': true, // → transparent\n * },\n * });\n *\n * // Now use in styles - tokens are replaced at parse time:\n * const Card = tasty({\n * styles: {\n * padding: '$spacing', // → calc(2 * var(--gap))\n * fill: '#accent', // → var(--purple-color)\n * },\n * });\n * ```\n */\n replaceTokens?: Record<`$${string}`, string | number | boolean> &\n Record<`#${string}`, string | number | boolean>;\n /**\n * Predefined style recipes -- named style bundles that can be applied via `recipe` style property.\n * Recipe values are flat tasty styles (no sub-element keys). They may contain base styles,\n * tokens (`$name`/`#name` definitions), local states, `@keyframes`, and `@property`.\n *\n * Components reference recipes via: `recipe: 'name1 name2'` in their styles.\n * Use `/` to separate base recipes from post recipes: `recipe: 'base1 base2 / post1'`.\n * Use `none` to skip base recipes: `recipe: 'none / post1'`.\n * Resolution order: `base_recipes → component styles → post_recipes`.\n *\n * Recipes cannot reference other recipes.\n *\n * @example\n * ```ts\n * configure({\n * recipes: {\n * card: { padding: '4x', fill: '#surface', radius: '1r', border: true },\n * elevated: { shadow: '2x 2x 4x #shadow' },\n * },\n * });\n *\n * // Usage in styles:\n * const Card = tasty({\n * styles: {\n * recipe: 'card elevated',\n * color: '#text', // Overrides recipe values\n * },\n * });\n * ```\n */\n recipes?: Record<string, RecipeStyles>;\n /**\n * Typography presets — shorthand for `generateTypographyTokens()`.\n * Accepts the same input and internally generates typography tokens\n * that are merged into `tokens`. Explicit `tokens` override preset-generated ones.\n *\n * @example\n * ```ts\n * configure({\n * presets: {\n * h1: { fontSize: '32px', lineHeight: '1.2', fontWeight: '700' },\n * t2: { fontSize: '16px', lineHeight: '1.5', fontWeight: '400' },\n * },\n * tokens: {\n * // Overrides the preset-generated $t2-font-weight\n * '$t2-font-weight': { '': '400', '@dark': '300' },\n * },\n * });\n * ```\n */\n presets?: Record<string, TypographyPreset>;\n /**\n * Global Tasty styles keyed by CSS selector.\n * Each entry applies the full Tasty style syntax (style properties,\n * tokens, state maps, selector-based sub-styling) to the given selector.\n * Injected alongside `:root` tokens when the first style is rendered.\n *\n * @example\n * ```ts\n * configure({\n * globalStyles: {\n * body: { fill: '#surface', color: '#text', preset: 't2', margin: 0 },\n * html: { overflow: 'hidden' },\n * },\n * });\n * ```\n */\n globalStyles?: Record<string, Styles>;\n}\n\n// Warnings tracking to avoid duplicates\nconst emittedWarnings = new Set<string>();\n\nconst devMode = isDevEnv();\n\n/**\n * Emit a warning only once\n */\nfunction warnOnce(key: string, message: string): void {\n if (devMode && !emittedWarnings.has(key)) {\n emittedWarnings.add(key);\n console.warn(message);\n }\n}\n\n// ============================================================================\n// Configuration State\n// ============================================================================\n\n// Current configuration (null until first configure() or auto-configured on first use)\nlet currentConfig: TastyConfig | null = null;\n\n// Global keyframes storage (null = no keyframes configured, empty object checked via hasGlobalKeyframes)\nlet globalKeyframes: Record<string, KeyframesSteps> | null = null;\n\n// Global recipes storage (null = no recipes configured)\nlet globalRecipes: Record<string, RecipeStyles> | null = null;\n\n// Global injector instance key\nconst GLOBAL_INJECTOR_KEY = '__TASTY_GLOBAL_INJECTOR__';\n\ninterface TastyGlobalStorage {\n [GLOBAL_INJECTOR_KEY]?: StyleInjector;\n}\n\ndeclare global {\n interface Window {\n [GLOBAL_INJECTOR_KEY]?: StyleInjector;\n }\n\n var __TASTY_GLOBAL_INJECTOR__: StyleInjector | undefined;\n}\n\n/**\n * Detect if we're running in a test environment\n */\nexport function isTestEnvironment(): boolean {\n // Check Node.js environment\n if (typeof process !== 'undefined' && process.env?.NODE_ENV === 'test') {\n return true;\n }\n\n // Check for test runner globals (safely)\n if (typeof global !== 'undefined') {\n const g = global as unknown as Record<string, unknown>;\n if (g.vi || g.jest || g.expect || g.describe || g.it) {\n return true;\n }\n }\n\n // Check for simulated DOM environments (common in tests)\n if (typeof window !== 'undefined') {\n const ua = window.navigator?.userAgent;\n if (ua?.includes('jsdom') || ua?.includes('HappyDOM')) {\n return true;\n }\n }\n\n // Check for other test runners\n if (typeof globalThis !== 'undefined') {\n const gt = globalThis as unknown as Record<string, unknown>;\n if (gt.vitest || gt.mocha) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Create default configuration with optional test environment detection\n */\nfunction createDefaultConfig(isTest?: boolean): TastyConfig {\n return {\n maxRulesPerSheet: 8192,\n forceTextInjection: isTest ?? false,\n devMode: isDevEnv(),\n namePrefix: DEFAULT_NAME_PREFIX,\n };\n}\n\n// ============================================================================\n// stylesGenerated Flag Management\n// ============================================================================\n\n/**\n * Mark that styles have been generated (called by injector on first inject)\n * This locks the configuration - no further changes allowed.\n * Also injects internal and global properties.\n */\nexport function markStylesGenerated(): void {\n if (!markStylesGeneratedState()) return;\n\n // When SSR styles are already in the document, the SSR collector's\n // collectInternals() already rendered tokens, @property, globalStyles,\n // @font-face, @counter-style, and @function. Skip client-side injection to\n // avoid duplicate CSS rules.\n if (\n typeof document !== 'undefined' &&\n document.querySelector('[data-tasty-ssr]')\n ) {\n warnOnce(\n 'ssr-globals-skip',\n '[Tasty] SSR styles detected — skipping client-side global CSS injection to avoid duplicates.',\n );\n return;\n }\n\n const injector = getGlobalInjector();\n const globalFontFaces = getGlobalFontFaces();\n const globalCounterStyles = getGlobalCounterStyles();\n const globalFunctions = getGlobalFunctions();\n const globalTokens = getGlobalConfigTokens();\n const configuredGlobalStyles = getGlobalStyles();\n\n // Inject all properties (defaults merged with user-configured overrides)\n for (const [token, definition] of Object.entries(getEffectiveProperties())) {\n injector.property(token, definition);\n }\n\n // Inject global @font-face rules (eagerly — fonts should be available before render)\n if (globalFontFaces && Object.keys(globalFontFaces).length > 0) {\n for (const [family, input] of Object.entries(globalFontFaces)) {\n const descriptors = Array.isArray(input) ? input : [input];\n for (const desc of descriptors) {\n injector.fontFace(family, desc);\n }\n }\n }\n\n // Inject global @counter-style rules (eagerly, weakly — never override a\n // component-local definition of the same name)\n if (globalCounterStyles && Object.keys(globalCounterStyles).length > 0) {\n for (const [name, descriptors] of Object.entries(globalCounterStyles)) {\n injector.counterStyle(name, descriptors, { weak: true });\n }\n }\n\n // Inject global @function rules (eagerly, weakly — never override a\n // component-local definition of the same name)\n if (globalFunctions && Object.keys(globalFunctions).length > 0) {\n for (const [name, definition] of Object.entries(globalFunctions)) {\n injector.func(name, definition, { weak: true });\n }\n }\n\n // Inject configured tokens as :root CSS custom properties\n if (globalTokens && Object.keys(globalTokens).length > 0) {\n const tokenRules = renderStyles(globalTokens, ':root') as StyleResult[];\n if (tokenRules.length > 0) {\n injector.injectGlobal(tokenRules);\n }\n }\n\n // Inject configured global styles\n if (configuredGlobalStyles) {\n for (const [selector, styles] of Object.entries(configuredGlobalStyles)) {\n if (Object.keys(styles).length > 0) {\n const rules = renderStyles(styles, selector) as StyleResult[];\n if (rules.length > 0) {\n injector.injectGlobal(rules);\n }\n }\n }\n }\n}\n\n/**\n * Check if styles have been generated (configuration is locked)\n */\nexport { hasStylesGenerated } from './config-state';\n\n/**\n * Reset styles generated flag (for testing only)\n */\nexport function resetStylesGenerated(): void {\n resetStylesGeneratedState();\n emittedWarnings.clear();\n}\n\n// ============================================================================\n// Global Keyframes Management\n// ============================================================================\n\nlet _hasGlobalKeyframes = false;\n\n/**\n * Check if any global keyframes are configured.\n * Uses a pre-computed flag to avoid Object.keys() allocation on every call.\n */\nexport function hasGlobalKeyframes(): boolean {\n return _hasGlobalKeyframes;\n}\n\n/**\n * Get global keyframes configuration.\n * Returns null if no keyframes configured (fast path for zero-overhead).\n */\nexport function getGlobalKeyframes(): Record<string, KeyframesSteps> | null {\n return globalKeyframes;\n}\n\n/**\n * Set global keyframes (called from configure).\n * Internal use only.\n */\nfunction setGlobalKeyframes(keyframes: Record<string, KeyframesSteps>): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'keyframes-after-styles',\n `[Tasty] Cannot update keyframes after styles have been generated.\\n` +\n `The new keyframes will be ignored.`,\n );\n return;\n }\n globalKeyframes = { ...(globalKeyframes ?? {}), ...keyframes };\n _hasGlobalKeyframes = Object.keys(globalKeyframes).length > 0;\n}\n\n// ============================================================================\n// Global Properties Management\n// ============================================================================\n\n/**\n * Set global properties (called from configure).\n * Internal use only.\n */\nfunction setGlobalProperties(\n properties: Record<string, PropertyDefinition>,\n): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'properties-after-styles',\n `[Tasty] Cannot update properties after styles have been generated.\\n` +\n `The new properties will be ignored.`,\n );\n return;\n }\n mergeGlobalProperties(properties);\n}\n\n// ============================================================================\n// Global Font Face Management\n// ============================================================================\n\n/**\n * Set global font faces (called from configure).\n * Internal use only.\n */\nfunction setGlobalFontFace(fontFace: Record<string, FontFaceInput>): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'fontface-after-styles',\n `[Tasty] Cannot update fontFaces after styles have been generated.\\n` +\n `The new font faces will be ignored.`,\n );\n return;\n }\n mergeGlobalFontFaces(fontFace);\n}\n\n// ============================================================================\n// Global Counter Style Management\n// ============================================================================\n\n/**\n * Set global counter styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalCounterStyle(\n counterStyle: Record<string, CounterStyleDescriptors>,\n): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'counterstyle-after-styles',\n `[Tasty] Cannot update counterStyles after styles have been generated.\\n` +\n `The new counter styles will be ignored.`,\n );\n return;\n }\n mergeGlobalCounterStyles(counterStyle);\n}\n\n// ============================================================================\n// Global Function Management\n// ============================================================================\n\n/**\n * Set global functions (called from configure).\n * Internal use only.\n */\nfunction setGlobalFunction(\n functions: Record<string, FunctionDefinition>,\n): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'function-after-styles',\n `[Tasty] Cannot update functions after styles have been generated.\\n` +\n `The new functions will be ignored.`,\n );\n return;\n }\n mergeGlobalFunctions(functions);\n}\n\n// ============================================================================\n// Polyfills Management\n// ============================================================================\n\n/**\n * Whether the CSS `@function` polyfill (inline expansion) is enabled.\n * Reads from globalThis first for cross-module SSR/zero-runtime support.\n */\nexport { isFunctionsPolyfillEnabled } from './config-state';\n\n// ============================================================================\n// Global Recipes Management\n// ============================================================================\n\n/**\n * Check if any global recipes are configured.\n * Fast path: returns false if no recipes were ever set.\n */\nexport function hasGlobalRecipes(): boolean {\n return globalRecipes !== null && Object.keys(globalRecipes).length > 0;\n}\n\n/**\n * Get global recipes configuration.\n * Returns null if no recipes configured (fast path for zero-overhead).\n */\nexport function getGlobalRecipes(): Record<string, RecipeStyles> | null {\n return globalRecipes;\n}\n\n/**\n * Set global recipes (called from configure).\n * Internal use only.\n */\nfunction setGlobalRecipes(recipes: Record<string, RecipeStyles>): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'recipes-after-styles',\n `[Tasty] Cannot update recipes after styles have been generated.\\n` +\n `The new recipes will be ignored.`,\n );\n return;\n }\n\n // Dev-mode validation\n if (devMode) {\n for (const [name, recipeStyles] of Object.entries(recipes)) {\n if (name === 'none') {\n warnOnce(\n 'recipe-reserved-none',\n `[Tasty] Recipe name \"none\" is reserved. ` +\n `It is used as a keyword meaning \"no base recipes\" ` +\n `(e.g. recipe: 'none / post-recipe'). ` +\n `Choose a different name for your recipe.`,\n );\n }\n\n for (const key of Object.keys(recipeStyles)) {\n if (isSelector(key)) {\n warnOnce(\n `recipe-selector-${name}-${key}`,\n `[Tasty] Recipe \"${name}\" contains sub-element key \"${key}\". ` +\n `Recipes must be flat styles without sub-element keys. ` +\n `Remove the sub-element key from the recipe definition.`,\n );\n }\n if (key === 'recipe') {\n warnOnce(\n `recipe-recursive-${name}`,\n `[Tasty] Recipe \"${name}\" contains a \"recipe\" key. ` +\n `Recipes cannot reference other recipes. ` +\n `Use space-separated names for composition: recipe: 'base elevated'.`,\n );\n }\n }\n }\n }\n\n globalRecipes = { ...(globalRecipes ?? {}), ...recipes };\n}\n\n// ============================================================================\n// Global Token Styles Management\n// ============================================================================\n\n/**\n * Set global token styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalConfigTokens(styles: ConfigTokens): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'tokens-after-styles',\n `[Tasty] Cannot update tokens after styles have been generated.\\n` +\n `The new tokens will be ignored.`,\n );\n return;\n }\n mergeGlobalConfigTokens(styles);\n}\n\n// ============================================================================\n// Global Styles Management\n// ============================================================================\n\n/**\n * Set configured global styles (called from configure).\n * Internal use only.\n */\nfunction setGlobalStyles(styles: Record<string, Styles>): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'globalStyles-after-styles',\n `[Tasty] Cannot update globalStyles after styles have been generated.\\n` +\n `The new global styles will be ignored.`,\n );\n return;\n }\n mergeGlobalStyles(styles);\n}\n\n/**\n * Check if configuration is locked (styles have been generated)\n */\nexport function isConfigLocked(): boolean {\n return hasStylesGenerated();\n}\n\n// ============================================================================\n// Configuration API\n// ============================================================================\n\n/**\n * Configure the Tasty style system.\n *\n * Must be called BEFORE any styles are generated (before first render that uses tasty).\n * After styles are generated, configuration is locked and calls to configure() will\n * emit a warning and be ignored.\n *\n * @example\n * ```ts\n * import { configure } from '@tenphi/tasty';\n *\n * // Configure before app renders\n * configure({\n * nonce: 'abc123',\n * states: {\n * '@mobile': '@media(w < 768px)',\n * '@dark': '@root(theme=dark)',\n * },\n * });\n * ```\n */\nexport function configure(config: Partial<TastyConfig> = {}): void {\n if (hasStylesGenerated()) {\n warnOnce(\n 'configure-after-styles',\n `[Tasty] Cannot call configure() after styles have been generated.\\n` +\n `Configuration must be done before the first render. The configuration will be ignored.`,\n );\n return;\n }\n\n // Validate namePrefix early so misconfiguration fails loudly before any\n // CSS is generated under a bad prefix.\n if (config.namePrefix !== undefined) {\n validateNamePrefix(config.namePrefix);\n }\n\n const normalized = normalizeConfig(config);\n const {\n propHandlers: mergedPropHandlers,\n propHandlerSources,\n baseStyleProps: mergedBaseStyleProps,\n properties: mergedProperties,\n keyframes: mergedKeyframes,\n fontFaces: mergedFontFaces,\n counterStyles: mergedCounterStyles,\n tokens: mergedConfigTokens,\n recipes: mergedRecipes,\n globalStyles: mergedGlobalStyles,\n } = normalized;\n\n const functionDefs = applyStyleConfig(config, normalized, warnOnce);\n\n if (!isFunctionsPolyfillEnabled() && Object.keys(functionDefs).length > 0) {\n setGlobalFunction(functionDefs);\n }\n\n // Handle keyframes\n if (Object.keys(mergedKeyframes).length > 0) {\n setGlobalKeyframes(mergedKeyframes);\n }\n\n // Handle properties\n if (Object.keys(mergedProperties).length > 0) {\n setGlobalProperties(mergedProperties);\n }\n\n // Handle font faces\n if (Object.keys(mergedFontFaces).length > 0) {\n setGlobalFontFace(mergedFontFaces);\n }\n\n // Handle counter styles\n if (Object.keys(mergedCounterStyles).length > 0) {\n setGlobalCounterStyle(mergedCounterStyles);\n }\n\n // Handle props middleware\n if (Object.keys(mergedPropHandlers).length > 0) {\n for (const [name, definition] of Object.entries(mergedPropHandlers)) {\n registerPropHandler(name, definition, {\n source: propHandlerSources.get(name),\n });\n }\n }\n\n // Handle promoted base style props\n if (mergedBaseStyleProps.length > 0) {\n registerBaseStyleProps(mergedBaseStyleProps);\n }\n\n // Handle tokens (CSS custom properties on :root)\n if (Object.keys(mergedConfigTokens).length > 0) {\n setGlobalConfigTokens(mergedConfigTokens);\n }\n\n // Handle recipes\n if (Object.keys(mergedRecipes).length > 0) {\n setGlobalRecipes(mergedRecipes);\n }\n\n // Handle global styles\n if (Object.keys(mergedGlobalStyles).length > 0) {\n setGlobalStyles(mergedGlobalStyles);\n }\n\n const {\n states: _states,\n parserCacheSize: _parserCacheSize,\n units: _units,\n functions: _functions,\n polyfills: _polyfills,\n plugins: _plugins,\n keyframes: _keyframes,\n properties: _properties,\n fontFaces: _fontFaces,\n counterStyles: _counterStyles,\n handlers: _handlers,\n propHandlers: _propHandlers,\n baseStyleProps: _baseStyleProps,\n tokens: _tokens,\n replaceTokens: _replaceTokens,\n recipes: _recipes,\n colorSpace: _colorSpace,\n presets: _presets,\n globalStyles: _globalStyles,\n ...injectorConfig\n } = config;\n\n const fullConfig: TastyConfig = {\n ...createDefaultConfig(),\n ...currentConfig,\n ...injectorConfig,\n };\n\n // Store the config\n currentConfig = fullConfig;\n setRuntimeConfigState(fullConfig);\n\n // Create/replace the global injector\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n storage[GLOBAL_INJECTOR_KEY] = new StyleInjector(fullConfig);\n}\n\n/**\n * Get the current configuration.\n * If not configured, returns default configuration.\n */\nexport function getConfig(): TastyConfig {\n if (currentConfig) return currentConfig;\n\n const defaultConfig = createDefaultConfig(isTestEnvironment());\n currentConfig = defaultConfig;\n setRuntimeConfigState(defaultConfig);\n return defaultConfig;\n}\n\n/**\n * Get the configured prefix used for every generated identifier\n * (class names, keyframe names, counter-style names).\n *\n * Falls back to the default prefix (`'t'`) when `configure()` has not\n * been called yet — this matches the auto-configuration behavior used\n * by the rest of the system.\n */\nexport function getNamePrefix(): string {\n return currentConfig?.namePrefix ?? DEFAULT_NAME_PREFIX;\n}\n\n/**\n * Get the global injector instance.\n * Auto-configures with defaults if not already configured.\n */\nexport function getGlobalInjector(): StyleInjector {\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n\n if (!storage[GLOBAL_INJECTOR_KEY]) {\n configure();\n }\n\n return storage[GLOBAL_INJECTOR_KEY]!;\n}\n\n/**\n * Reset configuration (for testing only).\n * Clears the global injector and allows reconfiguration.\n */\nexport function resetConfig(): void {\n resetStylesGeneratedState();\n currentConfig = null;\n globalKeyframes = null;\n _hasGlobalKeyframes = false;\n resetGlobalPolyfillsState();\n globalRecipes = null;\n resetConfigResources();\n resetGlobalPredefinedTokens();\n resetGlobalParseFunctions();\n resetFunctionPolyfills();\n resetHandlers();\n resetStyleChunks();\n resetPropHandlers();\n resetBaseStyleProps();\n clearPipelineCache();\n emittedWarnings.clear();\n resetStyleWarnings();\n\n const storage: TastyGlobalStorage =\n typeof window !== 'undefined' ? window : globalThis;\n delete storage[GLOBAL_INJECTOR_KEY];\n}\n","import { hashString } from '../utils/hash';\n\ninterface ChunkSheet {\n sheet: CSSStyleSheet;\n cssText: string;\n refCount: number;\n}\n\n/**\n * Global registry mapping CSS content hashes to shared constructable\n * CSSStyleSheet objects with reference counting.\n *\n * Multiple shadow roots adopting the same chunk share a single underlying\n * stylesheet object — parse once, adopt everywhere.\n */\nexport class ChunkSheetRegistry {\n private sheets = new Map<string, ChunkSheet>();\n private sheetToHash = new WeakMap<CSSStyleSheet, string>();\n\n /**\n * Get or create a CSSStyleSheet for the given CSS text.\n * Increments refCount. Uses content hash as the dedup key.\n */\n acquire(cssText: string): CSSStyleSheet {\n const hash = hashString(cssText);\n const existing = this.sheets.get(hash);\n\n if (existing) {\n existing.refCount++;\n return existing.sheet;\n }\n\n const sheet = new CSSStyleSheet();\n sheet.replaceSync(cssText);\n\n const entry: ChunkSheet = { sheet, cssText, refCount: 1 };\n this.sheets.set(hash, entry);\n this.sheetToHash.set(sheet, hash);\n\n return sheet;\n }\n\n /**\n * Decrement refCount for a sheet. When refCount reaches 0,\n * the sheet is removed from the registry.\n */\n release(sheet: CSSStyleSheet): void {\n const hash = this.sheetToHash.get(sheet);\n if (!hash) return;\n\n const entry = this.sheets.get(hash);\n if (!entry) return;\n\n entry.refCount--;\n\n if (entry.refCount <= 0) {\n this.sheets.delete(hash);\n this.sheetToHash.delete(sheet);\n }\n }\n\n /**\n * Bulk acquire — returns an array of CSSStyleSheet in the same order.\n */\n acquireAll(cssTexts: string[]): CSSStyleSheet[] {\n return cssTexts.map((text) => this.acquire(text));\n }\n\n /**\n * Bulk release — decrements refCount for each sheet.\n */\n releaseAll(sheets: CSSStyleSheet[]): void {\n for (const sheet of sheets) {\n this.release(sheet);\n }\n }\n\n /** Number of unique sheets currently held. */\n get size(): number {\n return this.sheets.size;\n }\n}\n\n/** Module-level singleton shared across the entire application. */\nexport const chunkSheetRegistry = new ChunkSheetRegistry();\n","import {\n getConfig,\n getGlobalInjector,\n getNamePrefix,\n isTestEnvironment,\n markStylesGenerated,\n} from '../config';\nimport type { StyleResult } from '../pipeline';\nimport { tastyClassRegex } from '../utils/name-prefix';\n\nimport { StyleInjector } from './injector';\nimport type {\n CounterStyleDescriptors,\n FontFaceDescriptors,\n FunctionDefinition,\n GCOptions,\n GlobalInjectResult,\n InjectOptions,\n InjectResult,\n KeyframesResult,\n KeyframesSteps,\n PropertyOptions,\n StyleInjectorConfig,\n} from './types';\n\n/**\n * Inject styles and return className with dispose function\n */\nexport function inject(\n rules: StyleResult[],\n options?: InjectOptions,\n): InjectResult {\n const injector = getGlobalInjector();\n\n markStylesGenerated();\n\n return injector.inject(rules, options);\n}\n\n/**\n * Inject global rules that should not reserve tasty class names\n */\nexport function injectGlobal(\n rules: StyleResult[],\n options?: { root?: Document | ShadowRoot },\n): GlobalInjectResult {\n return getGlobalInjector().injectGlobal(rules, options);\n}\n\n/**\n * Inject raw CSS text directly without parsing\n * This is a low-overhead method for injecting raw CSS that doesn't need tasty processing.\n * The CSS is inserted into a separate style element to avoid conflicts with tasty's chunking.\n *\n * @example\n * ```tsx\n * // Inject raw CSS\n * const { dispose } = injectRawCSS(`\n * body { margin: 0; padding: 0; }\n * .my-class { color: red; }\n * `);\n *\n * // Later, remove the injected CSS\n * dispose();\n * ```\n */\nexport function injectRawCSS(\n css: string,\n options?: { root?: Document | ShadowRoot },\n): { dispose: () => void } {\n return getGlobalInjector().injectRawCSS(css, options);\n}\n\n/**\n * Get raw CSS text for SSR\n */\nexport function getRawCSSText(options?: {\n root?: Document | ShadowRoot;\n}): string {\n return getGlobalInjector().getRawCSSText(options);\n}\n\n/**\n * Inject keyframes and return object with toString() and dispose()\n */\nexport function keyframes(\n steps: KeyframesSteps,\n nameOrOptions?: string | { root?: Document | ShadowRoot; name?: string },\n): KeyframesResult {\n return getGlobalInjector().keyframes(steps, nameOrOptions);\n}\n\n/**\n * Define a CSS @property custom property.\n * This enables advanced features like animating custom properties.\n *\n * Note: @property rules are global and persistent once defined.\n * Re-registering the same property name is a no-op.\n *\n * @param name - The custom property name (must start with --)\n * @param options - Property configuration\n *\n * @example\n * ```ts\n * // Define a color property that can be animated\n * property('--my-color', {\n * syntax: '<color>',\n * initialValue: 'red',\n * });\n *\n * // Define an angle property\n * property('--rotation', {\n * syntax: '<angle>',\n * inherits: false,\n * initialValue: '0deg',\n * });\n * ```\n */\nexport function property(name: string, options?: PropertyOptions): void {\n return getGlobalInjector().property(name, options);\n}\n\n/**\n * Check if a CSS @property has already been defined\n *\n * @param name - The custom property name to check\n * @param options - Options including root\n */\nexport function isPropertyDefined(\n name: string,\n options?: { root?: Document | ShadowRoot },\n): boolean {\n return getGlobalInjector().isPropertyDefined(name, options);\n}\n\n/**\n * Inject a CSS @font-face rule.\n *\n * Permanent and global — no dispose or ref-counting.\n * Deduplicates by content hash (family + descriptors).\n */\nexport function fontFace(\n family: string,\n descriptors: FontFaceDescriptors,\n options?: { root?: Document | ShadowRoot },\n): void {\n return getGlobalInjector().fontFace(family, descriptors, options);\n}\n\n/**\n * Inject a CSS @counter-style rule.\n *\n * Permanent and global — no dispose or ref-counting. Deduplicates by name and\n * overrides an existing rule by default. Pass `weak: true` for global\n * `configure()` definitions, which never clobber an existing rule.\n */\nexport function counterStyle(\n name: string,\n descriptors: CounterStyleDescriptors,\n options?: { root?: Document | ShadowRoot; weak?: boolean },\n): void {\n return getGlobalInjector().counterStyle(name, descriptors, options);\n}\n\n/**\n * Inject a CSS @function rule (custom function).\n *\n * Permanent and global — no dispose or ref-counting. Deduplicates by function\n * name and overrides an existing rule by default. Pass `weak: true` for global\n * `configure()` definitions, which never clobber an existing rule.\n *\n * @param name - The function name (`$$name`, `$name`, or `--name`)\n * @param definition - Function definition (args, returns, result, local vars)\n *\n * @example\n * ```ts\n * func('$$negative', { args: ['$value'], result: '(-1 * $value)' });\n * ```\n */\nexport function func(\n name: string,\n definition: FunctionDefinition,\n options?: { root?: Document | ShadowRoot; weak?: boolean },\n): void {\n return getGlobalInjector().func(name, definition, options);\n}\n\n/**\n * Get CSS text from all sheets (for SSR)\n */\nexport function getCSSText(options?: { root?: Document | ShadowRoot }): string {\n return getGlobalInjector().getCSSText(options);\n}\n\n/**\n * Collect only CSS used by a rendered subtree (like jest-styled-components).\n * Pass the container returned by render(...).\n */\nexport function getCSSTextForNode(\n node: ParentNode | Element | DocumentFragment,\n options?: { root?: Document | ShadowRoot },\n): string {\n // Collect tasty-generated class names from the subtree using the\n // configured namePrefix (default `'t'`).\n const classRegex = tastyClassRegex(getNamePrefix());\n const classSet = new Set<string>();\n\n const readClasses = (el: Element) => {\n const cls = el.getAttribute('class');\n if (!cls) return;\n for (const token of cls.split(/\\s+/)) {\n if (classRegex.test(token)) classSet.add(token);\n }\n };\n\n // Include node itself if it's an Element\n if ((node as Element).getAttribute) {\n readClasses(node as Element);\n }\n // Walk descendants\n const elements = (node as ParentNode).querySelectorAll\n ? (node as ParentNode).querySelectorAll('[class]')\n : ([] as unknown as NodeListOf<Element>);\n if (elements) elements.forEach(readClasses);\n\n return getGlobalInjector().getCSSTextForClasses(classSet, options);\n}\n\n/**\n * Take a reference on local `@keyframes` under the deterministic names the\n * caller resolved, and report which entry holds each. Pair with\n * `ownKeyframes()` once the rules exist to inspect.\n */\nexport function holdKeyframes(\n steps: Record<string, KeyframesSteps>,\n names: Map<string, string>,\n options?: { root?: Document | ShadowRoot },\n): Map<string, string> {\n return getGlobalInjector().holdKeyframes(steps, names, options);\n}\n\n/**\n * Record that a class animates these keyframes, so the reference is released\n * when the last such class is collected.\n */\nexport function ownKeyframes(\n key: string,\n className: string,\n options?: { root?: Document | ShadowRoot },\n): void {\n getGlobalInjector().ownKeyframes(key, className, options);\n}\n\n/**\n * Remove every injected rule that is neither in the DOM nor held by an\n * outstanding `inject()` handle. Equivalent to `gc({ force: true })`.\n */\nexport function cleanup(root?: Document | ShadowRoot): void {\n return getGlobalInjector().cleanup(root);\n}\n\n/**\n * Count a render, so that a collection pass is scheduled every\n * `gc.touchInterval` of them. Used internally by computeStyles and tasty().\n *\n * @deprecated The class name is ignored — collection asks the DOM what is\n * rendered rather than recording usage per class. The argument is kept so\n * existing calls still compile.\n */\nexport function touch(\n className: string,\n options?: { root?: Document | ShadowRoot },\n): void {\n if (!getConfig().gc) return;\n getGlobalInjector().touch(className, options);\n}\n\n/**\n * Synchronous garbage collection of unused styles — those no element carries\n * and no `inject()` handle references. Evicts the oldest ones once they exceed\n * capacity. With `{ force: true }`, removes all of them regardless of capacity.\n *\n * @returns Number of styles evicted.\n */\nexport function gc(options?: GCOptions): number {\n return getGlobalInjector().gc(options);\n}\n\n/**\n * Get the global injector instance for debugging\n */\nexport const injector = {\n get instance() {\n return getGlobalInjector();\n },\n};\n\n/**\n * Destroy all resources and clean up\n */\nexport function destroy(root?: Document | ShadowRoot): void {\n return getGlobalInjector().destroy(root);\n}\n\n/**\n * Create a new isolated injector instance\n */\nexport function createInjector(\n config: Partial<StyleInjectorConfig> = {},\n): StyleInjector {\n const defaultConfig = getConfig();\n\n const fullConfig: StyleInjectorConfig = {\n ...defaultConfig,\n // Auto-enable forceTextInjection in test environments\n forceTextInjection: config.forceTextInjection ?? isTestEnvironment(),\n ...config,\n };\n\n return new StyleInjector(fullConfig);\n}\n\n// Re-export types\nexport type {\n StyleInjectorConfig,\n InjectionMode,\n InjectOptions,\n InjectResult,\n DisposeFunction,\n RuleInfo,\n SheetInfo,\n RootRegistry,\n StyleRule,\n StyleUsage,\n KeyframesInfo,\n KeyframesResult,\n KeyframesSteps,\n KeyframesCacheEntry,\n CacheMetrics,\n RawCSSResult,\n PropertyDefinition,\n PropertyOptions,\n FontFaceDescriptors,\n FontFaceInput,\n CounterStyleDescriptors,\n FunctionDefinition,\n FunctionParameter,\n GCConfig,\n GCOptions,\n} from './types';\n\nexport { flushStyles, hasPendingStyleWrites, resetStyleBatch } from './batch';\nexport type { QueuedWrite } from './batch';\nexport { StyleInjector } from './injector';\nexport { SheetManager } from './sheet-manager';\nexport { ChunkSheetRegistry, chunkSheetRegistry } from './chunk-sheet-registry';\n","/**\n * Shared RSC (React Server Components) inline style cache.\n *\n * Uses React.cache for per-request memoization in Server Components.\n * Both computeStyles() and standalone style functions (useGlobalStyles,\n * useRawCSS, useKeyframes, useProperty, useFontFace, useCounterStyle)\n * share this cache so that CSS accumulated by standalone functions is\n * flushed into inline <style> tags by the next tasty() component.\n */\n\nimport { cache } from 'react';\n\nimport { getNamePrefix } from './config';\nimport type { ServerStyleCollector } from './ssr/collector';\nimport { getRegisteredSSRCollector } from './ssr/ssr-collector-ref';\nimport { hashString } from './utils/hash';\nimport { makeClassName } from './utils/name-prefix';\n\nexport interface RSCStyleCache {\n cacheKeyToClassName: Map<string, string>;\n emittedKeys: Set<string>;\n internalsEmitted: boolean;\n pendingCSS: string[];\n /** Maps dedup key -> its slot in `pendingCSS`, so slot-keyed CSS can be replaced. */\n keyToIndex: Map<string, number>;\n /** Maps dedup key -> generated name for keyframes and counter-styles in RSC mode. */\n generatedNames: Map<string, string>;\n}\n\n/**\n * Per-request RSC style cache using React.cache.\n * React.cache provides per-request memoization in Server Components,\n * so each request gets its own isolated cache.\n */\nexport const getRSCCache = cache((): RSCStyleCache => ({\n cacheKeyToClassName: new Map(),\n emittedKeys: new Set(),\n internalsEmitted: false,\n pendingCSS: [],\n keyToIndex: new Map(),\n generatedNames: new Map(),\n}));\n\nexport function rscAllocateClassName(\n rscCache: RSCStyleCache,\n cacheKey: string,\n): { className: string; isNew: boolean } {\n const existing = rscCache.cacheKeyToClassName.get(cacheKey);\n if (existing) return { className: existing, isNew: false };\n\n // Content-hash ensures stable names across all environments (RSC, SSR, client),\n // enabling cross-environment dedup and preventing class collisions.\n const className = makeClassName(getNamePrefix(), hashString(cacheKey));\n rscCache.cacheKeyToClassName.set(cacheKey, className);\n return { className, isNew: true };\n}\n\n/**\n * Flush any pending CSS accumulated by standalone functions.\n * Returns the CSS string and clears the buffer.\n */\nexport function flushPendingCSS(rscCache: RSCStyleCache): string {\n if (rscCache.pendingCSS.length === 0) return '';\n const css = rscCache.pendingCSS.join('\\n');\n rscCache.pendingCSS.length = 0;\n // The slots are gone with the buffer; a later replace has to append instead.\n rscCache.keyToIndex.clear();\n return css;\n}\n\n/**\n * Push CSS into the RSC pending buffer with dedup via emittedKeys.\n * Returns true if the CSS was added, false if it was already emitted.\n *\n * Pass `replace` for slot-keyed entries (an explicit `id`), where the last write\n * must win to match the client's update-tracking behavior. If the slot has\n * already been flushed into a `<style>` tag the new CSS is appended instead,\n * which still wins by cascade order.\n */\nexport function pushRSCCSS(\n rscCache: RSCStyleCache,\n key: string,\n css: string,\n replace?: boolean,\n): boolean {\n if (replace) {\n const pendingIndex = rscCache.keyToIndex.get(key);\n\n if (pendingIndex !== undefined) {\n rscCache.pendingCSS[pendingIndex] = css;\n return true;\n }\n } else if (rscCache.emittedKeys.has(key)) {\n return false;\n }\n\n rscCache.emittedKeys.add(key);\n rscCache.keyToIndex.set(key, rscCache.pendingCSS.length);\n rscCache.pendingCSS.push(css);\n return true;\n}\n\ntype StyleTarget =\n | { mode: 'ssr'; collector: ServerStyleCollector }\n | { mode: 'rsc'; cache: RSCStyleCache }\n | { mode: 'client' };\n\n/**\n * Determine the current style injection target.\n * Centralizes the three-way detection (SSR collector / RSC cache / client DOM)\n * used by all style functions.\n */\nexport function getStyleTarget(): StyleTarget {\n const collector = getRegisteredSSRCollector();\n if (collector) return { mode: 'ssr', collector };\n if (typeof document === 'undefined')\n return { mode: 'rsc', cache: getRSCCache() };\n return { mode: 'client' };\n}\n","/**\n * SSR / RSC auto-property inference.\n *\n * Scans rendered CSS declarations for custom properties whose types\n * can be inferred from their values (e.g. `--angle: 30deg` → `<angle>`).\n * Mirrors the client-side auto-inference in StyleInjector.inject().\n */\n\nimport type { StyleResult } from '../pipeline';\nimport { parsePropertyToken } from '../properties';\nimport { PropertyTypeResolver } from '../properties/property-type-resolver';\nimport type { RSCStyleCache } from '../rsc-cache';\nimport { pushRSCCSS } from '../rsc-cache';\nimport type { Styles } from '../styles/types';\n\nimport type { ServerStyleCollector } from './collector';\nimport { formatPropertyCSS } from './format-property';\n\n/**\n * Scan rendered rules for auto-inferable custom properties and emit\n * @property CSS via the provided callback.\n */\nfunction scanAndEmitAutoProperties(\n rules: StyleResult[],\n styles: Styles | undefined,\n emit: (name: string, css: string) => void,\n): void {\n const registered = new Set<string>();\n\n if (styles) {\n const localProps = styles['@property'];\n if (localProps && typeof localProps === 'object') {\n for (const token of Object.keys(localProps as Record<string, unknown>)) {\n const parsed = parsePropertyToken(token);\n if (parsed.isValid) {\n registered.add(parsed.cssName);\n }\n }\n }\n }\n\n const resolver = new PropertyTypeResolver();\n\n for (const rule of rules) {\n if (!rule.declarations) continue;\n resolver.scanDeclarations(\n rule.declarations,\n (name) => registered.has(name),\n (name, syntax, initialValue) => {\n registered.add(name);\n const css = formatPropertyCSS(name, {\n syntax,\n inherits: true,\n initialValue,\n });\n if (css) {\n emit(name, css);\n }\n },\n );\n }\n}\n\n/**\n * Scan rendered rules for custom property declarations and collect\n * auto-inferred @property rules via the SSR collector.\n *\n * @param rules - Rendered style rules containing CSS declarations\n * @param collector - SSR collector to emit @property CSS into\n * @param styles - Original styles object (used to skip explicit @property)\n */\nexport function collectAutoInferredProperties(\n rules: StyleResult[],\n collector: ServerStyleCollector,\n styles?: Styles,\n): void {\n scanAndEmitAutoProperties(rules, styles, (name, css) => {\n collector.collectProperty(`__auto:${name}`, css);\n });\n}\n\n/**\n * RSC variant: scan rendered rules and push auto-inferred @property CSS\n * into the RSC pending buffer.\n */\nexport function collectAutoInferredPropertiesRSC(\n rules: StyleResult[],\n rscCache: RSCStyleCache,\n styles?: Styles,\n): void {\n scanAndEmitAutoProperties(rules, styles, (name, css) => {\n pushRSCCSS(rscCache, `__auto:${name}`, css);\n });\n}\n","/**\n * Check if an object has any own enumerable keys.\n * Avoids the array allocation of Object.keys(obj).length > 0.\n */\nexport function hasKeys(obj: object): boolean {\n for (const _ in obj) return true;\n return false;\n}\n","import { getGlobalRecipes } from '../config';\nimport type { Styles } from '../styles/types';\n\nimport { resolveRecipesWith } from './resolve-recipes-core';\n\n/** Resolve recipe references against the globally configured recipe map. */\nexport function resolveRecipes(styles: Styles): Styles {\n return resolveRecipesWith(styles, getGlobalRecipes());\n}\n","/**\n * Hook-free, synchronous style computation.\n *\n * Extracts the core logic from useStyles() into a plain function that can\n * be called during React render without any hooks. Three code paths:\n *\n * 1. SSR collector — styles collected via ServerStyleCollector\n * 2. Client inject — styles injected synchronously into the DOM\n * 3. RSC inline — styles returned as CSS strings for inline <style> emission\n *\n * This enables tasty() components to work as React Server Components.\n */\n\nimport {\n categorizeStyleKeys,\n generateChunkCacheKey,\n renderStylesForChunk,\n} from './chunks';\nimport {\n getConfig,\n getGlobalKeyframes,\n hasGlobalKeyframes,\n isFunctionsPolyfillEnabled,\n} from './config';\nimport {\n counterStyle,\n fontFace,\n func,\n inject,\n holdKeyframes,\n ownKeyframes,\n property,\n touch,\n} from './injector';\nimport type { FontFaceDescriptors, KeyframesSteps } from './injector/types';\nimport {\n extractLocalCounterStyle,\n formatCounterStyleRule,\n} from './counter-style';\nimport {\n extractLocalFunctions,\n formatFunctionRule,\n parseFunctionName,\n registerLocalFunctionPolyfills,\n} from './functions';\nimport {\n extractLocalFontFace,\n fontFaceContentHash,\n formatFontFaceRule,\n} from './font-face';\nimport {\n extractAnimationNamesFromStyles,\n extractLocalKeyframes,\n filterUsedKeyframes,\n hasLocalKeyframes,\n mergeKeyframes,\n resolveKeyframesNames,\n replaceAnimationNames,\n} from './keyframes';\nimport type { StyleResult } from './pipeline';\nimport {\n flushPendingCSS,\n getRSCCache,\n rscAllocateClassName,\n} from './rsc-cache';\nimport type { RSCStyleCache } from './rsc-cache';\nimport { extractLocalProperties } from './properties';\nimport { collectAutoInferredProperties } from './ssr/collect-auto-properties';\nimport type { ServerStyleCollector } from './ssr/collector';\nimport { formatKeyframesCSS } from './ssr/format-keyframes';\nimport { formatPropertyCSS } from './ssr/format-property';\nimport { formatRules } from './ssr/format-rules';\nimport { getRegisteredSSRCollector } from './ssr/ssr-collector-ref';\nimport type { Styles } from './styles/types';\nimport { hasKeys } from './utils/has-keys';\nimport { resolveRecipes } from './utils/resolve-recipes';\n\nexport interface ComputeStylesResult {\n className: string;\n /** CSS text to emit as an inline <style> tag (RSC mode only). */\n css?: string;\n}\n\nexport interface ComputeStylesOptions {\n ssrCollector?: ServerStyleCollector | null;\n /** Target root for style injection (client only). Defaults to `document`. */\n root?: Document | ShadowRoot;\n /**\n * Set when `styles` outlives this call and will be passed in again — a\n * `tasty()` factory's own styles object rather than a per-render merge.\n * It lets chunk cache keys be memoized on the object, which is worth the\n * bookkeeping only when there is a next render to spend it on.\n */\n stableStyles?: boolean;\n}\n\ninterface ProcessedChunk {\n className: string;\n /** Rules retained only on the SSR path for automatic property inference. */\n rules?: StyleResult[];\n /** Local animations this chunk runs, by their authored names. */\n animations?: string[];\n}\n\nconst EMPTY_RESULT: ComputeStylesResult = { className: '' };\n\n// ---------------------------------------------------------------------------\n// RSC (React Server Components) inline style support\n// ---------------------------------------------------------------------------\n\n/**\n * Collect per-component ancillary CSS (keyframes, @property, font-face,\n * counter-style) for RSC mode.\n */\nfunction collectAncillaryRSC(\n rscCache: RSCStyleCache,\n styles: Styles,\n usedKf: Record<string, KeyframesSteps> | null,\n keyframeNames: Map<string, string> | null,\n): string {\n const parts: string[] = [];\n\n if (usedKf && keyframeNames) {\n for (const [authored, steps] of Object.entries(usedKf)) {\n const name = keyframeNames.get(authored) as string;\n const key = `__kf:${name}`;\n if (!rscCache.emittedKeys.has(key)) {\n rscCache.emittedKeys.add(key);\n parts.push(formatKeyframesCSS(name, steps));\n }\n }\n }\n\n const localProperties = extractLocalProperties(styles);\n if (localProperties) {\n for (const [token, definition] of Object.entries(localProperties)) {\n const key = `__prop:${token}`;\n if (!rscCache.emittedKeys.has(key)) {\n rscCache.emittedKeys.add(key);\n const css = formatPropertyCSS(token, definition);\n if (css) parts.push(css);\n }\n }\n }\n\n const localFontFace = extractLocalFontFace(styles);\n if (localFontFace) {\n for (const [family, input] of Object.entries(localFontFace)) {\n const descriptors: FontFaceDescriptors[] = Array.isArray(input)\n ? input\n : [input];\n for (const desc of descriptors) {\n const hash = fontFaceContentHash(family, desc);\n const key = `__ff:${hash}`;\n if (!rscCache.emittedKeys.has(key)) {\n rscCache.emittedKeys.add(key);\n parts.push(formatFontFaceRule(family, desc));\n }\n }\n }\n }\n\n const localCounterStyle = extractLocalCounterStyle(styles);\n if (localCounterStyle) {\n for (const [name, descriptors] of Object.entries(localCounterStyle)) {\n const key = `__cs:${name}:${JSON.stringify(descriptors)}`;\n if (!rscCache.emittedKeys.has(key)) {\n rscCache.emittedKeys.add(key);\n parts.push(formatCounterStyleRule(name, descriptors));\n }\n }\n }\n\n if (!isFunctionsPolyfillEnabled()) {\n const localFunctions = extractLocalFunctions(styles);\n if (localFunctions) {\n for (const [name, definition] of Object.entries(localFunctions)) {\n const key = `__func:${parseFunctionName(name)}`;\n if (!rscCache.emittedKeys.has(key)) {\n rscCache.emittedKeys.add(key);\n parts.push(formatFunctionRule(name, definition));\n }\n }\n }\n }\n\n return parts.join('\\n');\n}\n\n/**\n * Process all chunks in RSC mode: render CSS to strings, allocate classNames,\n * and return combined { className, css }.\n */\nfunction computeStylesRSC(\n styles: Styles,\n chunkMap: Map<string, string[]>,\n stableStyles: boolean,\n): ComputeStylesResult {\n const rscCache = getRSCCache();\n const cssParts: string[] = [];\n const classNames: string[] = [];\n const rscUsedKf = getUsedKeyframes(styles);\n const rscKeyframeNames = rscUsedKf ? resolveKeyframesNames(rscUsedKf) : null;\n\n // Flush CSS accumulated by standalone style functions\n const pendingCSS = flushPendingCSS(rscCache);\n if (pendingCSS) cssParts.push(pendingCSS);\n\n // Global internals are emitted by the SSR collector. This marker only keeps\n // the RSC request state aligned with that collector-owned lifecycle.\n rscCache.internalsEmitted = true;\n\n for (const [chunkName, chunkStyleKeys] of chunkMap) {\n if (chunkStyleKeys.length === 0) continue;\n\n const baseKey = generateChunkCacheKey(\n styles,\n chunkName,\n chunkStyleKeys,\n stableStyles,\n );\n\n // Rendered before the class is allocated, for the same reason as the other\n // two paths: the key has to carry which keyframes these rules animate.\n const renderResult = renderStylesForChunk(\n styles,\n chunkName,\n chunkStyleKeys,\n );\n if (renderResult.rules.length === 0) continue;\n\n const { rules, cacheKey } = applyKeyframeNames(\n renderResult.rules,\n baseKey,\n rscKeyframeNames,\n );\n\n const { className, isNew } = rscAllocateClassName(rscCache, cacheKey);\n classNames.push(className);\n\n if (isNew) {\n const css = formatRules(rules, className);\n if (css) cssParts.push(css);\n }\n }\n\n const ancillaryCSS = collectAncillaryRSC(\n rscCache,\n styles,\n rscUsedKf,\n rscKeyframeNames,\n );\n if (ancillaryCSS) cssParts.push(ancillaryCSS);\n\n if (classNames.length === 0) return EMPTY_RESULT;\n\n const css = cssParts.join('\\n');\n\n return {\n className: classNames.join(' '),\n css: css || undefined,\n };\n}\n\n/**\n * Get keyframes that are actually used in styles.\n * Returns null if no keyframes are used (fast path for zero overhead).\n */\nfunction getUsedKeyframes(\n styles: Styles,\n): Record<string, KeyframesSteps> | null {\n const hasLocal = hasLocalKeyframes(styles);\n const hasGlobal = hasGlobalKeyframes();\n if (!hasLocal && !hasGlobal) return null;\n\n const usedNames = extractAnimationNamesFromStyles(styles);\n if (usedNames.size === 0) return null;\n\n const local = hasLocal ? extractLocalKeyframes(styles) : null;\n const global = hasGlobal ? getGlobalKeyframes() : null;\n const allKeyframes = mergeKeyframes(local, global);\n\n return filterUsedKeyframes(allKeyframes, usedNames);\n}\n\n/**\n * Process a chunk on the SSR path: allocate via collector, render, collect CSS.\n */\nfunction processChunkSSR(\n collector: ServerStyleCollector,\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n stableStyles: boolean,\n keyframeNames?: Map<string, string> | null,\n): ProcessedChunk | null {\n if (styleKeys.length === 0) return null;\n\n const baseKey = generateChunkCacheKey(\n styles,\n chunkName,\n styleKeys,\n stableStyles,\n );\n\n // Rendered before the class is allocated: the key has to carry which\n // keyframes these rules animate, or two components authoring the same\n // shorthand over different definitions would share a class here and\n // disagree with the client, which does carry it.\n const renderResult = renderStylesForChunk(styles, chunkName, styleKeys);\n if (renderResult.rules.length === 0) return null;\n\n const { rules, cacheKey } = applyKeyframeNames(\n renderResult.rules,\n baseKey,\n keyframeNames,\n );\n\n const { className, isNewAllocation } = collector.allocateClassName(cacheKey);\n\n if (isNewAllocation) {\n collector.collectChunk(cacheKey, className, rules);\n return { className, rules };\n }\n\n return { className, rules: [] };\n}\n\n/**\n * Point a chunk's rules at the resolved keyframe names, and fold those names\n * into its cache key.\n *\n * Both halves matter, and both have to happen before the rules are written\n * anywhere: the declarations have to name the animation that will exist, and\n * the key has to distinguish two components that authored the same shorthand\n * over different definitions. Shared by the client and the server so they\n * cannot disagree about either.\n */\nfunction applyKeyframeNames(\n ruleset: StyleResult[],\n baseKey: string,\n keyframeNames?: Map<string, string> | null,\n): { animations: string[]; rules: StyleResult[]; cacheKey: string } {\n if (!keyframeNames || keyframeNames.size === 0) {\n return { animations: [], rules: ruleset, cacheKey: baseKey };\n }\n\n const usedNames = new Set<string>();\n let rules: StyleResult[] | undefined;\n\n for (let i = 0; i < ruleset.length; i++) {\n const rule = ruleset[i];\n const declarations = replaceAnimationNames(\n rule.declarations,\n keyframeNames,\n usedNames,\n );\n\n if (declarations !== rule.declarations) {\n rules ??= ruleset.slice();\n rules[i] = { ...rule, declarations };\n }\n }\n\n // Keep definition order for ownership bookkeeping. The cache fragment below\n // is sorted independently so class names stay order-insensitive.\n const animations = [...keyframeNames.keys()].filter((authored) =>\n usedNames.has(authored),\n );\n\n if (animations.length === 0) {\n return { animations, rules: ruleset, cacheKey: baseKey };\n }\n\n const cacheKey = `${baseKey}\\u0000kf:${animations\n .map((authored) => `${authored}=${keyframeNames.get(authored)}`)\n .sort()\n .join(',')}`;\n\n return { animations, rules: rules ?? ruleset, cacheKey };\n}\n\n/**\n * Process a chunk on the client: render, allocate className, and inject\n * CSS synchronously. The injector's cache makes this idempotent.\n */\nfunction processChunkSync(\n styles: Styles,\n chunkName: string,\n styleKeys: string[],\n stableStyles: boolean,\n root?: Document | ShadowRoot,\n keyframeNames?: Map<string, string> | null,\n): ProcessedChunk | null {\n if (styleKeys.length === 0) return null;\n\n const cacheKey = generateChunkCacheKey(\n styles,\n chunkName,\n styleKeys,\n stableStyles,\n );\n const renderResult = renderStylesForChunk(\n styles,\n chunkName,\n styleKeys,\n cacheKey,\n );\n if (renderResult.rules.length === 0) return null;\n\n const {\n animations,\n rules,\n cacheKey: injectKey,\n } = applyKeyframeNames(renderResult.rules, cacheKey, keyframeNames);\n\n // `pin: false` — the render path keeps no dispose handle; the DOM is the\n // record of use, and `gc()` reclaims the class once no element carries it.\n const { className } = inject(rules, {\n cacheKey: injectKey,\n root,\n pin: false,\n });\n\n return {\n className,\n animations,\n };\n}\n\n/**\n * Inject all ancillary rules (properties, font-faces, counter-styles) synchronously.\n */\nfunction injectAncillarySync(\n styles: Styles,\n root?: Document | ShadowRoot,\n): void {\n const localProperties = extractLocalProperties(styles);\n if (localProperties) {\n for (const [token, definition] of Object.entries(localProperties)) {\n property(token, { ...definition, root });\n }\n }\n\n const localFontFace = extractLocalFontFace(styles);\n if (localFontFace) {\n for (const [family, input] of Object.entries(localFontFace)) {\n const descriptors: FontFaceDescriptors[] = Array.isArray(input)\n ? input\n : [input];\n for (const desc of descriptors) {\n fontFace(family, desc, { root });\n }\n }\n }\n\n const localCounterStyle = extractLocalCounterStyle(styles);\n if (localCounterStyle) {\n for (const [name, descriptors] of Object.entries(localCounterStyle)) {\n counterStyle(name, descriptors, { root });\n }\n }\n\n if (!isFunctionsPolyfillEnabled()) {\n const localFunctions = extractLocalFunctions(styles);\n if (localFunctions) {\n for (const [name, definition] of Object.entries(localFunctions)) {\n func(name, definition, { root });\n }\n }\n }\n}\n\n/**\n * Collect all ancillary rules into the SSR collector.\n */\nfunction collectAncillarySSR(\n collector: ServerStyleCollector,\n styles: Styles,\n chunks: ProcessedChunk[],\n usedKf: Record<string, KeyframesSteps> | null,\n keyframeNames: Map<string, string> | null,\n): void {\n if (usedKf && keyframeNames) {\n // Emitted under the resolved name, so two different `fade` definitions are\n // two rules rather than one deduplicated by name — and so the client\n // agrees about which one a class animates.\n for (const [authored, steps] of Object.entries(usedKf)) {\n const name = keyframeNames.get(authored) as string;\n collector.collectKeyframes(name, formatKeyframesCSS(name, steps));\n }\n }\n\n const localProperties = extractLocalProperties(styles);\n if (localProperties) {\n for (const [token, definition] of Object.entries(localProperties)) {\n const css = formatPropertyCSS(token, definition);\n if (css) {\n collector.collectProperty(token, css);\n }\n }\n }\n\n const localFontFace = extractLocalFontFace(styles);\n if (localFontFace) {\n for (const [family, input] of Object.entries(localFontFace)) {\n const descriptors: FontFaceDescriptors[] = Array.isArray(input)\n ? input\n : [input];\n for (const desc of descriptors) {\n const hash = fontFaceContentHash(family, desc);\n const css = formatFontFaceRule(family, desc);\n collector.collectFontFace(hash, css);\n }\n }\n }\n\n const localCounterStyle = extractLocalCounterStyle(styles);\n if (localCounterStyle) {\n for (const [name, descriptors] of Object.entries(localCounterStyle)) {\n const css = formatCounterStyleRule(name, descriptors);\n collector.collectCounterStyle(name, css);\n }\n }\n\n if (!isFunctionsPolyfillEnabled()) {\n const localFunctions = extractLocalFunctions(styles);\n if (localFunctions) {\n for (const [name, definition] of Object.entries(localFunctions)) {\n const css = formatFunctionRule(name, definition);\n collector.collectFunction(parseFunctionName(name), css);\n }\n }\n }\n\n if (getConfig().autoPropertyTypes !== false) {\n const allRules = chunks.flatMap((chunk) => chunk.rules ?? []);\n if (allRules.length > 0) {\n collectAutoInferredProperties(allRules, collector, styles);\n }\n }\n}\n\n/**\n * Synchronous, hook-free style computation.\n *\n * Resolves recipes, categorizes style keys into chunks, renders CSS rules,\n * allocates class names, and injects / collects / returns the CSS.\n *\n * Three code paths:\n * 1. SSR collector — discovered via ALS or passed explicitly; CSS collected\n * 2. RSC inline — no collector and no `document`; CSS returned as `result.css`\n * for the caller to emit as an inline `<style>` tag\n * 3. Client inject — CSS injected synchronously into the DOM (idempotent)\n *\n * @param styles - Tasty styles object (or undefined for no styles)\n * @param options - Optional SSR collector override\n */\nexport function computeStyles(\n styles: Styles | undefined,\n options?: ComputeStylesOptions,\n): ComputeStylesResult {\n if (!styles || !hasKeys(styles as Record<string, unknown>)) {\n return EMPTY_RESULT;\n }\n\n const resolved = resolveRecipes(styles);\n\n // Only the caller's own object can be declared reusable. When recipe\n // resolution rewrites it, `resolved` is a fresh per-render object and\n // memoizing on it would be pure overhead.\n const stableStyles = options?.stableStyles === true && resolved === styles;\n\n // @function polyfill: register local definitions as inline closures BEFORE\n // any chunk is rendered, so call sites in this component expand to plain CSS.\n if (isFunctionsPolyfillEnabled()) {\n registerLocalFunctionPolyfills(resolved);\n }\n\n const chunkMap = categorizeStyleKeys(resolved as Record<string, unknown>);\n\n const collector =\n options?.ssrCollector !== undefined\n ? options.ssrCollector\n : getRegisteredSSRCollector();\n\n const chunks: ProcessedChunk[] = [];\n\n if (collector) {\n collector.collectInternals();\n\n const ssrKf = getUsedKeyframes(resolved);\n const ssrKeyframeNames = ssrKf ? resolveKeyframesNames(ssrKf) : null;\n\n for (const [chunkName, chunkStyleKeys] of chunkMap) {\n const chunk = processChunkSSR(\n collector,\n resolved,\n chunkName,\n chunkStyleKeys,\n stableStyles,\n ssrKeyframeNames,\n );\n if (chunk) chunks.push(chunk);\n }\n\n collectAncillarySSR(collector, resolved, chunks, ssrKf, ssrKeyframeNames);\n } else if (typeof document === 'undefined') {\n // RSC path: render CSS to strings for inline <style> emission\n return computeStylesRSC(resolved, chunkMap, stableStyles);\n } else {\n const root = options?.root;\n\n injectAncillarySync(resolved, root);\n\n const usedKf = getUsedKeyframes(resolved);\n\n // Names first, and resolved the same way on every path: the rules that\n // animate them carry the name, and a rule written before it is known\n // cannot be corrected afterwards.\n const keyframeNames = usedKf ? resolveKeyframesNames(usedKf) : null;\n const keyframeKeys =\n usedKf && keyframeNames\n ? holdKeyframes(usedKf, keyframeNames, { root })\n : null;\n\n for (const [chunkName, chunkStyleKeys] of chunkMap) {\n const chunk = processChunkSync(\n resolved,\n chunkName,\n chunkStyleKeys,\n stableStyles,\n root,\n keyframeNames,\n );\n if (chunk) chunks.push(chunk);\n }\n\n // Only the classes whose rules actually name the animation own it — one\n // that merely rendered alongside would keep it alive for its own lifetime.\n // The reference is taken once however many times this renders, and released\n // when the last owner is collected.\n if (keyframeKeys) {\n for (const chunk of chunks) {\n for (const authored of chunk.animations ?? []) {\n const key = keyframeKeys.get(authored);\n if (key) ownKeyframes(key, chunk.className, { root });\n }\n }\n }\n\n for (const chunk of chunks) {\n touch(chunk.className, { root });\n }\n }\n\n if (chunks.length === 0) return EMPTY_RESULT;\n if (chunks.length === 1) return { className: chunks[0].className };\n\n return { className: chunks.map((c) => c.className).join(' ') };\n}\n","const BasePropNames = new Set([\n 'role',\n 'as',\n 'element',\n 'css',\n 'qa',\n 'mods',\n 'qaVal',\n 'hidden',\n 'isHidden',\n 'disabled',\n 'isDisabled',\n 'children',\n 'style',\n 'className',\n 'href',\n 'target',\n 'tabIndex',\n]);\n\nconst eventRe = /^on[A-Z].+$/;\nconst ignoredEventProps = new Set([\n 'onPress',\n 'onHoverStart',\n 'onHoverEnd',\n 'onPressStart',\n 'onPressEnd',\n]);\n\ninterface PropsFilterOptions {\n // @deprecated\n labelable?: boolean;\n propNames?: Set<string>;\n eventProps?: boolean;\n}\n\n/**\n * Filters out all props that aren't valid DOM props or defined via override prop obj.\n * @param props - The component props to be filtered.\n * @param opts - Props to override.\n */\nexport function filterBaseProps<T extends object>(\n props: T,\n opts: PropsFilterOptions = {},\n): Partial<T> {\n const { propNames, eventProps } = opts;\n const filteredProps: Partial<T> = {};\n\n for (const prop of Object.keys(props) as (keyof T & string)[]) {\n if (\n prop === 'id' ||\n BasePropNames.has(prop) ||\n // Always preserve any ARIA attributes to maintain accessibility support.\n prop.startsWith('aria-') ||\n (eventProps && eventRe.test(prop) && !ignoredEventProps.has(prop)) ||\n propNames?.has(prop) ||\n prop.startsWith('data-')\n ) {\n filteredProps[prop] = props[prop];\n }\n }\n\n return filteredProps;\n}\n","/**\n * Generate data DOM attributes from modifier map.\n */\nimport type { AllBaseProps } from '../types';\n\nimport { Lru } from '../parser/lru';\nimport { camelToKebab } from './case-converter';\n\nconst cache = new Lru<string, Record<string, string>>();\n\nexport function modAttrs(\n map: AllBaseProps['mods'],\n): Record<string, string> | null {\n if (!map) return null;\n\n const cacheKey = JSON.stringify(map);\n const cached = cache.get(cacheKey);\n if (cached) return cached;\n\n const attrs: Record<string, string> = {};\n\n for (const key of Object.keys(map)) {\n const value = map[key];\n\n // Skip null, undefined, false\n if (value == null || value === false) continue;\n\n const attrName = `data-${camelToKebab(key)}`;\n\n if (value === true) {\n // Boolean true: data-{name}=\"\"\n attrs[attrName] = '';\n } else if (typeof value === 'string') {\n // String value: data-{name}=\"value\"\n attrs[attrName] = value;\n } else if (typeof value === 'number') {\n // Number: convert to string\n attrs[attrName] = String(value);\n } else if (process.env.NODE_ENV !== 'production') {\n // Reject other types (objects, arrays, functions)\n console.warn(\n `[Tasty] Invalid mod value for \"${key}\". Expected boolean, string, or number, got ${typeof value}`,\n );\n }\n }\n\n cache.set(cacheKey, attrs);\n return attrs;\n}\n","import type { Tokens, TokenValue } from '../types';\n\nimport type { CSSProperties } from './css-types';\n\nimport { normalizeDslName } from './string';\nimport { normalizeColorTokenValue, parseStyle } from './styles';\n\nexport { hslToRgbValues } from './color-math';\n\nconst devMode = process.env.NODE_ENV !== 'production';\n\n/**\n * Check if a value is a valid token value (string, number, or boolean - not object).\n * Returns false for `false` values (they mean \"skip this token\").\n */\nfunction isValidTokenValue(\n value: unknown,\n): value is Exclude<TokenValue, undefined | null | false> {\n if (value === undefined || value === null || value === false) {\n return false;\n }\n\n if (typeof value === 'object') {\n if (devMode) {\n console.warn(\n '[Tasty] Object values are not allowed in tokens prop. ' +\n 'Tokens do not support state-based styling. Use a primitive value instead.',\n );\n }\n return false;\n }\n\n return (\n typeof value === 'string' ||\n typeof value === 'number' ||\n typeof value === 'boolean'\n );\n}\n\n/**\n * Process a single token value through the tasty parser.\n * Numbers are converted to strings; 0 stays as \"0\".\n */\nfunction processTokenValue(value: string | number): string {\n if (typeof value === 'number') {\n // 0 should remain as \"0\", not converted to any unit\n if (value === 0) {\n return '0';\n }\n return parseStyle(String(value)).output;\n }\n return parseStyle(value).output;\n}\n\n/**\n * Resolve one `$name` / `#name` entry to the custom property it declares and\n * the value to declare, or `null` when the entry declares nothing.\n *\n * The two sigils differ only in the property name they build and in how `true`\n * is read: for a custom property it is the empty value, for a color it is\n * `transparent`.\n */\nfunction resolveTokenEntry(\n key: string,\n value: Exclude<TokenValue, undefined | null | false>,\n): [name: string, value: string] | null {\n const name = `--${normalizeDslName(key.slice(1))}`;\n\n if (key[0] === '$') {\n // Boolean true for custom properties converts to empty string (valid CSS value)\n return [name, processTokenValue(value === true ? '' : value)];\n }\n\n const colorValue = normalizeColorTokenValue(value);\n // Skip if normalized to null (shouldn't happen since false is filtered by isValidTokenValue)\n if (colorValue === null) return null;\n\n return [`${name}-color`, processTokenValue(colorValue)];\n}\n\n/**\n * Process tokens object into inline style properties.\n * - `$name` -> `--name` with the parsed value\n * - `#name` -> `--name-color` with the parsed value\n *\n * @param tokens - The tokens object to process\n * @returns CSSProperties object or undefined if no tokens to process\n */\nexport function processTokens(\n tokens: Tokens | undefined,\n): CSSProperties | undefined {\n if (!tokens) {\n return undefined;\n }\n\n const keys = Object.keys(tokens);\n if (keys.length === 0) {\n return undefined;\n }\n\n let result: Record<string, string> | undefined;\n\n for (const key of keys) {\n const value = tokens[key as keyof Tokens];\n\n // Skip undefined/null values\n if (!isValidTokenValue(value)) {\n continue;\n }\n\n if (key[0] !== '$' && key[0] !== '#') continue;\n\n const entry = resolveTokenEntry(key, value);\n if (!entry) continue;\n\n if (!result) result = {};\n result[entry[0]] = entry[1];\n }\n\n return result as CSSProperties | undefined;\n}\n","import { getGlobalInjector } from '../config';\n\n/**\n * Build a per-(injector, root) client state cache for the standalone style\n * functions (`useGlobalStyles`, `useRawCSS`, `useKeyframes`, `useCounterStyle`).\n *\n * Two levels, both weak:\n *\n * - **injector** — `configure()` replaces the global injector, and every dispose\n * handle and generated name we cache belongs to the one that produced it.\n * Keying by injector makes stale state fall away with it, instead of letting\n * change-detection keys suppress re-injection into the new sheets.\n * - **root** — the same selector or slot name can be used in several shadow\n * roots, and each holds its own injection.\n */\nexport function createClientState<T extends object>(\n create: () => T,\n): (root: Document | ShadowRoot) => T {\n const byInjector = new WeakMap<object, WeakMap<Document | ShadowRoot, T>>();\n\n return (root: Document | ShadowRoot): T => {\n const injector = getGlobalInjector() as unknown as object;\n\n let byRoot = byInjector.get(injector);\n if (!byRoot) {\n byRoot = new WeakMap();\n byInjector.set(injector, byRoot);\n }\n\n let state = byRoot.get(root);\n if (!state) {\n state = create();\n byRoot.set(root, state);\n }\n\n return state;\n };\n}\n","/**\n * Shallow comparison of two dependency arrays using Object.is semantics.\n * Returns true when both arrays have the same length and every element\n * at the same index is identical.\n */\nexport function depsEqual(\n a: readonly unknown[],\n b: readonly unknown[],\n): boolean {\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (!Object.is(a[i], b[i])) return false;\n }\n return true;\n}\n"],"mappings":";;;;;;;;AAwEA,MAAM,QAAQ;AAEd,MAAM,cAAc;AAEpB,MAAa,sBACV,YAAY,WACX,YAAY,SAAS;CAAE,OAAO;CAAM,MAAM,CAAC;AAAE;AAOjD,SAAS,UACP,KACA,YACA,SACuB;CACvB,MAAM,SAAS,SAAS,UAAU;CAElC,IAAI,OAAO,eAAe,YACxB,OAAO;EAAE;EAAK,UAAU,CAAC,GAAG;EAAG,IAAI;EAAY;CAAO;CAGxD,IAAI,MAAM,QAAQ,UAAU,GAAG;EAC7B,MAAM,CAAC,OAAO,MAAM;EAEpB,IAAI,OAAO,OAAO,YAChB,MAAM,IAAI,MACR,gDAAgD,IAAI,iGAEtD;EAGF,IAAI,UAAU,KACZ,OAAO;GAAE;GAAK,UAAU;G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