rainbowindex 0.1.4 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +0,0 @@
1
- {"version":3,"sources":["../../../node_modules/.pnpm/ignore@7.0.5/node_modules/ignore/index.js","../../@rainbowindex/oxide/src/index.ts","../../@rainbowindex/oxide/src/extractor-fast.ts","../src/index.ts","../src/utils/intern.ts","../src/ast/types.ts","../src/ast/walk.ts","../src/utils/default-map.ts","../src/ast/source-map.ts","../src/ast/print.ts","../src/candidate/types.ts","../src/utils/is-valid-arbitrary.ts","../src/utils/math-operators.ts","../src/utils/decode-arbitrary-value.ts","../src/native/conversions.ts","../src/utils/lru-cache.ts","../src/candidate/parse.ts","../src/theme/theme.ts","../src/theme/defaults.ts","../src/utils/is-color.ts","../src/utils/infer-data-type.ts","../src/utils/dimensions.ts","../src/utils/utility-trie.ts","../src/utilities/utilities.ts","../src/utils/compare-breakpoints.ts","../src/utilities/layout.ts","../src/utilities/spacing.ts","../src/utilities/sizing.ts","../src/utilities/colors.ts","../src/utilities/typography.ts","../src/utilities/borders.ts","../src/utilities/effects.ts","../src/utilities/transforms.ts","../src/utilities/filters.ts","../src/utilities/interactivity.ts","../src/utilities/transitions.ts","../src/utilities/animations.ts","../src/utilities/svg.ts","../src/utilities/accessibility.ts","../src/utilities/tables.ts","../src/utilities/backgrounds.ts","../src/utilities/masking.ts","../src/utilities/grid.ts","../src/utilities/index.ts","../src/utils/segment.ts","../src/variants/negate.ts","../src/variants/variants.ts","../src/variants/pseudo.ts","../src/variants/media.ts","../src/variants/data.ts","../src/variants/index.ts","../src/plugin/api.ts","../src/plugin/plugin.ts","../src/utils/escape.ts","../src/utils/compare.ts","../src/compile/sort.ts","../src/parser/advanced/value-parser.ts","../src/css-functions.ts","../src/optimize/constant-fold.ts","../src/compile/optimize.ts","../src/utils/variables.ts","../src/compile/native.ts","../src/compile/compile.ts","../src/compile/canonicalize.ts","../src/intellisense/index.ts","../src/parser/css-parser.ts","../src/utils/topological-sort.ts","../src/parser/directives/errors.ts","../src/parser/directives/rainbowindex.ts","../src/parser/directives/layer.ts","../src/parser/directives/preflight.ts","../src/utils/brace-expansion.ts","../src/parser/directives/source.ts","../src/parser/directives/theme.ts","../src/utils/expand-declaration.ts","../src/parser/directives/apply.ts","../src/parser/directives/utility.ts","../src/parser/directives/variant.ts","../src/parser/directives/color.ts","../src/parser/directives/import.ts","../src/parser/directives/font.ts","../src/parser/directives/injection.ts","../src/parser/directives.ts","../src/parser/parser-utils.ts","../src/parser/advanced/attribute-selector.ts","../src/parser/selector-parser.ts","../src/utils/cartesian.ts","../src/utils/at-import.ts","../src/utils/replace-shadow-colors.ts","../src/utils/google-metadata.ts","../src/utils/google.ts"],"sourcesContent":["// A simple implementation of make-array\nfunction makeArray (subject) {\n return Array.isArray(subject)\n ? subject\n : [subject]\n}\n\nconst UNDEFINED = undefined\nconst EMPTY = ''\nconst SPACE = ' '\nconst ESCAPE = '\\\\'\nconst REGEX_TEST_BLANK_LINE = /^\\s+$/\nconst REGEX_INVALID_TRAILING_BACKSLASH = /(?:[^\\\\]|^)\\\\$/\nconst REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION = /^\\\\!/\nconst REGEX_REPLACE_LEADING_EXCAPED_HASH = /^\\\\#/\nconst REGEX_SPLITALL_CRLF = /\\r?\\n/g\n\n// Invalid:\n// - /foo,\n// - ./foo,\n// - ../foo,\n// - .\n// - ..\n// Valid:\n// - .foo\nconst REGEX_TEST_INVALID_PATH = /^\\.{0,2}\\/|^\\.{1,2}$/\n\nconst REGEX_TEST_TRAILING_SLASH = /\\/$/\n\nconst SLASH = '/'\n\n// Do not use ternary expression here, since \"istanbul ignore next\" is buggy\nlet TMP_KEY_IGNORE = 'node-ignore'\n/* istanbul ignore else */\nif (typeof Symbol !== 'undefined') {\n TMP_KEY_IGNORE = Symbol.for('node-ignore')\n}\nconst KEY_IGNORE = TMP_KEY_IGNORE\n\nconst define = (object, key, value) => {\n Object.defineProperty(object, key, {value})\n return value\n}\n\nconst REGEX_REGEXP_RANGE = /([0-z])-([0-z])/g\n\nconst RETURN_FALSE = () => false\n\n// Sanitize the range of a regular expression\n// The cases are complicated, see test cases for details\nconst sanitizeRange = range => range.replace(\n REGEX_REGEXP_RANGE,\n (match, from, to) => from.charCodeAt(0) <= to.charCodeAt(0)\n ? match\n // Invalid range (out of order) which is ok for gitignore rules but\n // fatal for JavaScript regular expression, so eliminate it.\n : EMPTY\n)\n\n// See fixtures #59\nconst cleanRangeBackSlash = slashes => {\n const {length} = slashes\n return slashes.slice(0, length - length % 2)\n}\n\n// > If the pattern ends with a slash,\n// > it is removed for the purpose of the following description,\n// > but it would only find a match with a directory.\n// > In other words, foo/ will match a directory foo and paths underneath it,\n// > but will not match a regular file or a symbolic link foo\n// > (this is consistent with the way how pathspec works in general in Git).\n// '`foo/`' will not match regular file '`foo`' or symbolic link '`foo`'\n// -> ignore-rules will not deal with it, because it costs extra `fs.stat` call\n// you could use option `mark: true` with `glob`\n\n// '`foo/`' should not continue with the '`..`'\nconst REPLACERS = [\n\n [\n // Remove BOM\n // TODO:\n // Other similar zero-width characters?\n /^\\uFEFF/,\n () => EMPTY\n ],\n\n // > Trailing spaces are ignored unless they are quoted with backslash (\"\\\")\n [\n // (a\\ ) -> (a )\n // (a ) -> (a)\n // (a ) -> (a)\n // (a \\ ) -> (a )\n /((?:\\\\\\\\)*?)(\\\\?\\s+)$/,\n (_, m1, m2) => m1 + (\n m2.indexOf('\\\\') === 0\n ? SPACE\n : EMPTY\n )\n ],\n\n // Replace (\\ ) with ' '\n // (\\ ) -> ' '\n // (\\\\ ) -> '\\\\ '\n // (\\\\\\ ) -> '\\\\ '\n [\n /(\\\\+?)\\s/g,\n (_, m1) => {\n const {length} = m1\n return m1.slice(0, length - length % 2) + SPACE\n }\n ],\n\n // Escape metacharacters\n // which is written down by users but means special for regular expressions.\n\n // > There are 12 characters with special meanings:\n // > - the backslash \\,\n // > - the caret ^,\n // > - the dollar sign $,\n // > - the period or dot .,\n // > - the vertical bar or pipe symbol |,\n // > - the question mark ?,\n // > - the asterisk or star *,\n // > - the plus sign +,\n // > - the opening parenthesis (,\n // > - the closing parenthesis ),\n // > - and the opening square bracket [,\n // > - the opening curly brace {,\n // > These special characters are often called \"metacharacters\".\n [\n /[\\\\$.|*+(){^]/g,\n match => `\\\\${match}`\n ],\n\n [\n // > a question mark (?) matches a single character\n /(?!\\\\)\\?/g,\n () => '[^/]'\n ],\n\n // leading slash\n [\n\n // > A leading slash matches the beginning of the pathname.\n // > For example, \"/*.c\" matches \"cat-file.c\" but not \"mozilla-sha1/sha1.c\".\n // A leading slash matches the beginning of the pathname\n /^\\//,\n () => '^'\n ],\n\n // replace special metacharacter slash after the leading slash\n [\n /\\//g,\n () => '\\\\/'\n ],\n\n [\n // > A leading \"**\" followed by a slash means match in all directories.\n // > For example, \"**/foo\" matches file or directory \"foo\" anywhere,\n // > the same as pattern \"foo\".\n // > \"**/foo/bar\" matches file or directory \"bar\" anywhere that is directly\n // > under directory \"foo\".\n // Notice that the '*'s have been replaced as '\\\\*'\n /^\\^*\\\\\\*\\\\\\*\\\\\\//,\n\n // '**/foo' <-> 'foo'\n () => '^(?:.*\\\\/)?'\n ],\n\n // starting\n [\n // there will be no leading '/'\n // (which has been replaced by section \"leading slash\")\n // If starts with '**', adding a '^' to the regular expression also works\n /^(?=[^^])/,\n function startingReplacer () {\n // If has a slash `/` at the beginning or middle\n return !/\\/(?!$)/.test(this)\n // > Prior to 2.22.1\n // > If the pattern does not contain a slash /,\n // > Git treats it as a shell glob pattern\n // Actually, if there is only a trailing slash,\n // git also treats it as a shell glob pattern\n\n // After 2.22.1 (compatible but clearer)\n // > If there is a separator at the beginning or middle (or both)\n // > of the pattern, then the pattern is relative to the directory\n // > level of the particular .gitignore file itself.\n // > Otherwise the pattern may also match at any level below\n // > the .gitignore level.\n ? '(?:^|\\\\/)'\n\n // > Otherwise, Git treats the pattern as a shell glob suitable for\n // > consumption by fnmatch(3)\n : '^'\n }\n ],\n\n // two globstars\n [\n // Use lookahead assertions so that we could match more than one `'/**'`\n /\\\\\\/\\\\\\*\\\\\\*(?=\\\\\\/|$)/g,\n\n // Zero, one or several directories\n // should not use '*', or it will be replaced by the next replacer\n\n // Check if it is not the last `'/**'`\n (_, index, str) => index + 6 < str.length\n\n // case: /**/\n // > A slash followed by two consecutive asterisks then a slash matches\n // > zero or more directories.\n // > For example, \"a/**/b\" matches \"a/b\", \"a/x/b\", \"a/x/y/b\" and so on.\n // '/**/'\n ? '(?:\\\\/[^\\\\/]+)*'\n\n // case: /**\n // > A trailing `\"/**\"` matches everything inside.\n\n // #21: everything inside but it should not include the current folder\n : '\\\\/.+'\n ],\n\n // normal intermediate wildcards\n [\n // Never replace escaped '*'\n // ignore rule '\\*' will match the path '*'\n\n // 'abc.*/' -> go\n // 'abc.*' -> skip this rule,\n // coz trailing single wildcard will be handed by [trailing wildcard]\n /(^|[^\\\\]+)(\\\\\\*)+(?=.+)/g,\n\n // '*.js' matches '.js'\n // '*.js' doesn't match 'abc'\n (_, p1, p2) => {\n // 1.\n // > An asterisk \"*\" matches anything except a slash.\n // 2.\n // > Other consecutive asterisks are considered regular asterisks\n // > and will match according to the previous rules.\n const unescaped = p2.replace(/\\\\\\*/g, '[^\\\\/]*')\n return p1 + unescaped\n }\n ],\n\n [\n // unescape, revert step 3 except for back slash\n // For example, if a user escape a '\\\\*',\n // after step 3, the result will be '\\\\\\\\\\\\*'\n /\\\\\\\\\\\\(?=[$.|*+(){^])/g,\n () => ESCAPE\n ],\n\n [\n // '\\\\\\\\' -> '\\\\'\n /\\\\\\\\/g,\n () => ESCAPE\n ],\n\n [\n // > The range notation, e.g. [a-zA-Z],\n // > can be used to match one of the characters in a range.\n\n // `\\` is escaped by step 3\n /(\\\\)?\\[([^\\]/]*?)(\\\\*)($|\\])/g,\n (match, leadEscape, range, endEscape, close) => leadEscape === ESCAPE\n // '\\\\[bar]' -> '\\\\\\\\[bar\\\\]'\n ? `\\\\[${range}${cleanRangeBackSlash(endEscape)}${close}`\n : close === ']'\n ? endEscape.length % 2 === 0\n // A normal case, and it is a range notation\n // '[bar]'\n // '[bar\\\\\\\\]'\n ? `[${sanitizeRange(range)}${endEscape}]`\n // Invalid range notaton\n // '[bar\\\\]' -> '[bar\\\\\\\\]'\n : '[]'\n : '[]'\n ],\n\n // ending\n [\n // 'js' will not match 'js.'\n // 'ab' will not match 'abc'\n /(?:[^*])$/,\n\n // WTF!\n // https://git-scm.com/docs/gitignore\n // changes in [2.22.1](https://git-scm.com/docs/gitignore/2.22.1)\n // which re-fixes #24, #38\n\n // > If there is a separator at the end of the pattern then the pattern\n // > will only match directories, otherwise the pattern can match both\n // > files and directories.\n\n // 'js*' will not match 'a.js'\n // 'js/' will not match 'a.js'\n // 'js' will match 'a.js' and 'a.js/'\n match => /\\/$/.test(match)\n // foo/ will not match 'foo'\n ? `${match}$`\n // foo matches 'foo' and 'foo/'\n : `${match}(?=$|\\\\/$)`\n ]\n]\n\nconst REGEX_REPLACE_TRAILING_WILDCARD = /(^|\\\\\\/)?\\\\\\*$/\nconst MODE_IGNORE = 'regex'\nconst MODE_CHECK_IGNORE = 'checkRegex'\nconst UNDERSCORE = '_'\n\nconst TRAILING_WILD_CARD_REPLACERS = {\n [MODE_IGNORE] (_, p1) {\n const prefix = p1\n // '\\^':\n // '/*' does not match EMPTY\n // '/*' does not match everything\n\n // '\\\\\\/':\n // 'abc/*' does not match 'abc/'\n ? `${p1}[^/]+`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n },\n\n [MODE_CHECK_IGNORE] (_, p1) {\n // When doing `git check-ignore`\n const prefix = p1\n // '\\\\\\/':\n // 'abc/*' DOES match 'abc/' !\n ? `${p1}[^/]*`\n\n // 'a*' matches 'a'\n // 'a*' matches 'aa'\n : '[^/]*'\n\n return `${prefix}(?=$|\\\\/$)`\n }\n}\n\n// @param {pattern}\nconst makeRegexPrefix = pattern => REPLACERS.reduce(\n (prev, [matcher, replacer]) =>\n prev.replace(matcher, replacer.bind(pattern)),\n pattern\n)\n\nconst isString = subject => typeof subject === 'string'\n\n// > A blank line matches no files, so it can serve as a separator for readability.\nconst checkPattern = pattern => pattern\n && isString(pattern)\n && !REGEX_TEST_BLANK_LINE.test(pattern)\n && !REGEX_INVALID_TRAILING_BACKSLASH.test(pattern)\n\n // > A line starting with # serves as a comment.\n && pattern.indexOf('#') !== 0\n\nconst splitPattern = pattern => pattern\n.split(REGEX_SPLITALL_CRLF)\n.filter(Boolean)\n\nclass IgnoreRule {\n constructor (\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n prefix\n ) {\n this.pattern = pattern\n this.mark = mark\n this.negative = negative\n\n define(this, 'body', body)\n define(this, 'ignoreCase', ignoreCase)\n define(this, 'regexPrefix', prefix)\n }\n\n get regex () {\n const key = UNDERSCORE + MODE_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_IGNORE, key)\n }\n\n get checkRegex () {\n const key = UNDERSCORE + MODE_CHECK_IGNORE\n\n if (this[key]) {\n return this[key]\n }\n\n return this._make(MODE_CHECK_IGNORE, key)\n }\n\n _make (mode, key) {\n const str = this.regexPrefix.replace(\n REGEX_REPLACE_TRAILING_WILDCARD,\n\n // It does not need to bind pattern\n TRAILING_WILD_CARD_REPLACERS[mode]\n )\n\n const regex = this.ignoreCase\n ? new RegExp(str, 'i')\n : new RegExp(str)\n\n return define(this, key, regex)\n }\n}\n\nconst createRule = ({\n pattern,\n mark\n}, ignoreCase) => {\n let negative = false\n let body = pattern\n\n // > An optional prefix \"!\" which negates the pattern;\n if (body.indexOf('!') === 0) {\n negative = true\n body = body.substr(1)\n }\n\n body = body\n // > Put a backslash (\"\\\") in front of the first \"!\" for patterns that\n // > begin with a literal \"!\", for example, `\"\\!important!.txt\"`.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION, '!')\n // > Put a backslash (\"\\\") in front of the first hash for patterns that\n // > begin with a hash.\n .replace(REGEX_REPLACE_LEADING_EXCAPED_HASH, '#')\n\n const regexPrefix = makeRegexPrefix(body)\n\n return new IgnoreRule(\n pattern,\n mark,\n body,\n ignoreCase,\n negative,\n regexPrefix\n )\n}\n\nclass RuleManager {\n constructor (ignoreCase) {\n this._ignoreCase = ignoreCase\n this._rules = []\n }\n\n _add (pattern) {\n // #32\n if (pattern && pattern[KEY_IGNORE]) {\n this._rules = this._rules.concat(pattern._rules._rules)\n this._added = true\n return\n }\n\n if (isString(pattern)) {\n pattern = {\n pattern\n }\n }\n\n if (checkPattern(pattern.pattern)) {\n const rule = createRule(pattern, this._ignoreCase)\n this._added = true\n this._rules.push(rule)\n }\n }\n\n // @param {Array<string> | string | Ignore} pattern\n add (pattern) {\n this._added = false\n\n makeArray(\n isString(pattern)\n ? splitPattern(pattern)\n : pattern\n ).forEach(this._add, this)\n\n return this._added\n }\n\n // Test one single path without recursively checking parent directories\n //\n // - checkUnignored `boolean` whether should check if the path is unignored,\n // setting `checkUnignored` to `false` could reduce additional\n // path matching.\n // - check `string` either `MODE_IGNORE` or `MODE_CHECK_IGNORE`\n\n // @returns {TestResult} true if a file is ignored\n test (path, checkUnignored, mode) {\n let ignored = false\n let unignored = false\n let matchedRule\n\n this._rules.forEach(rule => {\n const {negative} = rule\n\n // | ignored : unignored\n // -------- | ---------------------------------------\n // negative | 0:0 | 0:1 | 1:0 | 1:1\n // -------- | ------- | ------- | ------- | --------\n // 0 | TEST | TEST | SKIP | X\n // 1 | TESTIF | SKIP | TEST | X\n\n // - SKIP: always skip\n // - TEST: always test\n // - TESTIF: only test if checkUnignored\n // - X: that never happen\n if (\n unignored === negative && ignored !== unignored\n || negative && !ignored && !unignored && !checkUnignored\n ) {\n return\n }\n\n const matched = rule[mode].test(path)\n\n if (!matched) {\n return\n }\n\n ignored = !negative\n unignored = negative\n\n matchedRule = negative\n ? UNDEFINED\n : rule\n })\n\n const ret = {\n ignored,\n unignored\n }\n\n if (matchedRule) {\n ret.rule = matchedRule\n }\n\n return ret\n }\n}\n\nconst throwError = (message, Ctor) => {\n throw new Ctor(message)\n}\n\nconst checkPath = (path, originalPath, doThrow) => {\n if (!isString(path)) {\n return doThrow(\n `path must be a string, but got \\`${originalPath}\\``,\n TypeError\n )\n }\n\n // We don't know if we should ignore EMPTY, so throw\n if (!path) {\n return doThrow(`path must not be empty`, TypeError)\n }\n\n // Check if it is a relative path\n if (checkPath.isNotRelative(path)) {\n const r = '`path.relative()`d'\n return doThrow(\n `path should be a ${r} string, but got \"${originalPath}\"`,\n RangeError\n )\n }\n\n return true\n}\n\nconst isNotRelative = path => REGEX_TEST_INVALID_PATH.test(path)\n\ncheckPath.isNotRelative = isNotRelative\n\n// On windows, the following function will be replaced\n/* istanbul ignore next */\ncheckPath.convert = p => p\n\n\nclass Ignore {\n constructor ({\n ignorecase = true,\n ignoreCase = ignorecase,\n allowRelativePaths = false\n } = {}) {\n define(this, KEY_IGNORE, true)\n\n this._rules = new RuleManager(ignoreCase)\n this._strictPathCheck = !allowRelativePaths\n this._initCache()\n }\n\n _initCache () {\n // A cache for the result of `.ignores()`\n this._ignoreCache = Object.create(null)\n\n // A cache for the result of `.test()`\n this._testCache = Object.create(null)\n }\n\n add (pattern) {\n if (this._rules.add(pattern)) {\n // Some rules have just added to the ignore,\n // making the behavior changed,\n // so we need to re-initialize the result cache\n this._initCache()\n }\n\n return this\n }\n\n // legacy\n addPattern (pattern) {\n return this.add(pattern)\n }\n\n // @returns {TestResult}\n _test (originalPath, cache, checkUnignored, slices) {\n const path = originalPath\n // Supports nullable path\n && checkPath.convert(originalPath)\n\n checkPath(\n path,\n originalPath,\n this._strictPathCheck\n ? throwError\n : RETURN_FALSE\n )\n\n return this._t(path, cache, checkUnignored, slices)\n }\n\n checkIgnore (path) {\n // If the path doest not end with a slash, `.ignores()` is much equivalent\n // to `git check-ignore`\n if (!REGEX_TEST_TRAILING_SLASH.test(path)) {\n return this.test(path)\n }\n\n const slices = path.split(SLASH).filter(Boolean)\n slices.pop()\n\n if (slices.length) {\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n this._testCache,\n true,\n slices\n )\n\n if (parent.ignored) {\n return parent\n }\n }\n\n return this._rules.test(path, false, MODE_CHECK_IGNORE)\n }\n\n _t (\n // The path to be tested\n path,\n\n // The cache for the result of a certain checking\n cache,\n\n // Whether should check if the path is unignored\n checkUnignored,\n\n // The path slices\n slices\n ) {\n if (path in cache) {\n return cache[path]\n }\n\n if (!slices) {\n // path/to/a.js\n // ['path', 'to', 'a.js']\n slices = path.split(SLASH).filter(Boolean)\n }\n\n slices.pop()\n\n // If the path has no parent directory, just test it\n if (!slices.length) {\n return cache[path] = this._rules.test(path, checkUnignored, MODE_IGNORE)\n }\n\n const parent = this._t(\n slices.join(SLASH) + SLASH,\n cache,\n checkUnignored,\n slices\n )\n\n // If the path contains a parent directory, check the parent first\n return cache[path] = parent.ignored\n // > It is not possible to re-include a file if a parent directory of\n // > that file is excluded.\n ? parent\n : this._rules.test(path, checkUnignored, MODE_IGNORE)\n }\n\n ignores (path) {\n return this._test(path, this._ignoreCache, false).ignored\n }\n\n createFilter () {\n return path => !this.ignores(path)\n }\n\n filter (paths) {\n return makeArray(paths).filter(this.createFilter())\n }\n\n // @returns {TestResult}\n test (path) {\n return this._test(path, this._testCache, true)\n }\n}\n\nconst factory = options => new Ignore(options)\n\nconst isPathValid = path =>\n checkPath(path && checkPath.convert(path), path, RETURN_FALSE)\n\n/* istanbul ignore next */\nconst setupWindows = () => {\n /* eslint no-control-regex: \"off\" */\n const makePosix = str => /^\\\\\\\\\\?\\\\/.test(str)\n || /[\"<>|\\u0000-\\u001F]+/u.test(str)\n ? str\n : str.replace(/\\\\/g, '/')\n\n checkPath.convert = makePosix\n\n // 'C:\\\\foo' <- 'C:\\\\foo' has been converted to 'C:/'\n // 'd:\\\\foo'\n const REGEX_TEST_WINDOWS_PATH_ABSOLUTE = /^[a-z]:\\//i\n checkPath.isNotRelative = path =>\n REGEX_TEST_WINDOWS_PATH_ABSOLUTE.test(path)\n || isNotRelative(path)\n}\n\n\n// Windows\n// --------------------------------------------------------------\n/* istanbul ignore next */\nif (\n // Detect `process` so that it can run in browsers.\n typeof process !== 'undefined'\n && process.platform === 'win32'\n) {\n setupWindows()\n}\n\n// COMMONJS_EXPORTS ////////////////////////////////////////////////////////////\n\nmodule.exports = factory\n\n// Although it is an anti-pattern,\n// it is still widely misused by a lot of libraries in github\n// Ref: https://github.com/search?q=ignore.default%28%29&type=code\nfactory.default = factory\n\nmodule.exports.isPathValid = isPathValid\n\n// For testing purposes\ndefine(module.exports, Symbol.for('setupWindows'), setupWindows)\n","/**\n * Rainbow Index Oxide Scanner\n *\n * Scans source files to extract utility class candidates.\n * Uses optimized TypeScript for single-string extraction (faster than N-API),\n * and native Rust for parallel file operations.\n */\n\nimport * as fs from \"node:fs\";\nimport * as path from \"node:path\";\nimport { fileURLToPath } from \"node:url\";\nimport { createRequire } from \"node:module\";\nimport { TextDecoder } from \"node:util\";\nimport ignore, { type Ignore } from \"ignore\";\nimport { extractCandidatesFast } from \"./extractor-fast.js\";\n\nconst PLATFORM_SUFFIXES: Record<string, string> = {\n \"darwin-arm64\": \"darwin-arm64\",\n \"darwin-x64\": \"darwin-x64\",\n \"linux-x64\": \"linux-x64-gnu\",\n \"linux-arm64\": \"linux-arm64-gnu\",\n \"win32-x64\": \"win32-x64-msvc\",\n};\n\n// ESM/CJS compatibility - get module directory\nfunction getModuleDir(): string {\n // Try ESM approach first\n try {\n // In ESM, import.meta.url is defined\n if (typeof import.meta?.url === \"string\") {\n return path.dirname(fileURLToPath(import.meta.url));\n }\n } catch {\n // ESM approach failed\n }\n\n const platformKey = `${process.platform}-${process.arch}`;\n const platformSuffix = PLATFORM_SUFFIXES[platformKey];\n const optionalPackage = platformSuffix ? `oxide-${platformSuffix}` : null;\n\n // For CJS, we need to find the package root\n // Try common locations in monorepo structure\n const candidates = [\n // Running from within monorepo\n path.resolve(\"packages\", \"@rainbowindex\", \"oxide\"),\n platformSuffix ? path.resolve(\"packages\", \"@rainbowindex\", \"oxide\", \"npm\", platformSuffix) : null,\n // Installed in node_modules\n path.resolve(\"node_modules\", \"@rainbowindex\", \"oxide\"),\n optionalPackage ? path.resolve(\"node_modules\", \"@rainbowindex\", optionalPackage) : null,\n // Process cwd might be the package\n process.cwd(),\n ].filter(Boolean) as string[];\n\n for (const dir of candidates) {\n // Check if the native module exists here\n if (platformSuffix) {\n const platformFile = path.join(dir, `rainbowindex-oxide.${platformSuffix}.node`);\n if (fs.existsSync(platformFile)) {\n return dir;\n }\n }\n const genericFile = path.join(dir, \"rainbowindex-oxide.node\");\n if (fs.existsSync(genericFile)) {\n return dir;\n }\n }\n\n // Last resort - return cwd\n return process.cwd();\n}\n\nfunction getRequireFunc(): NodeRequire {\n try {\n if (typeof import.meta?.url === \"string\") {\n return createRequire(import.meta.url);\n }\n } catch {\n // ESM approach failed\n }\n // CJS fallback - use global require\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n return ((id: string) => require(id)) as unknown as NodeRequire;\n}\n\nconst __dirnameCompat = getModuleDir();\nconst requireCompat = getRequireFunc();\n\n// ============================================\n// Types\n// ============================================\n\nexport interface ScannerSource {\n base: string;\n pattern: string;\n negated?: boolean;\n}\n\nexport interface ScannerOptions {\n sources: ScannerSource[];\n}\n\nexport interface ScanWithFilesResult {\n candidates: string[];\n files: { file: string; candidates: string[] }[];\n}\n\n// ============================================\n// Candidate Parser Types\n// ============================================\n\nexport interface CandidateValue {\n kind: \"named\" | \"arbitrary\";\n value: string;\n fraction?: string | null;\n dataType?: string | null;\n}\n\nexport interface CandidateModifier {\n kind: \"named\" | \"arbitrary\";\n value: string;\n dashedIdent?: string | null;\n}\n\nexport interface Variant {\n kind: \"static\" | \"functional\" | \"arbitrary\" | \"compound\";\n root?: string | null;\n selector?: string | null;\n relative?: boolean | null;\n value?: CandidateValue | null;\n modifier?: CandidateModifier | null;\n compoundVariant?: string | null; // JSON-serialized nested variant for compound\n}\n\nexport interface Candidate {\n kind: \"static\" | \"functional\" | \"arbitrary\";\n root?: string | null;\n property?: string | null;\n value?: CandidateValue | null;\n modifier?: CandidateModifier | null;\n variants: Variant[];\n important: boolean;\n raw: string;\n}\n\n// ============================================\n// Native Module Loading\n// ============================================\n\ninterface NativeScanner {\n scan(): string[];\n files(): string[];\n rescanFile(filePath: string): string[];\n scanWithFiles?(): ScanWithFilesResult;\n scanErrors?(): string[];\n reset?(): void;\n}\n\n/** CSS AST Node from native compilation */\nexport interface AstNode {\n kind: \"rule\" | \"at-rule\" | \"declaration\" | \"comment\" | \"context\" | \"at-root\";\n selector?: string | null;\n params?: string | null;\n property?: string | null;\n value?: string | null;\n important?: boolean | null;\n nodes?: AstNode[] | null;\n}\n\n/** Theme values for utility compilation */\nexport interface Theme {\n values?: Record<string, Record<string, string>>;\n prefix?: string;\n}\n\n/** Print options for CSS output */\nexport interface PrintOptions {\n /** Whether to minify output (default: false) */\n minify?: boolean;\n /** Indentation style: \"2space\" | \"4space\" | \"tab\" (default: \"2space\") */\n indent?: \"2space\" | \"4space\" | \"tab\";\n}\n\n/** CSS node from native CSS parser */\nexport interface CssNode {\n kind: \"rule\" | \"at-rule\" | \"declaration\" | \"comment\";\n selector?: string | null;\n name?: string | null;\n params?: string | null;\n property?: string | null;\n value?: string | null;\n important?: boolean | null;\n nodes?: CssNode[] | null;\n src?: { start: number; end: number } | null;\n}\n\n/** Result of parsing CSS */\nexport interface CssParseResult {\n ast: CssNode[];\n licenseComments: string[];\n metrics?: {\n totalNs: number;\n commentNs: number;\n atRuleNs: number;\n ruleDeclNs: number;\n };\n}\n\ninterface NativeModule {\n Scanner: new (options: { sources: Array<{ base: string; pattern: string; negated?: boolean }> }) => NativeScanner;\n extractCandidates(content: string): string[];\n extractCandidatesBatch?(contents: string[]): string[][];\n extractCandidatesBatchCombined?(contents: string[]): string[];\n parseCandidate(input: string): Candidate | null;\n parseCandidateWithUtilitySet?(input: string): Candidate | null;\n parseCandidatesBatchSequential(inputs: string[]): (Candidate | null)[];\n parseCandidatesBatchSequentialWithUtilitySet?(inputs: string[]): (Candidate | null)[];\n isCandidateParserAvailable(): boolean;\n // Utility set for findRoot\n loadUtilitySet(utilities: string[]): void;\n clearUtilitySet?(): void;\n isUtilitySetLoaded(): boolean;\n findRoot(input: string): string[] | null;\n // Utility compilation\n compileCandidateString(input: string, theme?: Theme): AstNode[] | null;\n compileCandidatesBatch(inputs: string[], theme?: Theme): (AstNode[] | null)[];\n compileCandidate(candidate: Candidate, theme?: Theme): AstNode[] | null;\n hasUtility(name: string): boolean;\n hasVariant(name: string): boolean;\n // CSS printing\n toCss(nodes: AstNode[], options?: PrintOptions): string;\n toCssMinified(nodes: AstNode[]): string;\n toCssPretty(nodes: AstNode[], indent?: string): string;\n compileToCss(inputs: string[], theme?: Theme, options?: PrintOptions): string;\n // CSS parser (high-performance)\n parseCss(input: string): CssParseResult;\n isCssParserAvailable(): boolean;\n setCssParserTimings(enabled: boolean): void;\n}\n\nlet nativeModule: NativeModule | null = null;\nlet nativeLoadAttempted = false;\nconst VERIFY_SCAN_CACHE = process.env.RI_SCAN_VERIFY === \"1\";\nconst ENABLE_SCAN_MTIME = process.env.RI_SCAN_MTIME !== \"0\";\nconst LOG_NATIVE_ERRORS = process.env.RI_NATIVE_LOG === \"1\";\nconst LOG_SCAN_ERRORS = process.env.RI_SCAN_LOG_ERRORS === \"1\";\n\nconst EXTRACT_CACHE_LIMIT = 512;\nconst EXTRACT_CACHE_MAX_LEN = 2_000_000;\n// Extract cache keyed by a stable content hash to avoid duplicating large strings in memory.\nconst extractCache = new Map<string, string[]>();\nconst ENABLE_EXTRACT_CACHE = process.env.RI_EXTRACT_CACHE !== \"0\";\nconst SCAN_CACHE_LIMIT = 32;\ntype ScanCacheEntry = { candidates: string[]; mtimes: Map<string, number> | null };\nconst scanCache = new Map<string, ScanCacheEntry>();\nconst ENABLE_GLOBAL_SCAN_CACHE = process.env.RI_SCAN_GLOBAL_CACHE !== \"0\";\nconst PARSE_CACHE_LIMIT = 5000;\nconst parseCandidateCache = new Map<string, Candidate | null>();\nconst parseCandidateWithUtilitySetCache = new Map<string, Candidate | null>();\n\nconst loggedMessages = new Set<string>();\n\nfunction logOnce(key: string, message: string, error?: unknown): void {\n const allow = LOG_NATIVE_ERRORS || LOG_SCAN_ERRORS;\n if (!allow) return;\n if (loggedMessages.has(key)) return;\n loggedMessages.add(key);\n if (error instanceof Error) {\n console.warn(`${message}\\n${error.stack ?? error.message}`);\n return;\n }\n if (error !== undefined) {\n console.warn(`${message}\\n${String(error)}`);\n return;\n }\n console.warn(message);\n}\n\nfunction warnOnce(key: string, message: string): void {\n if (loggedMessages.has(key)) return;\n loggedMessages.add(key);\n console.warn(message);\n}\n\nconst FNV_OFFSET_BASIS_64 = 0xcbf29ce484222325n;\nconst FNV_PRIME_64 = 0x100000001b3n;\nconst FNV_MASK_64 = 0xffffffffffffffffn;\n\n// Threshold above which we use sampling instead of hashing every character.\n// 100KB is a reasonable cutoff where BigInt overhead becomes noticeable.\nconst HASH_SAMPLE_THRESHOLD = 100_000;\n// Number of bytes to hash at start and end of large files.\nconst HASH_SAMPLE_SIZE = 8192;\n// Number of sample points in the middle of large files.\nconst HASH_SAMPLE_POINTS = 16;\n\nfunction getExtractCacheKey(content: string): string {\n const len = content.length;\n let hash = FNV_OFFSET_BASIS_64;\n\n if (len <= HASH_SAMPLE_THRESHOLD) {\n // Small files: hash every character\n for (let i = 0; i < len; i += 1) {\n hash ^= BigInt(content.charCodeAt(i));\n hash = (hash * FNV_PRIME_64) & FNV_MASK_64;\n }\n } else {\n // Large files: sample prefix, suffix, and middle points.\n // This provides a good collision resistance while avoiding O(n) BigInt ops.\n\n // Hash prefix\n const prefixEnd = Math.min(HASH_SAMPLE_SIZE, len);\n for (let i = 0; i < prefixEnd; i += 1) {\n hash ^= BigInt(content.charCodeAt(i));\n hash = (hash * FNV_PRIME_64) & FNV_MASK_64;\n }\n\n // Hash suffix\n const suffixStart = Math.max(len - HASH_SAMPLE_SIZE, prefixEnd);\n for (let i = suffixStart; i < len; i += 1) {\n hash ^= BigInt(content.charCodeAt(i));\n hash = (hash * FNV_PRIME_64) & FNV_MASK_64;\n }\n\n // Hash evenly spaced sample points in the middle\n const middleStart = prefixEnd;\n const middleEnd = suffixStart;\n const middleLen = middleEnd - middleStart;\n if (middleLen > 0) {\n const step = Math.floor(middleLen / HASH_SAMPLE_POINTS);\n for (let p = 0; p < HASH_SAMPLE_POINTS && step > 0; p += 1) {\n const idx = middleStart + p * step;\n // Sample a small window at each point\n for (let i = idx; i < idx + 64 && i < middleEnd; i += 1) {\n hash ^= BigInt(content.charCodeAt(i));\n hash = (hash * FNV_PRIME_64) & FNV_MASK_64;\n }\n }\n }\n }\n\n const hex = hash.toString(16).padStart(16, \"0\");\n // Hash collisions are possible but extremely unlikely for typical source inputs.\n // For large files, collision risk is slightly higher due to sampling, but the\n // length prefix and sample coverage make accidental collisions rare in practice.\n return `${len}:${hex}`;\n}\n\nconst UTF8_DECODER = typeof TextDecoder !== \"undefined\" ? new TextDecoder(\"utf-8\", { fatal: true }) : null;\n\nfunction readFileContent(filePath: string): string {\n const buffer = fs.readFileSync(filePath);\n if (UTF8_DECODER) {\n try {\n return UTF8_DECODER.decode(buffer);\n } catch (error) {\n if (LOG_SCAN_ERRORS) {\n logOnce(`scan-utf8:${filePath}`, `[rainbowindex] Non-UTF8 source file encountered: ${filePath}`, error);\n }\n // Preserve raw bytes for ASCII candidate extraction.\n return buffer.toString(\"latin1\");\n }\n }\n // Preserve raw bytes when UTF-8 validation isn't available.\n return buffer.toString(\"latin1\");\n}\n\n/**\n * Evict the oldest entry from an LRU cache (Map maintains insertion order).\n */\nfunction evictOldestEntry<K, V>(cache: Map<K, V>): void {\n const oldestKey = cache.keys().next().value;\n if (oldestKey !== undefined) {\n cache.delete(oldestKey);\n }\n}\n\nfunction getCachedExtractByKey(key: string): string[] | null {\n const cached = extractCache.get(key);\n if (!cached) return null;\n // LRU: refresh entry\n extractCache.delete(key);\n extractCache.set(key, cached);\n return cached;\n}\n\nfunction setCachedExtractByKey(key: string, candidates: string[]): void {\n if (extractCache.size >= EXTRACT_CACHE_LIMIT) {\n evictOldestEntry(extractCache);\n }\n extractCache.set(key, candidates);\n}\n\nfunction getScanCacheKey(sources: ScannerSource[]): string {\n return sources.map((s) => `${path.resolve(s.base)}|${s.pattern}|${s.negated ? 1 : 0}`).join(\";\");\n}\n\nfunction getGlobalScanCache(key: string): ScanCacheEntry | null {\n const cached = scanCache.get(key);\n if (!cached) return null;\n if (ENABLE_SCAN_MTIME || VERIFY_SCAN_CACHE) {\n if (!cached.mtimes) {\n scanCache.delete(key);\n return null;\n }\n for (const [file, mtime] of cached.mtimes) {\n try {\n const current = fs.statSync(file).mtimeMs;\n if (current !== mtime) {\n scanCache.delete(key);\n return null;\n }\n } catch (error) {\n if (LOG_SCAN_ERRORS) {\n logOnce(`scan-stat:${file}`, `[rainbowindex] Failed to stat source file: ${file}`, error);\n }\n scanCache.delete(key);\n return null;\n }\n }\n }\n scanCache.delete(key);\n scanCache.set(key, cached);\n return cached;\n}\n\nfunction setGlobalScanCache(key: string, candidates: string[], mtimes: Map<string, number> | null): void {\n if (scanCache.size >= SCAN_CACHE_LIMIT) {\n evictOldestEntry(scanCache);\n }\n scanCache.set(key, { candidates, mtimes });\n}\n\nfunction getCachedParse(cache: Map<string, Candidate | null>, input: string): Candidate | null | undefined {\n if (!cache.has(input)) return undefined;\n const value = cache.get(input) as Candidate | null;\n cache.delete(input);\n cache.set(input, value);\n return value;\n}\n\nfunction setCachedParse(cache: Map<string, Candidate | null>, input: string, value: Candidate | null): void {\n if (cache.has(input)) {\n cache.delete(input);\n }\n cache.set(input, value);\n if (cache.size > PARSE_CACHE_LIMIT) {\n evictOldestEntry(cache);\n }\n}\n\nfunction toPosixPath(file: string): string {\n return file.replace(/\\\\/g, \"/\");\n}\n\ntype GitIgnoreState = { matcher: Ignore; patterns: string[] };\n\nfunction readGitIgnoreLines(filePath: string): string[] {\n try {\n const content = fs.readFileSync(filePath, \"utf-8\");\n return content\n .split(/\\r?\\n/)\n .map((line) => line.trim())\n .filter((line) => line.length > 0 && !line.startsWith(\"#\"));\n } catch (error) {\n if (LOG_SCAN_ERRORS) {\n logOnce(`gitignore-read:${filePath}`, `[rainbowindex] Failed to read .gitignore: ${filePath}`, error);\n }\n return [];\n }\n}\n\nfunction prefixGitIgnorePattern(pattern: string, prefix: string): string {\n if (!prefix) return pattern;\n const negated = pattern.startsWith(\"!\");\n const body = negated ? pattern.slice(1) : pattern;\n const normalized = body.startsWith(\"/\") ? body.slice(1) : body;\n const joined = normalized.length > 0 ? `${prefix}/${normalized}` : prefix;\n return negated ? `!${joined}` : joined;\n}\n\nfunction buildGitIgnoreState(base: string, dir: string, parentPatterns: string[]): GitIgnoreState {\n const patterns = parentPatterns.slice();\n const ignoreFile = path.join(dir, \".gitignore\");\n if (fs.existsSync(ignoreFile)) {\n const relDir = toPosixPath(path.relative(base, dir));\n const prefix = relDir === \"\" || relDir === \".\" ? \"\" : relDir;\n const lines = readGitIgnoreLines(ignoreFile);\n for (const line of lines) {\n patterns.push(prefixGitIgnorePattern(line, prefix));\n }\n }\n const matcher = ignore().add(patterns);\n return { matcher, patterns };\n}\n\nfunction matchGlob(relativePath: string, pattern: string): boolean {\n if (pattern === \"*\" || pattern === \"**\" || pattern === \"**/*\") return true;\n\n if (!pattern.includes(\"*\") && !pattern.includes(\"?\") && !pattern.includes(\"{\") && !pattern.includes(\"[\")) {\n return relativePath === pattern;\n }\n\n // Match **/*.ext patterns (any file with extension anywhere)\n const anyDirExtMatch = pattern.match(/^\\*\\*\\/\\*\\.([a-z0-9]+)$/i);\n if (anyDirExtMatch) {\n return relativePath.endsWith(`.${anyDirExtMatch[1]}`);\n }\n\n // Match prefix/**/*.ext patterns (files with extension under prefix directory)\n const prefixExtMatch = pattern.match(/^([^*]+)\\/\\*\\*\\/\\*\\.([a-z0-9]+)$/i);\n if (prefixExtMatch) {\n const [, prefix, ext] = prefixExtMatch;\n return relativePath.startsWith(`${prefix}/`) && relativePath.endsWith(`.${ext}`);\n }\n\n // Match prefix/**/*.{ext1,ext2} patterns\n const prefixBraceMatch = pattern.match(/^([^*]+)\\/\\*\\*\\/\\*\\.\\{([^}]+)\\}$/);\n if (prefixBraceMatch) {\n const [, prefix, extList] = prefixBraceMatch;\n const exts = extList!.split(\",\").map((ext) => ext.trim().replace(/^\\./, \"\"));\n return (\n relativePath.startsWith(`${prefix}/`) &&\n exts.some((ext) => ext.length > 0 && relativePath.endsWith(`.${ext}`))\n );\n }\n\n const braceMatch = pattern.match(/\\*\\.\\{([^}]+)\\}$/);\n if (braceMatch) {\n const exts = braceMatch[1]!.split(\",\").map((ext) => ext.trim().replace(/^\\./, \"\"));\n return exts.some((ext) => ext.length > 0 && relativePath.endsWith(`.${ext}`));\n }\n\n const extMatch = pattern.match(/\\*\\.([a-z0-9]+)$/i);\n if (extMatch) {\n return relativePath.endsWith(`.${extMatch[1]}`);\n }\n\n warnOnce(\n `glob-unsupported:${pattern}`,\n `[rainbowindex] Unsupported glob pattern '${pattern}' in TS fallback; skipping.`\n );\n return false;\n}\n\nfunction matchesSourcePattern(file: string, base: string, pattern: string): boolean {\n if (!pattern || pattern === \"**/*\" || pattern === \"*\") return true;\n\n const relative = path.relative(base, file);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) return false;\n\n const relPosix = toPosixPath(relative);\n const patternPosix = toPosixPath(pattern).replace(/^\\.\\//, \"\");\n\n return matchGlob(relPosix, patternPosix);\n}\n\nfunction tryLoadNative(): NativeModule | null {\n if (nativeLoadAttempted) return nativeModule;\n nativeLoadAttempted = true;\n\n // Determine platform-specific binary name\n const platform = process.platform;\n const arch = process.arch;\n const platformKey = `${platform}-${arch}`;\n const platformSuffix = PLATFORM_SUFFIXES[platformKey];\n\n // Find package root (works from src/ or dist/)\n const packageRoot =\n __dirnameCompat.endsWith(\"src\") || __dirnameCompat.endsWith(\"dist\")\n ? path.dirname(__dirnameCompat)\n : __dirnameCompat;\n\n let resolvedPackageRoot: string | null = null;\n try {\n resolvedPackageRoot = path.dirname(requireCompat.resolve(\"@rainbowindex/oxide/package.json\"));\n } catch {\n resolvedPackageRoot = null;\n }\n\n const searchRoots = new Set<string>();\n searchRoots.add(packageRoot);\n searchRoots.add(__dirnameCompat);\n searchRoots.add(process.cwd());\n if (resolvedPackageRoot) {\n searchRoots.add(resolvedPackageRoot);\n searchRoots.add(path.join(resolvedPackageRoot, \"dist\"));\n }\n searchRoots.add(path.dirname(packageRoot));\n\n const pathsToTry: string[] = [];\n const seen = new Set<string>();\n const addPath = (candidate?: string | null) => {\n if (!candidate) return;\n if (seen.has(candidate)) return;\n seen.add(candidate);\n pathsToTry.push(candidate);\n };\n\n const envPath = process.env.RI_OXIDE_PATH;\n if (envPath) {\n const resolved = path.resolve(envPath);\n if (resolved.endsWith(\".node\")) {\n addPath(resolved);\n } else {\n searchRoots.add(resolved);\n }\n }\n\n for (const root of searchRoots) {\n addPath(platformSuffix && path.join(root, `rainbowindex-oxide.${platformSuffix}.node`));\n addPath(path.join(root, \"rainbowindex-oxide.node\"));\n addPath(platformSuffix && path.join(root, \"napi\", `rainbowindex-oxide.${platformSuffix}.node`));\n addPath(path.join(root, \"napi\", \"rainbowindex-oxide.node\"));\n addPath(platformSuffix && path.join(root, \"..\", `rainbowindex-oxide.${platformSuffix}.node`));\n addPath(path.join(root, \"..\", \"rainbowindex-oxide.node\"));\n }\n\n let lastError: unknown = null;\n\n for (const modulePath of pathsToTry) {\n try {\n nativeModule = requireCompat(modulePath) as NativeModule;\n return nativeModule;\n } catch (error) {\n lastError = error;\n // Try next path\n }\n }\n\n if (LOG_NATIVE_ERRORS) {\n const attempts = pathsToTry.length > 0 ? pathsToTry.join(\", \") : \"(no candidate paths)\";\n logOnce(\"native-load-failed\", `[rainbowindex] Native module not available. Tried: ${attempts}`, lastError);\n }\n\n // Native module not available, will use TypeScript fallback\n return null;\n}\n\nfunction looksLikeMarkup(content: string): boolean {\n if (content.indexOf(\"<\") === -1) return false;\n return (\n content.indexOf(\"class=\") !== -1 ||\n content.indexOf(\"class =\") !== -1 ||\n content.indexOf(\"className=\") !== -1 ||\n content.indexOf(\"className =\") !== -1\n );\n}\n\n/**\n * Check if native scanner is available.\n */\nexport function isNativeAvailable(): boolean {\n return tryLoadNative() !== null;\n}\n\nconst EXTRACT_NATIVE_MIN_SIZE = Number(process.env.RI_EXTRACT_NATIVE_MIN_SIZE ?? 8192);\n\nfunction extractCandidatesImpl(content: string): string[] {\n const native = tryLoadNative();\n const preferFast = looksLikeMarkup(content) && content.length < EXTRACT_NATIVE_MIN_SIZE;\n return native && content.length >= EXTRACT_NATIVE_MIN_SIZE && !preferFast\n ? native.extractCandidates(content)\n : extractCandidatesFast(content);\n}\n\n/**\n * Extract candidates from content.\n *\n * Uses optimized TypeScript implementation by default because it's faster\n * than N-API for single-string extraction (no FFI overhead).\n *\n * For batch file operations, use the Scanner class which leverages\n * Rust's parallel file walking.\n */\nexport function extractCandidates(content: string): string[] {\n if (ENABLE_EXTRACT_CACHE && content.length <= EXTRACT_CACHE_MAX_LEN) {\n const key = getExtractCacheKey(content);\n const cached = getCachedExtractByKey(key);\n if (cached) {\n return cached.slice();\n }\n const result = extractCandidatesImpl(content);\n setCachedExtractByKey(key, result.slice());\n return result;\n }\n const result = extractCandidatesImpl(content);\n return result;\n}\n\n/**\n * Extract candidates without using the module-level cache.\n * Useful for benchmarks and correctness comparisons.\n */\nexport function extractCandidatesUncached(content: string): string[] {\n return extractCandidatesImpl(content);\n}\n\n/**\n * Extract candidates using the native Rust implementation.\n * Useful for testing/benchmarking. For production, use extractCandidates().\n */\nexport function extractCandidatesNative(content: string): string[] {\n const native = tryLoadNative();\n if (native) {\n return native.extractCandidates(content);\n }\n return extractCandidatesFast(content);\n}\n\n/**\n * Clear the module-level extract cache.\n * Useful for benchmarks that need cold-start behavior.\n */\nexport function clearExtractCache(): void {\n extractCache.clear();\n}\n\n/**\n * Clear the module-level scan cache.\n * Useful for benchmarks that need cold-start behavior.\n */\nexport function clearScanCache(): void {\n scanCache.clear();\n}\n\n// ============================================\n// Batch Extraction API\n// ============================================\n\n/**\n * Batch extract candidates from multiple content strings.\n *\n * This is more efficient than calling extractCandidates for each string\n * separately when using the native module because it amortizes the N-API\n * overhead and processes all strings in parallel using Rayon.\n *\n * Falls back to sequential TypeScript extraction when native is unavailable.\n *\n * @param contents - Array of content strings to extract from\n * @returns Array of candidate arrays, one per input\n */\nexport function extractCandidatesBatch(contents: string[]): string[][] {\n if (contents.length === 0) {\n return [];\n }\n if (contents.length === 1) {\n return [extractCandidates(contents[0]!)];\n }\n\n const native = tryLoadNative();\n if (native?.extractCandidatesBatch) {\n return native.extractCandidatesBatch(contents);\n }\n\n // Fallback: sequential TypeScript extraction\n return contents.map((content) => extractCandidates(content));\n}\n\n/**\n * Batch extract candidates from multiple content strings, returning\n * a flattened unique set of all candidates across all inputs.\n *\n * This is useful when you don't need per-file results and just want\n * the combined candidate set for compilation.\n *\n * Uses native parallel extraction when available.\n *\n * @param contents - Array of content strings to extract from\n * @returns Sorted array of unique candidates from all inputs\n */\nexport function extractCandidatesBatchCombined(contents: string[]): string[] {\n if (contents.length === 0) {\n return [];\n }\n if (contents.length === 1) {\n return extractCandidates(contents[0]!);\n }\n\n const native = tryLoadNative();\n if (native?.extractCandidatesBatchCombined) {\n return native.extractCandidatesBatchCombined(contents);\n }\n\n // Fallback: collect and dedupe manually\n const seen = new Set<string>();\n for (const content of contents) {\n for (const candidate of extractCandidates(content)) {\n seen.add(candidate);\n }\n }\n return Array.from(seen).sort();\n}\n\n// ============================================\n// TypeScript Scanner (Fallback)\n// ============================================\n\nclass TsScanner {\n private sources: ScannerSource[];\n private scannedFiles: Set<string> = new Set();\n private seenCandidates: Set<string> = new Set(); // Track all seen candidates for incremental builds\n\n constructor(options: ScannerOptions) {\n this.sources = options.sources;\n }\n\n /**\n * Scan all sources and return candidate class names.\n * Clears state for full re-scan (matches Rust Scanner behavior).\n */\n scan(): string[] {\n // Clear for full re-scan (matches Rust behavior)\n this.scannedFiles.clear();\n this.seenCandidates.clear();\n const results: string[] = [];\n\n for (const source of this.sources) {\n if (source.negated) continue;\n\n const files = this.resolveGlob(source.base, source.pattern);\n\n for (const file of files) {\n this.scannedFiles.add(file);\n\n try {\n const content = readFileContent(file);\n const extracted = extractCandidatesFast(content);\n\n for (const candidate of extracted) {\n if (!this.seenCandidates.has(candidate)) {\n this.seenCandidates.add(candidate);\n results.push(candidate);\n }\n }\n } catch (error) {\n if (LOG_SCAN_ERRORS) {\n logOnce(`scan-read:${file}`, `[rainbowindex] Failed to read source file: ${file}`, error);\n }\n // Skip files that can't be read\n }\n }\n }\n return results;\n }\n\n /**\n * Scan all sources and return candidates plus per-file candidates.\n */\n scanWithFiles(): ScanWithFilesResult {\n // Clear for full re-scan (matches Rust behavior)\n this.scannedFiles.clear();\n this.seenCandidates.clear();\n\n const files: { file: string; candidates: string[] }[] = [];\n const candidates: string[] = [];\n\n for (const source of this.sources) {\n if (source.negated) continue;\n\n const resolvedFiles = this.resolveGlob(source.base, source.pattern);\n\n for (const file of resolvedFiles) {\n this.scannedFiles.add(file);\n\n try {\n const content = readFileContent(file);\n const extracted = extractCandidatesFast(content);\n const unique = new Set<string>();\n\n for (const candidate of extracted) {\n unique.add(candidate);\n if (!this.seenCandidates.has(candidate)) {\n this.seenCandidates.add(candidate);\n candidates.push(candidate);\n }\n }\n\n files.push({ file, candidates: Array.from(unique) });\n } catch (error) {\n if (LOG_SCAN_ERRORS) {\n logOnce(`scan-read:${file}`, `[rainbowindex] Failed to read source file: ${file}`, error);\n }\n // Skip files that can't be read\n }\n }\n }\n\n return { candidates, files };\n }\n\n /**\n * Get list of scanned files.\n */\n get files(): string[] {\n return Array.from(this.scannedFiles);\n }\n\n /**\n * Get list of scanned globs.\n */\n get globs(): ScannerSource[] {\n return this.sources.filter((s) => !s.negated);\n }\n\n /**\n * Rescan a single file and return only NEW candidates.\n * Matches Rust Scanner behavior for incremental builds.\n */\n rescanFile(filePath: string): string[] {\n const newCandidates: string[] = [];\n\n try {\n const content = readFileContent(filePath);\n const extracted = extractCandidatesFast(content);\n\n for (const candidate of extracted) {\n // Only return if not already seen\n if (!this.seenCandidates.has(candidate)) {\n this.seenCandidates.add(candidate);\n newCandidates.push(candidate);\n }\n }\n } catch (error) {\n if (LOG_SCAN_ERRORS) {\n logOnce(`scan-read:${filePath}`, `[rainbowindex] Failed to read source file: ${filePath}`, error);\n }\n // Skip files that can't be read\n }\n\n return newCandidates;\n }\n\n /**\n * Clear all tracked state (useful for testing or forced re-scan).\n */\n reset(): void {\n this.scannedFiles.clear();\n this.seenCandidates.clear();\n }\n\n /**\n * Resolve a glob pattern to file paths (TypeScript fallback).\n *\n * Note: The fallback scanner only supports simple glob semantics. It\n * walks the base directory and filters by known extensions, then applies\n * lightweight matching for patterns like `** / *.tsx` or `*.{ts,tsx}`.\n * This keeps the fallback small and predictable.\n *\n * Security note: The scanner only extracts text that looks like CSS class\n * names from files. It does not expose file contents directly. The base\n * path comes from @source directives in CSS files which are typically\n * authored by the project developer. Path normalization is applied to\n * prevent accidental traversal outside expected directories.\n */\n private resolveGlob(base: string, pattern: string): string[] {\n const files: string[] = [];\n\n // Normalize the base path to prevent traversal issues\n const normalizedBase = path.resolve(base);\n\n // Simple implementation - walk directory and match extensions\n // A production implementation would use a proper glob library\n const extensions = [\n \".html\",\n \".htm\",\n \".jsx\",\n \".tsx\",\n \".js\",\n \".ts\",\n \".mjs\",\n \".mts\",\n \".vue\",\n \".svelte\",\n \".astro\",\n \".md\",\n \".mdx\",\n \".markdown\",\n \".json\",\n \".jsonc\",\n \".rs\",\n \".rb\",\n \".php\",\n \".erb\",\n \".haml\",\n \".slim\",\n \".pug\",\n \".twig\",\n \".liquid\",\n \".clj\",\n \".cljs\",\n \".cljc\",\n \".ex\",\n \".exs\",\n \".eex\",\n \".heex\",\n \".leex\",\n \".cshtml\",\n \".razor\",\n ];\n\n const normalizedPattern = pattern && pattern.length > 0 ? pattern : \"**/*\";\n\n const walkDir = (dir: string, ignoreState: GitIgnoreState) => {\n const currentIgnoreState = buildGitIgnoreState(normalizedBase, dir, ignoreState.patterns);\n const matcher = currentIgnoreState.matcher;\n try {\n const entries = fs.readdirSync(dir, { withFileTypes: true });\n\n for (const entry of entries) {\n const fullPath = path.join(dir, entry.name);\n const relative = path.relative(normalizedBase, fullPath);\n if (relative.startsWith(\"..\") || path.isAbsolute(relative)) {\n continue;\n }\n const relPosix = toPosixPath(relative);\n\n if (entry.isDirectory()) {\n // Skip node_modules and hidden directories\n if (entry.name !== \"node_modules\" && !entry.name.startsWith(\".\")) {\n if (!matcher.ignores(`${relPosix}/`)) {\n walkDir(fullPath, currentIgnoreState);\n }\n }\n } else if (entry.isFile()) {\n if (matcher.ignores(relPosix)) {\n continue;\n }\n const ext = path.extname(entry.name);\n const hasSpecialExt = entry.name.endsWith(\".blade.php\");\n if (\n (extensions.includes(ext) || hasSpecialExt) &&\n matchesSourcePattern(fullPath, normalizedBase, normalizedPattern)\n ) {\n files.push(fullPath);\n }\n }\n }\n } catch (error) {\n if (LOG_SCAN_ERRORS) {\n logOnce(`scan-dir:${dir}`, `[rainbowindex] Failed to read directory: ${dir}`, error);\n }\n // Skip directories that can't be read\n }\n };\n\n const rootIgnoreState = buildGitIgnoreState(normalizedBase, normalizedBase, []);\n walkDir(normalizedBase, rootIgnoreState);\n return files;\n }\n}\n\n// ============================================\n// Unified Scanner Class\n// ============================================\n\n/**\n * Scanner that uses native Rust bindings when available,\n * falls back to TypeScript implementation otherwise.\n */\nexport class Scanner {\n private impl: TsScanner | NativeScanner;\n private sources: ScannerSource[];\n private useNative: boolean;\n private tsFallback: TsScanner | null = null;\n private cachedCandidates: string[] | null = null;\n private cachedMtimes: Map<string, number> | null = null;\n private fastScan: (() => string[]) | null = null;\n\n constructor(options: ScannerOptions) {\n this.sources = options.sources;\n const native = tryLoadNative();\n\n if (native) {\n this.useNative = true;\n this.impl = new native.Scanner({\n sources: options.sources.map((s) => ({\n base: s.base,\n pattern: s.pattern,\n negated: s.negated,\n })),\n });\n } else {\n this.useNative = false;\n this.impl = new TsScanner(options);\n }\n }\n\n /**\n * Scan all sources and return candidate class names.\n */\n scan(): string[] {\n if (this.fastScan) {\n return this.fastScan();\n }\n const cacheKey = ENABLE_GLOBAL_SCAN_CACHE ? getScanCacheKey(this.sources) : null;\n if (cacheKey) {\n const cached = getGlobalScanCache(cacheKey);\n if (cached) {\n this.cachedCandidates = cached.candidates;\n this.cachedMtimes = cached.mtimes;\n if (!ENABLE_SCAN_MTIME && !VERIFY_SCAN_CACHE) {\n this.fastScan = () => (this.cachedCandidates ? this.cachedCandidates.slice() : []);\n }\n return cached.candidates.slice();\n }\n }\n if (this.cachedCandidates) {\n if (!ENABLE_SCAN_MTIME && !VERIFY_SCAN_CACHE) {\n return this.cachedCandidates.slice();\n }\n if (this.isCacheValid()) {\n return this.cachedCandidates.slice();\n }\n }\n\n if (this.useNative) {\n const nativeImpl = this.impl as NativeScanner;\n const candidates = nativeImpl.scan();\n const nativeFiles = getNativeFilesSafe(nativeImpl);\n const scanErrors = getNativeScanErrorsSafe(nativeImpl);\n if (scanErrors.length > 0) {\n logOnce(\"native-scan-errors\", `[rainbowindex] Native scan reported errors:\\n${scanErrors.join(\"\\n\")}`);\n }\n\n // If native returns nothing and no files, fall back to TS scanner\n if (candidates.length === 0 && nativeFiles.length === 0) {\n if (scanErrors.length > 0) {\n throw new Error(`Native scan failed with errors:\\n${scanErrors.join(\"\\n\")}`);\n }\n const tsImpl = this.getTsFallback();\n this.impl = tsImpl;\n this.useNative = false;\n this.invalidateCache();\n const fallback = tsImpl.scan();\n this.updateCache(fallback);\n return fallback;\n }\n\n return this.finalizeScan(candidates, cacheKey);\n }\n\n const candidates = (this.impl as TsScanner).scan();\n return this.finalizeScan(candidates, cacheKey);\n }\n\n private finalizeScan(candidates: string[], cacheKey: string | null): string[] {\n this.updateCache(candidates);\n if (cacheKey) {\n setGlobalScanCache(cacheKey, candidates, this.cachedMtimes);\n }\n if (!VERIFY_SCAN_CACHE && !ENABLE_SCAN_MTIME) {\n this.fastScan = () => (this.cachedCandidates ? this.cachedCandidates.slice() : []);\n }\n return candidates;\n }\n\n /**\n * Scan all sources and return candidates plus per-file candidates.\n */\n scanWithFiles(): ScanWithFilesResult {\n this.invalidateCache();\n\n if (this.useNative) {\n const nativeImpl = this.impl as NativeScanner;\n if (typeof nativeImpl.scanWithFiles === \"function\") {\n const result = nativeImpl.scanWithFiles();\n const scanErrors = getNativeScanErrorsSafe(nativeImpl);\n if (scanErrors.length > 0) {\n logOnce(\n \"native-scan-errors\",\n `[rainbowindex] Native scan reported errors:\\n${scanErrors.join(\"\\n\")}`\n );\n }\n if (result.candidates.length === 0 && result.files.length === 0) {\n if (scanErrors.length > 0) {\n throw new Error(`Native scan failed with errors:\\n${scanErrors.join(\"\\n\")}`);\n }\n const tsImpl = this.getTsFallback();\n this.impl = tsImpl;\n this.useNative = false;\n return tsImpl.scanWithFiles();\n }\n this.updateCache(result.candidates);\n return result;\n }\n const tsImpl = this.getTsFallback();\n this.impl = tsImpl;\n this.useNative = false;\n const result = tsImpl.scanWithFiles();\n this.updateCache(result.candidates);\n return result;\n }\n\n const result = (this.impl as TsScanner).scanWithFiles();\n this.updateCache(result.candidates);\n return result;\n }\n\n /**\n * Get list of scanned files.\n */\n get files(): string[] {\n if (this.useNative) {\n return getNativeFilesSafe(this.impl as NativeScanner);\n }\n return (this.impl as TsScanner).files;\n }\n\n /**\n * Get list of scanned globs.\n */\n get globs(): ScannerSource[] {\n return this.sources.filter((s) => !s.negated);\n }\n\n /**\n * Rescan a single file (for watch mode).\n * Returns only NEW candidates not seen before.\n */\n rescanFile(filePath: string): string[] {\n this.invalidateCache();\n if (this.useNative) {\n return (this.impl as NativeScanner).rescanFile(filePath);\n }\n // TypeScript fallback: use TsScanner's incremental rescan\n return (this.impl as TsScanner).rescanFile(filePath);\n }\n\n /**\n * Reset scanner state for fresh scan.\n */\n reset(): void {\n this.invalidateCache();\n if (this.useNative) {\n const nativeImpl = this.impl as NativeScanner;\n if (typeof nativeImpl.reset === \"function\") {\n nativeImpl.reset();\n }\n return;\n }\n (this.impl as TsScanner).reset();\n }\n\n /**\n * Check if using native implementation.\n */\n get isNative(): boolean {\n return this.useNative;\n }\n\n private invalidateCache(): void {\n this.cachedCandidates = null;\n this.cachedMtimes = null;\n this.fastScan = null;\n }\n\n private isCacheValid(): boolean {\n if (!this.cachedCandidates) return false;\n if (!ENABLE_SCAN_MTIME && !VERIFY_SCAN_CACHE) return true;\n if (!this.cachedMtimes) return false;\n for (const [file, mtime] of this.cachedMtimes) {\n try {\n const current = fs.statSync(file).mtimeMs;\n if (current !== mtime) {\n return false;\n }\n } catch (error) {\n if (LOG_SCAN_ERRORS) {\n logOnce(`scan-stat:${file}`, `[rainbowindex] Failed to stat source file: ${file}`, error);\n }\n return false;\n }\n }\n return true;\n }\n\n private updateCache(candidates: string[]): void {\n if (!ENABLE_SCAN_MTIME && !VERIFY_SCAN_CACHE) {\n this.cachedCandidates = candidates;\n this.cachedMtimes = null;\n return;\n }\n const mtimes = new Map<string, number>();\n for (const file of this.files) {\n try {\n mtimes.set(file, fs.statSync(file).mtimeMs);\n } catch (error) {\n if (LOG_SCAN_ERRORS) {\n logOnce(`scan-stat:${file}`, `[rainbowindex] Failed to stat source file: ${file}`, error);\n }\n // Ignore unreadable files\n }\n }\n this.cachedCandidates = candidates;\n this.cachedMtimes = mtimes;\n }\n\n private getTsFallback(): TsScanner {\n if (!this.tsFallback) {\n this.tsFallback = new TsScanner({ sources: this.sources });\n }\n return this.tsFallback;\n }\n}\n\nfunction getNativeFilesSafe(nativeImpl: NativeScanner): string[] {\n const filesValue = (nativeImpl as unknown as { files?: (() => string[]) | string[] }).files;\n if (typeof filesValue === \"function\") {\n return filesValue.call(nativeImpl);\n }\n if (Array.isArray(filesValue)) {\n return filesValue;\n }\n return [];\n}\n\nfunction getNativeScanErrorsSafe(nativeImpl: NativeScanner): string[] {\n const errorsValue = (nativeImpl as unknown as { scanErrors?: (() => string[]) | string[] }).scanErrors;\n if (typeof errorsValue === \"function\") {\n return errorsValue.call(nativeImpl);\n }\n if (Array.isArray(errorsValue)) {\n return errorsValue;\n }\n return [];\n}\n\n// ============================================\n// Candidate Parser Functions\n// ============================================\n\n/**\n * Parse a candidate string into structured data using native Rust parser.\n * Returns null if the input is not a valid candidate.\n */\nexport function parseCandidate(input: string): Candidate | null {\n const cached = getCachedParse(parseCandidateCache, input);\n if (cached !== undefined) {\n return cached;\n }\n const native = tryLoadNative();\n if (native) {\n const result = native.parseCandidate(input);\n setCachedParse(parseCandidateCache, input, result);\n return result;\n }\n // Native module required for parsing\n throw new Error(\"Native module not available. parseCandidate requires the native Rust parser.\");\n}\n\n/**\n * Parse a candidate string using the loaded utility set for accurate root matching.\n * Requires loadUtilitySet to be called first.\n */\nexport function parseCandidateWithUtilitySet(input: string): Candidate | null {\n const cached = getCachedParse(parseCandidateWithUtilitySetCache, input);\n if (cached !== undefined) {\n return cached;\n }\n const native = tryLoadNative();\n if (native && typeof native.parseCandidateWithUtilitySet === \"function\") {\n const result = native.parseCandidateWithUtilitySet(input);\n setCachedParse(parseCandidateWithUtilitySetCache, input, result);\n return result;\n }\n throw new Error(\"Native module not available. parseCandidateWithUtilitySet requires the native Rust parser.\");\n}\n\n/**\n * Parse multiple candidate strings in a batch.\n * More efficient than calling parseCandidate multiple times.\n */\nexport function parseCandidatesBatch(inputs: string[]): (Candidate | null)[] {\n let allCached = true;\n const cachedResults: (Candidate | null)[] = new Array(inputs.length);\n for (let i = 0; i < inputs.length; i++) {\n const cached = getCachedParse(parseCandidateCache, inputs[i]!);\n if (cached === undefined) {\n allCached = false;\n break;\n }\n cachedResults[i] = cached;\n }\n if (allCached) {\n return cachedResults;\n }\n\n const native = tryLoadNative();\n if (native) {\n const result = native.parseCandidatesBatchSequential(inputs);\n for (let i = 0; i < inputs.length; i++) {\n setCachedParse(parseCandidateCache, inputs[i]!, result[i] ?? null);\n }\n return result;\n }\n // Native module required for parsing\n throw new Error(\"Native module not available. parseCandidatesBatch requires the native Rust parser.\");\n}\n\n/**\n * Parse multiple candidate strings sequentially using the loaded utility set.\n * Requires loadUtilitySet to be called first.\n */\nexport function parseCandidatesBatchWithUtilitySet(inputs: string[]): (Candidate | null)[] {\n let allCached = true;\n const cachedResults: (Candidate | null)[] = new Array(inputs.length);\n for (let i = 0; i < inputs.length; i++) {\n const cached = getCachedParse(parseCandidateWithUtilitySetCache, inputs[i]!);\n if (cached === undefined) {\n allCached = false;\n break;\n }\n cachedResults[i] = cached;\n }\n if (allCached) {\n return cachedResults;\n }\n\n const native = tryLoadNative();\n if (native && typeof native.parseCandidatesBatchSequentialWithUtilitySet === \"function\") {\n const result = native.parseCandidatesBatchSequentialWithUtilitySet(inputs);\n for (let i = 0; i < inputs.length; i++) {\n setCachedParse(parseCandidateWithUtilitySetCache, inputs[i]!, result[i] ?? null);\n }\n return result;\n }\n throw new Error(\"Native module not available. parseCandidatesBatchWithUtilitySet requires the native Rust parser.\");\n}\n\n/**\n * Check if the native candidate parser is available.\n */\nexport function isParserAvailable(): boolean {\n const native = tryLoadNative();\n return native !== null && typeof native.parseCandidate === \"function\";\n}\n\n/**\n * Check if the native candidate parser is available.\n * Alias for isParserAvailable for consistency with CSS parser naming.\n */\nexport function isCandidateParserAvailable(): boolean {\n return isParserAvailable();\n}\n\n// ============================================\n// Native Utility Set for findRoot\n// ============================================\n\n/**\n * Load a set of utility names into the native module for findRoot lookups.\n * This should be called once when the design system is created.\n *\n * @param utilities - Array of utility names to load\n */\nexport function loadUtilitySet(utilities: string[]): void {\n const native = tryLoadNative();\n if (native && typeof native.loadUtilitySet === \"function\") {\n native.loadUtilitySet(utilities);\n parseCandidateWithUtilitySetCache.clear();\n }\n}\n\n/**\n * Clear the loaded utility set from the native module.\n */\nexport function clearUtilitySet(): void {\n const native = tryLoadNative();\n if (native && typeof native.clearUtilitySet === \"function\") {\n native.clearUtilitySet();\n parseCandidateWithUtilitySetCache.clear();\n }\n}\n\n/**\n * Check if the utility set has been loaded into the native module.\n */\nexport function isUtilitySetLoaded(): boolean {\n const native = tryLoadNative();\n if (native && typeof native.isUtilitySetLoaded === \"function\") {\n return native.isUtilitySetLoaded();\n }\n return false;\n}\n\n/**\n * Find the longest matching utility root using the native module.\n * Requires loadUtilitySet to be called first.\n *\n * @param input - The utility base string (e.g., \"bg-red-500\")\n * @returns [root, value] tuple if found, null otherwise\n */\nexport function findRootNative(input: string): [string, string] | null {\n const native = tryLoadNative();\n if (native && typeof native.findRoot === \"function\") {\n const result = native.findRoot(input);\n if (result && result.length === 2 && result[0] !== undefined && result[1] !== undefined) {\n return [result[0], result[1]];\n }\n }\n return null;\n}\n\n// ============================================\n// Utility Compilation Functions\n// ============================================\n\n/**\n * Compile a candidate string to CSS AST nodes using native Rust compiler.\n * Returns null if the candidate is invalid or compilation fails.\n */\nexport function compileCandidateString(input: string, theme?: Theme): AstNode[] | null {\n const native = tryLoadNative();\n if (native) {\n return native.compileCandidateString(input, theme);\n }\n throw new Error(\"Native module not available. compileCandidateString requires the native Rust compiler.\");\n}\n\n/**\n * Compile multiple candidate strings to CSS AST nodes.\n * More efficient than calling compileCandidateString multiple times.\n */\nexport function compileCandidatesBatch(inputs: string[], theme?: Theme): (AstNode[] | null)[] {\n const native = tryLoadNative();\n if (native) {\n return native.compileCandidatesBatch(inputs, theme);\n }\n throw new Error(\"Native module not available. compileCandidatesBatch requires the native Rust compiler.\");\n}\n\n/**\n * Compile a parsed candidate to CSS AST nodes.\n */\nexport function compileCandidate(candidate: Candidate, theme?: Theme): AstNode[] | null {\n const native = tryLoadNative();\n if (native) {\n return native.compileCandidate(candidate, theme);\n }\n throw new Error(\"Native module not available. compileCandidate requires the native Rust compiler.\");\n}\n\n/**\n * Check if a utility exists in the native registry.\n */\nexport function hasUtility(name: string): boolean {\n const native = tryLoadNative();\n if (native) {\n return native.hasUtility(name);\n }\n return false;\n}\n\n/**\n * Check if a variant exists in the native registry.\n */\nexport function hasVariant(name: string): boolean {\n const native = tryLoadNative();\n if (native) {\n return native.hasVariant(name);\n }\n return false;\n}\n\n/**\n * Check if the native utility compiler is available.\n */\nexport function isCompilerAvailable(): boolean {\n const native = tryLoadNative();\n return native !== null && typeof native.compileCandidateString === \"function\";\n}\n\n// ============================================\n// CSS Printing Functions\n// ============================================\n\n/**\n * Convert CSS AST nodes to CSS string with options.\n * Uses native Rust printer for high performance.\n */\nexport function toCss(nodes: AstNode[], options?: PrintOptions): string {\n const native = tryLoadNative();\n if (native) {\n return native.toCss(nodes, options);\n }\n throw new Error(\"Native module not available. toCss requires the native Rust printer.\");\n}\n\n/**\n * Convert CSS AST nodes to minified CSS string.\n * Optimized for smallest output size.\n */\nexport function toCssMinified(nodes: AstNode[]): string {\n const native = tryLoadNative();\n if (native) {\n return native.toCssMinified(nodes);\n }\n throw new Error(\"Native module not available. toCssMinified requires the native Rust printer.\");\n}\n\n/**\n * Convert CSS AST nodes to pretty-printed CSS string.\n */\nexport function toCssPretty(nodes: AstNode[], indent?: \"2space\" | \"4space\" | \"tab\"): string {\n const native = tryLoadNative();\n if (native) {\n return native.toCssPretty(nodes, indent);\n }\n throw new Error(\"Native module not available. toCssPretty requires the native Rust printer.\");\n}\n\n/**\n * Compile candidates directly to CSS string (parse + compile + print in one call).\n * Most efficient way to generate CSS from candidate strings.\n */\nexport function compileToCss(inputs: string[], theme?: Theme, options?: PrintOptions): string {\n const native = tryLoadNative();\n if (native) {\n return native.compileToCss(inputs, theme, options);\n }\n throw new Error(\"Native module not available. compileToCss requires the native Rust printer.\");\n}\n\n/**\n * Check if the native CSS printer is available.\n */\nexport function isPrinterAvailable(): boolean {\n const native = tryLoadNative();\n return native !== null && typeof native.toCss === \"function\";\n}\n\n// ============================================\n// CSS Parser Functions\n// ============================================\n\n/**\n * Parse CSS string into AST using native Rust parser.\n * This is significantly faster (3-10x) than the TypeScript parser.\n *\n * @param input CSS source string\n * @returns Parse result with AST and license comments\n */\nexport function parseCss(input: string): CssParseResult {\n const native = tryLoadNative();\n if (native && native.parseCss) {\n return native.parseCss(input);\n }\n throw new Error(\"Native module not available. parseCss requires the native Rust parser.\");\n}\n\nexport function setCssParserTimings(enabled: boolean): void {\n const native = tryLoadNative();\n if (native && native.setCssParserTimings) {\n native.setCssParserTimings(enabled);\n return;\n }\n throw new Error(\"Native module not available. setCssParserTimings requires the native Rust parser.\");\n}\n\n/**\n * Check if the native CSS parser is available.\n */\nexport function isCssParserAvailable(): boolean {\n const native = tryLoadNative();\n return native !== null && typeof native.parseCss === \"function\";\n}\n","/**\n * High-performance CSS utility class extractor\n *\n * This module provides multiple extraction strategies optimized for different use cases.\n *\n * ## Recommended Extractor\n *\n * - `extractCandidatesFast` (RECOMMENDED): Most feature-complete extractor.\n * Handles class, className, template literals, and helper functions\n * (clsx, cn, classNames, twMerge, cva). Best for React/Vue projects.\n *\n * ## Optimizations\n *\n * 1. indexOf-based scanning for fast pattern matching\n * 2. Minimal string allocations with Set-based deduplication\n * 3. Inline character code validation for speed\n */\n\nconst HELPER_PATTERNS = [\n { needle: \"clsx(\", type: \"clsx\", len: 5 },\n { needle: \"cn(\", type: \"cn\", len: 3 },\n { needle: \"classNames(\", type: \"classNames\", len: 11 },\n { needle: \"twMerge(\", type: \"twMerge\", len: 8 },\n { needle: \"cva(\", type: \"cva\", len: 4 },\n] as const;\n\n// Whitespace set for fast lookup\nconst WHITESPACE = new Set([\" \", \"\\t\", \"\\n\", \"\\r\"]);\n\n/**\n * Check if a character code is valid for starting a utility class.\n * Valid: a-z, A-Z, 0-9, -, @\n */\nfunction isValidStartChar(charCode: number): boolean {\n return (\n (charCode >= 97 && charCode <= 122) || // a-z\n (charCode >= 65 && charCode <= 90) || // A-Z\n (charCode >= 48 && charCode <= 57) || // 0-9\n charCode === 45 || // -\n charCode === 64 || // @\n charCode === 91 // [\n );\n}\n\n/**\n * Check if a character code is valid within a utility class.\n * Valid: a-z, A-Z, 0-9, -, _, :, /, ., [, ], (, ), %, #, @, !\n */\nfunction isValidUtilityChar(charCode: number): boolean {\n if (charCode > 127) return true;\n return (\n (charCode >= 97 && charCode <= 122) || // a-z\n (charCode >= 65 && charCode <= 90) || // A-Z\n (charCode >= 48 && charCode <= 57) || // 0-9\n charCode === 45 || // -\n charCode === 95 || // _\n charCode === 58 || // :\n charCode === 47 || // /\n charCode === 46 || // .\n charCode === 91 || // [\n charCode === 93 || // ]\n charCode === 40 || // (\n charCode === 41 || // )\n charCode === 37 || // %\n charCode === 35 || // #\n charCode === 64 || // @\n charCode === 33 || // !\n charCode === 38 || // &\n charCode === 92 || // \\\n charCode === 39 || // '\n charCode === 34 || // \"\n charCode === 96 // `\n );\n}\n\nfunction hasBalancedDelimiters(str: string): boolean {\n const stack: string[] = [];\n let quote: string | null = null;\n\n for (let i = 0; i < str.length; i += 1) {\n const ch = str[i]!;\n\n if (quote) {\n if (ch === \"\\\\\" && i + 1 < str.length) {\n i += 1;\n continue;\n }\n if (ch === quote) {\n quote = null;\n }\n continue;\n }\n\n if (ch === \"'\" || ch === '\"' || ch === \"`\") {\n quote = ch;\n continue;\n }\n\n if (ch === \"\\\\\" && i + 1 < str.length) {\n i += 1;\n continue;\n }\n\n if (ch === \"[\" || ch === \"(\" || ch === \"{\") {\n stack.push(ch === \"[\" ? \"]\" : ch === \"(\" ? \")\" : \"}\");\n continue;\n }\n\n if (ch === \"]\" || ch === \")\" || ch === \"}\") {\n if (stack.pop() !== ch) return false;\n }\n }\n\n return stack.length === 0 && quote === null;\n}\n\n/**\n * RECOMMENDED: Fast single-pass candidate extraction.\n *\n * This is the most feature-complete extractor, supporting:\n * - `class=\"...\"` and `className=\"...\"` attributes\n * - Template literals: `className={\\`...\\`}`\n * - Helper functions: clsx(), cn(), classNames(), twMerge(), cva()\n *\n * Uses indexOf-based scanning which is significantly faster than regex\n * for large files, while still handling nested parentheses correctly.\n *\n * @param content - The source code to extract candidates from\n * @returns Array of unique CSS utility class candidates\n */\nexport function extractCandidatesFast(content: string): string[] {\n const len = content.length;\n if (len === 0) return [];\n\n // Pre-allocate with capacity hint (rough estimate: 1 class per 100 chars)\n const candidates: string[] = [];\n const seen = new Set<string>();\n\n let i = 0;\n\n while (i < len) {\n // Fast skip to next potential match\n const nextClass = content.indexOf(\"class\", i);\n const hasClass = nextClass !== -1;\n\n // Find the earliest match\n let earliest = hasClass ? nextClass : len;\n let matchType: \"class\" | \"clsx\" | \"cn\" | \"classNames\" | \"twMerge\" | \"cva\" | null = hasClass ? \"class\" : null;\n let helperLen = 0;\n\n for (const helper of HELPER_PATTERNS) {\n const idx = content.indexOf(helper.needle, i);\n if (idx !== -1 && idx <= earliest) {\n earliest = idx;\n matchType = helper.type;\n helperLen = helper.len;\n }\n }\n\n if (matchType === null) break;\n\n i = earliest;\n\n if (matchType === \"class\") {\n // Handle class=\"...\" or className=\"...\" or className={`...`}\n const afterClass = i + 5; // \"class\".length\n\n if (afterClass >= len) break;\n\n // Check for className vs class\n let attrEnd: number;\n if (content[afterClass] === \"N\" && content.substring(afterClass, afterClass + 5) === \"Name=\") {\n attrEnd = afterClass + 5;\n } else if (content[afterClass] === \"=\") {\n attrEnd = afterClass + 1;\n } else {\n i = afterClass;\n continue;\n }\n\n if (attrEnd >= len) break;\n\n const quoteChar = content[attrEnd];\n\n if (quoteChar === '\"' || quoteChar === \"'\") {\n // class=\"...\" or className=\"...\"\n const closeQuote = content.indexOf(quoteChar, attrEnd + 1);\n if (closeQuote === -1) {\n i = attrEnd + 1;\n continue;\n }\n\n const classValue = content.substring(attrEnd + 1, closeQuote);\n extractClassesFromString(classValue, candidates, seen);\n i = closeQuote + 1;\n } else if (quoteChar === \"{\" && content[attrEnd + 1] === \"`\") {\n // className={`...`}\n const closeBacktick = content.indexOf(\"`\", attrEnd + 2);\n if (closeBacktick === -1) {\n i = attrEnd + 2;\n continue;\n }\n\n const templateValue = content.substring(attrEnd + 2, closeBacktick);\n // Remove ${...} expressions\n const staticParts = templateValue.replace(/\\$\\{[^}]*\\}/g, \" \");\n extractClassesFromString(staticParts, candidates, seen);\n i = closeBacktick + 1;\n } else {\n i = attrEnd + 1;\n }\n } else {\n // Handle clsx(), cn(), classNames(), twMerge(), cva()\n const openParen = i + helperLen - 1; // Position of '('\n\n if (openParen >= len) break;\n\n // Find matching close paren, handling nesting\n let depth = 1;\n let j = openParen + 1;\n\n while (j < len && depth > 0) {\n const char = content[j];\n if (char === \"(\") {\n depth++;\n } else if (char === \")\") {\n depth--;\n } else if ((char === '\"' || char === \"'\") && depth === 1) {\n // Extract string literal\n const closeQuote = content.indexOf(char, j + 1);\n if (closeQuote !== -1) {\n const stringValue = content.substring(j + 1, closeQuote);\n extractClassesFromString(stringValue, candidates, seen);\n j = closeQuote;\n }\n }\n j++;\n }\n\n i = j;\n }\n }\n\n return candidates;\n}\n\n/**\n * Extract individual class names from a string value.\n * Handles whitespace-separated classes.\n */\nfunction extractClassesFromString(value: string, candidates: string[], seen: Set<string>): void {\n const len = value.length;\n let start = 0;\n\n for (let i = 0; i <= len; i++) {\n const isEnd = i === len;\n const isWhitespace = !isEnd && WHITESPACE.has(value[i]!);\n\n if ((isEnd || isWhitespace) && i > start) {\n const token = value.substring(start, i);\n\n // Quick validation: must start with letter, @, -, or digit\n const firstChar = token.charCodeAt(0);\n\n if (isValidStartChar(firstChar) && !seen.has(token) && isLikelyUtility(token)) {\n seen.add(token);\n candidates.push(token);\n }\n }\n\n if (isWhitespace || isEnd) {\n start = i + 1;\n }\n }\n}\n\n/**\n * Fast check if a string looks like a utility class.\n * Uses character code checks instead of regex for speed.\n */\nfunction isLikelyUtility(str: string): boolean {\n const len = str.length;\n if (len === 0 || len > 2048) return false;\n\n const bangIndex = str.indexOf(\"!\");\n if (bangIndex === 0) return false;\n if (bangIndex !== -1 && bangIndex !== len - 1) return false;\n\n // Check for valid characters only\n for (let i = 0; i < len; i++) {\n if (!isValidUtilityChar(str.charCodeAt(i))) {\n return false;\n }\n }\n\n // Exclude obvious non-utilities\n if (str === \"true\" || str === \"false\" || str === \"null\" || str === \"undefined\") {\n return false;\n }\n\n if (\n str.indexOf(\"[\") !== -1 ||\n str.indexOf(\"]\") !== -1 ||\n str.indexOf(\"(\") !== -1 ||\n str.indexOf(\")\") !== -1 ||\n str.indexOf(\"{\") !== -1 ||\n str.indexOf(\"}\") !== -1\n ) {\n if (!hasBalancedDelimiters(str)) {\n return false;\n }\n }\n\n return true;\n}\n","/**\n * Rainbow Index\n *\n * A production-ready CSS compiler with utility-first approach.\n */\n\nexport * from \"./ast\";\nexport * from \"./candidate\";\nexport * from \"./compile\";\nexport * from \"./css-functions\";\nexport * from \"./intellisense\";\nexport * from \"./optimize\";\nexport * from \"./parser\";\nexport * from \"./plugin\";\nexport * from \"./theme\";\nexport * from \"./utilities\";\nexport * from \"./utils\";\nexport * from \"./variants\";\n\n// Feature flags for Lightning CSS integration\nexport const Features = {\n /** Enable CSS nesting transformation */\n Nesting: 1 << 0,\n /** Enable media query transformations */\n MediaQueries: 1 << 1,\n /** Transform logical properties */\n LogicalProperties: 1 << 2,\n /** Transform :dir() selector */\n DirSelector: 1 << 3,\n /** Transform light-dark() function */\n LightDark: 1 << 4,\n /** Transform oklch/oklab colors */\n OklabColors: 1 << 5,\n /** Transform lab/lch colors */\n LabColors: 1 << 6,\n /** Transform display-p3 colors */\n P3Colors: 1 << 7,\n /** Transform color() function */\n ColorFunction: 1 << 8,\n /** No features enabled */\n None: 0,\n /** All features enabled */\n All: (1 << 9) - 1, // All bits up to ColorFunction\n} as const;\n\nexport type FeatureFlags = number;\n\n/** Maximum valid feature flag value (all features enabled) */\nconst MAX_FEATURE_FLAGS = Features.All;\n\n/**\n * Validate that a value is a valid feature flags bitmask.\n * Returns true if the value is a non-negative integer within the valid range.\n */\nexport function isValidFeatureFlags(value: unknown): value is FeatureFlags {\n return typeof value === \"number\" && Number.isInteger(value) && value >= 0 && value <= MAX_FEATURE_FLAGS;\n}\n\n/**\n * Validate feature flags and return a safe value.\n * If the input is invalid, returns Features.None.\n *\n * @param value - The value to validate\n * @returns A valid feature flags value\n */\nexport function validateFeatureFlags(value: unknown): FeatureFlags {\n if (isValidFeatureFlags(value)) {\n return value;\n }\n return Features.None;\n}\n\n/**\n * Check if specific feature flags are enabled in a bitmask.\n *\n * @param flags - The feature flags bitmask\n * @param feature - The feature to check for\n * @returns true if the feature is enabled\n */\nexport function hasFeature(flags: FeatureFlags, feature: FeatureFlags): boolean {\n return (flags & feature) === feature;\n}\n","/**\n * String Interning Pool\n *\n * Reduces memory usage by reusing identical strings across the codebase.\n * Particularly effective for common CSS property names and values.\n *\n * PERFORMANCE: String interning helps V8 optimize property comparisons\n * and reduces GC pressure by avoiding duplicate string allocations.\n */\n\n// String interning pool - maps string content to interned reference\nconst INTERN_POOL = new Map<string, string>();\n\n// Pre-populate with common CSS property names\nconst COMMON_PROPERTIES = [\n // Layout\n \"display\",\n \"position\",\n \"flex\",\n \"grid\",\n \"float\",\n \"clear\",\n \"visibility\",\n \"overflow\",\n \"overflow-x\",\n \"overflow-y\",\n // Flexbox\n \"flex-direction\",\n \"flex-wrap\",\n \"flex-flow\",\n \"flex-grow\",\n \"flex-shrink\",\n \"flex-basis\",\n \"justify-content\",\n \"align-items\",\n \"align-content\",\n \"align-self\",\n \"order\",\n \"gap\",\n \"row-gap\",\n \"column-gap\",\n // Grid\n \"grid-template-columns\",\n \"grid-template-rows\",\n \"grid-column\",\n \"grid-row\",\n \"grid-area\",\n \"grid-auto-flow\",\n \"grid-auto-columns\",\n \"grid-auto-rows\",\n // Box Model\n \"margin\",\n \"margin-top\",\n \"margin-right\",\n \"margin-bottom\",\n \"margin-left\",\n \"padding\",\n \"padding-top\",\n \"padding-right\",\n \"padding-bottom\",\n \"padding-left\",\n \"width\",\n \"min-width\",\n \"max-width\",\n \"height\",\n \"min-height\",\n \"max-height\",\n // Position\n \"top\",\n \"right\",\n \"bottom\",\n \"left\",\n \"inset\",\n \"z-index\",\n // Border\n \"border\",\n \"border-width\",\n \"border-style\",\n \"border-color\",\n \"border-radius\",\n \"border-top\",\n \"border-right\",\n \"border-bottom\",\n \"border-left\",\n \"border-top-left-radius\",\n \"border-top-right-radius\",\n \"border-bottom-left-radius\",\n \"border-bottom-right-radius\",\n // Background\n \"background\",\n \"background-color\",\n \"background-image\",\n \"background-position\",\n \"background-size\",\n \"background-repeat\",\n \"background-attachment\",\n // Typography\n \"color\",\n \"font\",\n \"font-family\",\n \"font-size\",\n \"font-weight\",\n \"font-style\",\n \"line-height\",\n \"letter-spacing\",\n \"text-align\",\n \"text-decoration\",\n \"text-transform\",\n \"text-indent\",\n \"white-space\",\n \"word-break\",\n \"word-spacing\",\n // Effects\n \"opacity\",\n \"box-shadow\",\n \"text-shadow\",\n \"filter\",\n \"backdrop-filter\",\n \"transform\",\n \"transform-origin\",\n \"transition\",\n \"animation\",\n // Cursor & Events\n \"cursor\",\n \"pointer-events\",\n \"user-select\",\n // Content\n \"content\",\n \"list-style\",\n \"list-style-type\",\n] as const;\n\n// Pre-populate with common CSS values\nconst COMMON_VALUES = [\n // Display\n \"none\",\n \"block\",\n \"inline\",\n \"inline-block\",\n \"flex\",\n \"inline-flex\",\n \"grid\",\n \"inline-grid\",\n \"contents\",\n \"flow-root\",\n \"list-item\",\n \"table\",\n // Position\n \"static\",\n \"relative\",\n \"absolute\",\n \"fixed\",\n \"sticky\",\n // Flex\n \"row\",\n \"row-reverse\",\n \"column\",\n \"column-reverse\",\n \"nowrap\",\n \"wrap\",\n \"wrap-reverse\",\n \"flex-start\",\n \"flex-end\",\n \"center\",\n \"space-between\",\n \"space-around\",\n \"space-evenly\",\n \"stretch\",\n \"baseline\",\n // Common values\n \"auto\",\n \"inherit\",\n \"initial\",\n \"unset\",\n \"revert\",\n \"0\",\n \"0px\",\n \"1px\",\n \"100%\",\n \"50%\",\n \"transparent\",\n \"currentColor\",\n \"normal\",\n \"bold\",\n \"italic\",\n \"hidden\",\n \"visible\",\n \"scroll\",\n \"solid\",\n \"dashed\",\n \"dotted\",\n \"left\",\n \"right\",\n \"center\",\n \"justify\",\n \"top\",\n \"bottom\",\n \"middle\",\n \"uppercase\",\n \"lowercase\",\n \"capitalize\",\n \"pointer\",\n \"default\",\n \"not-allowed\",\n] as const;\n\n// Initialize pool with common strings\nfor (const prop of COMMON_PROPERTIES) {\n INTERN_POOL.set(prop, prop);\n}\nfor (const val of COMMON_VALUES) {\n INTERN_POOL.set(val, val);\n}\n\n/**\n * Intern a string to reduce memory usage.\n *\n * If the string is already in the pool, returns the pooled reference.\n * Otherwise, adds short strings (<=32 chars) to the pool.\n *\n * @param str - String to intern\n * @returns Interned string reference\n */\nexport function intern(str: string): string {\n const existing = INTERN_POOL.get(str);\n if (existing !== undefined) return existing;\n\n // Only intern short strings to avoid memory bloat\n if (str.length <= 32) {\n INTERN_POOL.set(str, str);\n }\n return str;\n}\n\n/**\n * Check if a string is interned.\n */\nexport function isInterned(str: string): boolean {\n return INTERN_POOL.has(str);\n}\n\n/**\n * Get the current size of the intern pool.\n * Useful for debugging and memory profiling.\n */\nexport function getInternPoolSize(): number {\n return INTERN_POOL.size;\n}\n\n/**\n * Clear the intern pool (for testing purposes).\n * Re-populates with common strings after clearing.\n */\nexport function clearInternPool(): void {\n INTERN_POOL.clear();\n for (const prop of COMMON_PROPERTIES) {\n INTERN_POOL.set(prop, prop);\n }\n for (const val of COMMON_VALUES) {\n INTERN_POOL.set(val, val);\n }\n}\n","/**\n * Rainbow Index AST Types\n *\n * Defines the Abstract Syntax Tree structure for CSS parsing and generation.\n */\n\nimport { intern } from \"../utils/intern\";\n\n/** Source location tracking for source maps */\nexport interface Source {\n file: string | null;\n code: string;\n}\n\nexport type SourceLocation = [source: Source, start: number, end: number];\n\n/** CSS Style Rule: selector { declarations } */\nexport interface StyleRule {\n kind: \"rule\";\n selector: string;\n nodes: AstNode[];\n src?: SourceLocation;\n dst?: SourceLocation;\n}\n\n/** CSS At-Rule: @name params { nodes } */\nexport interface AtRule {\n kind: \"at-rule\";\n name: string;\n params: string;\n nodes: AstNode[];\n src?: SourceLocation;\n dst?: SourceLocation;\n}\n\n/** CSS Declaration: property: value */\nexport interface Declaration {\n kind: \"declaration\";\n property: string;\n value: string | undefined;\n important: boolean;\n src?: SourceLocation;\n dst?: SourceLocation;\n}\n\n/** CSS Comment */\nexport interface Comment {\n kind: \"comment\";\n value: string;\n src?: SourceLocation;\n dst?: SourceLocation;\n}\n\n/** Internal context node for tracking metadata during compilation */\nexport interface Context {\n kind: \"context\";\n context: Record<string, string | boolean>;\n nodes: AstNode[];\n}\n\n/** At-root node for hoisting content outside current rule */\nexport interface AtRoot {\n kind: \"at-root\";\n nodes: AstNode[];\n}\n\n/** Union of all AST node types */\nexport type AstNode = StyleRule | AtRule | Declaration | Comment | Context | AtRoot;\n\n/** Rule types (nodes that can contain other nodes) */\nexport type Rule = StyleRule | AtRule;\n\n// ============================================\n// AST Construction Helpers\n// ============================================\n\nexport function styleRule(selector: string, nodes: AstNode[] = []): StyleRule {\n return { kind: \"rule\", selector, nodes };\n}\n\nexport function atRule(name: string, params: string = \"\", nodes: AstNode[] = []): AtRule {\n // Normalize @ prefix at construction time (not print time) for performance\n return { kind: \"at-rule\", name: name.charCodeAt(0) === 64 ? name : `@${name}`, params, nodes };\n}\n\nexport function decl(property: string, value: string | undefined, important = false): Declaration {\n // PERFORMANCE: Intern property names to reduce memory usage.\n // Property names are frequently repeated (e.g., \"display\", \"padding\").\n return { kind: \"declaration\", property: intern(property), value, important };\n}\n\nexport function comment(value: string): Comment {\n return { kind: \"comment\", value };\n}\n\nexport function context(ctx: Record<string, string | boolean>, nodes: AstNode[] = []): Context {\n return { kind: \"context\", context: ctx, nodes };\n}\n\nexport function atRoot(nodes: AstNode[] = []): AtRoot {\n return { kind: \"at-root\", nodes };\n}\n\n// ============================================\n// Type Guards\n// ============================================\n\nexport function isStyleRule(node: AstNode): node is StyleRule {\n return node.kind === \"rule\";\n}\n\nexport function isAtRule(node: AstNode): node is AtRule {\n return node.kind === \"at-rule\";\n}\n\nexport function isDeclaration(node: AstNode): node is Declaration {\n return node.kind === \"declaration\";\n}\n\nexport function isComment(node: AstNode): node is Comment {\n return node.kind === \"comment\";\n}\n\nexport function isContext(node: AstNode): node is Context {\n return node.kind === \"context\";\n}\n\nexport function isAtRoot(node: AstNode): node is AtRoot {\n return node.kind === \"at-root\";\n}\n\nexport function isRule(node: AstNode): node is Rule {\n return node.kind === \"rule\" || node.kind === \"at-rule\";\n}\n\n// ============================================\n// AST Cloning (Optimized following tailwindcss pattern)\n// ============================================\n\n/**\n * Clone an AST node efficiently.\n * Uses explicit property assignment instead of spread operators\n * for better V8 optimization (tailwindcss pattern).\n */\nexport function cloneAstNode<T extends AstNode>(node: T): T {\n switch (node.kind) {\n case \"rule\":\n return {\n kind: \"rule\",\n selector: node.selector,\n nodes: node.nodes.map(cloneAstNode),\n src: node.src,\n dst: node.dst,\n } as T;\n\n case \"at-rule\":\n return {\n kind: \"at-rule\",\n name: node.name,\n params: node.params,\n nodes: node.nodes.map(cloneAstNode),\n src: node.src,\n dst: node.dst,\n } as T;\n\n case \"declaration\":\n return {\n kind: \"declaration\",\n property: node.property,\n value: node.value,\n important: node.important,\n src: node.src,\n dst: node.dst,\n } as T;\n\n case \"comment\":\n return {\n kind: \"comment\",\n value: node.value,\n src: node.src,\n dst: node.dst,\n } as T;\n\n case \"context\":\n return {\n kind: \"context\",\n context: { ...node.context },\n nodes: node.nodes.map(cloneAstNode),\n } as T;\n\n case \"at-root\":\n return {\n kind: \"at-root\",\n nodes: node.nodes.map(cloneAstNode),\n } as T;\n\n default:\n node satisfies never;\n throw new Error(`Unknown node kind: ${(node as AstNode).kind}`);\n }\n}\n","/**\n * AST Walking Utilities\n *\n * Provides traversal and transformation capabilities for the CSS AST.\n */\n\nimport type { AstNode, Rule } from \"./types\";\n\n/** Actions that can be returned from walk callbacks */\nexport const WalkAction = {\n /** Continue traversal to children and siblings */\n Continue: Symbol(\"continue\"),\n /** Skip children but continue to siblings */\n Skip: Symbol(\"skip\"),\n /** Stop all traversal */\n Stop: Symbol(\"stop\"),\n} as const;\n\nexport type WalkActionType = (typeof WalkAction)[keyof typeof WalkAction];\n\n/** Replace current node with new nodes */\nexport interface ReplaceAction {\n kind: \"replace\";\n nodes: AstNode[];\n /** If true, skip traversing the replacement nodes */\n skip?: boolean;\n /** If true, stop all traversal after replacement */\n stop?: boolean;\n}\n\nexport type WalkResult = WalkActionType | ReplaceAction | void;\n\n/** Context passed to walk callbacks */\nexport interface WalkContext {\n /** Parent node, or null if at root */\n parent: Rule | null;\n /** Current depth in the tree (0 = root) */\n depth: number;\n /** Index of this node in parent's children */\n index: number;\n /** Get path from root to current node */\n path(): AstNode[];\n}\n\ntype WalkCallback = (node: AstNode, ctx: WalkContext) => WalkResult;\n\n/** Options for walk function */\nexport interface WalkOptions {\n /** Maximum depth to traverse (default: 1000) */\n maxDepth?: number;\n}\n\n/** Default maximum depth to prevent stack overflow */\nconst DEFAULT_MAX_DEPTH = 1000;\n\n/**\n * Error thrown when a cycle is detected in the AST.\n */\nexport class AstCycleError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AstCycleError\";\n }\n}\n\n/**\n * Error thrown when maximum depth is exceeded.\n */\nexport class AstMaxDepthError extends Error {\n constructor(depth: number, maxDepth: number) {\n super(`Maximum AST depth exceeded: ${depth} > ${maxDepth}`);\n this.name = \"AstMaxDepthError\";\n }\n}\n\n/**\n * Walk the AST depth-first, calling the callback for each node.\n * Includes cycle detection and maximum depth limit to prevent stack overflow.\n *\n * @param ast - Root nodes to traverse\n * @param callback - Function called for each node\n * @param options - Walk options (maxDepth)\n * @returns Modified AST (may be mutated in place)\n * @throws {AstCycleError} If a circular reference is detected\n * @throws {AstMaxDepthError} If maximum depth is exceeded\n */\nexport function walk(ast: AstNode[], callback: WalkCallback, options: WalkOptions = {}): AstNode[] {\n const pathStack: AstNode[] = [];\n const visiting = new Set<AstNode>(); // Track nodes in current path for cycle detection\n const maxDepth = options.maxDepth ?? DEFAULT_MAX_DEPTH;\n\n function walkNodes(nodes: AstNode[], parent: Rule | null, depth: number): AstNode[] {\n // Check maximum depth\n if (depth > maxDepth) {\n throw new AstMaxDepthError(depth, maxDepth);\n }\n const result: AstNode[] = [];\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i]!;\n\n // Cycle detection - check if we've already seen this node in current path\n if (visiting.has(node)) {\n throw new AstCycleError(\"Circular reference detected in AST\");\n }\n visiting.add(node);\n pathStack.push(node);\n\n const ctx: WalkContext = {\n parent,\n depth,\n index: i,\n path: () => [...pathStack],\n };\n\n const action = callback(node, ctx);\n\n // Handle replacement action\n if (action && typeof action === \"object\" && action.kind === \"replace\") {\n result.push(...action.nodes);\n visiting.delete(node);\n pathStack.pop();\n\n if (action.stop) {\n return result;\n }\n if (!action.skip) {\n // Walk the replacement nodes\n for (const replacement of action.nodes) {\n if (\"nodes\" in replacement) {\n (replacement as Rule).nodes = walkNodes(\n (replacement as Rule).nodes,\n replacement as Rule,\n depth + 1\n );\n }\n }\n }\n continue;\n }\n\n // Handle stop action\n if (action === WalkAction.Stop) {\n result.push(node);\n visiting.delete(node);\n pathStack.pop();\n return result;\n }\n\n // Add node to result\n result.push(node);\n\n // Handle skip action - don't traverse children\n if (action !== WalkAction.Skip) {\n // Traverse children for rule nodes\n if (\"nodes\" in node && Array.isArray(node.nodes)) {\n const parentRule = node.kind === \"rule\" || node.kind === \"at-rule\" ? node : parent;\n node.nodes = walkNodes(node.nodes, parentRule as Rule, depth + 1);\n }\n }\n\n visiting.delete(node);\n pathStack.pop();\n }\n\n return result;\n }\n\n return walkNodes(ast, null, 0);\n}\n\n/**\n * Replace nodes matching a predicate with new nodes.\n */\nexport function replace(\n ast: AstNode[],\n predicate: (node: AstNode) => boolean,\n replacer: (node: AstNode) => AstNode[]\n): AstNode[] {\n return walk(ast, (node) => {\n if (predicate(node)) {\n return { kind: \"replace\", nodes: replacer(node) };\n }\n });\n}\n\n/**\n * Remove nodes matching a predicate.\n */\nexport function remove(ast: AstNode[], predicate: (node: AstNode) => boolean): AstNode[] {\n return walk(ast, (node) => {\n if (predicate(node)) {\n return { kind: \"replace\", nodes: [] };\n }\n });\n}\n\n/**\n * Find all nodes matching a predicate.\n */\nexport function findAll(ast: AstNode[], predicate: (node: AstNode) => boolean): AstNode[] {\n const found: AstNode[] = [];\n walk(ast, (node) => {\n if (predicate(node)) {\n found.push(node);\n }\n });\n return found;\n}\n\n/**\n * Find the first node matching a predicate.\n */\nexport function find(ast: AstNode[], predicate: (node: AstNode) => boolean): AstNode | null {\n let found: AstNode | null = null;\n walk(ast, (node) => {\n if (predicate(node)) {\n found = node;\n return WalkAction.Stop;\n }\n });\n return found;\n}\n","/**\n * DefaultMap\n *\n * A Map that automatically creates missing values using a factory function.\n * Useful for grouping and accumulation patterns.\n */\n\n/**\n * A Map that creates default values for missing keys.\n *\n * @example\n * ```ts\n * const groups = new DefaultMap<string, string[]>(() => []);\n * groups.get(\"a\").push(\"item1\");\n * groups.get(\"a\").push(\"item2\");\n * groups.get(\"b\").push(\"item3\");\n * // groups.get(\"a\") = [\"item1\", \"item2\"]\n * // groups.get(\"b\") = [\"item3\"]\n * ```\n */\nexport class DefaultMap<K, V> extends Map<K, V> {\n private factory: (key: K, self: DefaultMap<K, V>) => V;\n\n constructor(factory: (key: K, self: DefaultMap<K, V>) => V, entries?: Iterable<[K, V]>) {\n super(entries);\n this.factory = factory;\n }\n\n /**\n * Get a value, creating it with the factory if it doesn't exist.\n * The factory receives both the key and a reference to this map (useful for nested caches).\n */\n get(key: K): V {\n if (!super.has(key)) {\n const value = this.factory(key, this);\n super.set(key, value);\n return value;\n }\n return super.get(key)!;\n }\n\n /**\n * Get a value only if it exists (doesn't create).\n */\n peek(key: K): V | undefined {\n return super.get(key);\n }\n}\n\n/**\n * Create a DefaultMap that creates arrays for missing keys.\n *\n * @example\n * ```ts\n * const groups = arrayMap<string, number>();\n * groups.get(\"evens\").push(2, 4, 6);\n * groups.get(\"odds\").push(1, 3, 5);\n * ```\n */\nexport function arrayMap<K, V>(): DefaultMap<K, V[]> {\n return new DefaultMap<K, V[]>(() => []);\n}\n\n/**\n * Create a DefaultMap that creates Sets for missing keys.\n *\n * @example\n * ```ts\n * const seen = setMap<string, number>();\n * seen.get(\"file1\").add(1).add(2);\n * seen.get(\"file2\").add(3);\n * ```\n */\nexport function setMap<K, V>(): DefaultMap<K, Set<V>> {\n return new DefaultMap<K, Set<V>>(() => new Set());\n}\n\n/**\n * Create a DefaultMap that creates Maps for missing keys.\n *\n * @example\n * ```ts\n * const nested = mapMap<string, string, number>();\n * nested.get(\"outer1\").set(\"inner1\", 1);\n * nested.get(\"outer1\").set(\"inner2\", 2);\n * ```\n */\nexport function mapMap<K, K2, V>(): DefaultMap<K, Map<K2, V>> {\n return new DefaultMap<K, Map<K2, V>>(() => new Map());\n}\n\n/**\n * Create a DefaultMap that initializes numbers to 0.\n *\n * @example\n * ```ts\n * const counts = counterMap<string>();\n * counts.set(\"a\", counts.get(\"a\") + 1);\n * counts.set(\"a\", counts.get(\"a\") + 1);\n * // counts.get(\"a\") = 2\n * ```\n */\nexport function counterMap<K>(): DefaultMap<K, number> {\n return new DefaultMap<K, number>(() => 0);\n}\n","/**\n * Source Map Generator\n *\n * Generates source maps in the standard v3 format with VLQ encoding.\n * Also provides ECMA-426 decoded source map types for structured access.\n *\n * ## Pipeline Stages and Source Map Flow\n *\n * The Rainbow Index build pipeline generates source maps through multiple stages:\n *\n * 1. **Parser** (parse.ts)\n * - Input: Raw CSS/Rainbow syntax\n * - Output: AST with `src[]` location metadata\n * - Source Map: Implicit via SourceLocation tuples on nodes\n *\n * 2. **Compiler** (compile.ts)\n * - Input: AST with `src[]`\n * - Output: Transformed AST with `dst[]` added\n * - Source Map: `createSourceMap({ ast })` generates DecodedSourceMap\n *\n * 3. **Printer** (print.ts)\n * - Input: Compiled AST\n * - Output: CSS string\n * - Source Map: `generateSourceMap()` produces v3 SourceMap\n *\n * 4. **Optimizer** (optimize.ts in @rainbowindex/node)\n * - Input: CSS string + optional source map\n * - Output: Optimized CSS + composed source map\n * - Source Map: Uses `@jridgewell/remapping` for composition\n *\n * ## Composition Functions\n *\n * - `chainSourceMaps(original, transformed)`: Chains two sequential maps.\n * Maps from final output -> intermediate -> original source.\n *\n * - `mergeSourceMaps(maps[])`: Combines maps from parallel sources.\n * Used when concatenating CSS from multiple input files.\n *\n * - `@jridgewell/remapping`: External library used in optimizer for\n * composing maps through Lightning CSS and MagicString transformations.\n *\n * ## Example Usage\n *\n * ```typescript\n * // Chain maps through a 3-stage pipeline\n * const map1 = chainSourceMaps(parseMap, compileMap);\n * const finalMap = chainSourceMaps(map1, optimizeMap);\n *\n * // Merge maps from multiple input files\n * const bundleMap = mergeSourceMaps([resetMap, utilsMap, componentsMap]);\n * ```\n */\n\nimport type { AstNode, Source, SourceLocation } from \"./types\";\nimport { DefaultMap } from \"../utils/default-map\";\nimport { walk, WalkAction } from \"./walk\";\n\n// ============================================\n// Types (Standard Source Map v3 Format)\n// ============================================\n\n/**\n * Standard source map format (JSON v3 specification).\n * @see https://sourcemaps.info/spec.html\n */\nexport interface SourceMap {\n version: 3;\n file?: string;\n sourceRoot?: string;\n sources: string[];\n sourcesContent: (string | null)[];\n names: string[];\n mappings: string;\n}\n\nexport interface SourceMapGenerator {\n addMapping(generated: Position, original?: Position, source?: number): void;\n addSource(file: string, content?: string): number;\n toJSON(): SourceMap;\n toString(): string;\n}\n\nexport interface Position {\n /** Line number (0-based for internal use, 1-based in ECMA-426) */\n line: number;\n /** Column number (0-based) */\n column: number;\n}\n\n// ============================================\n// ECMA-426 Decoded Source Map Types\n// ============================================\n\n/**\n * ECMA-426 Decoded Source (decoded-source-record)\n */\nexport interface DecodedSource {\n /** Source file URL or path (null for generated code) */\n url: string | null;\n /** Source file content */\n content: string | null;\n /** Whether to ignore this source when debugging */\n ignore: boolean;\n}\n\n/**\n * ECMA-426 Original Position with source reference\n */\nexport interface OriginalPosition extends Position {\n /** Reference to the source containing this position */\n source: DecodedSource;\n}\n\n/**\n * ECMA-426 Decoded Mapping (decoded-mapping-record)\n */\nexport interface DecodedMapping {\n /** Position in the original source (null if generated-only) */\n originalPosition: OriginalPosition | null;\n /** Position in the generated output */\n generatedPosition: Position;\n /** Name reference (for identifiers) */\n name: string | null;\n}\n\n/**\n * ECMA-426 Decoded Source Map (decoded-source-map-record)\n */\nexport interface DecodedSourceMap {\n /** Output file name */\n file: string | null;\n /** All source files */\n sources: DecodedSource[];\n /** All mappings */\n mappings: DecodedMapping[];\n}\n\n/**\n * Translation for a single AST node\n */\nexport type Translation = [\n originalStart: Position,\n originalEnd: Position,\n generatedStart: Position | null,\n generatedEnd: Position | null,\n];\n\n// ============================================\n// VLQ Encoding\n// ============================================\n\nconst BASE64_CHARS = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/\";\n\n/**\n * Encode a number as VLQ (Variable-Length Quantity).\n */\nfunction encodeVLQ(value: number): string {\n let result = \"\";\n let vlq = value < 0 ? (-value << 1) + 1 : value << 1;\n\n do {\n let digit = vlq & 0x1f;\n vlq >>>= 5;\n if (vlq > 0) {\n digit |= 0x20; // continuation bit\n }\n result += BASE64_CHARS[digit];\n } while (vlq > 0);\n\n return result;\n}\n\n// ============================================\n// Source Map Generator\n// ============================================\n\n/**\n * Create a source map generator.\n */\nexport function createSourceMapGenerator(file?: string): SourceMapGenerator {\n const sources: string[] = [];\n const sourcesContent: (string | null)[] = [];\n const names: string[] = [];\n const mappings: Array<Array<number[]>> = []; // [line][segment]\n\n // Previous values for delta encoding\n let prevGeneratedColumn = 0;\n let prevOriginalLine = 0;\n let prevOriginalColumn = 0;\n let prevSourceIndex = 0;\n\n let currentLine = 0;\n\n function ensureLine(line: number): void {\n while (mappings.length <= line) {\n mappings.push([]);\n }\n }\n\n return {\n addSource(sourceFile: string, content?: string): number {\n const index = sources.indexOf(sourceFile);\n if (index >= 0) return index;\n\n sources.push(sourceFile);\n sourcesContent.push(content ?? null);\n return sources.length - 1;\n },\n\n addMapping(generated: Position, original?: Position, source?: number): void {\n // Handle line changes\n if (generated.line !== currentLine) {\n prevGeneratedColumn = 0;\n currentLine = generated.line;\n }\n\n ensureLine(generated.line);\n\n if (original === undefined || source === undefined) {\n // Generated-only segment (no original source)\n mappings[generated.line]!.push([generated.column - prevGeneratedColumn]);\n prevGeneratedColumn = generated.column;\n return;\n }\n\n // Full mapping segment: [genCol, sourceIdx, origLine, origCol]\n const segment = [\n generated.column - prevGeneratedColumn,\n source - prevSourceIndex,\n original.line - prevOriginalLine,\n original.column - prevOriginalColumn,\n ];\n\n mappings[generated.line]!.push(segment);\n\n prevGeneratedColumn = generated.column;\n prevSourceIndex = source;\n prevOriginalLine = original.line;\n prevOriginalColumn = original.column;\n },\n\n toJSON(): SourceMap {\n // Encode mappings to VLQ string\n const encodedMappings = mappings\n .map((line) => line.map((segment) => segment.map((v) => encodeVLQ(v)).join(\"\")).join(\",\"))\n .join(\";\");\n\n return {\n version: 3,\n file,\n sources,\n sourcesContent,\n names,\n mappings: encodedMappings,\n };\n },\n\n toString(): string {\n return JSON.stringify(this.toJSON());\n },\n };\n}\n\n// ============================================\n// Source Location Helpers\n// ============================================\n\n/**\n * Create a source object for tracking locations.\n */\nexport function createSource(file: string | null, code: string): Source {\n return { file, code };\n}\n\n/**\n * Create a source location tuple.\n */\nexport function createSourceLocation(source: Source, start: number, end: number): SourceLocation {\n return [source, start, end];\n}\n\n/**\n * Convert an offset in a source to line/column position.\n */\nexport function offsetToPosition(code: string, offset: number): Position {\n let line = 0;\n let column = 0;\n\n for (let i = 0; i < offset && i < code.length; i++) {\n if (code.charCodeAt(i) === 0x0a) {\n line++;\n column = 0;\n } else {\n column++;\n }\n }\n\n return { line, column };\n}\n\n/**\n * Check if a node has source location properties.\n */\nfunction hasSourceLocation(node: AstNode): node is AstNode & { src?: SourceLocation; dst?: SourceLocation } {\n return node.kind !== \"context\" && node.kind !== \"at-root\";\n}\n\n// ============================================\n// Line Table (Performance Optimization)\n// ============================================\n\n/**\n * Pre-computed line positions for fast offset-to-position lookups.\n * Provides O(log n) binary search methods.\n */\nexport interface LineTable {\n /** Line start offsets */\n lineStarts: number[];\n /** Total length of the code */\n length: number;\n /**\n * Find the line/column position for a given byte offset.\n * O(log N) binary search where N is the number of lines.\n */\n find(offset: number): Position;\n /**\n * Find the byte offset for a given line/column position.\n */\n findOffset(pos: Position): number;\n}\n\n/**\n * Build a line table for efficient position lookups.\n * Returns an object with both data and methods.\n *\n * Optimized for performance:\n * - Uses `let` for V8 optimization in tight loops\n * - Avoids non-null assertions (TypeScript overhead)\n * - Caches array length\n */\nexport function buildLineTable(code: string): LineTable {\n const lineStarts: number[] = [0];\n const codeLength = code.length;\n\n for (let i = 0; i < codeLength; i++) {\n if (code.charCodeAt(i) === 0x0a) {\n lineStarts.push(i + 1);\n }\n }\n\n const tableLength = lineStarts.length;\n\n return {\n lineStarts,\n length: codeLength,\n\n find(offset: number): Position {\n // Binary search based on esbuild's implementation\n // `| 0` and `let` improve V8 performance\n let line = 0;\n let count = tableLength;\n while (count > 0) {\n const mid = (count | 0) >> 1;\n const i = line + mid;\n if (lineStarts[i]! <= offset) {\n line = i + 1;\n count = count - mid - 1;\n } else {\n count = mid;\n }\n }\n\n line -= 1;\n const column = offset - lineStarts[line]!;\n\n return { line, column };\n },\n\n findOffset({ line, column }: Position): number {\n line = Math.min(Math.max(line, 0), tableLength - 1);\n\n const offsetA = lineStarts[line]!;\n const offsetB = lineStarts[line + 1] ?? codeLength;\n\n return Math.min(Math.max(offsetA + column, 0), offsetB);\n },\n };\n}\n\n/**\n * Create a line table from source string.\n * Alias for buildLineTable with ECMA-426 naming.\n */\nexport const createLineTable = buildLineTable;\n\n// ============================================\n// Source Map Chaining\n// ============================================\n\n/**\n * Decoded source map segment.\n */\nexport interface DecodedSegment {\n generatedColumn: number;\n sourceIndex?: number;\n originalLine?: number;\n originalColumn?: number;\n nameIndex?: number;\n}\n\n/**\n * Decode VLQ-encoded mappings to an array of segments.\n */\nexport function decodeMappings(mappings: string): DecodedSegment[][] {\n const lines: DecodedSegment[][] = [];\n let currentLine: DecodedSegment[] = [];\n\n let generatedColumn = 0;\n let sourceIndex = 0;\n let originalLine = 0;\n let originalColumn = 0;\n let nameIndex = 0;\n\n let i = 0;\n while (i < mappings.length) {\n const char = mappings[i];\n\n if (char === \";\") {\n lines.push(currentLine);\n currentLine = [];\n generatedColumn = 0;\n i++;\n continue;\n }\n\n if (char === \",\") {\n i++;\n continue;\n }\n\n // Decode VLQ values\n const values: number[] = [];\n while (i < mappings.length && mappings[i] !== \",\" && mappings[i] !== \";\") {\n let value = 0;\n let shift = 0;\n let continuation = true;\n\n while (continuation && i < mappings.length) {\n const charCode = mappings.charCodeAt(i);\n let digit: number;\n\n if (charCode >= 65 && charCode <= 90) {\n digit = charCode - 65;\n } else if (charCode >= 97 && charCode <= 122) {\n digit = charCode - 97 + 26;\n } else if (charCode >= 48 && charCode <= 57) {\n digit = charCode - 48 + 52;\n } else if (charCode === 43) {\n digit = 62;\n } else if (charCode === 47) {\n digit = 63;\n } else {\n break;\n }\n\n continuation = (digit & 32) !== 0;\n value |= (digit & 31) << shift;\n shift += 5;\n i++;\n }\n\n // Convert from VLQ to signed\n const negate = (value & 1) !== 0;\n value = value >> 1;\n if (negate) value = -value;\n\n values.push(value);\n }\n\n if (values.length >= 1) {\n generatedColumn += values[0]!;\n\n const segment: DecodedSegment = { generatedColumn };\n\n if (values.length >= 4) {\n sourceIndex += values[1]!;\n originalLine += values[2]!;\n originalColumn += values[3]!;\n\n segment.sourceIndex = sourceIndex;\n segment.originalLine = originalLine;\n segment.originalColumn = originalColumn;\n }\n\n if (values.length >= 5) {\n nameIndex += values[4]!;\n segment.nameIndex = nameIndex;\n }\n\n currentLine.push(segment);\n }\n }\n\n lines.push(currentLine);\n return lines;\n}\n\n/**\n * Chain two source maps together.\n * The resulting map maps from the generated output through the intermediate\n * file to the original source.\n *\n * @param original - Source map from original to intermediate\n * @param transformed - Source map from intermediate to final output\n */\nexport function chainSourceMaps(original: SourceMap, transformed: SourceMap): SourceMap {\n // Decode both mappings\n const originalDecoded = decodeMappings(original.mappings);\n const transformedDecoded = decodeMappings(transformed.mappings);\n\n // Build lookup for original map (intermediate positions -> original positions)\n const originalLookup = new Map<string, DecodedSegment>();\n\n for (let line = 0; line < originalDecoded.length; line++) {\n for (const segment of originalDecoded[line]!) {\n if (segment.sourceIndex !== undefined) {\n const key = `${line}:${segment.generatedColumn}`;\n originalLookup.set(key, segment);\n }\n }\n }\n\n // Create new generator\n const generator = createSourceMapGenerator(transformed.file);\n\n // Add all original sources\n for (let i = 0; i < original.sources.length; i++) {\n generator.addSource(original.sources[i]!, original.sourcesContent[i] ?? undefined);\n }\n\n // Process transformed mappings\n for (let line = 0; line < transformedDecoded.length; line++) {\n for (const segment of transformedDecoded[line]!) {\n if (segment.originalLine !== undefined && segment.originalColumn !== undefined) {\n // Look up in original map\n const key = `${segment.originalLine}:${segment.originalColumn}`;\n const originalSegment = originalLookup.get(key);\n\n if (originalSegment && originalSegment.originalLine !== undefined) {\n generator.addMapping(\n { line, column: segment.generatedColumn },\n { line: originalSegment.originalLine, column: originalSegment.originalColumn! },\n originalSegment.sourceIndex\n );\n continue;\n }\n }\n\n // No original mapping found, add generated-only\n generator.addMapping({ line, column: segment.generatedColumn });\n }\n }\n\n return generator.toJSON();\n}\n\n/**\n * Merge multiple source maps into one.\n * Used when combining CSS from multiple files.\n */\nexport function mergeSourceMaps(maps: SourceMap[], options: { file?: string } = {}): SourceMap {\n const generator = createSourceMapGenerator(options.file);\n const sourceOffsets: number[] = [];\n\n // Add all sources and track offsets\n for (const map of maps) {\n const offset =\n sourceOffsets.length > 0\n ? sourceOffsets[sourceOffsets.length - 1]! + maps[sourceOffsets.length - 1]!.sources.length\n : 0;\n sourceOffsets.push(offset);\n\n for (let i = 0; i < map.sources.length; i++) {\n generator.addSource(map.sources[i]!, map.sourcesContent[i] ?? undefined);\n }\n }\n\n // Merge mappings (simplified - assumes sequential concatenation)\n let lineOffset = 0;\n\n for (let mapIndex = 0; mapIndex < maps.length; mapIndex++) {\n const map = maps[mapIndex]!;\n const decoded = decodeMappings(map.mappings);\n const sourceOffset = sourceOffsets[mapIndex]!;\n\n for (let line = 0; line < decoded.length; line++) {\n for (const segment of decoded[line]!) {\n if (segment.sourceIndex !== undefined && segment.originalLine !== undefined) {\n generator.addMapping(\n { line: line + lineOffset, column: segment.generatedColumn },\n { line: segment.originalLine, column: segment.originalColumn! },\n segment.sourceIndex + sourceOffset\n );\n }\n }\n }\n\n lineOffset += decoded.length;\n }\n\n return generator.toJSON();\n}\n\n/**\n * Extract source map from AST nodes.\n */\nexport function generateSourceMap(\n nodes: AstNode[],\n outputCode: string,\n options: { file?: string } = {}\n): SourceMap | null {\n const generator = createSourceMapGenerator(options.file);\n const sourceIndices = new Map<Source, number>();\n\n function getSourceIndex(source: Source): number {\n let idx = sourceIndices.get(source);\n if (idx === undefined) {\n idx = generator.addSource(source.file ?? \"input.css\", source.code);\n sourceIndices.set(source, idx);\n }\n return idx;\n }\n\n function processNode(node: AstNode): void {\n if (hasSourceLocation(node) && node.src && node.dst) {\n const [srcSource, srcStart] = node.src;\n const [dstSource, dstStart] = node.dst;\n\n const sourceIdx = getSourceIndex(srcSource);\n const originalPos = offsetToPosition(srcSource.code, srcStart);\n const generatedPos = offsetToPosition(dstSource.code, dstStart);\n\n generator.addMapping(generatedPos, originalPos, sourceIdx);\n }\n\n // Process children\n if (\"nodes\" in node && Array.isArray(node.nodes)) {\n for (const child of node.nodes) {\n processNode(child);\n }\n }\n }\n\n for (const node of nodes) {\n processNode(node);\n }\n\n return generator.toJSON();\n}\n\n// ============================================\n// ECMA-426 Source Map Creation\n// ============================================\n\n/**\n * Build an ECMA-426 decoded source map from the given AST.\n *\n * Takes the parsed CSS AST with src/dst metadata and generates a decoded source map.\n * Handles @import by supporting multiple sources.\n * Uses DefaultMap for lazy computation of line tables.\n *\n * @example\n * const ast = parse(css);\n * const map = createSourceMap({ ast });\n * // map.mappings contains all position mappings\n * // map.sources contains all referenced source files\n */\nexport function createSourceMap({ ast }: { ast: AstNode[] }): DecodedSourceMap {\n // Compute line tables lazily for each source\n const lineTables = new DefaultMap<Source, LineTable>((src) => createLineTable(src.code));\n\n // Create decoded sources lazily\n const sourceTable = new DefaultMap<Source, DecodedSource>((src) => ({\n url: src.file,\n content: src.code,\n ignore: false,\n }));\n\n const map: DecodedSourceMap = {\n file: null,\n sources: [],\n mappings: [],\n };\n\n // Walk AST to build mappings\n walk(ast, (node) => {\n if (!hasSourceLocation(node) || !node.src || !node.dst) {\n return WalkAction.Continue;\n }\n\n const originalSource = sourceTable.get(node.src[0]);\n if (!originalSource.content) return WalkAction.Continue;\n\n const originalTable = lineTables.get(node.src[0]);\n const generatedTable = lineTables.get(node.dst[0]);\n\n // Handle multi-line mappings by scanning original text\n const originalSlice = originalSource.content.slice(node.src[1], node.src[2]);\n let offset = 0;\n\n for (const line of originalSlice.split(\"\\n\")) {\n if (line.trim() !== \"\") {\n const originalStart = originalTable.find(node.src[1] + offset);\n const generatedStart = generatedTable.find(node.dst[1]);\n\n map.mappings.push({\n name: null,\n originalPosition: {\n source: originalSource,\n ...originalStart,\n },\n generatedPosition: generatedStart,\n });\n }\n offset += line.length + 1;\n }\n\n // Add end position mapping\n const originalEnd = originalTable.find(node.src[2]);\n const generatedEnd = generatedTable.find(node.dst[2]);\n\n map.mappings.push({\n name: null,\n originalPosition: {\n source: originalSource,\n ...originalEnd,\n },\n generatedPosition: generatedEnd,\n });\n\n return WalkAction.Continue;\n });\n\n // Populate sources array (deduplicated)\n const seenSources = new Set<DecodedSource>();\n for (const source of lineTables.keys()) {\n const decodedSource = sourceTable.get(source);\n if (!seenSources.has(decodedSource)) {\n seenSources.add(decodedSource);\n map.sources.push(decodedSource);\n }\n }\n\n // Sort mappings by generated position\n map.mappings.sort((a, b) => {\n return (\n a.generatedPosition.line - b.generatedPosition.line ||\n a.generatedPosition.column - b.generatedPosition.column ||\n (a.originalPosition?.line ?? 0) - (b.originalPosition?.line ?? 0) ||\n (a.originalPosition?.column ?? 0) - (b.originalPosition?.column ?? 0)\n );\n });\n\n return map;\n}\n\n/**\n * Create a translation map helper for tracking position transformations.\n *\n * Used during compilation to track how source positions map to generated positions.\n * Returns a function that, given an AST node, returns its position translations.\n *\n * @example\n * const translate = createTranslationMap({ original: inputCss, generated: outputCss });\n * for (const node of ast) {\n * const translations = translate(node);\n * for (const [origStart, origEnd, genStart, genEnd] of translations) {\n * console.log(`${origStart.line}:${origStart.column} -> ${genStart?.line}:${genStart?.column}`);\n * }\n * }\n */\nexport function createTranslationMap({\n original,\n generated,\n}: {\n original: string;\n generated: string;\n}): (node: AstNode) => Translation[] {\n const originalTable = createLineTable(original);\n const generatedTable = createLineTable(generated);\n\n return (node: AstNode): Translation[] => {\n if (!hasSourceLocation(node) || !node.src) {\n return [];\n }\n\n const translations: Translation[] = [];\n\n translations.push([\n originalTable.find(node.src[1]),\n originalTable.find(node.src[2]),\n node.dst ? generatedTable.find(node.dst[1]) : null,\n node.dst ? generatedTable.find(node.dst[2]) : null,\n ]);\n\n return translations;\n };\n}\n\n/**\n * Convert a decoded source map to V3 format.\n */\nexport function encodeSourceMap(decoded: DecodedSourceMap, file?: string): SourceMap {\n const generator = createSourceMapGenerator(file ?? decoded.file ?? undefined);\n const sourceIndices = new Map<DecodedSource, number>();\n\n // Add all sources\n for (const source of decoded.sources) {\n const idx = generator.addSource(source.url ?? \"unknown\", source.content ?? undefined);\n sourceIndices.set(source, idx);\n }\n\n // Add all mappings\n for (const mapping of decoded.mappings) {\n if (mapping.originalPosition) {\n const sourceIdx = sourceIndices.get(mapping.originalPosition.source);\n if (sourceIdx !== undefined) {\n generator.addMapping(\n mapping.generatedPosition,\n { line: mapping.originalPosition.line, column: mapping.originalPosition.column },\n sourceIdx\n );\n }\n } else {\n generator.addMapping(mapping.generatedPosition);\n }\n }\n\n return generator.toJSON();\n}\n","/**\n * AST Printer\n *\n * Converts AST nodes back to CSS strings.\n * Optimized following tailwindcss patterns:\n * - Pre-computed indentation array\n * - Separate CSS generation from source map tracking\n * - ECMA-426 decoded source maps with deferred VLQ encoding\n * - Binary search position lookups via line tables\n */\n\nimport type { AstNode, Source } from \"./types\";\nimport {\n type SourceMap,\n type DecodedSourceMap,\n type DecodedSource,\n type DecodedMapping,\n type LineTable,\n buildLineTable,\n encodeSourceMap,\n} from \"./source-map\";\nimport { DefaultMap } from \"../utils/default-map\";\n\n/**\n * Error thrown when source map generation encounters invalid offsets.\n * This indicates a bug in upstream code that produced the AST.\n */\nexport class SourceMapError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"SourceMapError\";\n }\n}\n\n// Pre-computed indentation strings for depth 0-31 (covers all practical use cases)\n// This avoids calling indent.repeat(depth) on every node\nconst INDENTS_2 = Array.from({ length: 32 }, (_, i) => \" \".repeat(i));\nconst INDENTS_4 = Array.from({ length: 32 }, (_, i) => \" \".repeat(i));\nconst INDENTS_TAB = Array.from({ length: 32 }, (_, i) => \"\\t\".repeat(i));\n\nfunction getIndentArray(indent: string): string[] {\n if (indent === \" \") return INDENTS_2;\n if (indent === \" \") return INDENTS_4;\n if (indent === \"\\t\") return INDENTS_TAB;\n // Fallback for custom indentation\n return Array.from({ length: 32 }, (_, i) => indent.repeat(i));\n}\n\nexport interface PrintOptions {\n /** Use minified output (no whitespace) */\n minify?: boolean;\n /** Indentation string (default: \" \") */\n indent?: string;\n /** Generate source map */\n sourceMap?: boolean;\n /**\n * Return decoded source map (ECMA-426 format) instead of V3.\n * This is faster as it skips VLQ encoding.\n * Use encodeSourceMap() to convert to V3 when needed.\n */\n decodedSourceMap?: boolean;\n /** Output file name for source map */\n file?: string;\n}\n\nexport interface PrintResult {\n /** The generated CSS string */\n code: string;\n /** V3 source map (if sourceMap option was true) */\n map?: SourceMap;\n /** Decoded source map (if decodedSourceMap option was true) */\n decodedMap?: DecodedSourceMap;\n}\n\n/**\n * Raw source map result - byte offsets only, no line/column computation.\n * This is the fastest path, matching Tailwind's toCss(ast, true) approach.\n * Line/column positions can be computed later using buildLineTable().\n */\nexport interface RawSourceMapResult {\n /** The generated CSS string */\n code: string;\n /** Generated line starts (for deferred position lookup) */\n generatedLineStarts: number[];\n /** Raw mappings: parallel arrays of [source, srcOffset, dstOffset] */\n rawMappings: {\n sources: Source[];\n srcOffsets: number[];\n dstOffsets: number[];\n };\n}\n\n/**\n * Convert AST to CSS string.\n */\nexport function print(ast: AstNode[], options: PrintOptions = {}): string {\n const { minify = false, indent = \" \" } = options;\n\n // Fast path: inline the entire print logic for non-source-map case\n if (!options.sourceMap) {\n return toCss(ast, minify, indent);\n }\n\n return printWithSourceMap(ast, options).code;\n}\n\n/**\n * Generate CSS with raw source map data (byte offsets only).\n *\n * This is the fastest source map path - matches Tailwind's toCss(ast, true).\n * Returns byte offsets without computing line/column positions.\n * Use buildLineTable() + binarySearchLine() to convert to positions when needed.\n *\n * ~3x faster than printWithSourceMap() by deferring position computation.\n */\nexport function printWithRawSourceMap(ast: AstNode[], options: PrintOptions = {}): RawSourceMapResult {\n const { minify = false, indent = \" \" } = options;\n return toCssWithRawMappings(ast, minify, indent);\n}\n\n/**\n * Convert AST to CSS string with optional source map.\n *\n * Uses Option C: Single-pass with deferred line/column computation.\n * Key optimizations:\n * 1. Single AST traversal (no two-pass overhead)\n * 2. Only byte offsets stored during hot path (minimal allocation)\n * 3. Batch line/column conversion at end using binary search\n * 4. Deferred VLQ encoding (only when V3 format requested)\n */\nexport function printWithSourceMap(ast: AstNode[], options: PrintOptions = {}): PrintResult {\n const { minify = false, indent = \" \", sourceMap = false, decodedSourceMap = false, file } = options;\n\n // Fast path: no source map needed\n if (!sourceMap && !decodedSourceMap) {\n return { code: toCss(ast, minify, indent) };\n }\n\n // Option C: Single-pass with deferred line/column computation\n // This is the fastest path - generates CSS and collects raw byte offsets,\n // then batch converts to line/column at the end.\n const { code, decodedMap } = toCssWithDecodedMap(ast, minify, indent, file);\n\n // Fast path: return decoded map without VLQ encoding\n if (decodedSourceMap && !sourceMap) {\n return { code, decodedMap };\n }\n\n // Encode to V3 format (deferred VLQ encoding)\n const map = encodeSourceMap(decodedMap, file);\n\n // Return both if both requested\n if (decodedSourceMap) {\n return { code, map, decodedMap };\n }\n\n return { code, map };\n}\n\n/**\n * High-performance CSS printer.\n * Key optimizations:\n * - Pre-computed indentation array\n * - Template literal consolidation (single concatenation per node)\n * - Separate minified/pretty paths (no conditionals in hot path)\n * - Return-based design for better JIT optimization\n */\nfunction toCss(ast: AstNode[], minify: boolean, indent: string): string {\n // Separate paths eliminate conditionals from hot loop\n return minify ? toCssMinified(ast) : toCssPretty(ast, indent);\n}\n\n/**\n * Pretty-print CSS with indentation and newlines.\n * Uses return-based design for better JIT optimization.\n */\nfunction toCssPretty(ast: AstNode[], indent: string): string {\n const indents = getIndentArray(indent);\n\n function stringify(node: AstNode, depth: number): string {\n const ind = indents[depth] ?? indent.repeat(depth);\n\n // Declaration - most common case, check first\n if (node.kind === \"declaration\") {\n // Single template literal instead of 7 separate += operations\n return node.value === undefined\n ? \"\"\n : `${ind}${node.property}: ${node.value}${node.important ? \" !important\" : \"\"};\\n`;\n }\n\n // Rule\n if (node.kind === \"rule\") {\n if (node.nodes.length === 0) {\n return `${ind}${node.selector} {}\\n`;\n }\n let css = `${ind}${node.selector} {\\n`;\n for (const child of node.nodes) {\n css += stringify(child, depth + 1);\n }\n return css + `${ind}}\\n`;\n }\n\n // At-rule - @ prefix already normalized in atRule() factory\n if (node.kind === \"at-rule\") {\n const params = node.params ? ` ${node.params}` : \"\";\n\n // Empty at-rules use ; (like Tailwind)\n if (node.nodes.length === 0) {\n return `${ind}${node.name}${params};\\n`;\n }\n\n let css = `${ind}${node.name}${params} {\\n`;\n for (const child of node.nodes) {\n css += stringify(child, depth + 1);\n }\n return css + `${ind}}\\n`;\n }\n\n // Comment\n if (node.kind === \"comment\") {\n // Preserve preflight module markers as license comments so they survive parse/print cycles\n const isPreflightMarker = node.value.includes(\"@preflight-module\");\n return isPreflightMarker ? `${ind}/*!${node.value}*/\\n` : `${ind}/*${node.value}*/\\n`;\n }\n\n // Context - flatten at same depth\n if (node.kind === \"context\") {\n let css = \"\";\n for (const child of node.nodes) {\n css += stringify(child, depth);\n }\n return css;\n }\n\n // At-root - flatten to depth 0\n if (node.kind === \"at-root\") {\n let css = \"\";\n for (const child of node.nodes) {\n css += stringify(child, 0);\n }\n return css;\n }\n\n return \"\";\n }\n\n let css = \"\";\n for (const node of ast) {\n css += stringify(node, 0);\n }\n return css;\n}\n\n/**\n * Minified CSS output - no whitespace, no comments.\n * Separate function eliminates all minify conditionals from hot path.\n */\nfunction toCssMinified(ast: AstNode[]): string {\n function stringify(node: AstNode): string {\n // Declaration\n if (node.kind === \"declaration\") {\n return node.value === undefined\n ? \"\"\n : `${node.property}:${node.value}${node.important ? \"!important\" : \"\"};`;\n }\n\n // Rule\n if (node.kind === \"rule\") {\n if (node.nodes.length === 0) {\n return `${node.selector}{}`;\n }\n let css = `${node.selector}{`;\n for (const child of node.nodes) {\n css += stringify(child);\n }\n return css + \"}\";\n }\n\n // At-rule - @ prefix already normalized in atRule() factory\n if (node.kind === \"at-rule\") {\n const params = node.params ? ` ${node.params}` : \"\";\n\n if (node.nodes.length === 0) {\n return `${node.name}${params};`;\n }\n\n let css = `${node.name}${params}{`;\n for (const child of node.nodes) {\n css += stringify(child);\n }\n return css + \"}\";\n }\n\n // Comment - skip in minified output\n if (node.kind === \"comment\") {\n return \"\";\n }\n\n // Context - flatten\n if (node.kind === \"context\") {\n let css = \"\";\n for (const child of node.nodes) {\n css += stringify(child);\n }\n return css;\n }\n\n // At-root - flatten\n if (node.kind === \"at-root\") {\n let css = \"\";\n for (const child of node.nodes) {\n css += stringify(child);\n }\n return css;\n }\n\n return \"\";\n }\n\n let css = \"\";\n for (const node of ast) {\n css += stringify(node);\n }\n return css;\n}\n\n// ============================================\n// Optimized Source Map Generation (Option C: Deferred Line/Column)\n// ============================================\n\ninterface PositionResult {\n code: string;\n source: Source;\n}\n\n/**\n * Generate CSS while tracking generated positions on AST nodes.\n *\n * This is Pass 1 of the optimized source map pipeline.\n * Instead of generating mappings inline, we annotate each node with its\n * generated position (dst). This allows us to use the fast CSS generation\n * path while still collecting position data.\n *\n * Key optimizations:\n * - Uses array-join pattern for better V8 optimization\n * - Single position calculation per node (not per segment)\n * - No VLQ encoding during this pass\n */\nfunction _toCssWithPositions(ast: AstNode[], minify: boolean, indent: string, file?: string): PositionResult {\n const indents = minify ? null : getIndentArray(indent);\n const parts: string[] = [];\n let pos = 0;\n\n // Create source object for generated code\n const source: Source = { file: file ?? null, code: \"\" };\n\n function annotate(node: AstNode, start: number, end: number): void {\n // Skip context/at-root nodes (they don't have positions)\n if (node.kind === \"context\" || node.kind === \"at-root\") return;\n\n // Annotate node with generated position\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic property assignment\n (node as any).dst = [source, start, end];\n }\n\n function stringify(node: AstNode, depth: number): void {\n const ind = indents ? (indents[depth] ?? indent.repeat(depth)) : \"\";\n\n // Declaration\n if (node.kind === \"declaration\") {\n if (node.value === undefined) return;\n\n const start = pos;\n let segment: string;\n\n if (minify) {\n segment = `${node.property}:${node.value}${node.important ? \"!important\" : \"\"};`;\n } else {\n segment = `${ind}${node.property}: ${node.value}${node.important ? \" !important\" : \"\"};\\n`;\n }\n\n parts.push(segment);\n pos += segment.length;\n annotate(node, start, pos);\n return;\n }\n\n // Rule\n if (node.kind === \"rule\") {\n const start = pos;\n\n if (node.nodes.length === 0) {\n const segment = minify ? `${node.selector}{}` : `${ind}${node.selector} {}\\n`;\n parts.push(segment);\n pos += segment.length;\n annotate(node, start, pos);\n return;\n }\n\n const openSegment = minify ? `${node.selector}{` : `${ind}${node.selector} {\\n`;\n parts.push(openSegment);\n pos += openSegment.length;\n\n for (const child of node.nodes) {\n stringify(child, depth + 1);\n }\n\n const closeSegment = minify ? \"}\" : `${ind}}\\n`;\n parts.push(closeSegment);\n pos += closeSegment.length;\n annotate(node, start, pos);\n return;\n }\n\n // At-rule\n if (node.kind === \"at-rule\") {\n const start = pos;\n const params = node.params ? ` ${node.params}` : \"\";\n\n if (node.nodes.length === 0) {\n const segment = minify ? `${node.name}${params};` : `${ind}${node.name}${params};\\n`;\n parts.push(segment);\n pos += segment.length;\n annotate(node, start, pos);\n return;\n }\n\n const openSegment = minify ? `${node.name}${params}{` : `${ind}${node.name}${params} {\\n`;\n parts.push(openSegment);\n pos += openSegment.length;\n\n for (const child of node.nodes) {\n stringify(child, depth + 1);\n }\n\n const closeSegment = minify ? \"}\" : `${ind}}\\n`;\n parts.push(closeSegment);\n pos += closeSegment.length;\n annotate(node, start, pos);\n return;\n }\n\n // Comment\n if (node.kind === \"comment\") {\n if (minify) return; // Skip comments in minified output\n\n const start = pos;\n const segment = `${ind}/*${node.value}*/\\n`;\n parts.push(segment);\n pos += segment.length;\n annotate(node, start, pos);\n return;\n }\n\n // Context - flatten at same depth\n if (node.kind === \"context\") {\n for (const child of node.nodes) {\n stringify(child, depth);\n }\n return;\n }\n\n // At-root - flatten to depth 0\n if (node.kind === \"at-root\") {\n for (const child of node.nodes) {\n stringify(child, 0);\n }\n return;\n }\n }\n\n for (const node of ast) {\n stringify(node, 0);\n }\n\n const code = parts.join(\"\");\n source.code = code;\n\n return { code, source };\n}\n\n/**\n * Build a decoded source map from AST nodes.\n *\n * This is Pass 2 of the optimized source map pipeline.\n * Uses pre-computed line tables for O(log n) position lookups.\n *\n * Key optimizations:\n * - Binary search via line tables (not O(offset) scans)\n * - Lazy line table computation via DefaultMap\n * - No VLQ encoding - outputs ECMA-426 decoded format\n */\nfunction _buildDecodedSourceMap(ast: AstNode[], generatedSource: Source): DecodedSourceMap {\n // Lazy line table computation - only computed once per source\n const lineTables = new DefaultMap<Source, LineTable>((src) => buildLineTable(src.code));\n\n // Lazy decoded source creation\n const sourceTable = new DefaultMap<Source, DecodedSource>((src) => ({\n url: src.file,\n content: src.code,\n ignore: false,\n }));\n\n const map: DecodedSourceMap = {\n file: generatedSource.file,\n sources: [],\n mappings: [],\n };\n\n // Get generated line table once\n const generatedTable = lineTables.get(generatedSource);\n\n function processNode(node: AstNode): void {\n // Skip nodes without source positions\n if (node.kind === \"context\" || node.kind === \"at-root\") {\n // Process children\n for (const child of node.nodes) {\n processNode(child);\n }\n return;\n }\n\n // Need both src (original) and dst (generated) positions\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic property access\n if (node.src && (node as any).dst) {\n const [srcSource, srcStart] = node.src;\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- dynamic property access\n const [, dstStart] = (node as any).dst;\n\n const originalSource = sourceTable.get(srcSource);\n const originalTable = lineTables.get(srcSource);\n\n // O(log n) position lookups via binary search\n const originalPos = originalTable.find(srcStart);\n const generatedPos = generatedTable.find(dstStart);\n\n map.mappings.push({\n name: null,\n originalPosition: {\n source: originalSource,\n ...originalPos,\n },\n generatedPosition: generatedPos,\n });\n }\n\n // Process children\n if (\"nodes\" in node && Array.isArray(node.nodes)) {\n for (const child of node.nodes) {\n processNode(child);\n }\n }\n }\n\n for (const node of ast) {\n processNode(node);\n }\n\n // Populate sources array (deduplicated)\n const seenSources = new Set<DecodedSource>();\n for (const [, decodedSource] of sourceTable.entries()) {\n if (!seenSources.has(decodedSource)) {\n seenSources.add(decodedSource);\n map.sources.push(decodedSource);\n }\n }\n\n return map;\n}\n\n// ============================================\n// Option C: Single-Pass with Deferred Line/Column\n// ============================================\n\n/**\n * CSS generation with raw byte offset tracking (no line/column computation).\n * This matches Tailwind's toCss(ast, true) approach for maximum performance.\n */\nfunction toCssWithRawMappings(ast: AstNode[], minify: boolean, indent: string): RawSourceMapResult {\n const indents = minify ? null : getIndentArray(indent);\n let code = \"\";\n const generatedLineStarts = [0];\n\n // Raw mappings - just byte offsets\n const sources: Source[] = [];\n const srcOffsets: number[] = [];\n const dstOffsets: number[] = [];\n\n function stringify(node: AstNode, depth: number): void {\n const ind = indents ? (indents[depth] ?? indent.repeat(depth)) : \"\";\n\n if (node.kind === \"declaration\") {\n if (node.value === undefined) return;\n const start = code.length;\n if (minify) {\n code += node.property + \":\" + node.value + (node.important ? \"!important\" : \"\") + \";\";\n } else {\n code += ind + node.property + \": \" + node.value + (node.important ? \" !important\" : \"\") + \";\\n\";\n generatedLineStarts.push(code.length);\n }\n if (node.src) {\n sources.push(node.src[0]);\n srcOffsets.push(node.src[1]);\n dstOffsets.push(start);\n }\n return;\n }\n\n if (node.kind === \"rule\") {\n const start = code.length;\n if (node.nodes.length === 0) {\n code += minify ? node.selector + \"{}\" : ind + node.selector + \" {}\\n\";\n if (!minify) generatedLineStarts.push(code.length);\n } else {\n code += minify ? node.selector + \"{\" : ind + node.selector + \" {\\n\";\n if (!minify) generatedLineStarts.push(code.length);\n for (const child of node.nodes) stringify(child, depth + 1);\n code += minify ? \"}\" : ind + \"}\\n\";\n if (!minify) generatedLineStarts.push(code.length);\n }\n if (node.src) {\n sources.push(node.src[0]);\n srcOffsets.push(node.src[1]);\n dstOffsets.push(start);\n }\n return;\n }\n\n if (node.kind === \"at-rule\") {\n const start = code.length;\n const params = node.params ? \" \" + node.params : \"\";\n if (node.nodes.length === 0) {\n code += minify ? node.name + params + \";\" : ind + node.name + params + \";\\n\";\n if (!minify) generatedLineStarts.push(code.length);\n } else {\n code += minify ? node.name + params + \"{\" : ind + node.name + params + \" {\\n\";\n if (!minify) generatedLineStarts.push(code.length);\n for (const child of node.nodes) stringify(child, depth + 1);\n code += minify ? \"}\" : ind + \"}\\n\";\n if (!minify) generatedLineStarts.push(code.length);\n }\n if (node.src) {\n sources.push(node.src[0]);\n srcOffsets.push(node.src[1]);\n dstOffsets.push(start);\n }\n return;\n }\n\n if (node.kind === \"comment\") {\n if (minify) return;\n const start = code.length;\n code += ind + \"/*\" + node.value + \"*/\\n\";\n generatedLineStarts.push(code.length);\n if (node.src) {\n sources.push(node.src[0]);\n srcOffsets.push(node.src[1]);\n dstOffsets.push(start);\n }\n return;\n }\n\n if (node.kind === \"context\") {\n for (const child of node.nodes) stringify(child, depth);\n return;\n }\n\n if (node.kind === \"at-root\") {\n for (const child of node.nodes) stringify(child, 0);\n return;\n }\n }\n\n for (const node of ast) stringify(node, 0);\n\n return {\n code,\n generatedLineStarts,\n rawMappings: { sources, srcOffsets, dstOffsets },\n };\n}\n\n/**\n * Build line starts array - minimal overhead version.\n * Returns array of byte offsets where each line starts.\n * Handles both LF (\\n) and CRLF (\\r\\n) line endings.\n */\nfunction buildLineStarts(code: string): number[] {\n const lineStarts = [0];\n const LF = 0x0a; // \\n\n const CR = 0x0d; // \\r\n\n for (let i = 0; i < code.length; i++) {\n const char = code.charCodeAt(i);\n if (char === LF) {\n // LF or end of CRLF\n lineStarts.push(i + 1);\n } else if (char === CR) {\n // CR - check if followed by LF (CRLF)\n if (code.charCodeAt(i + 1) === LF) {\n // CRLF - skip LF, line starts after both\n lineStarts.push(i + 2);\n i++; // Skip the LF\n } else {\n // Standalone CR (old Mac style)\n lineStarts.push(i + 1);\n }\n }\n }\n return lineStarts;\n}\n\n/**\n * Binary search to find line number for a byte offset.\n * Returns 0-based line number.\n */\nfunction binarySearchLine(lineStarts: number[], offset: number): number {\n let line = 0;\n let count = lineStarts.length;\n while (count > 0) {\n const mid = (count | 0) >> 1;\n const i = line + mid;\n if (lineStarts[i]! <= offset) {\n line = i + 1;\n count = count - mid - 1;\n } else {\n count = mid;\n }\n }\n return line - 1;\n}\n\n/**\n * Single-pass CSS generation with deferred line/column computation.\n *\n * Key optimizations:\n * - Single AST traversal (no two-pass overhead)\n * - Direct string concatenation (V8 optimizes this well)\n * - Flat array for raw mappings (no object allocation in hot path)\n * - Batch line/column conversion using inline binary search\n * - Cached source lookups\n *\n * This is the fastest path for decoded source maps.\n */\nfunction toCssWithDecodedMap(\n ast: AstNode[],\n minify: boolean,\n indent: string,\n file?: string\n): { code: string; decodedMap: DecodedSourceMap } {\n const indents = minify ? null : getIndentArray(indent);\n\n // Use direct concatenation - V8 optimizes this well for string building\n let code = \"\";\n\n // Track generated line starts during CSS generation (avoids second pass)\n const generatedLineStarts = [0];\n\n // Flat raw mappings: [src, srcOffset, dstOffset, src, srcOffset, dstOffset, ...]\n // Using flat array avoids object allocation overhead in hot path\n const rawSources: Source[] = [];\n const rawSrcOffsets: number[] = [];\n const rawDstOffsets: number[] = [];\n\n function stringify(node: AstNode, depth: number): void {\n const ind = indents ? (indents[depth] ?? indent.repeat(depth)) : \"\";\n\n // Declaration - most common case\n if (node.kind === \"declaration\") {\n if (node.value === undefined) return;\n\n const start = code.length;\n\n if (minify) {\n code += node.property;\n code += \":\";\n code += node.value;\n if (node.important) code += \"!important\";\n code += \";\";\n } else {\n code += ind;\n code += node.property;\n code += \": \";\n code += node.value;\n if (node.important) code += \" !important\";\n code += \";\\n\";\n generatedLineStarts.push(code.length); // Track newline\n }\n\n if (node.src) {\n rawSources.push(node.src[0]);\n rawSrcOffsets.push(node.src[1]);\n rawDstOffsets.push(start);\n }\n return;\n }\n\n // Rule\n if (node.kind === \"rule\") {\n const start = code.length;\n\n if (node.nodes.length === 0) {\n if (minify) {\n code += node.selector;\n code += \"{}\";\n } else {\n code += ind;\n code += node.selector;\n code += \" {}\\n\";\n generatedLineStarts.push(code.length);\n }\n if (node.src) {\n rawSources.push(node.src[0]);\n rawSrcOffsets.push(node.src[1]);\n rawDstOffsets.push(start);\n }\n return;\n }\n\n if (minify) {\n code += node.selector;\n code += \"{\";\n } else {\n code += ind;\n code += node.selector;\n code += \" {\\n\";\n generatedLineStarts.push(code.length);\n }\n\n for (const child of node.nodes) {\n stringify(child, depth + 1);\n }\n\n if (minify) {\n code += \"}\";\n } else {\n code += ind;\n code += \"}\\n\";\n generatedLineStarts.push(code.length);\n }\n\n if (node.src) {\n rawSources.push(node.src[0]);\n rawSrcOffsets.push(node.src[1]);\n rawDstOffsets.push(start);\n }\n return;\n }\n\n // At-rule\n if (node.kind === \"at-rule\") {\n const start = code.length;\n\n if (node.nodes.length === 0) {\n if (minify) {\n code += node.name;\n if (node.params) {\n code += \" \";\n code += node.params;\n }\n code += \";\";\n } else {\n code += ind;\n code += node.name;\n if (node.params) {\n code += \" \";\n code += node.params;\n }\n code += \";\\n\";\n generatedLineStarts.push(code.length);\n }\n if (node.src) {\n rawSources.push(node.src[0]);\n rawSrcOffsets.push(node.src[1]);\n rawDstOffsets.push(start);\n }\n return;\n }\n\n if (minify) {\n code += node.name;\n if (node.params) {\n code += \" \";\n code += node.params;\n }\n code += \"{\";\n } else {\n code += ind;\n code += node.name;\n if (node.params) {\n code += \" \";\n code += node.params;\n }\n code += \" {\\n\";\n generatedLineStarts.push(code.length);\n }\n\n for (const child of node.nodes) {\n stringify(child, depth + 1);\n }\n\n if (minify) {\n code += \"}\";\n } else {\n code += ind;\n code += \"}\\n\";\n generatedLineStarts.push(code.length);\n }\n\n if (node.src) {\n rawSources.push(node.src[0]);\n rawSrcOffsets.push(node.src[1]);\n rawDstOffsets.push(start);\n }\n return;\n }\n\n // Comment\n if (node.kind === \"comment\") {\n if (minify) return;\n\n const start = code.length;\n code += ind;\n code += \"/*\";\n code += node.value;\n code += \"*/\\n\";\n generatedLineStarts.push(code.length);\n\n if (node.src) {\n rawSources.push(node.src[0]);\n rawSrcOffsets.push(node.src[1]);\n rawDstOffsets.push(start);\n }\n return;\n }\n\n // Context - flatten at same depth\n if (node.kind === \"context\") {\n for (const child of node.nodes) {\n stringify(child, depth);\n }\n return;\n }\n\n // At-root - flatten to depth 0\n if (node.kind === \"at-root\") {\n for (const child of node.nodes) {\n stringify(child, 0);\n }\n return;\n }\n }\n\n // Generate CSS and collect raw mappings (line starts tracked inline)\n for (const node of ast) {\n stringify(node, 0);\n }\n\n // Source line starts - use Map for O(1) lookup\n const sourceLineStarts = new Map<Source, number[]>();\n const decodedSources = new Map<Source, DecodedSource>();\n\n function getLineStarts(src: Source): number[] {\n let starts = sourceLineStarts.get(src);\n if (!starts) {\n starts = buildLineStarts(src.code);\n sourceLineStarts.set(src, starts);\n }\n return starts;\n }\n\n function getDecodedSource(src: Source): DecodedSource {\n let decoded = decodedSources.get(src);\n if (!decoded) {\n decoded = { url: src.file, content: src.code, ignore: false };\n decodedSources.set(src, decoded);\n }\n return decoded;\n }\n\n // Convert raw mappings to decoded mappings\n const mappingCount = rawSources.length;\n const mappings: DecodedMapping[] = new Array(mappingCount);\n\n for (let i = 0; i < mappingCount; i++) {\n const src = rawSources[i]!;\n const srcOffset = rawSrcOffsets[i]!;\n const dstOffset = rawDstOffsets[i]!;\n\n const originalSource = getDecodedSource(src);\n const originalLineStarts = getLineStarts(src);\n const sourceLength = src.code.length;\n\n // Validate srcOffset is within source bounds\n // Throw an error instead of silently clamping - out-of-bounds offsets indicate upstream bugs\n if (srcOffset < 0 || srcOffset > sourceLength) {\n throw new SourceMapError(\n `Source offset ${srcOffset} out of bounds for source \"${src.file ?? \"<anonymous>\"}\" (length ${sourceLength}). ` +\n `This indicates a bug in the code that generated the AST.`\n );\n }\n\n // Handle BOM (U+FEFF) offset correction\n // If source starts with BOM, the CSS parser replaces it with a space at position 0,\n // preserving byte offsets. This means srcOffset values remain valid without adjustment.\n // We verify BOM handling is correct by checking the source hasn't been truncated.\n\n // Inline binary search for original position\n const srcLine = binarySearchLine(originalLineStarts, srcOffset);\n // Ensure srcLine is valid (handles edge case of empty source)\n const validSrcLine = Math.max(0, Math.min(srcLine, originalLineStarts.length - 1));\n const srcColumn = srcOffset - (originalLineStarts[validSrcLine] ?? 0);\n\n // Inline binary search for generated position\n const dstLine = binarySearchLine(generatedLineStarts, dstOffset);\n // Ensure dstLine is valid\n const validDstLine = Math.max(0, Math.min(dstLine, generatedLineStarts.length - 1));\n const dstColumn = dstOffset - (generatedLineStarts[validDstLine] ?? 0);\n\n mappings[i] = {\n name: null,\n originalPosition: {\n source: originalSource,\n line: validSrcLine,\n column: Math.max(0, srcColumn), // Ensure column is non-negative\n },\n generatedPosition: {\n line: validDstLine,\n column: Math.max(0, dstColumn), // Ensure column is non-negative\n },\n };\n }\n\n // Collect unique sources\n const sources = Array.from(decodedSources.values());\n\n return {\n code,\n decodedMap: {\n file: file ?? null,\n sources,\n mappings,\n },\n };\n}\n\n// ============================================\n// Native Acceleration (optional fast path)\n// ============================================\n\n/**\n * Try to print using native Rust printer.\n * Returns null if native is unavailable.\n *\n * This is faster than the TypeScript implementation for large ASTs,\n * but doesn't support source maps.\n */\nexport function printNative(ast: AstNode[], options: { minify?: boolean } = {}): string | null {\n try {\n // Dynamic import to avoid hard dependency\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const oxide = require(\"@rainbowindex/oxide\");\n\n if (typeof oxide.toCss !== \"function\") {\n return null;\n }\n\n // Convert AST to native format\n const nativeAst = ast.map(nodeToNative);\n\n if (options.minify) {\n return oxide.toCssMinified(nativeAst);\n }\n\n return oxide.toCssPretty(nativeAst);\n } catch {\n return null;\n }\n}\n\n/**\n * Convert a TypeScript AST node to native format.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any -- native format uses dynamic structure\nfunction nodeToNative(node: AstNode): any {\n if (node.kind === \"declaration\") {\n return {\n kind: \"declaration\",\n property: node.property,\n value: node.value,\n important: node.important,\n };\n }\n if (node.kind === \"rule\") {\n return {\n kind: \"rule\",\n selector: node.selector,\n nodes: node.nodes.map(nodeToNative),\n };\n }\n if (node.kind === \"at-rule\") {\n return {\n kind: \"at-rule\",\n selector: node.name,\n params: node.params,\n nodes: node.nodes.map(nodeToNative),\n };\n }\n if (node.kind === \"comment\") {\n return {\n kind: \"comment\",\n value: node.value,\n };\n }\n if (node.kind === \"context\") {\n return {\n kind: \"context\",\n nodes: node.nodes.map(nodeToNative),\n };\n }\n if (node.kind === \"at-root\") {\n return {\n kind: \"at-root\",\n nodes: (node as { nodes: AstNode[] }).nodes.map(nodeToNative),\n };\n }\n return node;\n}\n\n/**\n * @internal\n * Exposed for tests and tooling only.\n */\nexport const __nodeToNative = nodeToNative;\n\n/**\n * @internal\n * Exposed for tests and tooling only.\n */\nexport const __toCssWithPositions = _toCssWithPositions;\n\n/**\n * @internal\n * Exposed for tests and tooling only.\n */\nexport const __buildDecodedSourceMap = _buildDecodedSourceMap;\n\n/**\n * Minify CSS by removing whitespace and comments.\n */\nexport function minify(css: string): string {\n // Remove comments\n css = css.replace(/\\/\\*[\\s\\S]*?\\*\\//g, \"\");\n\n // Remove whitespace around special characters\n css = css.replace(/\\s*([{};:,>+~])\\s*/g, \"$1\");\n\n // Remove whitespace around brackets in selectors\n css = css.replace(/\\s*\\[\\s*/g, \"[\");\n css = css.replace(/\\s*\\]\\s*/g, \"]\");\n\n // Collapse multiple spaces\n css = css.replace(/\\s+/g, \" \");\n\n // Remove leading/trailing whitespace\n css = css.trim();\n\n return css;\n}\n","/**\n * Candidate Types\n *\n * Defines the structure of parsed utility class candidates.\n * A candidate like \"hover:bg-red-500/75\" is parsed into its constituent parts.\n */\n\n/** A named value like \"red-500\" in \"bg-red-500\" */\nexport interface NamedValue {\n kind: \"named\";\n /** The value name, e.g., \"red-500\" */\n value: string;\n /** Fraction part if present, e.g., \"1/2\" in \"w-1/2\" */\n fraction: string | null;\n}\n\n/** An arbitrary value like \"[#ff0000]\" in \"bg-[#ff0000]\" */\nexport interface ArbitraryValue {\n kind: \"arbitrary\";\n /** The raw value inside brackets */\n value: string;\n /** Optional data type hint, e.g., \"color\" in \"bg-[color:#ff0000]\" */\n dataType: string | null;\n}\n\nexport type CandidateValue = NamedValue | ArbitraryValue;\n\n/** A named modifier like \"75\" in \"bg-red-500/75\" */\nexport interface NamedModifier {\n kind: \"named\";\n value: string;\n}\n\n/** An arbitrary modifier like \"[0.5]\" in \"bg-red-500/[0.5]\" */\nexport interface ArbitraryModifier {\n kind: \"arbitrary\";\n value: string;\n dashedIdent: string | null;\n}\n\nexport type CandidateModifier = NamedModifier | ArbitraryModifier;\n\n/** A static variant like \"hover\" */\nexport interface StaticVariant {\n kind: \"static\";\n root: string;\n}\n\n/** A functional variant like \"aria-disabled\" or \"md\" */\nexport interface FunctionalVariant {\n kind: \"functional\";\n root: string;\n value: CandidateValue | null;\n modifier: CandidateModifier | null;\n}\n\n/** An arbitrary variant like \"[&_p]\" */\nexport interface ArbitraryVariant {\n kind: \"arbitrary\";\n selector: string;\n relative: boolean;\n}\n\n/** A compound variant like \"group-hover\" */\nexport interface CompoundVariant {\n kind: \"compound\";\n root: string;\n modifier: CandidateModifier | null;\n variant: Variant;\n}\n\nexport type Variant = StaticVariant | FunctionalVariant | ArbitraryVariant | CompoundVariant;\n\n/** A static candidate like \"flex\" or \"hidden\" */\nexport interface StaticCandidate {\n kind: \"static\";\n /** The utility name */\n root: string;\n /** Applied variants in order */\n variants: Variant[];\n /** Whether !important is applied */\n important: boolean;\n /** Original raw string */\n raw: string;\n}\n\n/** A functional candidate like \"bg-red-500\" or \"p-4\" */\nexport interface FunctionalCandidate {\n kind: \"functional\";\n /** The utility prefix, e.g., \"bg\" */\n root: string;\n /** The value part */\n value: CandidateValue | null;\n /** The modifier part (e.g., opacity) */\n modifier: CandidateModifier | null;\n /** Applied variants in order */\n variants: Variant[];\n /** Whether !important is applied */\n important: boolean;\n /** Original raw string */\n raw: string;\n}\n\n/** An arbitrary property candidate like \"[color:red]\" */\nexport interface ArbitraryCandidate {\n kind: \"arbitrary\";\n /** CSS property name */\n property: string;\n /** CSS value */\n value: string;\n /** The modifier part */\n modifier: CandidateModifier | null;\n /** Applied variants in order */\n variants: Variant[];\n /** Whether !important is applied */\n important: boolean;\n /** Original raw string */\n raw: string;\n}\n\nexport type Candidate = StaticCandidate | FunctionalCandidate | ArbitraryCandidate;\n\nexport function isStaticCandidate(c: Candidate): c is StaticCandidate {\n return c.kind === \"static\";\n}\n\nexport function isFunctionalCandidate(c: Candidate): c is FunctionalCandidate {\n return c.kind === \"functional\";\n}\n\nexport function isArbitraryCandidate(c: Candidate): c is ArbitraryCandidate {\n return c.kind === \"arbitrary\";\n}\n\nexport function isStaticVariant(v: Variant): v is StaticVariant {\n return v.kind === \"static\";\n}\n\nexport function isFunctionalVariant(v: Variant): v is FunctionalVariant {\n return v.kind === \"functional\";\n}\n\nexport function isArbitraryVariant(v: Variant): v is ArbitraryVariant {\n return v.kind === \"arbitrary\";\n}\n\nexport function isCompoundVariant(v: Variant): v is CompoundVariant {\n return v.kind === \"compound\";\n}\n","/**\n * Arbitrary Value Validation\n *\n * Validates that arbitrary values have balanced brackets, parentheses, and quotes.\n * Prevents malformed CSS from being generated.\n *\n * Tailwind-compatible restrictions:\n * - Top-level semicolons are invalid (would end the declaration)\n * - Top-level curly braces are invalid (would start a new rule)\n */\n\n/** Bracket pairs for nesting (parentheses and square brackets) */\nconst BRACKETS: Record<string, string> = {\n \"(\": \")\",\n \"[\": \"]\",\n};\n\nconst CLOSING_BRACKETS = new Set([\")\", \"]\"]);\n\n/** Curly braces are tracked separately (invalid at top level) */\nconst CURLY_OPEN = \"{\";\nconst CURLY_CLOSE = \"}\";\n\n// Quote characters\nconst QUOTES = new Set([\"'\", '\"', \"`\"]);\n\n/**\n * Check if a character is a valid escape target.\n * Rejects control characters (0x00-0x1F, 0x7F) that could be used for injection attacks.\n *\n * Valid escape targets:\n * - Printable ASCII (0x20-0x7E)\n * - Unicode characters (0x80+)\n * - Newlines (backslash-newline is line continuation in CSS)\n */\nfunction isValidEscapeTarget(char: string | undefined): boolean {\n if (char === undefined) return false;\n\n const code = char.charCodeAt(0);\n\n // Allow newlines (line continuation) and carriage returns\n if (code === 0x0a || code === 0x0d) return true;\n\n // Reject control characters (0x00-0x1F except newlines, and 0x7F DEL)\n // Allow everything else (printable ASCII and Unicode)\n return code >= 0x20 && code !== 0x7f;\n}\n\n/**\n * Check if an arbitrary value has balanced brackets and quotes.\n *\n * Tailwind-compatible restrictions:\n * - Top-level semicolons are invalid (would end the declaration)\n * - Top-level curly braces are invalid (would start a new rule)\n *\n * @param value - The arbitrary value to validate (without outer brackets)\n * @returns true if the value is valid, false otherwise\n *\n * @example\n * ```ts\n * isValidArbitrary(\"calc(100% - 10px)\") // true\n * isValidArbitrary(\"url('image.png')\") // true\n * isValidArbitrary(\"calc(100% - 10px\") // false - unbalanced paren\n * isValidArbitrary(\"url('image.png)\") // false - unbalanced quote\n * isValidArbitrary(\"red; color: blue\") // false - top-level semicolon\n * isValidArbitrary(\"{ color: red }\") // false - top-level curly braces\n * ```\n */\n// Char codes for faster comparison\nconst CHAR_BACKSLASH = 0x5c; // \\\nconst CHAR_SINGLE_QUOTE = 0x27; // '\nconst CHAR_DOUBLE_QUOTE = 0x22; // \"\nconst CHAR_BACKTICK = 0x60; // `\nconst CHAR_SEMICOLON = 0x3b; // ;\nconst CHAR_OPEN_BRACE = 0x7b; // {\nconst CHAR_CLOSE_BRACE = 0x7d; // }\nconst CHAR_OPEN_PAREN = 0x28; // (\nconst CHAR_CLOSE_PAREN = 0x29; // )\nconst CHAR_OPEN_BRACKET = 0x5b; // [\nconst CHAR_CLOSE_BRACKET = 0x5d; // ]\n\nexport function isValidArbitrary(value: string): boolean {\n const len = value.length;\n\n // Fast path for very short values:\n // If length <= 4 and no special chars, it's valid.\n if (len <= 4) {\n let hasSpecial = false;\n for (let j = 0; j < len; j++) {\n const c = value.charCodeAt(j);\n if (\n c === CHAR_OPEN_PAREN ||\n c === CHAR_CLOSE_PAREN ||\n c === CHAR_OPEN_BRACKET ||\n c === CHAR_CLOSE_BRACKET ||\n c === CHAR_OPEN_BRACE ||\n c === CHAR_CLOSE_BRACE ||\n c === CHAR_DOUBLE_QUOTE ||\n c === CHAR_SINGLE_QUOTE ||\n c === CHAR_BACKTICK ||\n c === CHAR_SEMICOLON ||\n c === CHAR_BACKSLASH\n ) {\n hasSpecial = true;\n break;\n }\n }\n if (!hasSpecial) {\n return true;\n }\n }\n\n // Fast path: check if we need full validation\n // If no brackets, quotes, semicolons, or curly braces, it's valid\n let needsValidation = false;\n for (let j = 0; j < len; j++) {\n const c = value.charCodeAt(j);\n // Check for ( ) [ ] { } \" ' ` ; \\\n if (\n c === CHAR_OPEN_PAREN ||\n c === CHAR_CLOSE_PAREN ||\n c === CHAR_OPEN_BRACKET ||\n c === CHAR_CLOSE_BRACKET ||\n c === CHAR_OPEN_BRACE ||\n c === CHAR_CLOSE_BRACE ||\n c === CHAR_DOUBLE_QUOTE ||\n c === CHAR_SINGLE_QUOTE ||\n c === CHAR_BACKTICK ||\n c === CHAR_SEMICOLON ||\n c === CHAR_BACKSLASH\n ) {\n needsValidation = true;\n break;\n }\n }\n if (!needsValidation) {\n return true;\n }\n\n // Use numeric stack for bracket tracking (faster than string array)\n // Stack stores expected closing bracket char codes\n const stack: number[] = [];\n let inQuote = 0; // 0 = not in quote, otherwise the quote char code\n let curlyDepth = 0;\n let i = 0;\n\n while (i < len) {\n const c = value.charCodeAt(i);\n\n // Handle escape sequences\n if (c === CHAR_BACKSLASH) {\n // Check for trailing backslash (invalid)\n if (i + 1 >= len) {\n return false;\n }\n // Validate the escaped character - reject control characters\n const next = value[i + 1];\n if (!isValidEscapeTarget(next)) {\n return false;\n }\n i += 2;\n continue;\n }\n\n // Handle quotes\n if (c === CHAR_SINGLE_QUOTE || c === CHAR_DOUBLE_QUOTE || c === CHAR_BACKTICK) {\n if (inQuote === 0) {\n inQuote = c;\n } else if (inQuote === c) {\n inQuote = 0;\n }\n i++;\n continue;\n }\n\n // If we're in a quoted string, skip all other handling\n if (inQuote !== 0) {\n i++;\n continue;\n }\n\n // Check for top-level semicolon (invalid - would end declaration)\n if (c === CHAR_SEMICOLON && stack.length === 0 && curlyDepth === 0) {\n return false;\n }\n\n // Handle curly braces (invalid at top level)\n if (c === CHAR_OPEN_BRACE) {\n if (stack.length === 0 && curlyDepth === 0) {\n return false;\n }\n curlyDepth++;\n i++;\n continue;\n }\n\n if (c === CHAR_CLOSE_BRACE) {\n if (curlyDepth === 0) {\n return false;\n }\n curlyDepth--;\n i++;\n continue;\n }\n\n // Handle opening brackets - push expected closing\n if (c === CHAR_OPEN_PAREN) {\n stack.push(CHAR_CLOSE_PAREN);\n i++;\n continue;\n }\n if (c === CHAR_OPEN_BRACKET) {\n stack.push(CHAR_CLOSE_BRACKET);\n i++;\n continue;\n }\n\n // Handle closing brackets\n if (c === CHAR_CLOSE_PAREN || c === CHAR_CLOSE_BRACKET) {\n if (stack.length === 0 || stack.pop() !== c) {\n return false;\n }\n i++;\n continue;\n }\n\n i++;\n }\n\n // Valid if no unclosed quotes, all brackets are closed, and curly braces balanced\n return inQuote === 0 && stack.length === 0 && curlyDepth === 0;\n}\n\n/**\n * Detailed validation result with error information.\n */\nexport interface ValidationResult {\n valid: boolean;\n error?: string;\n position?: number;\n}\n\n/**\n * Validate an arbitrary value with detailed error reporting.\n *\n * @param value - The arbitrary value to validate\n * @returns Validation result with error details if invalid\n *\n * @example\n * ```ts\n * validateArbitrary(\"calc(100% - 10px)\")\n * // { valid: true }\n *\n * validateArbitrary(\"calc(100% - 10px\")\n * // { valid: false, error: \"Unclosed '('\", position: 4 }\n *\n * validateArbitrary(\"red; color: blue\")\n * // { valid: false, error: \"Top-level semicolon not allowed\", position: 3 }\n * ```\n */\nexport function validateArbitrary(value: string): ValidationResult {\n const stack: Array<{ char: string; position: number }> = [];\n const curlyStack: Array<{ position: number }> = [];\n let inQuote: { char: string; position: number } | null = null;\n let i = 0;\n\n while (i < value.length) {\n const char = value[i]!;\n\n // Handle escape sequences\n if (char === \"\\\\\") {\n if (i + 1 >= value.length) {\n return {\n valid: false,\n error: \"Trailing backslash\",\n position: i,\n };\n }\n const next = value[i + 1];\n if (!isValidEscapeTarget(next)) {\n const code = next?.charCodeAt(0) ?? 0;\n return {\n valid: false,\n error: `Invalid escape target: control character (0x${code.toString(16).padStart(2, \"0\")})`,\n position: i + 1,\n };\n }\n i += 2;\n continue;\n }\n\n // Handle quotes\n if (QUOTES.has(char)) {\n if (inQuote === null) {\n inQuote = { char, position: i };\n } else if (inQuote.char === char) {\n inQuote = null;\n }\n i++;\n continue;\n }\n\n // Skip all other handling inside quotes\n if (inQuote !== null) {\n i++;\n continue;\n }\n\n // Check for top-level semicolon\n if (char === \";\" && stack.length === 0 && curlyStack.length === 0) {\n return {\n valid: false,\n error: \"Top-level semicolon not allowed\",\n position: i,\n };\n }\n\n // Handle curly braces (invalid at top level)\n if (char === CURLY_OPEN) {\n if (stack.length === 0 && curlyStack.length === 0) {\n return {\n valid: false,\n error: \"Top-level curly brace not allowed\",\n position: i,\n };\n }\n curlyStack.push({ position: i });\n i++;\n continue;\n }\n\n if (char === CURLY_CLOSE) {\n if (curlyStack.length === 0) {\n return {\n valid: false,\n error: `Unexpected closing '}'`,\n position: i,\n };\n }\n curlyStack.pop();\n i++;\n continue;\n }\n\n // Handle opening brackets\n if (char in BRACKETS) {\n stack.push({ char, position: i });\n i++;\n continue;\n }\n\n // Handle closing brackets\n if (CLOSING_BRACKETS.has(char)) {\n const opening = stack.pop();\n if (!opening) {\n return {\n valid: false,\n error: `Unexpected closing '${char}'`,\n position: i,\n };\n }\n if (BRACKETS[opening.char] !== char) {\n return {\n valid: false,\n error: `Mismatched brackets: expected '${BRACKETS[opening.char]}' but found '${char}'`,\n position: i,\n };\n }\n i++;\n continue;\n }\n\n i++;\n }\n\n // Check for unclosed quotes\n if (inQuote !== null) {\n return {\n valid: false,\n error: `Unclosed quote '${inQuote.char}'`,\n position: inQuote.position,\n };\n }\n\n // Check for unclosed brackets\n if (stack.length > 0) {\n const unclosed = stack[stack.length - 1]!;\n return {\n valid: false,\n error: `Unclosed '${unclosed.char}'`,\n position: unclosed.position,\n };\n }\n\n // Check for unclosed curly braces\n if (curlyStack.length > 0) {\n const unclosed = curlyStack[curlyStack.length - 1]!;\n return {\n valid: false,\n error: `Unclosed '{'`,\n position: unclosed.position,\n };\n }\n\n return { valid: true };\n}\n\n/**\n * Extract the content of balanced brackets starting at a position.\n * Useful for parsing nested structures.\n *\n * @param value - The string to parse\n * @param start - Starting position (should be at an opening bracket)\n * @returns The content inside the brackets, or null if unbalanced\n *\n * @example\n * ```ts\n * extractBracketContent(\"calc(100% - min(50px, 10%))\", 4)\n * // \"100% - min(50px, 10%)\"\n * ```\n */\nexport function extractBracketContent(value: string, start: number): string | null {\n const openChar = value[start];\n if (!openChar || !(openChar in BRACKETS)) {\n return null;\n }\n\n const closeChar = BRACKETS[openChar]!;\n let depth = 1;\n let i = start + 1;\n let inQuote: string | null = null;\n\n while (i < value.length && depth > 0) {\n const char = value[i]!;\n\n // Handle escapes\n if (char === \"\\\\\") {\n i += 2;\n continue;\n }\n\n // Handle quotes\n if (QUOTES.has(char)) {\n if (inQuote === null) {\n inQuote = char;\n } else if (inQuote === char) {\n inQuote = null;\n }\n i++;\n continue;\n }\n\n // Skip bracket handling inside quotes\n if (inQuote !== null) {\n i++;\n continue;\n }\n\n if (char === openChar) {\n depth++;\n } else if (char === closeChar) {\n depth--;\n }\n\n i++;\n }\n\n if (depth !== 0) {\n return null; // Unbalanced\n }\n\n return value.slice(start + 1, i - 1);\n}\n\n/**\n * Split a string by a delimiter, respecting brackets and quotes.\n *\n * @param value - The string to split\n * @param delimiter - The delimiter to split by\n * @returns Array of split segments\n *\n * @example\n * ```ts\n * splitBalanced(\"a, b, c\", \",\")\n * // [\"a\", \" b\", \" c\"]\n *\n * splitBalanced(\"rgb(255, 0, 0), blue\", \",\")\n * // [\"rgb(255, 0, 0)\", \" blue\"]\n * ```\n */\nexport function splitBalanced(value: string, delimiter: string): string[] {\n const result: string[] = [];\n let current = \"\";\n let depth = 0;\n let inQuote: string | null = null;\n let i = 0;\n\n while (i < value.length) {\n const char = value[i]!;\n\n // Handle escapes\n if (char === \"\\\\\") {\n current += char + (value[i + 1] ?? \"\");\n i += 2;\n continue;\n }\n\n // Handle quotes\n if (QUOTES.has(char)) {\n if (inQuote === null) {\n inQuote = char;\n } else if (inQuote === char) {\n inQuote = null;\n }\n current += char;\n i++;\n continue;\n }\n\n // Handle brackets (including curly braces for depth tracking)\n if (inQuote === null) {\n if (char in BRACKETS || char === CURLY_OPEN) {\n depth++;\n } else if (CLOSING_BRACKETS.has(char) || char === CURLY_CLOSE) {\n depth--;\n }\n }\n\n // Check for delimiter\n if (depth === 0 && inQuote === null && value.slice(i, i + delimiter.length) === delimiter) {\n result.push(current);\n current = \"\";\n i += delimiter.length;\n continue;\n }\n\n current += char;\n i++;\n }\n\n result.push(current);\n return result;\n}\n","/**\n * Math Operators\n *\n * Utilities for handling CSS math functions (calc, min, max, clamp).\n */\n\n// Pre-compiled pattern for simple number validation (hoisted to avoid recreation on every call)\nconst SIMPLE_NUMBER_PATTERN = /^-?(?:\\d+\\.?\\d*|\\.\\d+)(?:[a-zA-Z%]+)?$/;\n\n/**\n * CSS math functions that require whitespace around operators.\n */\nconst MATH_FUNCTIONS = new Set([\n \"calc\",\n \"min\",\n \"max\",\n \"clamp\",\n \"round\",\n \"mod\",\n \"rem\",\n \"sin\",\n \"cos\",\n \"tan\",\n \"asin\",\n \"acos\",\n \"atan\",\n \"atan2\",\n \"pow\",\n \"sqrt\",\n \"hypot\",\n \"log\",\n \"exp\",\n \"abs\",\n \"sign\",\n]);\n\n/**\n * Check if a value contains a CSS math function.\n *\n * @example\n * ```ts\n * hasMathFunction(\"calc(100% - 20px)\") // true\n * hasMathFunction(\"min(100px, 50%)\") // true\n * hasMathFunction(\"10px\") // false\n * ```\n */\nexport function hasMathFunction(value: string): boolean {\n const lower = value.toLowerCase();\n for (const fn of MATH_FUNCTIONS) {\n if (lower.includes(`${fn}(`)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Add whitespace around math operators (+, -, *, /) in CSS math functions.\n * Ensures valid CSS calc() syntax.\n *\n * @example\n * ```ts\n * addWhitespaceAroundMathOperators(\"calc(100%-20px)\")\n * // \"calc(100% - 20px)\"\n *\n * addWhitespaceAroundMathOperators(\"calc(2*3)\")\n * // \"calc(2 * 3)\"\n * ```\n */\nexport function addWhitespaceAroundMathOperators(value: string): string {\n if (!hasMathFunction(value)) {\n return value;\n }\n\n let result = \"\";\n let i = 0;\n let depth = 0;\n let inMathFn = false;\n let mathFnDepth = 0;\n\n while (i < value.length) {\n const char = value[i]!;\n const prevChar = i > 0 ? value[i - 1] : \"\";\n const nextChar = i < value.length - 1 ? value[i + 1] : \"\";\n\n // Track function depth\n if (char === \"(\") {\n // Check if we're entering a math function\n const beforeParen = value.slice(Math.max(0, i - 10), i).toLowerCase();\n for (const fn of MATH_FUNCTIONS) {\n if (beforeParen.endsWith(fn)) {\n if (!inMathFn) {\n inMathFn = true;\n mathFnDepth = depth + 1;\n }\n break;\n }\n }\n depth++;\n result += char;\n i++;\n continue;\n }\n\n if (char === \")\") {\n depth--;\n if (inMathFn && depth < mathFnDepth) {\n inMathFn = false;\n }\n result += char;\n i++;\n continue;\n }\n\n // Only process operators inside math functions\n if (!inMathFn) {\n result += char;\n i++;\n continue;\n }\n\n // Handle operators\n if (char === \"+\" || char === \"-\") {\n // Don't add space if:\n // - It's a sign for a number (after operator or open paren)\n // - It's in scientific notation (e.g., 1e-5)\n const isSign =\n prevChar === \"(\" ||\n prevChar === \",\" ||\n prevChar === \"+\" ||\n prevChar === \"-\" ||\n prevChar === \"*\" ||\n prevChar === \"/\" ||\n prevChar === \"\" ||\n /[eE]$/.test(result);\n\n if (isSign) {\n result += char;\n } else {\n // Add whitespace around the operator\n if (prevChar !== \" \") {\n result += \" \";\n }\n result += char;\n if (nextChar !== \" \" && nextChar !== \"\") {\n result += \" \";\n }\n }\n i++;\n continue;\n }\n\n if (char === \"*\" || char === \"/\") {\n // Add whitespace around multiplication and division\n if (prevChar !== \" \") {\n result += \" \";\n }\n result += char;\n if (nextChar !== \" \" && nextChar !== \"\") {\n result += \" \";\n }\n i++;\n continue;\n }\n\n result += char;\n i++;\n }\n\n // Clean up any double spaces\n return result.replace(/ +/g, \" \");\n}\n\n/**\n * Remove unnecessary whitespace from math expressions.\n * The opposite of addWhitespaceAroundMathOperators.\n *\n * @example\n * ```ts\n * removeWhitespaceAroundMathOperators(\"calc( 100% - 20px )\")\n * // \"calc(100%-20px)\"\n * ```\n */\nexport function removeWhitespaceAroundMathOperators(value: string): string {\n if (!hasMathFunction(value)) {\n return value;\n }\n\n // Remove spaces around operators (but this makes invalid CSS for calc!)\n // This is mainly for comparison/normalization purposes\n return value\n .replace(/\\s*\\+\\s*/g, \"+\")\n .replace(/\\s*-\\s*/g, \"-\")\n .replace(/\\s*\\*\\s*/g, \"*\")\n .replace(/\\s*\\/\\s*/g, \"/\")\n .replace(/\\(\\s+/g, \"(\")\n .replace(/\\s+\\)/g, \")\");\n}\n\n/**\n * Normalize a CSS math expression for consistent formatting.\n *\n * @example\n * ```ts\n * normalizeMathExpression(\"calc( 100% -20px )\")\n * // \"calc(100% - 20px)\"\n * ```\n */\nexport function normalizeMathExpression(value: string): string {\n // First, collapse all whitespace\n let normalized = value.replace(/\\s+/g, \" \").trim();\n\n // Then add proper whitespace around operators\n normalized = addWhitespaceAroundMathOperators(normalized);\n\n // Clean up spaces after ( and before )\n normalized = normalized.replace(/\\(\\s+/g, \"(\").replace(/\\s+\\)/g, \")\");\n\n // Clean up spaces around commas\n normalized = normalized.replace(/\\s*,\\s*/g, \", \");\n\n return normalized;\n}\n\n/**\n * Extract all math functions from a CSS value.\n *\n * @example\n * ```ts\n * extractMathFunctions(\"width: calc(100% - 20px); height: min(50vh, 300px)\")\n * // [\"calc(100% - 20px)\", \"min(50vh, 300px)\"]\n * ```\n */\nexport function extractMathFunctions(value: string): string[] {\n const result: string[] = [];\n const lower = value.toLowerCase();\n\n for (const fn of MATH_FUNCTIONS) {\n const pattern = new RegExp(`${fn}\\\\(`, \"gi\");\n let match: RegExpExecArray | null;\n\n while ((match = pattern.exec(lower)) !== null) {\n const start = match.index;\n let depth = 1;\n let end = start + fn.length + 1;\n\n while (end < value.length && depth > 0) {\n if (value[end] === \"(\") depth++;\n if (value[end] === \")\") depth--;\n end++;\n }\n\n if (depth === 0) {\n result.push(value.slice(start, end));\n }\n }\n }\n\n return result;\n}\n\n/**\n * Check if a value is a simple number (no math required).\n */\nexport function isSimpleNumber(value: string): boolean {\n return SIMPLE_NUMBER_PATTERN.test(value.trim());\n}\n\n/**\n * Simplification patterns for calc expressions.\n * Each pattern extracts the simplified value from capture group 1.\n */\nconst SIMPLIFY_PATTERNS: RegExp[] = [\n // calc(x +/- 0) -> x\n /^calc\\(\\s*([^+*/-]+)\\s*[+-]\\s*0(?:px|em|rem|%)?\\s*\\)$/i,\n // calc(0 + x) -> x\n /^calc\\(\\s*0(?:px|em|rem|%)?\\s*\\+\\s*(.+)\\s*\\)$/i,\n // calc(x * 1) -> x\n /^calc\\(\\s*(.+)\\s*\\*\\s*1\\s*\\)$/i,\n // calc(1 * x) -> x\n /^calc\\(\\s*1\\s*\\*\\s*(.+)\\s*\\)$/i,\n // calc(x / 1) -> x\n /^calc\\(\\s*(.+)\\s*\\/\\s*1\\s*\\)$/i,\n];\n\n/**\n * Try to simplify a math expression if possible.\n * Returns the original value if simplification isn't possible.\n *\n * @example\n * ```ts\n * simplifyMath(\"calc(10px + 10px)\") // \"20px\"\n * simplifyMath(\"calc(100% - 0px)\") // \"100%\"\n * simplifyMath(\"calc(100% - 20px)\") // \"calc(100% - 20px)\" (can't simplify mixed units)\n * ```\n */\nexport function simplifyMath(value: string): string {\n for (const pattern of SIMPLIFY_PATTERNS) {\n const match = value.match(pattern);\n if (match) return match[1]!.trim();\n }\n return value;\n}\n","/**\n * Decode Arbitrary Value\n *\n * Optimized implementation following tailwindcss pattern:\n * - Lightweight charCodeAt-based value parser\n * - Single-pass AST decoding (merged from two-pass)\n * - Cached function type detection\n * - Pre-compiled regex patterns\n * - Special handling for url(), var(), and theme()\n */\n\nimport { addWhitespaceAroundMathOperators } from \"./math-operators\";\nimport {\n BACKSLASH,\n CLOSE_PAREN,\n COLON,\n COMMA,\n DOUBLE_QUOTE,\n EQUALS,\n GREATER_THAN,\n LESS_THAN,\n LINE_BREAK as NEWLINE,\n OPEN_PAREN,\n SINGLE_QUOTE,\n SLASH,\n SPACE,\n TAB,\n} from \"../parser/char-codes\";\n\n// ============================================\n// Lightweight Value Parser (tailwindcss pattern)\n// ============================================\n\ntype ValueWordNode = {\n kind: \"word\";\n value: string;\n};\n\ntype ValueFunctionNode = {\n kind: \"function\";\n value: string;\n nodes: ValueAstNode[];\n};\n\ntype ValueSeparatorNode = {\n kind: \"separator\";\n value: string;\n};\n\ntype ValueAstNode = ValueWordNode | ValueFunctionNode | ValueSeparatorNode;\n\nfunction word(value: string): ValueWordNode {\n return { kind: \"word\", value };\n}\n\nfunction fun(value: string, nodes: ValueAstNode[]): ValueFunctionNode {\n return { kind: \"function\", value, nodes };\n}\n\nfunction separator(value: string): ValueSeparatorNode {\n return { kind: \"separator\", value };\n}\n\n// Pre-compiled regex patterns\nconst COMMA_NO_SPACE = /,(?!\\s)/g;\n\n// Fast math function check (inline version for performance)\nconst MATH_FN_QUICK = /\\b(?:calc|min|max|clamp)\\s*\\(/;\n\n/**\n * Parse a CSS value string into an AST.\n * Optimized with charCodeAt for fast character comparison and slice-based parsing.\n */\nfunction parseValue(input: string): ValueAstNode[] {\n const ast: ValueAstNode[] = [];\n const stack: (ValueFunctionNode | null)[] = [];\n let parent: ValueFunctionNode | null = null;\n let bufferStart = 0;\n let bufferEnd = 0;\n\n // Helper to flush buffer\n const flushBuffer = () => {\n if (bufferEnd > bufferStart) {\n const value = input.slice(bufferStart, bufferEnd);\n const node = word(value);\n if (parent) {\n parent.nodes.push(node);\n } else {\n ast.push(node);\n }\n }\n };\n\n for (let i = 0; i < input.length; i++) {\n const currentChar = input.charCodeAt(i);\n\n switch (currentChar) {\n // Escaped character - consume with next\n case BACKSLASH: {\n // Include both backslash and next char in buffer\n if (bufferEnd !== i) {\n flushBuffer();\n bufferStart = i;\n }\n bufferEnd = i + 2;\n i++;\n break;\n }\n\n // Slash as separate word (for theme(colors.red.500/10))\n case SLASH: {\n flushBuffer();\n const node = word(\"/\");\n if (parent) {\n parent.nodes.push(node);\n } else {\n ast.push(node);\n }\n bufferStart = i + 1;\n bufferEnd = i + 1;\n break;\n }\n\n // Separators (space, comma, colon, etc.)\n case COLON:\n case COMMA:\n case EQUALS:\n case GREATER_THAN:\n case LESS_THAN:\n case NEWLINE:\n case SPACE:\n case TAB: {\n flushBuffer();\n\n // Look ahead for consecutive separators\n const start = i;\n let end = i + 1;\n for (; end < input.length; end++) {\n const peekChar = input.charCodeAt(end);\n if (\n peekChar !== COLON &&\n peekChar !== COMMA &&\n peekChar !== EQUALS &&\n peekChar !== GREATER_THAN &&\n peekChar !== LESS_THAN &&\n peekChar !== NEWLINE &&\n peekChar !== SPACE &&\n peekChar !== TAB\n ) {\n break;\n }\n }\n i = end - 1;\n\n const node = separator(input.slice(start, end));\n if (parent) {\n parent.nodes.push(node);\n } else {\n ast.push(node);\n }\n bufferStart = i + 1;\n bufferEnd = i + 1;\n break;\n }\n\n // String literals\n case SINGLE_QUOTE:\n case DOUBLE_QUOTE: {\n // Include string in current buffer\n if (bufferEnd !== i) {\n flushBuffer();\n bufferStart = i;\n }\n for (let j = i + 1; j < input.length; j++) {\n const peekChar = input.charCodeAt(j);\n if (peekChar === BACKSLASH) {\n j += 1;\n } else if (peekChar === currentChar) {\n i = j;\n break;\n }\n }\n bufferEnd = i + 1;\n break;\n }\n\n // Function call start\n case OPEN_PAREN: {\n const funcName = input.slice(bufferStart, bufferEnd);\n const node = fun(funcName, []);\n if (parent) {\n parent.nodes.push(node);\n } else {\n ast.push(node);\n }\n stack.push(node);\n parent = node;\n bufferStart = i + 1;\n bufferEnd = i + 1;\n break;\n }\n\n // Function call end\n case CLOSE_PAREN: {\n const tail = stack.pop();\n if (bufferEnd > bufferStart && tail) {\n tail.nodes.push(word(input.slice(bufferStart, bufferEnd)));\n }\n parent = stack.length > 0 ? stack[stack.length - 1]! : null;\n bufferStart = i + 1;\n bufferEnd = i + 1;\n break;\n }\n\n // All other characters - extend buffer\n default: {\n if (bufferEnd !== i) {\n // Buffer was reset, start fresh\n flushBuffer();\n bufferStart = i;\n }\n bufferEnd = i + 1;\n }\n }\n }\n\n // Collect remainder\n flushBuffer();\n\n return ast;\n}\n\n/**\n * Serialize AST back to CSS string.\n */\nfunction toCss(ast: ValueAstNode[]): string {\n const parts: string[] = [];\n toCssParts(ast, parts);\n return parts.join(\"\");\n}\n\nfunction toCssParts(ast: ValueAstNode[], parts: string[]): void {\n for (const node of ast) {\n switch (node.kind) {\n case \"word\":\n case \"separator\":\n parts.push(node.value);\n break;\n case \"function\":\n parts.push(node.value, \"(\");\n toCssParts(node.nodes, parts);\n parts.push(\")\");\n break;\n }\n }\n}\n\n/**\n * Serialize AST for var/theme functions - normalizes comma spacing.\n */\nfunction _toCssNormalized(ast: ValueAstNode[]): string {\n const parts: string[] = [];\n toCssNormalizedParts(ast, parts);\n return parts.join(\"\");\n}\n\nfunction toCssNormalizedParts(ast: ValueAstNode[], parts: string[]): void {\n for (const node of ast) {\n switch (node.kind) {\n case \"word\":\n parts.push(node.value);\n break;\n case \"separator\":\n // Normalize comma separators to include space after\n parts.push(node.value.replace(/,(?!\\s)/g, \", \"));\n break;\n case \"function\":\n parts.push(node.value, \"(\");\n toCssNormalizedParts(node.nodes, parts);\n parts.push(\")\");\n break;\n }\n }\n}\n\n// ============================================\n// Arbitrary Value Decoding\n// ============================================\n\n/**\n * Convert `_` to ` `, except for escaped underscores `\\_` which become `_`.\n * Optimized to use slice-based building instead of character concatenation.\n */\nfunction convertUnderscoresToWhitespace(input: string, skipUnderscoreToSpace = false): string {\n // Fast path: no underscores or backslashes\n const underscoreIdx = input.indexOf(\"_\");\n const backslashIdx = input.indexOf(\"\\\\\");\n\n if (underscoreIdx === -1 && backslashIdx === -1) {\n return input;\n }\n\n // Only underscores to convert, no escapes\n if (backslashIdx === -1 && !skipUnderscoreToSpace) {\n // Fast path: replace all underscores with spaces\n return input.replace(/_/g, \" \");\n }\n\n // Full processing needed - use slice-based approach\n const len = input.length;\n const parts: string[] = [];\n let start = 0;\n\n for (let i = 0; i < len; i++) {\n const char = input.charCodeAt(i);\n\n // Escaped underscore: \\_ becomes _\n if (char === BACKSLASH && input.charCodeAt(i + 1) === 0x5f /* _ */) {\n // Add everything before the backslash\n if (i > start) {\n parts.push(input.slice(start, i));\n }\n parts.push(\"_\");\n i += 1; // Skip the underscore too\n start = i + 1;\n }\n // Unescaped underscore: _ becomes space (unless skipped)\n else if (char === 0x5f /* _ */ && !skipUnderscoreToSpace) {\n // Add everything before the underscore\n if (i > start) {\n parts.push(input.slice(start, i));\n }\n parts.push(\" \");\n start = i + 1;\n }\n }\n\n // Add remaining part\n if (start < len) {\n parts.push(input.slice(start));\n }\n\n return parts.join(\"\");\n}\n\n/**\n * Check if a node's value starts with whitespace or underscore.\n * Underscore check is needed because underscores become spaces after decoding.\n */\nfunction startsWithSpaceOrUnderscore(node: ValueAstNode): boolean {\n if (node.kind !== \"word\" && node.kind !== \"separator\") return false;\n const first = node.value.charCodeAt(0);\n // Space, tab, newline, carriage return, or underscore (which becomes space)\n return first === 0x20 || first === 0x09 || first === 0x0a || first === 0x0d || first === 0x5f;\n}\n\n/**\n * Recursively decode arbitrary values in an AST.\n * Single-pass optimization: decodes and normalizes in one traversal.\n * Handles special cases for url(), var(), and theme().\n */\nfunction recursivelyDecodeArbitraryValues(ast: ValueAstNode[]): void {\n for (const node of ast) {\n // Handle non-function nodes directly\n if (node.kind !== \"function\") {\n if (node.kind === \"separator\" || node.kind === \"word\") {\n node.value = convertUnderscoresToWhitespace(node.value);\n }\n continue;\n }\n\n // Inline function type detection (avoids Map lookup for common cases)\n const funcName = node.value;\n const isUrl = funcName === \"url\" || funcName.endsWith(\"_url\");\n const isVarOrTheme =\n funcName === \"var\" || funcName === \"theme\" || funcName.endsWith(\"_var\") || funcName.endsWith(\"_theme\");\n\n // Decode function name\n node.value = convertUnderscoresToWhitespace(node.value);\n\n // url() - don't decode content, only name\n if (isUrl) {\n continue;\n }\n\n // var() and theme() - special handling for first argument\n if (isVarOrTheme) {\n const nodes = node.nodes;\n const len = nodes.length;\n\n // Single-pass: decode and normalize in one loop\n for (let i = 0; i < len; i++) {\n const child = nodes[i]!;\n\n // First argument of var()/theme() - preserve underscores\n if (i === 0 && child.kind === \"word\") {\n child.value = convertUnderscoresToWhitespace(child.value, true);\n continue;\n }\n\n if (child.kind === \"function\") {\n recursivelyDecodeArbitraryValues([child]);\n } else if (child.kind === \"separator\" || child.kind === \"word\") {\n child.value = convertUnderscoresToWhitespace(child.value);\n\n // Inline comma normalization (merged from second pass)\n // Check startsWithSpaceOrUnderscore because underscore becomes space after decoding\n if (child.kind === \"separator\" && child.value.includes(\",\")) {\n const nextChild = nodes[i + 1];\n if (!nextChild || !startsWithSpaceOrUnderscore(nextChild)) {\n child.value = child.value.replace(COMMA_NO_SPACE, \", \");\n }\n }\n }\n }\n continue;\n }\n\n // Normal functions - recursively decode arguments\n recursivelyDecodeArbitraryValues(node.nodes);\n }\n}\n\n/**\n * Decode an arbitrary value from Tailwind class syntax.\n *\n * Transformations:\n * 1. Replace unescaped underscores with spaces\n * 2. Keep escaped underscores (\\_) as literal underscores\n * 3. Normalize whitespace around math operators in calc(), etc.\n * 4. Handle var(), url(), and theme() segments specially\n *\n * @example\n * ```ts\n * decodeArbitraryValue(\"hello_world\") // \"hello world\"\n * decodeArbitraryValue(\"hello\\\\_world\") // \"hello_world\"\n * decodeArbitraryValue(\"calc(100%-20px)\") // \"calc(100% - 20px)\"\n * decodeArbitraryValue(\"var(--my-var)\") // \"var(--my-var)\"\n * decodeArbitraryValue(\"url('/path/to_file.png')\") // \"url('/path/to_file.png')\"\n * ```\n */\nexport function decodeArbitraryValue(input: string): string {\n if (!input) return \"\";\n\n // Fast path: no functions in the input (most common case)\n const parenIdx = input.indexOf(\"(\");\n if (parenIdx === -1) {\n return convertUnderscoresToWhitespace(input);\n }\n\n // Check if we need math operator processing (before AST parsing)\n const needsMathProcessing = MATH_FN_QUICK.test(input);\n\n // Parse, decode, and serialize\n const ast = parseValue(input);\n recursivelyDecodeArbitraryValues(ast);\n let result = toCss(ast);\n\n // Normalize math operator spacing only if needed\n if (needsMathProcessing) {\n result = addWhitespaceAroundMathOperators(result);\n }\n\n return result;\n}\n\n/**\n * Encode a value for use in arbitrary syntax.\n * This is the reverse of decodeArbitraryValue.\n *\n * @example\n * ```ts\n * encodeArbitraryValue(\"hello world\") // \"hello_world\"\n * encodeArbitraryValue(\"hello_world\") // \"hello\\\\_world\"\n * ```\n */\nexport function encodeArbitraryValue(value: string): string {\n let result = \"\";\n\n for (let i = 0; i < value.length; i++) {\n const char = value[i]!;\n\n if (char === \" \") {\n result += \"_\";\n } else if (char === \"_\") {\n result += \"\\\\_\";\n } else {\n result += char;\n }\n }\n\n return result;\n}\n\n/**\n * Check if a value needs decoding.\n */\nexport function needsDecoding(value: string): boolean {\n return value.includes(\"_\") || hasMathFunction(value);\n}\n\n// Pre-compiled regex for math function detection\nconst MATH_FUNCTION = /\\b(?:calc|min|max|clamp)\\s*\\(/;\n\n/**\n * Check if a value contains a math function that may need normalization.\n */\nfunction hasMathFunction(value: string): boolean {\n return MATH_FUNCTION.test(value);\n}\n\n/**\n * Extract segments from an arbitrary value.\n * Useful for complex values with multiple parts.\n *\n * @example\n * ```ts\n * extractValueSegments(\"10px_20px\")\n * // [\"10px\", \"20px\"]\n *\n * extractValueSegments(\"var(--a)_10px\")\n * // [\"var(--a)\", \"10px\"]\n * ```\n */\nexport function extractValueSegments(value: string): string[] {\n const decoded = decodeArbitraryValue(value);\n return decoded.split(/\\s+/).filter(Boolean);\n}\n\n/**\n * Parse a complex arbitrary value into structured parts.\n *\n * @example\n * ```ts\n * parseComplexValue(\"inset_0_2px_4px_rgba(0,0,0,0.1)\")\n * // {\n * // parts: [\"inset\", \"0\", \"2px\", \"4px\", \"rgba(0,0,0,0.1)\"],\n * // functions: [{ name: \"rgba\", args: \"0,0,0,0.1\", index: 4 }]\n * // }\n * ```\n */\nexport function parseComplexValue(value: string): {\n parts: string[];\n functions: Array<{ name: string; args: string; index: number }>;\n} {\n const decoded = decodeArbitraryValue(value);\n const parts: string[] = [];\n const functions: Array<{ name: string; args: string; index: number }> = [];\n\n let current = \"\";\n let depth = 0;\n let funcName = \"\";\n let funcStart = -1;\n\n for (let i = 0; i < decoded.length; i++) {\n const char = decoded[i]!;\n\n if (char === \"(\") {\n if (depth === 0) {\n funcName = current.trim();\n funcStart = parts.length;\n }\n depth++;\n current += char;\n } else if (char === \")\") {\n depth--;\n current += char;\n\n if (depth === 0 && funcName) {\n const args = current.slice(funcName.length + 1, -1);\n functions.push({ name: funcName, args, index: funcStart });\n funcName = \"\";\n funcStart = -1;\n }\n } else if (char === \" \" && depth === 0) {\n if (current.trim()) {\n parts.push(current.trim());\n }\n current = \"\";\n } else {\n current += char;\n }\n }\n\n if (current.trim()) {\n parts.push(current.trim());\n }\n\n return { parts, functions };\n}\n","/**\n * Native Candidate Conversions\n *\n * Shared native -> TypeScript candidate conversion utilities.\n */\n\nimport type {\n ArbitraryModifier,\n ArbitraryValue,\n ArbitraryVariant,\n Candidate,\n CandidateModifier,\n CandidateValue,\n CompoundVariant,\n FunctionalVariant,\n NamedModifier,\n NamedValue,\n StaticVariant,\n Variant,\n} from \"../candidate/types\";\n\nexport interface NativeCandidate {\n kind: \"static\" | \"functional\" | \"arbitrary\";\n root?: string | null;\n property?: string | null;\n value?: NativeCandidateValue | null;\n modifier?: NativeCandidateModifier | null;\n variants: NativeVariant[];\n important: boolean;\n raw: string;\n}\n\nexport interface NativeCandidateValue {\n kind: \"named\" | \"arbitrary\";\n value: string;\n fraction?: string | null;\n dataType?: string | null;\n}\n\nexport interface NativeCandidateModifier {\n kind: \"named\" | \"arbitrary\";\n value: string;\n dashedIdent?: string | null;\n}\n\nexport interface NativeVariant {\n kind: \"static\" | \"functional\" | \"arbitrary\" | \"compound\";\n root?: string | null;\n selector?: string | null;\n relative?: boolean | null;\n value?: NativeCandidateValue | null;\n modifier?: NativeCandidateModifier | null;\n compoundVariant?: string | null;\n}\n\nexport function convertNativeCandidate(native: NativeCandidate): Candidate {\n const variants: Variant[] = native.variants.map(convertNativeVariant);\n\n if (native.kind === \"static\") {\n return {\n kind: \"static\",\n root: native.root ?? \"\",\n variants,\n important: native.important,\n raw: native.raw,\n };\n }\n\n if (native.kind === \"arbitrary\") {\n return {\n kind: \"arbitrary\",\n property: native.property ?? \"\",\n value: native.value?.value ?? \"\",\n modifier: native.modifier ? convertNativeModifier(native.modifier) : null,\n variants,\n important: native.important,\n raw: native.raw,\n };\n }\n\n // Functional\n return {\n kind: \"functional\",\n root: native.root ?? \"\",\n value: native.value ? convertNativeValue(native.value) : null,\n modifier: native.modifier ? convertNativeModifier(native.modifier) : null,\n variants,\n important: native.important,\n raw: native.raw,\n };\n}\n\nfunction convertNativeValue(native: NativeCandidateValue): CandidateValue {\n if (native.kind === \"arbitrary\") {\n return {\n kind: \"arbitrary\",\n value: native.value,\n dataType: native.dataType ?? null,\n } as ArbitraryValue;\n }\n return {\n kind: \"named\",\n value: native.value,\n fraction: native.fraction ?? null,\n } as NamedValue;\n}\n\nfunction convertNativeModifier(native: NativeCandidateModifier): CandidateModifier {\n if (native.kind === \"arbitrary\") {\n return {\n kind: \"arbitrary\",\n value: native.value,\n dashedIdent: native.dashedIdent ?? null,\n } as ArbitraryModifier;\n }\n return {\n kind: \"named\",\n value: native.value,\n } as NamedModifier;\n}\n\nfunction convertNativeVariant(native: NativeVariant): Variant {\n if (native.kind === \"static\") {\n return {\n kind: \"static\",\n root: native.root ?? \"\",\n } as StaticVariant;\n }\n\n if (native.kind === \"arbitrary\") {\n return {\n kind: \"arbitrary\",\n selector: native.selector ?? \"\",\n relative: native.relative ?? false,\n } as ArbitraryVariant;\n }\n\n if (native.kind === \"compound\") {\n // Parse the nested variant from JSON\n let innerVariant: Variant = { kind: \"static\", root: \"\" } as StaticVariant;\n if (native.compoundVariant) {\n try {\n const parsed = JSON.parse(native.compoundVariant) as NativeVariant;\n innerVariant = convertNativeVariant(parsed);\n } catch {\n // Use default if parsing fails\n }\n }\n\n return {\n kind: \"compound\",\n root: native.root ?? \"\",\n modifier: native.modifier ? convertNativeModifier(native.modifier) : null,\n variant: innerVariant,\n } as CompoundVariant;\n }\n\n // Functional\n return {\n kind: \"functional\",\n root: native.root ?? \"\",\n value: native.value ? convertNativeValue(native.value) : null,\n modifier: native.modifier ? convertNativeModifier(native.modifier) : null,\n } as FunctionalVariant;\n}\n","/**\n * Tiny LRU cache with O(1) get/set/evict.\n *\n * Uses a Map for key lookup and a doubly-linked list for recency.\n * Includes optional telemetry for hit/miss tracking.\n */\n\ntype Node<K, V> = {\n key: K;\n value: V;\n prev: Node<K, V> | null;\n next: Node<K, V> | null;\n};\n\nexport interface CacheStats {\n hits: number;\n misses: number;\n hitRate: number;\n size: number;\n maxSize: number;\n}\n\nexport class LruCache<K, V> {\n private map = new Map<K, Node<K, V>>();\n private head: Node<K, V> | null = null;\n private tail: Node<K, V> | null = null;\n private _hits = 0;\n private _misses = 0;\n\n constructor(private maxSize: number) {}\n\n get(key: K): V | undefined {\n const node = this.map.get(key);\n if (!node) {\n this._misses++;\n return undefined;\n }\n this._hits++;\n if (node !== this.head) {\n this.detach(node);\n this.attach(node);\n }\n return node.value;\n }\n\n set(key: K, value: V): void {\n if (this.maxSize <= 0) return;\n const existing = this.map.get(key);\n if (existing) {\n existing.value = value;\n if (existing !== this.head) {\n this.detach(existing);\n this.attach(existing);\n }\n return;\n }\n\n const node: Node<K, V> = { key, value, prev: null, next: null };\n this.map.set(key, node);\n this.attach(node);\n\n if (this.map.size > this.maxSize) {\n this.evict();\n }\n }\n\n clear(): void {\n this.map.clear();\n this.head = null;\n this.tail = null;\n }\n\n get size(): number {\n return this.map.size;\n }\n\n /** Get cache statistics including hit rate */\n get stats(): CacheStats {\n const total = this._hits + this._misses;\n return {\n hits: this._hits,\n misses: this._misses,\n hitRate: total > 0 ? this._hits / total : 0,\n size: this.map.size,\n maxSize: this.maxSize,\n };\n }\n\n /** Reset statistics counters */\n resetStats(): void {\n this._hits = 0;\n this._misses = 0;\n }\n\n private attach(node: Node<K, V>): void {\n node.prev = null;\n node.next = this.head;\n if (this.head) {\n this.head.prev = node;\n }\n this.head = node;\n if (!this.tail) {\n this.tail = node;\n }\n }\n\n private detach(node: Node<K, V>): void {\n if (node.prev) {\n node.prev.next = node.next;\n } else {\n this.head = node.next;\n }\n if (node.next) {\n node.next.prev = node.prev;\n } else {\n this.tail = node.prev;\n }\n node.prev = null;\n node.next = null;\n }\n\n private evict(): void {\n const tail = this.tail;\n if (!tail) return;\n this.map.delete(tail.key);\n this.detach(tail);\n }\n}\n","/**\n * Candidate Parser\n *\n * Parses utility class strings into structured Candidate objects.\n *\n * Examples:\n * \"flex\" -> StaticCandidate { root: \"flex\" }\n * \"bg-red-500\" -> FunctionalCandidate { root: \"bg\", value: \"red-500\" }\n * \"hover:bg-red-500/75\" -> FunctionalCandidate with variant and modifier\n * \"[color:red]\" -> ArbitraryCandidate { property: \"color\", value: \"red\" }\n *\n * Performance: When the native Rust parser is available (from @rainbowindex/oxide),\n * it will be used automatically for 3x+ faster parsing. The TypeScript implementation\n * serves as a fallback when the native module is not available.\n */\n\nimport type {\n ArbitraryModifier,\n ArbitraryValue,\n ArbitraryVariant,\n Candidate,\n CandidateModifier,\n CompoundVariant,\n FunctionalVariant,\n NamedModifier,\n NamedValue,\n StaticVariant,\n Variant,\n} from \"./types\";\nimport { isValidArbitrary } from \"../utils/is-valid-arbitrary\";\nimport { decodeArbitraryValue } from \"../utils/decode-arbitrary-value\";\nimport { convertNativeCandidate, type NativeCandidate } from \"../native/conversions\";\nimport { LruCache } from \"../utils/lru-cache\";\n\n// Native parser function (loaded lazily)\nlet nativeParseCandidate: ((input: string) => NativeCandidate | null) | null = null;\nlet nativeParseCandidateWithUtilitySet: ((input: string) => NativeCandidate | null) | null = null;\nlet nativeIsUtilitySetLoaded: (() => boolean) | null = null;\nlet nativeParserLoadAttempted = false;\n\nfunction tryLoadNativeParser(): typeof nativeParseCandidate {\n if (nativeParserLoadAttempted) return nativeParseCandidate;\n nativeParserLoadAttempted = true;\n\n try {\n // Try to load the native module\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const oxide = require(\"@rainbowindex/oxide\");\n if (oxide && typeof oxide.parseCandidate === \"function\" && oxide.isCandidateParserAvailable?.()) {\n nativeParseCandidate = oxide.parseCandidate;\n }\n if (oxide && typeof oxide.parseCandidateWithUtilitySet === \"function\") {\n nativeParseCandidateWithUtilitySet = oxide.parseCandidateWithUtilitySet;\n }\n if (oxide && typeof oxide.isUtilitySetLoaded === \"function\") {\n nativeIsUtilitySetLoaded = oxide.isUtilitySetLoaded;\n }\n } catch {\n // Native module not available, use TypeScript fallback\n }\n\n return nativeParseCandidate;\n}\n\n/**\n * @internal\n * Test hook to inject native parser implementations.\n */\nexport function __setNativeCandidateParser(\n parser: {\n parseCandidate?: ((input: string) => NativeCandidate | null) | null;\n parseCandidateWithUtilitySet?: ((input: string) => NativeCandidate | null) | null;\n isUtilitySetLoaded?: (() => boolean) | null;\n } | null\n): void {\n if (!parser) {\n nativeParseCandidate = null;\n nativeParseCandidateWithUtilitySet = null;\n nativeIsUtilitySetLoaded = null;\n nativeParserLoadAttempted = false;\n return;\n }\n nativeParseCandidate = parser.parseCandidate ?? null;\n nativeParseCandidateWithUtilitySet = parser.parseCandidateWithUtilitySet ?? null;\n nativeIsUtilitySetLoaded = parser.isUtilitySetLoaded ?? null;\n nativeParserLoadAttempted = true;\n}\n\n/**\n * Check if the native candidate parser is available.\n */\nexport function isNativeCandidateParserAvailable(): boolean {\n return tryLoadNativeParser() !== null;\n}\n\n// Characters that have special meaning\nconst COLON = 0x3a; // :\nconst SLASH = 0x2f; // /\nconst OPEN_BRACKET = 0x5b; // [\nconst CLOSE_BRACKET = 0x5d; // ]\nconst OPEN_PAREN = 0x28; // (\nconst CLOSE_PAREN = 0x29; // )\nconst DASH = 0x2d; // -\nconst BANG = 0x21; // !\nconst AT = 0x40; // @\n\n// Pre-computed set for compound variant roots (O(1) lookup)\nconst COMPOUND_ROOTS = new Set([\"group\", \"peer\", \"has\", \"in\", \"not\"]);\nconst EMPTY_CANDIDATES: readonly Candidate[] = Object.freeze([] as Candidate[]);\n\nfunction isNumericOnly(input: string): boolean {\n const len = input.length;\n if (len === 0) return false;\n for (let i = 0; i < len; i++) {\n const c = input.charCodeAt(i);\n if (c < 48 || c > 57) return false;\n }\n return true;\n}\n\n// ============================================\n// Cache Configuration\n// ============================================\n// These limits are tuned for typical web projects (500-5000 unique classes).\n// Rationale:\n// - 1024 for arbitrary values: covers ~95% of projects using arbitrary values\n// (e.g., bg-[#abc], text-[14px]). Arbitrary values are less common than\n// named utilities, so a smaller cache suffices.\n// - 512 for variants: most projects use <100 unique variants (hover, focus,\n// responsive). 512 provides headroom for complex designs with many custom variants.\n// - 2048 for parsed candidates: typical project has 500-2000 unique classes.\n// 2048 covers most projects with room for growth during development iteration.\n// - These caches use LRU eviction, so exceeding the limit only affects performance\n// (repeated parsing), not correctness.\n// ============================================\n\nconst ARBITRARY_CACHE_LIMIT = 1024;\nconst arbitraryDecodeCache = new LruCache<string, string>(ARBITRARY_CACHE_LIMIT);\nconst arbitraryValidCache = new LruCache<string, boolean>(ARBITRARY_CACHE_LIMIT);\n\n// Static variants (hover, focus, dark, etc.) are unbounded since there are\n// only ~50 built-in variants and they're reused across all candidates.\nconst staticVariantCache = new Map<string, StaticVariant>();\n\nconst VARIANT_CACHE_LIMIT = 512;\nconst variantCache = new LruCache<string, Variant | null>(VARIANT_CACHE_LIMIT);\nconst primedFindRoots = new WeakSet<(input: string) => [string, string] | null>();\n\nconst PARSE_CACHE_LIMIT = 2048;\nconst parseCacheNoRoot = new LruCache<string, readonly Candidate[]>(PARSE_CACHE_LIMIT);\n\nconst VARIANT_CHAIN_CACHE_LIMIT = 512;\nconst variantChainCache = new LruCache<string, readonly Variant[]>(VARIANT_CHAIN_CACHE_LIMIT);\n\nfunction decodeArbitraryCached(input: string): string {\n const cached = arbitraryDecodeCache.get(input);\n if (cached !== undefined) return cached;\n const decoded = decodeArbitraryValue(input);\n arbitraryDecodeCache.set(input, decoded);\n return decoded;\n}\n\nfunction isValidArbitraryCached(input: string): boolean {\n const cached = arbitraryValidCache.get(input);\n if (cached !== undefined) return cached;\n const valid = isValidArbitrary(input);\n arbitraryValidCache.set(input, valid);\n return valid;\n}\n\nfunction getStaticVariant(root: string): StaticVariant {\n const cached = staticVariantCache.get(root);\n if (cached) return cached;\n const variant = Object.freeze({ kind: \"static\", root }) as StaticVariant;\n staticVariantCache.set(root, variant);\n return variant;\n}\n\nfunction parseVariantFast(input: string): Variant | null {\n if (!input) return null;\n\n // Fast path for common static/numeric variants (no special chars)\n for (let i = 0; i < input.length; i++) {\n const c = input.charCodeAt(i);\n if (c === DASH || c === OPEN_BRACKET || c === SLASH || c === AT) {\n return parseVariant(input);\n }\n }\n\n const firstChar = input.charCodeAt(0);\n if (firstChar >= 48 && firstChar <= 57) {\n if (isNumericOnly(input)) {\n return {\n kind: \"functional\",\n root: input,\n value: null,\n modifier: null,\n } as FunctionalVariant;\n }\n }\n\n return getStaticVariant(input);\n}\n\nfunction primeUtilitySet(findRoot?: (input: string) => [string, string] | null): void {\n if (!findRoot) return;\n if (primedFindRoots.has(findRoot)) return;\n primedFindRoots.add(findRoot);\n try {\n // Trigger Utilities.getTrie() -> loadUtilitySetToNative once per design system.\n findRoot(\"p-0\");\n } catch {\n // Ignore failures; we'll fall back to TS parsing.\n }\n}\n\nfunction getParseCache(\n findRoot?: (input: string) => [string, string] | null\n): LruCache<string, readonly Candidate[]> | null {\n if (findRoot) return null;\n return parseCacheNoRoot;\n}\n\nfunction rememberParseResult(\n cache: LruCache<string, readonly Candidate[]> | null,\n key: string,\n value: readonly Candidate[]\n): readonly Candidate[] {\n if (!cache) return value;\n const frozen = value.length === 0 ? value : Object.freeze(value);\n cache.set(key, frozen);\n return frozen;\n}\n\nfunction getCachedVariantChain(chain: string): readonly Variant[] | null {\n return variantChainCache.get(chain) ?? null;\n}\n\nfunction rememberVariantChain(chain: string, variants: Variant[]): readonly Variant[] {\n const frozen = Object.freeze(variants);\n variantChainCache.set(chain, frozen);\n return frozen;\n}\n\n/**\n * Options for parsing candidates.\n */\nexport interface ParseOptions {\n /**\n * Function to find the longest matching utility root.\n * When provided, uses O(n) trie-based lookup for utility roots.\n *\n * @param input - The utility base string (e.g., \"bg-red-500\")\n * @returns [root, value] tuple if found, null otherwise\n */\n findRoot?: (input: string) => [string, string] | null;\n}\n\n/**\n * Parse a utility class string into Candidate objects.\n * Returns zero or one candidate for a given input.\n *\n * Uses the native Rust parser when available for 3x+ faster parsing.\n * Falls back to TypeScript implementation when native module is unavailable\n * or when the `findRoot` option is provided (native doesn't support callbacks).\n *\n * @param input - The utility class string to parse\n * @param options - Optional parsing options including utility root lookup\n */\nexport function parseCandidate(input: string, options?: ParseOptions): readonly Candidate[] {\n input = input.trim();\n if (!input) return EMPTY_CANDIDATES;\n\n for (let i = 0; i < input.length; i++) {\n const code = input.charCodeAt(i);\n if (code <= 0x1f || code === 0x7f) {\n return EMPTY_CANDIDATES;\n }\n }\n\n const cache = getParseCache(options?.findRoot);\n if (cache) {\n const cached = cache.get(input);\n if (cached !== undefined) return cached;\n }\n\n // Native parser with utility-set root matching when findRoot is provided\n if (options?.findRoot) {\n tryLoadNativeParser();\n if (nativeParseCandidateWithUtilitySet) {\n primeUtilitySet(options.findRoot);\n }\n if (nativeParseCandidateWithUtilitySet && nativeIsUtilitySetLoaded?.()) {\n const result = nativeParseCandidateWithUtilitySet(input);\n if (result) {\n return rememberParseResult(cache, input, [convertNativeCandidate(result)]);\n }\n return rememberParseResult(cache, input, EMPTY_CANDIDATES);\n }\n }\n\n // Try native parser when available and no design system lookup is needed\n // (Native parser doesn't support the findRoot callback for utility lookup)\n if (!options?.findRoot) {\n const nativeParse = tryLoadNativeParser();\n if (nativeParse) {\n const result = nativeParse(input);\n if (result) {\n return rememberParseResult(cache, input, [convertNativeCandidate(result)]);\n }\n // Native parser returned null, input is invalid\n return rememberParseResult(cache, input, EMPTY_CANDIDATES);\n }\n }\n\n // Fall back to TypeScript implementation\n const candidate = parseCandidateTypeScript(input, options);\n return rememberParseResult(cache, input, candidate ? [candidate] : EMPTY_CANDIDATES);\n}\n\n/**\n * Quick check if input is a simple static utility (no special chars).\n * Uses early exit for maximum performance.\n */\nfunction isSimpleStatic(input: string): boolean {\n for (let i = 0; i < input.length; i++) {\n const c = input.charCodeAt(i);\n // Exit immediately on any special char\n if (c === COLON || c === DASH || c === OPEN_BRACKET || c === OPEN_PAREN || c === SLASH) {\n return false;\n }\n }\n return true;\n}\n\n/**\n * TypeScript implementation of candidate parsing.\n * Used as fallback when native parser is unavailable or when findRoot lookup is needed.\n */\nfunction parseCandidateTypeScript(input: string, options?: ParseOptions): Candidate | null {\n // Preserve the original input for the raw property\n const originalInput = input;\n\n // `!` prefix is legacy syntax; reject it\n if (input.charCodeAt(0) === BANG) {\n return null;\n }\n\n // Check for !important suffix\n let important = false;\n if (input.charCodeAt(input.length - 1) === BANG) {\n important = true;\n input = input.slice(0, -1);\n if (!input) return null;\n }\n\n // Fast path for simple static utilities (no colons, brackets, dashes, slashes)\n // This is the most common case and should be as fast as possible\n // NOTE: Skip this fast path when findRoot is provided, as utilities like \"rounded\"\n // may be registered as functional (with default values) and need trie lookup\n if (!options?.findRoot && isSimpleStatic(input)) {\n return {\n kind: \"static\",\n root: input,\n variants: [],\n important,\n raw: originalInput,\n };\n }\n\n // Full parsing needed for all other cases\n let variants: Variant[];\n let base: string;\n\n const firstColon = input.indexOf(\":\");\n const hasBrackets = input.indexOf(\"[\") !== -1 || input.indexOf(\"(\") !== -1;\n\n if (firstColon !== -1 && !hasBrackets) {\n // Fast path for stacked variants without brackets\n const lastColon = input.lastIndexOf(\":\");\n base = input.slice(lastColon + 1);\n if (!base) return null;\n\n const chainKey = input.slice(0, lastColon);\n const cachedChain = getCachedVariantChain(chainKey);\n if (cachedChain) {\n variants = cachedChain as Variant[];\n } else {\n const parts = chainKey.split(\":\");\n const built: Variant[] = [];\n for (const part of parts) {\n const variant = parseVariantFast(part);\n if (!variant) return null;\n built.push(variant);\n }\n variants = rememberVariantChain(chainKey, built) as Variant[];\n }\n } else {\n const parsed = parseVariantsAndBase(input);\n if (!parsed) return null;\n variants = parsed.variants;\n base = parsed.base;\n }\n\n // Last segment is the base utility\n if (base.charCodeAt(0) === BANG) {\n return null;\n }\n\n // Try parsing as arbitrary property: [property:value]\n if (base.charCodeAt(0) === OPEN_BRACKET && base.charCodeAt(base.length - 1) === CLOSE_BRACKET) {\n const inner = base.slice(1, -1);\n const colonIdx = inner.indexOf(\":\");\n\n if (colonIdx > 0) {\n const property = inner.slice(0, colonIdx);\n let value = inner.slice(colonIdx + 1);\n\n // Validate the arbitrary value has balanced brackets/quotes\n if (!isValidArbitraryCached(value)) {\n // Invalid arbitrary value - skip this candidate\n return null;\n }\n\n // Check for modifier\n let modifier: CandidateModifier | null = null;\n const modifierResult = extractModifier(value);\n if (modifierResult) {\n value = modifierResult.base;\n modifier = modifierResult.modifier;\n }\n\n return {\n kind: \"arbitrary\",\n property: decodeArbitraryCached(property),\n value: decodeArbitraryCached(value),\n modifier,\n variants,\n important,\n raw: originalInput,\n };\n }\n }\n\n // Extract modifier (e.g., /75 or /[0.5])\n let baseWithoutModifier = base;\n let modifier: CandidateModifier | null = null;\n\n const modifierResult = extractModifier(base);\n if (modifierResult) {\n baseWithoutModifier = modifierResult.base;\n modifier = modifierResult.modifier;\n }\n\n // Check for arbitrary value: root-[value] or root-[type:value]\n if (baseWithoutModifier.indexOf(\"[\") !== -1) {\n const bracketIdx = baseWithoutModifier.indexOf(\"-[\");\n if (bracketIdx > 0 && baseWithoutModifier.charCodeAt(baseWithoutModifier.length - 1) === CLOSE_BRACKET) {\n const root = baseWithoutModifier.slice(0, bracketIdx);\n const arbitraryPart = baseWithoutModifier.slice(bracketIdx + 2, -1);\n\n // Validate the arbitrary value has balanced brackets/quotes\n if (!isValidArbitraryCached(arbitraryPart)) {\n // Invalid arbitrary value - skip this candidate\n return null;\n }\n\n // Check for data type: bg-[color:#ff0000]\n const colonIdx = arbitraryPart.indexOf(\":\");\n let dataType: string | null = null;\n let value: string;\n\n if (colonIdx > 0 && !arbitraryPart.startsWith(\"--\")) {\n dataType = arbitraryPart.slice(0, colonIdx);\n value = arbitraryPart.slice(colonIdx + 1);\n } else {\n value = arbitraryPart;\n }\n\n return {\n kind: \"functional\",\n root,\n value: {\n kind: \"arbitrary\",\n value: decodeArbitraryCached(value),\n dataType,\n } as ArbitraryValue,\n modifier,\n variants,\n important,\n raw: originalInput,\n };\n }\n }\n\n // Check for CSS variable shorthand: root-(--var)\n if (baseWithoutModifier.indexOf(\"(\") !== -1) {\n const parenIdx = baseWithoutModifier.indexOf(\"-(\");\n if (parenIdx > 0 && baseWithoutModifier.charCodeAt(baseWithoutModifier.length - 1) === CLOSE_PAREN) {\n const root = baseWithoutModifier.slice(0, parenIdx);\n const varPart = baseWithoutModifier.slice(parenIdx + 2, -1);\n\n return {\n kind: \"functional\",\n root,\n value: {\n kind: \"arbitrary\",\n value: `var(${varPart})`,\n dataType: null,\n } as ArbitraryValue,\n modifier,\n variants,\n important,\n raw: originalInput,\n };\n }\n }\n\n // Check for negative utility: -m-4, -p-px, etc.\n let negative = false;\n let utilityBase = baseWithoutModifier;\n\n if (baseWithoutModifier.charCodeAt(0) === DASH && baseWithoutModifier.length > 1) {\n // Check if this is a negative utility (second char shouldn't be a bracket)\n const secondChar = baseWithoutModifier.charCodeAt(1);\n if (secondChar !== OPEN_BRACKET) {\n negative = true;\n utilityBase = baseWithoutModifier.slice(1);\n }\n }\n\n // Find the root and value using trie-based lookup (O(n))\n // This allows compound utilities like \"inset-shadow\", \"text-shadow\" to work\n let rootValue: [string, string] | null = null;\n if (options?.findRoot) {\n rootValue = options.findRoot(utilityBase);\n }\n\n if (rootValue) {\n const [rootPart, valuePart] = rootValue;\n const root = (negative ? \"-\" : \"\") + rootPart;\n\n // Empty value part means this is a functional utility used without a value\n // (e.g., \"rounded\" instead of \"rounded-lg\"). Return null value to indicate default.\n // This also handles static utilities like \"flex\" - they will be returned as\n // functional candidates with null value, and if they're only registered as static,\n // the compile step will fall back to static matching.\n if (!valuePart) {\n return {\n kind: \"functional\",\n root,\n value: null,\n modifier,\n variants,\n important,\n raw: originalInput,\n };\n }\n\n // Check for fraction: w-1/2\n const fractionIdx = valuePart.indexOf(\"/\");\n let fraction: string | null = null;\n let valueStr = valuePart;\n\n if (fractionIdx > 0) {\n const beforeSlash = valuePart.slice(0, fractionIdx);\n const afterSlash = valuePart.slice(fractionIdx + 1);\n\n // Only treat as fraction if both parts are numeric-ish\n if (isNumericOnly(beforeSlash) && isNumericOnly(afterSlash)) {\n fraction = valuePart;\n valueStr = valuePart;\n }\n }\n\n return {\n kind: \"functional\",\n root,\n value: {\n kind: \"named\",\n value: valueStr,\n fraction,\n } as NamedValue,\n modifier,\n variants,\n important,\n raw: originalInput,\n };\n }\n\n // Static utility: just a name like \"flex\" or \"hidden\"\n return {\n kind: \"static\",\n root: baseWithoutModifier,\n variants,\n important,\n raw: originalInput,\n };\n}\n\n/**\n * Parse a variant string into a Variant object.\n */\nfunction parseVariant(input: string): Variant | null {\n if (!input) return null;\n\n const cached = variantCache.get(input);\n if (cached !== undefined) {\n return cached;\n }\n\n // Arbitrary variant: [&_p] or [&:hover]\n if (input.charCodeAt(0) === OPEN_BRACKET && input.charCodeAt(input.length - 1) === CLOSE_BRACKET) {\n // Reject at-rule arbitrary variants that also include selectors (deprecated in Tailwind)\n if (input.charCodeAt(1) === 0x40 /* @ */ && input.includes(\"&\")) {\n return null;\n }\n\n const selector = decodeArbitraryCached(input.slice(1, -1));\n\n if (!isValidArbitraryCached(selector)) {\n return null;\n }\n\n if (selector.length === 0 || selector.trim().length === 0) {\n return null;\n }\n\n const relative = selector[0] === \">\" || selector[0] === \"+\" || selector[0] === \"~\";\n let normalizedSelector = selector;\n\n if (!relative && selector[0] !== \"@\" && !selector.includes(\"&\")) {\n normalizedSelector = `&:is(${selector})`;\n }\n\n const variant = {\n kind: \"arbitrary\",\n selector: normalizedSelector,\n relative,\n } as ArbitraryVariant;\n variantCache.set(input, variant);\n return variant;\n }\n\n // Container query variants with @ prefix\n if (input.charCodeAt(0) === 0x40 /* @ */) {\n const variantModifier = extractModifier(input, true);\n const baseInput = variantModifier ? variantModifier.base : input;\n const modifier = variantModifier ? variantModifier.modifier : null;\n const rootDash = baseInput.indexOf(\"-\");\n let root = \"@\";\n let valuePart = \"\";\n\n if (rootDash > 0) {\n root = baseInput.slice(0, rootDash);\n valuePart = baseInput.slice(rootDash + 1);\n } else {\n valuePart = baseInput.slice(1);\n }\n\n if (!valuePart) {\n return null;\n }\n\n if (valuePart.charCodeAt(0) === OPEN_BRACKET && valuePart.charCodeAt(valuePart.length - 1) === CLOSE_BRACKET) {\n const value = decodeArbitraryCached(valuePart.slice(1, -1));\n if (!isValidArbitraryCached(value)) return null;\n const variant = {\n kind: \"functional\",\n root,\n value: { kind: \"arbitrary\", value, dataType: null } as ArbitraryValue,\n modifier,\n } as FunctionalVariant;\n variantCache.set(input, variant);\n return variant;\n }\n\n const variant = {\n kind: \"functional\",\n root,\n value: { kind: \"named\", value: valuePart, fraction: null } as NamedValue,\n modifier,\n } as FunctionalVariant;\n variantCache.set(input, variant);\n return variant;\n }\n\n // Check for compound variant: group-hover, peer-focus\n const dashIdx = input.indexOf(\"-\");\n if (dashIdx > 0) {\n const root = input.slice(0, dashIdx);\n const rest = input.slice(dashIdx + 1);\n\n // Check if this is a compound variant root\n if (COMPOUND_ROOTS.has(root)) {\n const innerVariant = parseVariant(rest);\n if (innerVariant) {\n const variant = {\n kind: \"compound\",\n root,\n modifier: null,\n variant: innerVariant,\n } as CompoundVariant;\n variantCache.set(input, variant);\n return variant;\n }\n }\n\n // Check for modifier on compound: group/name-hover\n const slashIdx = root.indexOf(\"/\");\n if (slashIdx > 0) {\n const actualRoot = root.slice(0, slashIdx);\n const modifierPart = root.slice(slashIdx + 1);\n\n if (COMPOUND_ROOTS.has(actualRoot)) {\n const innerVariant = parseVariant(rest);\n if (innerVariant) {\n const variant = {\n kind: \"compound\",\n root: actualRoot,\n modifier: { kind: \"named\", value: modifierPart } as NamedModifier,\n variant: innerVariant,\n } as CompoundVariant;\n variantCache.set(input, variant);\n return variant;\n }\n }\n }\n\n // Functional variant with arbitrary value: data-[state=open], aria-[hidden=true]\n if (rest.charCodeAt(0) === OPEN_BRACKET && rest.charCodeAt(rest.length - 1) === CLOSE_BRACKET) {\n const value = decodeArbitraryCached(rest.slice(1, -1));\n if (!isValidArbitraryCached(value)) return null;\n const variant = {\n kind: \"functional\",\n root,\n value: { kind: \"arbitrary\", value, dataType: null } as ArbitraryValue,\n modifier: null,\n } as FunctionalVariant;\n variantCache.set(input, variant);\n return variant;\n }\n\n // Functional variant with value: aria-disabled, data-active\n const variant = {\n kind: \"functional\",\n root,\n value: { kind: \"named\", value: rest, fraction: null } as NamedValue,\n modifier: null,\n } as FunctionalVariant;\n variantCache.set(input, variant);\n return variant;\n }\n\n // Fast path: non-numeric variants (most common)\n const firstChar = input.charCodeAt(0);\n if (firstChar < 48 || firstChar > 57) {\n const variant = getStaticVariant(input);\n variantCache.set(input, variant);\n return variant;\n }\n\n // Check for numeric variant (breakpoint): 64, 48, etc.\n if (isNumericOnly(input)) {\n const variant = {\n kind: \"functional\",\n root: input,\n value: null,\n modifier: null,\n } as FunctionalVariant;\n variantCache.set(input, variant);\n return variant;\n }\n\n // Static variant: hover, focus, dark, etc.\n const variant = getStaticVariant(input);\n variantCache.set(input, variant);\n return variant;\n}\n\n/**\n * Split a string by colons, respecting bracket depth.\n * Optimized with multiple fast paths for common cases.\n */\nfunction parseVariantsAndBase(input: string): { variants: Variant[]; base: string } | null {\n const len = input.length;\n const firstColon = input.indexOf(\":\");\n if (firstColon === -1) {\n return { variants: [], base: input };\n }\n\n const variants: Variant[] = [];\n\n // Fast path: no brackets or parens, split using indexOf without allocations\n if (input.indexOf(\"[\") === -1 && input.indexOf(\"(\") === -1) {\n let start = 0;\n let idx = firstColon;\n while (idx !== -1) {\n const segment = input.slice(start, idx);\n const variant = parseVariantFast(segment);\n if (!variant) return null;\n variants.push(variant);\n start = idx + 1;\n idx = input.indexOf(\":\", start);\n }\n const base = input.slice(start);\n if (!base) return null;\n return { variants, base };\n }\n\n // Full parsing: respect bracket/paren depth\n let depth = 0;\n let start = 0;\n\n for (let i = 0; i < len; i++) {\n const char = input.charCodeAt(i);\n\n if (char === OPEN_BRACKET || char === OPEN_PAREN) {\n depth++;\n } else if (char === CLOSE_BRACKET || char === CLOSE_PAREN) {\n if (depth > 0) depth--;\n } else if (char === COLON && depth === 0) {\n const segment = input.slice(start, i);\n const variant = parseVariantFast(segment);\n if (!variant) return null;\n variants.push(variant);\n start = i + 1;\n }\n }\n\n const base = input.slice(start);\n if (!base) return null;\n return { variants, base };\n}\n\n/**\n * Extract modifier from a string (value or variant).\n * E.g., \"red-500/75\" -> { base: \"red-500\", modifier: { kind: \"named\", value: \"75\" } }\n *\n * @param input - The string to extract modifier from\n * @param validateArbitrary - If true, validate arbitrary values with isValidArbitrary\n */\nfunction extractModifier(\n input: string,\n validateArbitrary = false\n): { base: string; modifier: CandidateModifier } | null {\n // Quick exit: no slash at all\n if (input.indexOf(\"/\") === -1) return null;\n\n // Fast path: no brackets, so last slash is always the modifier\n if (input.indexOf(\"[\") === -1) {\n const lastSlashIdx = input.lastIndexOf(\"/\");\n if (lastSlashIdx <= 0) return null;\n const base = input.slice(0, lastSlashIdx);\n const modifierPart = input.slice(lastSlashIdx + 1);\n if (!modifierPart) return null;\n return {\n base,\n modifier: {\n kind: \"named\",\n value: modifierPart,\n } as NamedModifier,\n };\n }\n\n // Find last slash not inside brackets\n let depth = 0;\n let lastSlashIdx = -1;\n\n for (let i = input.length - 1; i >= 0; i--) {\n const char = input.charCodeAt(i);\n\n if (char === CLOSE_BRACKET) depth++;\n else if (char === OPEN_BRACKET) depth--;\n else if (char === SLASH && depth === 0) {\n lastSlashIdx = i;\n break;\n }\n }\n\n if (lastSlashIdx <= 0) return null;\n\n const base = input.slice(0, lastSlashIdx);\n const modifierPart = input.slice(lastSlashIdx + 1);\n\n if (!modifierPart) return null;\n\n // Arbitrary modifier: /[0.5]\n if (\n modifierPart.charCodeAt(0) === OPEN_BRACKET &&\n modifierPart.charCodeAt(modifierPart.length - 1) === CLOSE_BRACKET\n ) {\n const value = decodeArbitraryCached(modifierPart.slice(1, -1));\n if (validateArbitrary && !isValidArbitraryCached(value)) return null;\n return {\n base,\n modifier: {\n kind: \"arbitrary\",\n value,\n dashedIdent: value.startsWith(\"--\") ? value : null,\n } as ArbitraryModifier,\n };\n }\n\n // Named modifier: /75\n return {\n base,\n modifier: {\n kind: \"named\",\n value: modifierPart,\n } as NamedModifier,\n };\n}\n","/**\n * Theme System\n *\n * Manages CSS custom property definitions and resolution.\n * Handles @theme declarations and provides lookups for utilities.\n */\n\nimport type { AtRule, SourceLocation } from \"../ast\";\n\n// ============================================\n// Theme Options\n// ============================================\n\nexport const enum ThemeOptions {\n /** No special options */\n NONE = 0,\n /** Inline in :root (not registered via @property) */\n INLINE = 1 << 0,\n /** Reference only - don't output the declaration */\n REFERENCE = 1 << 1,\n /** Default value that can be overridden */\n DEFAULT = 1 << 2,\n /** Static value that cannot use var() */\n STATIC = 1 << 3,\n /** Mark as used (for tree-shaking) */\n USED = 1 << 4,\n}\n\n// ============================================\n// Theme Key Types\n// ============================================\n\n/** Theme keys always start with -- */\nexport type ThemeKey = `--${string}`;\n\ninterface ThemeEntry {\n value: string;\n options: ThemeOptions;\n src?: SourceLocation;\n}\n\n// ============================================\n// Theme Class\n// ============================================\n\nexport class Theme {\n /** Stored theme values */\n private values = new Map<string, ThemeEntry>();\n\n /** Keyframe animations */\n private keyframes = new Map<string, AtRule>();\n\n /** Theme prefix (e.g., \"ri\" for --ri-*) */\n prefix: string | null = null;\n\n /** Track which variables are used */\n private usedVariables = new Set<string>();\n\n /**\n * Create a new Theme with the same values/keyframes.\n * Used to speed up cold starts without sharing mutation state.\n */\n clone(): Theme {\n const next = new Theme();\n next.values = new Map(this.values);\n next.keyframes = new Map(this.keyframes);\n next.prefix = this.prefix;\n return next;\n }\n\n /**\n * Add a theme value.\n */\n add(key: string, value: string, options: ThemeOptions = ThemeOptions.NONE, src?: SourceLocation): void {\n // Normalize key to always start with --\n if (!key.startsWith(\"--\")) {\n key = `--${key}`;\n }\n\n const existing = this.values.get(key);\n\n // Don't override non-default with default\n if (existing && options & ThemeOptions.DEFAULT && !(existing.options & ThemeOptions.DEFAULT)) {\n return;\n }\n\n this.values.set(key, { value, options, src });\n }\n\n /**\n * Get a raw theme value by key.\n */\n get(key: string): string | null {\n if (!key.startsWith(\"--\")) {\n key = `--${key}`;\n }\n\n let entry = this.values.get(key);\n\n if (!entry && this.prefix) {\n if (key.startsWith(`--${this.prefix}-`)) {\n const unprefixed = `--${key.slice(this.prefix.length + 3)}`;\n entry = this.values.get(unprefixed) ?? this.values.get(key);\n } else {\n const prefixed = `--${this.prefix}-${key.slice(2)}`;\n entry = this.values.get(prefixed);\n }\n }\n\n return entry?.value ?? null;\n }\n\n /**\n * Check if a theme key exists.\n */\n has(key: string): boolean {\n if (!key.startsWith(\"--\")) {\n key = `--${key}`;\n }\n if (this.values.has(key)) return true;\n\n if (this.prefix) {\n if (key.startsWith(`--${this.prefix}-`)) {\n const unprefixed = `--${key.slice(this.prefix.length + 3)}`;\n return this.values.has(unprefixed) || this.values.has(key);\n }\n\n const prefixed = `--${this.prefix}-${key.slice(2)}`;\n return this.values.has(prefixed);\n }\n\n return false;\n }\n\n /**\n * Resolve a candidate value against theme keys.\n *\n * For example, resolve(\"red-500\", [\"--background-color\", \"--color\"])\n * will look for --background-color-red-500 or --color-red-500.\n *\n * Returns a var() reference or the inline value based on ThemeOptions:\n * - STATIC: always inlines the value (no var())\n * - INLINE: inlines the value (no var())\n * - REFERENCE: returns var() with fallback value\n * - Default: returns var() without fallback\n *\n * When a prefix is set, applies it to the emitted var() key.\n */\n resolve(candidateValue: string | null, themeKeys: ThemeKey[]): string | null {\n for (const namespace of themeKeys) {\n const fullKey = candidateValue !== null ? `${namespace}-${candidateValue}` : namespace;\n\n let entry = this.values.get(fullKey);\n\n if (!entry && this.prefix) {\n const prefixed = `--${this.prefix}-${fullKey.slice(2)}`;\n entry = this.values.get(prefixed);\n }\n if (entry) {\n this.usedVariables.add(fullKey);\n\n // Static and inline values are returned directly (no var() reference)\n if (entry.options & (ThemeOptions.STATIC | ThemeOptions.INLINE)) {\n return entry.value;\n }\n\n // Apply prefix to the emitted key if set\n const emittedKey = this.prefix ? `--${this.prefix}-${fullKey.slice(2)}` : fullKey;\n\n // Reference values include a fallback\n if (entry.options & ThemeOptions.REFERENCE) {\n return `var(${emittedKey}, ${entry.value})`;\n }\n\n // Default: var() without fallback (value is emitted in :root)\n return `var(${emittedKey})`;\n }\n }\n\n return null;\n }\n\n /**\n * Get all values in a namespace.\n * E.g., namespace(\"--color\") returns all --color-* values.\n */\n namespace(namespace: ThemeKey): Map<string | null, string> {\n const result = new Map<string | null, string>();\n const prefix = `${namespace}-`;\n const prefixedNamespace = this.prefix ? `--${this.prefix}-${namespace.slice(2)}` : null;\n const prefixedPrefix = prefixedNamespace ? `${prefixedNamespace}-` : null;\n\n for (const [key, entry] of this.values) {\n if (prefixedNamespace) {\n if (key === prefixedNamespace) {\n result.set(null, entry.value);\n continue;\n }\n if (prefixedPrefix && key.startsWith(prefixedPrefix)) {\n const suffix = key.slice(prefixedPrefix.length);\n result.set(suffix, entry.value);\n continue;\n }\n }\n\n if (key === namespace) {\n if (!result.has(null)) {\n result.set(null, entry.value);\n }\n } else if (key.startsWith(prefix)) {\n const suffix = key.slice(prefix.length);\n if (!result.has(suffix)) {\n result.set(suffix, entry.value);\n }\n }\n }\n\n return result;\n }\n\n /**\n * Add a keyframe animation.\n */\n addKeyframes(name: string, keyframes: AtRule): void {\n this.keyframes.set(name, keyframes);\n }\n\n /**\n * Get a keyframe animation.\n */\n getKeyframes(name: string): AtRule | null {\n return this.keyframes.get(name) ?? null;\n }\n\n /**\n * Get all keyframe animations.\n */\n getAllKeyframes(): Map<string, AtRule> {\n return new Map(this.keyframes);\n }\n\n /**\n * Mark a variable as used.\n */\n markUsed(key: string): void {\n if (!key.startsWith(\"--\")) {\n key = `--${key}`;\n }\n if (this.prefix && key.startsWith(`--${this.prefix}-`)) {\n key = `--${key.slice(this.prefix.length + 3)}`;\n }\n this.usedVariables.add(key);\n }\n\n /**\n * Check if a variable has been used.\n */\n isUsed(key: string): boolean {\n if (!key.startsWith(\"--\")) {\n key = `--${key}`;\n }\n if (this.prefix && key.startsWith(`--${this.prefix}-`)) {\n key = `--${key.slice(this.prefix.length + 3)}`;\n }\n return this.usedVariables.has(key);\n }\n\n /**\n * Get all theme entries (for output generation).\n */\n entries(): IterableIterator<[string, ThemeEntry]> {\n return this.values.entries();\n }\n\n /**\n * Get all used theme entries.\n */\n usedEntries(): [string, ThemeEntry][] {\n return Array.from(this.values.entries()).filter(([key]) => this.usedVariables.has(key));\n }\n\n /**\n * Create a child theme that inherits from this one.\n */\n child(): Theme {\n const child = new Theme();\n child.prefix = this.prefix;\n\n // Copy values as defaults\n for (const [key, entry] of this.values) {\n child.values.set(key, { ...entry, options: entry.options | ThemeOptions.DEFAULT });\n }\n\n // Copy keyframes\n for (const [name, keyframes] of this.keyframes) {\n child.keyframes.set(name, keyframes);\n }\n\n return child;\n }\n\n /**\n * Merge another theme into this one.\n */\n merge(other: Theme): void {\n for (const [key, entry] of other.values) {\n const existing = this.values.get(key);\n\n // Don't override non-default with default\n if (existing && entry.options & ThemeOptions.DEFAULT && !(existing.options & ThemeOptions.DEFAULT)) {\n continue;\n }\n\n this.values.set(key, entry);\n }\n\n for (const [name, keyframes] of other.keyframes) {\n this.keyframes.set(name, keyframes);\n }\n }\n}\n","/**\n * Default Theme Tokens\n *\n * Contains the default theme values for Rainbow Index.\n * Uses OKLch color space for perceptually uniform colors.\n */\n\nimport type { Theme } from \"./theme\";\nimport { ThemeOptions } from \"./theme\";\n\n/**\n * Load default theme values into a Theme instance.\n */\nexport function loadDefaultTheme(theme: Theme): void {\n // ============================================\n // Spacing\n // ============================================\n\n theme.add(\"--spacing\", \"0.25rem\", ThemeOptions.DEFAULT);\n\n // ============================================\n // Breakpoints\n // ============================================\n\n theme.add(\"--breakpoint-sm\", \"40rem\", ThemeOptions.DEFAULT); // 640px\n theme.add(\"--breakpoint-md\", \"48rem\", ThemeOptions.DEFAULT); // 768px\n theme.add(\"--breakpoint-lg\", \"64rem\", ThemeOptions.DEFAULT); // 1024px\n theme.add(\"--breakpoint-xl\", \"80rem\", ThemeOptions.DEFAULT); // 1280px\n theme.add(\"--breakpoint-2xl\", \"96rem\", ThemeOptions.DEFAULT); // 1536px\n\n // ============================================\n // Font Families\n // ============================================\n\n theme.add(\n \"--font-sans\",\n 'ui-sans-serif, system-ui, sans-serif, \"Apple Color Emoji\", \"Segoe UI Emoji\", \"Segoe UI Symbol\", \"Noto Color Emoji\"',\n ThemeOptions.DEFAULT | ThemeOptions.REFERENCE\n );\n theme.add(\n \"--font-serif\",\n 'ui-serif, Georgia, Cambria, \"Times New Roman\", Times, serif',\n ThemeOptions.DEFAULT | ThemeOptions.REFERENCE\n );\n theme.add(\n \"--font-mono\",\n 'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, \"Liberation Mono\", \"Courier New\", monospace',\n ThemeOptions.DEFAULT | ThemeOptions.REFERENCE\n );\n\n // ============================================\n // Font Sizes\n // ============================================\n\n theme.add(\"--text-xs\", \"0.75rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-xs--line-height\", \"1rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-sm\", \"0.875rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-sm--line-height\", \"1.25rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-base\", \"1rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-base--line-height\", \"1.5rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-lg\", \"1.125rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-lg--line-height\", \"1.75rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-xl\", \"1.25rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-xl--line-height\", \"1.75rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-2xl\", \"1.5rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-2xl--line-height\", \"2rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-3xl\", \"1.875rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-3xl--line-height\", \"2.25rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-4xl\", \"2.25rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-4xl--line-height\", \"2.5rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-5xl\", \"3rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-5xl--line-height\", \"1\", ThemeOptions.DEFAULT);\n theme.add(\"--text-6xl\", \"3.75rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-6xl--line-height\", \"1\", ThemeOptions.DEFAULT);\n theme.add(\"--text-7xl\", \"4.5rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-7xl--line-height\", \"1\", ThemeOptions.DEFAULT);\n theme.add(\"--text-8xl\", \"6rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-8xl--line-height\", \"1\", ThemeOptions.DEFAULT);\n theme.add(\"--text-9xl\", \"8rem\", ThemeOptions.DEFAULT);\n theme.add(\"--text-9xl--line-height\", \"1\", ThemeOptions.DEFAULT);\n\n // ============================================\n // Font Weights\n // ============================================\n\n theme.add(\"--font-weight-thin\", \"100\", ThemeOptions.DEFAULT);\n theme.add(\"--font-weight-extralight\", \"200\", ThemeOptions.DEFAULT);\n theme.add(\"--font-weight-light\", \"300\", ThemeOptions.DEFAULT);\n theme.add(\"--font-weight-normal\", \"400\", ThemeOptions.DEFAULT);\n theme.add(\"--font-weight-medium\", \"500\", ThemeOptions.DEFAULT);\n theme.add(\"--font-weight-semibold\", \"600\", ThemeOptions.DEFAULT);\n theme.add(\"--font-weight-bold\", \"700\", ThemeOptions.DEFAULT);\n theme.add(\"--font-weight-extrabold\", \"800\", ThemeOptions.DEFAULT);\n theme.add(\"--font-weight-black\", \"900\", ThemeOptions.DEFAULT);\n\n // ============================================\n // Letter Spacing\n // ============================================\n\n theme.add(\"--tracking-tighter\", \"-0.05em\", ThemeOptions.DEFAULT);\n theme.add(\"--tracking-tight\", \"-0.025em\", ThemeOptions.DEFAULT);\n theme.add(\"--tracking-normal\", \"0em\", ThemeOptions.DEFAULT);\n theme.add(\"--tracking-wide\", \"0.025em\", ThemeOptions.DEFAULT);\n theme.add(\"--tracking-wider\", \"0.05em\", ThemeOptions.DEFAULT);\n theme.add(\"--tracking-widest\", \"0.1em\", ThemeOptions.DEFAULT);\n\n // ============================================\n // Line Heights\n // ============================================\n\n theme.add(\"--leading-none\", \"1\", ThemeOptions.DEFAULT);\n theme.add(\"--leading-tight\", \"1.25\", ThemeOptions.DEFAULT);\n theme.add(\"--leading-snug\", \"1.375\", ThemeOptions.DEFAULT);\n theme.add(\"--leading-normal\", \"1.5\", ThemeOptions.DEFAULT);\n theme.add(\"--leading-relaxed\", \"1.625\", ThemeOptions.DEFAULT);\n theme.add(\"--leading-loose\", \"2\", ThemeOptions.DEFAULT);\n\n // ============================================\n // Border Radius\n // ============================================\n\n // Unit-based system: radius values are multiples of --spacing\n // e.g., rounded-2 = calc(2 * var(--spacing))\n theme.add(\"--radius\", \"0.25rem\", ThemeOptions.DEFAULT);\n theme.add(\"--radius-full\", \"9999px\", ThemeOptions.DEFAULT);\n\n // Squircle scaling factor (radius is scaled by this when using squircle)\n theme.add(\"--ri-squircle-scale\", \"1.6\", ThemeOptions.DEFAULT);\n\n // ============================================\n // Shadows\n // ============================================\n\n theme.add(\"--shadow-sm\", \"0 1px 2px 0 rgb(0 0 0 / 0.05)\", ThemeOptions.DEFAULT);\n theme.add(\"--shadow\", \"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)\", ThemeOptions.DEFAULT);\n theme.add(\"--shadow-md\", \"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)\", ThemeOptions.DEFAULT);\n theme.add(\n \"--shadow-lg\",\n \"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)\",\n ThemeOptions.DEFAULT\n );\n theme.add(\n \"--shadow-xl\",\n \"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)\",\n ThemeOptions.DEFAULT\n );\n theme.add(\"--shadow-2xl\", \"0 25px 50px -12px rgb(0 0 0 / 0.25)\", ThemeOptions.DEFAULT);\n theme.add(\"--shadow-inner\", \"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)\", ThemeOptions.DEFAULT);\n theme.add(\"--shadow-none\", \"0 0 #0000\", ThemeOptions.DEFAULT);\n\n // ============================================\n // Colors (OKLch)\n // ============================================\n\n // Transparent and current\n theme.add(\"--color-transparent\", \"transparent\", ThemeOptions.DEFAULT | ThemeOptions.STATIC);\n theme.add(\"--color-current\", \"currentColor\", ThemeOptions.DEFAULT | ThemeOptions.STATIC);\n theme.add(\"--color-inherit\", \"inherit\", ThemeOptions.DEFAULT | ThemeOptions.STATIC);\n\n // Paper/Ink (absolute light/dark anchors)\n theme.add(\"--color-paper\", \"light-dark(oklch(100% 0 0), oklch(0% 0 0))\", ThemeOptions.DEFAULT);\n theme.add(\"--color-ink\", \"light-dark(oklch(0% 0 0), oklch(100% 0 0))\", ThemeOptions.DEFAULT);\n theme.add(\"--color-0\", \"var(--color-paper)\", ThemeOptions.DEFAULT);\n theme.add(\"--color-1000\", \"var(--color-ink)\", ThemeOptions.DEFAULT);\n\n // Gray (neutral)\n loadPalette(theme, { name: \"mono\", hue: 0, intensity: 0 });\n\n // ============================================\n // Animations\n // ============================================\n\n // Built-in animations\n theme.add(\"--animate-spin\", \"ri-spin 1s linear infinite\", ThemeOptions.DEFAULT);\n theme.add(\"--animate-ping\", \"ri-ping 1s cubic-bezier(0, 0, 0.2, 1) infinite\", ThemeOptions.DEFAULT);\n theme.add(\"--animate-pulse\", \"ri-pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite\", ThemeOptions.DEFAULT);\n theme.add(\"--animate-bounce\", \"ri-bounce 1s infinite\", ThemeOptions.DEFAULT);\n\n // Component-specific animations\n theme.add(\"--animate-accordion-down\", \"ri-accordion-down 200ms ease-out forwards\", ThemeOptions.DEFAULT);\n theme.add(\"--animate-accordion-up\", \"ri-accordion-up 200ms ease-out forwards\", ThemeOptions.DEFAULT);\n theme.add(\"--animate-collapsible-down\", \"ri-collapsible-down 200ms ease-out forwards\", ThemeOptions.DEFAULT);\n theme.add(\"--animate-collapsible-up\", \"ri-collapsible-up 200ms ease-out forwards\", ThemeOptions.DEFAULT);\n theme.add(\"--animate-caret-blink\", \"ri-caret-blink 1.25s ease-out infinite\", ThemeOptions.DEFAULT);\n\n // ============================================\n // Transitions\n // ============================================\n\n theme.add(\"--ease-linear\", \"linear\", ThemeOptions.DEFAULT);\n theme.add(\"--ease-in\", \"cubic-bezier(0.4, 0, 1, 1)\", ThemeOptions.DEFAULT);\n theme.add(\"--ease-out\", \"cubic-bezier(0, 0, 0.2, 1)\", ThemeOptions.DEFAULT);\n theme.add(\"--ease-in-out\", \"cubic-bezier(0.4, 0, 0.2, 1)\", ThemeOptions.DEFAULT);\n\n theme.add(\"--duration-75\", \"75ms\", ThemeOptions.DEFAULT);\n theme.add(\"--duration-100\", \"100ms\", ThemeOptions.DEFAULT);\n theme.add(\"--duration-150\", \"150ms\", ThemeOptions.DEFAULT);\n theme.add(\"--duration-200\", \"200ms\", ThemeOptions.DEFAULT);\n theme.add(\"--duration-300\", \"300ms\", ThemeOptions.DEFAULT);\n theme.add(\"--duration-500\", \"500ms\", ThemeOptions.DEFAULT);\n theme.add(\"--duration-700\", \"700ms\", ThemeOptions.DEFAULT);\n theme.add(\"--duration-1000\", \"1000ms\", ThemeOptions.DEFAULT);\n}\n\n// ============================================\n// Light/Dark Color Scale Generation\n// ============================================\n\n/**\n * Parameters for generating a light/dark color palette.\n */\nexport interface PaletteLDParams {\n /** Color name (will generate --color-{name}-{step} variables) */\n name: string;\n /** Hue value (0-360) */\n hue: number;\n /** Chroma/intensity value (0-1) */\n intensity: number;\n /** Chroma-dependent lightness correction coefficient (default: 0.0) */\n a?: number;\n /** Dark-mode chroma multiplier, e.g. 0.8 = 20% reduction (default: 0.80) */\n kDark?: number;\n /** Chroma distribution shape (default: \"bell\") */\n chromaShape?: \"bell\" | \"flat\";\n /** Custom lightness schedule overrides */\n lightnessByToken?: Partial<Record<number, number>>;\n}\n\n/** 19 token steps from 50 to 950 */\nconst TOKENS_19 = [\n 50, 100, 150, 200, 250, 300, 350, 400, 450, 500, 550, 600, 650, 700, 750, 800, 850, 900, 950,\n] as const;\n\n/** Default lightness schedule (0-1 range) */\nconst DEFAULT_L_SCHEDULE: Record<number, number> = {\n 50: 0.976,\n 100: 0.932,\n 150: 0.888,\n 200: 0.844,\n 250: 0.8,\n 300: 0.756,\n 350: 0.712,\n 400: 0.668,\n 450: 0.624,\n 500: 0.58,\n 550: 0.536,\n 600: 0.492,\n 650: 0.448,\n 700: 0.404,\n 750: 0.36,\n 800: 0.316,\n 850: 0.272,\n 900: 0.228,\n 950: 0.184,\n};\n\nfunction clamp01(x: number): number {\n return Math.max(0, Math.min(1, x));\n}\n\n/** Hue-dependent weight for lightness correction (blue needs more correction) */\nfunction hueWeight(h: number): number {\n const hue = ((h % 360) + 360) % 360;\n if (hue >= 80 && hue < 130) return 0.1; // yellow-ish\n if (hue >= 130 && hue < 170) return 0.2; // green-ish\n if (hue >= 170 && hue < 220) return 0.4; // cyan-ish\n if (hue >= 240 && hue < 300) return 1.0; // blue-ish\n if (hue >= 300 && hue < 350) return 0.7; // magenta-ish\n return 0.6; // red-ish\n}\n\n/** Bell curve for mid-tone emphasis: 0 at ends, 1 at middle */\nfunction bell01(t: number): number {\n t = clamp01(t);\n return 4 * t * (1 - t);\n}\n\n/** Mirror tokens for dark scale (50↔950, 100↔900, etc.) */\nfunction mirrorToken(token: number): number {\n return 1000 - token;\n}\n\n/** Apply chroma-dependent lightness correction */\nfunction applyLightnessCorrection(L: number, C: number, H: number, a: number): number {\n return clamp01(L - a * C * hueWeight(H));\n}\n\n/** Format as oklch() CSS value */\nfunction formatOklch(L: number, C: number, H: number): string {\n return `oklch(${(L * 100).toFixed(1)}% ${C.toFixed(3)} ${H.toFixed(1)})`;\n}\n\ninterface SwatchOptions {\n L: number;\n hue: number;\n intensity: number;\n a: number;\n t: number; // 0..1 within this mode (used for chroma shaping)\n chromaShape: \"bell\" | \"flat\";\n chromaMultiplier: number; // for dark mode (kDark) or 1.0\n}\n\nfunction computeSwatch(opts: SwatchOptions): { L: number; C: number; css: string } {\n const { L, hue, intensity, a, t, chromaShape, chromaMultiplier } = opts;\n\n // Base chroma budget\n let C0 = intensity * 0.35;\n\n // Mid-tone chroma emphasis (continuous and stable)\n if (chromaShape === \"bell\") {\n const shape = bell01(t);\n C0 *= 0.15 + 0.85 * shape;\n }\n\n // Dark surround compensation: reduce chroma in dark mode\n C0 *= chromaMultiplier;\n\n // Apply fitted chroma-dependent lightness correction\n const L1 = applyLightnessCorrection(L, C0, hue, a);\n\n return { L: L1, C: C0, css: formatOklch(L1, C0, hue) };\n}\n\n/**\n * Generates 19 tokens (50-950) as `light-dark()` values:\n * --color-{name}-{token}: light-dark(oklch(...light...), oklch(...dark...));\n *\n * Features:\n * - Two independently computed scales (light + dark)\n * - Dark mode gets additional chroma reduction via kDark\n * - Chroma-dependent lightness correction via `a` parameter\n * - Perceptually uniform lightness schedule\n */\nexport function loadPalette(theme: Theme, params: PaletteLDParams): void {\n const { name, hue, intensity, a = 0.0, kDark = 0.8, chromaShape = \"bell\", lightnessByToken = {} } = params;\n\n const Ls: Partial<Record<number, number>> = { ...DEFAULT_L_SCHEDULE, ...lightnessByToken };\n\n for (const token of TOKENS_19) {\n const L_light = Ls[token];\n const L_dark = Ls[mirrorToken(token)];\n\n if (L_light === undefined || L_dark === undefined) continue;\n\n // Mode-local t for chroma shaping:\n // light: 50 is light end (t=1), 950 is dark end (t=0)\n // dark: 50 is dark end (t=0), 950 is light end (t=1)\n const tLight = (950 - token) / 900;\n const tDark = (token - 50) / 900;\n\n const light = computeSwatch({\n L: L_light,\n hue,\n intensity,\n a,\n t: tLight,\n chromaShape,\n chromaMultiplier: 1.0,\n });\n\n const dark = computeSwatch({\n L: L_dark,\n hue,\n intensity,\n a,\n t: tDark,\n chromaShape,\n chromaMultiplier: kDark,\n });\n\n const value = `light-dark(${light.css}, ${dark.css})`;\n theme.add(`--color-${name}-${token}`, value, ThemeOptions.DEFAULT);\n }\n}\n","/**\n * Color Validation\n *\n * Central validator for CSS color values.\n * Replaces ad-hoc color checks throughout the codebase.\n */\n\n/**\n * Named CSS colors (CSS Color Level 4 + CSS Color Level 3).\n * Includes all standard named colors plus 'transparent' and 'currentColor'.\n */\nconst NAMED_COLORS = new Set([\n // Basic colors\n \"black\",\n \"silver\",\n \"gray\",\n \"white\",\n \"maroon\",\n \"red\",\n \"purple\",\n \"fuchsia\",\n \"green\",\n \"lime\",\n \"olive\",\n \"yellow\",\n \"navy\",\n \"blue\",\n \"teal\",\n \"aqua\",\n\n // Extended colors\n \"aliceblue\",\n \"antiquewhite\",\n \"aquamarine\",\n \"azure\",\n \"beige\",\n \"bisque\",\n \"blanchedalmond\",\n \"blueviolet\",\n \"brown\",\n \"burlywood\",\n \"cadetblue\",\n \"chartreuse\",\n \"chocolate\",\n \"coral\",\n \"cornflowerblue\",\n \"cornsilk\",\n \"crimson\",\n \"cyan\",\n \"darkblue\",\n \"darkcyan\",\n \"darkgoldenrod\",\n \"darkgray\",\n \"darkgreen\",\n \"darkgrey\",\n \"darkkhaki\",\n \"darkmagenta\",\n \"darkolivegreen\",\n \"darkorange\",\n \"darkorchid\",\n \"darkred\",\n \"darksalmon\",\n \"darkseagreen\",\n \"darkslateblue\",\n \"darkslategray\",\n \"darkslategrey\",\n \"darkturquoise\",\n \"darkviolet\",\n \"deeppink\",\n \"deepskyblue\",\n \"dimgray\",\n \"dimgrey\",\n \"dodgerblue\",\n \"firebrick\",\n \"floralwhite\",\n \"forestgreen\",\n \"gainsboro\",\n \"ghostwhite\",\n \"gold\",\n \"goldenrod\",\n \"greenyellow\",\n \"grey\",\n \"honeydew\",\n \"hotpink\",\n \"indianred\",\n \"indigo\",\n \"ivory\",\n \"khaki\",\n \"lavender\",\n \"lavenderblush\",\n \"lawngreen\",\n \"lemonchiffon\",\n \"lightblue\",\n \"lightcoral\",\n \"lightcyan\",\n \"lightgoldenrodyellow\",\n \"lightgray\",\n \"lightgreen\",\n \"lightgrey\",\n \"lightpink\",\n \"lightsalmon\",\n \"lightseagreen\",\n \"lightskyblue\",\n \"lightslategray\",\n \"lightslategrey\",\n \"lightsteelblue\",\n \"lightyellow\",\n \"limegreen\",\n \"linen\",\n \"magenta\",\n \"mediumaquamarine\",\n \"mediumblue\",\n \"mediumorchid\",\n \"mediumpurple\",\n \"mediumseagreen\",\n \"mediumslateblue\",\n \"mediumspringgreen\",\n \"mediumturquoise\",\n \"mediumvioletred\",\n \"midnightblue\",\n \"mintcream\",\n \"mistyrose\",\n \"moccasin\",\n \"navajowhite\",\n \"oldlace\",\n \"olivedrab\",\n \"orange\",\n \"orangered\",\n \"orchid\",\n \"palegoldenrod\",\n \"palegreen\",\n \"paleturquoise\",\n \"palevioletred\",\n \"papayawhip\",\n \"peachpuff\",\n \"peru\",\n \"pink\",\n \"plum\",\n \"powderblue\",\n \"rosybrown\",\n \"royalblue\",\n \"saddlebrown\",\n \"salmon\",\n \"sandybrown\",\n \"seagreen\",\n \"seashell\",\n \"sienna\",\n \"skyblue\",\n \"slateblue\",\n \"slategray\",\n \"slategrey\",\n \"snow\",\n \"springgreen\",\n \"steelblue\",\n \"tan\",\n \"thistle\",\n \"tomato\",\n \"turquoise\",\n \"violet\",\n \"wheat\",\n \"whitesmoke\",\n \"yellowgreen\",\n\n // Special values\n \"transparent\",\n \"currentcolor\",\n \"currentColor\",\n \"inherit\",\n \"initial\",\n \"unset\",\n\n // System colors (CSS Color Level 4)\n \"canvas\",\n \"canvastext\",\n \"linktext\",\n \"visitedtext\",\n \"activetext\",\n \"buttonface\",\n \"buttontext\",\n \"buttonborder\",\n \"field\",\n \"fieldtext\",\n \"highlight\",\n \"highlighttext\",\n \"selecteditem\",\n \"selecteditemtext\",\n \"mark\",\n \"marktext\",\n \"graytext\",\n \"accentcolor\",\n \"accentcolortext\",\n]);\n\n/**\n * Color function prefixes (Set for O(1) lookup).\n */\nconst COLOR_FUNCTIONS = new Set([\n \"rgb\",\n \"rgba\",\n \"hsl\",\n \"hsla\",\n \"hwb\",\n \"lab\",\n \"lch\",\n \"oklab\",\n \"oklch\",\n \"color\",\n \"color-mix\",\n \"light-dark\",\n]);\n\n/**\n * Regex patterns for color formats.\n */\nconst HEX_COLOR_3 = /^#[0-9a-fA-F]{3}$/;\nconst HEX_COLOR_4 = /^#[0-9a-fA-F]{4}$/;\nconst HEX_COLOR_6 = /^#[0-9a-fA-F]{6}$/;\nconst HEX_COLOR_8 = /^#[0-9a-fA-F]{8}$/;\n\n// Pre-compiled pattern for hex-like values without # prefix (hoisted to avoid recreation)\nconst HEX_LIKE_PATTERN = /^[0-9a-f]{3,8}$/i;\n\n// Color-related keywords for looksLikeColor check (hoisted to avoid recreation)\nconst COLOR_KEYWORDS = [\"rgb\", \"hsl\", \"hwb\", \"lab\", \"lch\", \"oklab\", \"oklch\", \"color\"];\n\n/**\n * Check if a value is a valid CSS color.\n *\n * @param value - The value to check\n * @returns true if the value is a valid color, false otherwise\n *\n * @example\n * ```ts\n * isColor(\"red\") // true\n * isColor(\"#ff0000\") // true\n * isColor(\"rgb(255, 0, 0)\") // true\n * isColor(\"oklch(0.6 0.2 250)\") // true\n * isColor(\"10px\") // false\n * ```\n */\nexport function isColor(value: string): boolean {\n if (!value) return false;\n\n const trimmed = value.trim();\n const lowercased = trimmed.toLowerCase();\n\n // Check for named colors (case-insensitive, plus case-sensitive for currentColor)\n if (NAMED_COLORS.has(lowercased) || NAMED_COLORS.has(trimmed)) {\n return true;\n }\n\n // Check for hex colors\n if (lowercased.startsWith(\"#\")) {\n return (\n HEX_COLOR_3.test(lowercased) ||\n HEX_COLOR_4.test(lowercased) ||\n HEX_COLOR_6.test(lowercased) ||\n HEX_COLOR_8.test(lowercased)\n );\n }\n\n // Check for color functions - extract function name before '(' and lookup in Set\n const parenIdx = lowercased.indexOf(\"(\");\n if (parenIdx > 0) {\n const fnName = lowercased.slice(0, parenIdx);\n if (COLOR_FUNCTIONS.has(fnName)) {\n return true;\n }\n }\n\n // Check for CSS variable (could be a color)\n if (lowercased.startsWith(\"var(\")) {\n return true; // Can't validate at compile time, assume it could be a color\n }\n\n return false;\n}\n\n/**\n * Check if a value looks like it could be a color (less strict).\n * Useful for arbitrary value type inference.\n *\n * @param value - The value to check\n * @returns true if the value might be a color\n */\nexport function looksLikeColor(value: string): boolean {\n if (isColor(value)) return true;\n\n const trimmed = value.trim().toLowerCase();\n\n // Might be a color if it contains color-related keywords\n for (const keyword of COLOR_KEYWORDS) {\n if (trimmed.includes(keyword)) return true;\n }\n\n // Might be a color if it's a hex-like value\n if (HEX_LIKE_PATTERN.test(trimmed)) return true;\n\n return false;\n}\n\n/**\n * Parse a hex color into RGB components.\n *\n * @param hex - Hex color string (with or without #)\n * @returns RGB values or null if invalid\n */\nexport function parseHexColor(hex: string): { r: number; g: number; b: number; a?: number } | null {\n let normalized = hex.trim();\n if (normalized.startsWith(\"#\")) {\n normalized = normalized.slice(1);\n }\n\n let r: number, g: number, b: number, a: number | undefined;\n\n switch (normalized.length) {\n case 3:\n case 4: {\n r = parseInt(normalized[0]! + normalized[0], 16);\n g = parseInt(normalized[1]! + normalized[1], 16);\n b = parseInt(normalized[2]! + normalized[2], 16);\n if (normalized.length === 4) {\n a = parseInt(normalized[3]! + normalized[3], 16) / 255;\n }\n break;\n }\n case 6:\n case 8: {\n r = parseInt(normalized.slice(0, 2), 16);\n g = parseInt(normalized.slice(2, 4), 16);\n b = parseInt(normalized.slice(4, 6), 16);\n if (normalized.length === 8) {\n a = parseInt(normalized.slice(6, 8), 16) / 255;\n }\n break;\n }\n default:\n return null;\n }\n\n if (isNaN(r) || isNaN(g) || isNaN(b)) {\n return null;\n }\n\n return a !== undefined ? { r, g, b, a } : { r, g, b };\n}\n\n/**\n * Convert RGB to hex color.\n *\n * @param r - Red (0-255)\n * @param g - Green (0-255)\n * @param b - Blue (0-255)\n * @param a - Alpha (0-1, optional)\n * @returns Hex color string\n */\nexport function rgbToHex(r: number, g: number, b: number, a?: number): string {\n const toHex = (n: number) =>\n Math.round(Math.max(0, Math.min(255, n)))\n .toString(16)\n .padStart(2, \"0\");\n\n let hex = `#${toHex(r)}${toHex(g)}${toHex(b)}`;\n\n if (a !== undefined && a < 1) {\n hex += toHex(a * 255);\n }\n\n return hex;\n}\n\n/**\n * Get the color format type.\n *\n * @param value - Color value\n * @returns The format type or null if not a color\n */\nexport function getColorFormat(value: string): string | null {\n if (!value) return null;\n\n const trimmed = value.trim().toLowerCase();\n\n if (NAMED_COLORS.has(trimmed)) return \"named\";\n if (trimmed.startsWith(\"var(\")) return \"variable\";\n\n if (trimmed.startsWith(\"#\")) {\n if (HEX_COLOR_3.test(trimmed) || HEX_COLOR_4.test(trimmed)) return \"hex-short\";\n if (HEX_COLOR_6.test(trimmed) || HEX_COLOR_8.test(trimmed)) return \"hex\";\n return null;\n }\n\n // Extract function name before '(' and lookup in Set\n const parenIdx = trimmed.indexOf(\"(\");\n if (parenIdx > 0) {\n const fnName = trimmed.slice(0, parenIdx);\n if (COLOR_FUNCTIONS.has(fnName)) {\n return fnName;\n }\n }\n\n return null;\n}\n\n/**\n * Check if a color value includes alpha/opacity.\n *\n * @param value - Color value\n * @returns true if the color has an alpha component\n */\nexport function hasAlpha(value: string): boolean {\n const trimmed = value.trim().toLowerCase();\n\n // 4 or 8 digit hex\n if (trimmed.startsWith(\"#\")) {\n const hex = trimmed.slice(1);\n return hex.length === 4 || hex.length === 8;\n }\n\n // rgba, hsla\n if (trimmed.startsWith(\"rgba(\") || trimmed.startsWith(\"hsla(\")) {\n return true;\n }\n\n // Modern syntax with / for alpha\n if (trimmed.includes(\"/\")) {\n return true;\n }\n\n return false;\n}\n","/**\n * Data Type Inference\n *\n * Infers CSS data types from arbitrary values.\n * Used for better handling of arbitrary values in utilities.\n */\n\nimport { isColor, looksLikeColor } from \"./is-color\";\n\n/**\n * CSS data types that can be inferred.\n */\nexport type DataType =\n | \"color\"\n | \"length\"\n | \"percentage\"\n | \"number\"\n | \"angle\"\n | \"time\"\n | \"frequency\"\n | \"resolution\"\n | \"flex\"\n | \"integer\"\n | \"ratio\"\n | \"url\"\n | \"image\"\n | \"gradient\"\n | \"position\"\n | \"shadow\"\n | \"line-names\"\n | \"any\";\n\n/**\n * CSS length units.\n */\nconst LENGTH_UNITS = new Set([\n // Absolute units\n \"px\",\n \"cm\",\n \"mm\",\n \"in\",\n \"pt\",\n \"pc\",\n \"Q\",\n // Relative units\n \"em\",\n \"rem\",\n \"ex\",\n \"rex\",\n \"cap\",\n \"rcap\",\n \"ch\",\n \"rch\",\n \"ic\",\n \"ric\",\n \"lh\",\n \"rlh\",\n // Viewport units\n \"vw\",\n \"vh\",\n \"vi\",\n \"vb\",\n \"vmin\",\n \"vmax\",\n \"svw\",\n \"svh\",\n \"svi\",\n \"svb\",\n \"svmin\",\n \"svmax\",\n \"lvw\",\n \"lvh\",\n \"lvi\",\n \"lvb\",\n \"lvmin\",\n \"lvmax\",\n \"dvw\",\n \"dvh\",\n \"dvi\",\n \"dvb\",\n \"dvmin\",\n \"dvmax\",\n // Container query units\n \"cqw\",\n \"cqh\",\n \"cqi\",\n \"cqb\",\n \"cqmin\",\n \"cqmax\",\n]);\n\n/**\n * CSS angle units.\n */\nconst ANGLE_UNITS = new Set([\"deg\", \"grad\", \"rad\", \"turn\"]);\n\n/**\n * CSS time units.\n */\nconst TIME_UNITS = new Set([\"s\", \"ms\"]);\n\n/**\n * CSS frequency units.\n */\nconst FREQUENCY_UNITS = new Set([\"Hz\", \"kHz\", \"hz\", \"khz\"]);\n\n/**\n * CSS resolution units.\n */\nconst RESOLUTION_UNITS = new Set([\"dpi\", \"dpcm\", \"dppx\", \"x\"]);\n\n/**\n * Position keywords for background-position, object-position, etc.\n */\nconst POSITION_KEYWORDS = new Set([\"top\", \"bottom\", \"left\", \"right\", \"center\"]);\n\n/**\n * CSS gradient functions.\n */\nconst GRADIENT_FUNCTIONS = [\n \"linear-gradient\",\n \"radial-gradient\",\n \"conic-gradient\",\n \"repeating-linear-gradient\",\n \"repeating-radial-gradient\",\n \"repeating-conic-gradient\",\n];\n\n/**\n * CSS image functions.\n */\nconst IMAGE_FUNCTIONS = [\"url\", \"image\", \"image-set\", \"cross-fade\", \"element\", ...GRADIENT_FUNCTIONS];\n\n/**\n * Regex for numbers with optional units.\n */\nconst NUMBER_WITH_UNIT = /^-?(?:\\d+\\.?\\d*|\\.\\d+)([a-zA-Z%]+)?$/;\n\n/**\n * Regex for ratio values (e.g., 16/9).\n */\nconst RATIO_PATTERN = /^\\d+\\s*\\/\\s*\\d+$/;\n\n/**\n * Regex for integer values (e.g., 1, -5, 0).\n */\nconst INTEGER_PATTERN = /^-?\\d+$/;\n\n/**\n * Infer the data type of an arbitrary value.\n *\n * @param value - The arbitrary value to analyze\n * @returns The inferred data type\n *\n * @example\n * ```ts\n * inferDataType(\"10px\") // \"length\"\n * inferDataType(\"#ff0000\") // \"color\"\n * inferDataType(\"45deg\") // \"angle\"\n * inferDataType(\"url(image.png)\") // \"url\"\n * inferDataType(\"linear-gradient(red, blue)\") // \"gradient\"\n * ```\n */\nexport function inferDataType(value: string): DataType {\n if (!value) return \"any\";\n\n const trimmed = value.trim();\n\n // Check for URL\n if (trimmed.startsWith(\"url(\")) {\n return \"url\";\n }\n\n // Check for gradients\n for (const fn of GRADIENT_FUNCTIONS) {\n if (trimmed.startsWith(`${fn}(`)) {\n return \"gradient\";\n }\n }\n\n // Check for other image functions\n for (const fn of IMAGE_FUNCTIONS) {\n if (trimmed.startsWith(`${fn}(`)) {\n return \"image\";\n }\n }\n\n // Check for color\n if (isColor(trimmed)) {\n return \"color\";\n }\n\n // Check for ratio\n if (RATIO_PATTERN.test(trimmed)) {\n return \"ratio\";\n }\n\n // Check for line names [name]\n if (trimmed.startsWith(\"[\") && trimmed.endsWith(\"]\")) {\n return \"line-names\";\n }\n\n // Check for number with unit\n const match = trimmed.match(NUMBER_WITH_UNIT);\n if (match) {\n const unit = match[1];\n\n if (!unit) {\n return trimmed.includes(\".\") ? \"number\" : \"integer\";\n }\n\n if (unit === \"%\") return \"percentage\";\n if (unit === \"fr\") return \"flex\";\n if (LENGTH_UNITS.has(unit)) return \"length\";\n if (ANGLE_UNITS.has(unit)) return \"angle\";\n if (TIME_UNITS.has(unit)) return \"time\";\n if (FREQUENCY_UNITS.has(unit.toLowerCase())) return \"frequency\";\n if (RESOLUTION_UNITS.has(unit.toLowerCase())) return \"resolution\";\n }\n\n // Check for calc() or other math functions\n if (\n trimmed.startsWith(\"calc(\") ||\n trimmed.startsWith(\"min(\") ||\n trimmed.startsWith(\"max(\") ||\n trimmed.startsWith(\"clamp(\")\n ) {\n // Try to infer from the content\n return inferMathFunctionType(trimmed);\n }\n\n // Check for CSS variable\n if (trimmed.startsWith(\"var(\")) {\n // Can't infer type from variable at compile time\n return \"any\";\n }\n\n // Check if it looks like a color but wasn't caught earlier\n if (looksLikeColor(trimmed)) {\n return \"color\";\n }\n\n // Check for position keywords\n if (isPositionValue(trimmed)) {\n return \"position\";\n }\n\n // Check for shadow-like values\n if (looksLikeShadow(trimmed)) {\n return \"shadow\";\n }\n\n return \"any\";\n}\n\n/**\n * Infer type from a math function (calc, min, max, clamp).\n */\nfunction inferMathFunctionType(value: string): DataType {\n const openParen = value.indexOf(\"(\");\n const closeParen = value.lastIndexOf(\")\");\n if (openParen === -1 || closeParen === -1) return \"any\";\n\n const content = value.slice(openParen + 1, closeParen);\n\n for (const unit of LENGTH_UNITS) {\n if (content.includes(unit)) return \"length\";\n }\n for (const unit of ANGLE_UNITS) {\n if (content.includes(unit)) return \"angle\";\n }\n for (const unit of TIME_UNITS) {\n if (content.includes(unit)) return \"time\";\n }\n\n return content.includes(\"%\") ? \"percentage\" : \"number\";\n}\n\n/**\n * Check if a value is a position keyword.\n */\nfunction isPositionValue(value: string): boolean {\n const parts = value.split(/\\s+/);\n\n if (parts.length > 4) return false;\n\n for (const part of parts) {\n const normalized = part.toLowerCase();\n if (!POSITION_KEYWORDS.has(normalized) && !NUMBER_WITH_UNIT.test(part)) {\n return false;\n }\n }\n\n return parts.some((p) => POSITION_KEYWORDS.has(p.toLowerCase()));\n}\n\n/**\n * Check if a value looks like a box-shadow or text-shadow.\n */\nfunction looksLikeShadow(value: string): boolean {\n // Shadows typically have multiple space-separated values\n // including lengths and optionally colors\n const parts = value.split(/\\s+/);\n if (parts.length < 2) return false;\n\n let hasLength = false;\n let hasColor = false;\n\n for (const part of parts) {\n if (NUMBER_WITH_UNIT.test(part)) {\n const unit = part.match(NUMBER_WITH_UNIT)?.[1];\n if (!unit || unit === \"%\" || LENGTH_UNITS.has(unit)) {\n hasLength = true;\n }\n }\n if (isColor(part) || part === \"inset\") {\n hasColor = true;\n }\n }\n\n return hasLength && (hasColor || parts.length >= 2);\n}\n\n/**\n * Check if a value matches a specific data type.\n *\n * @param value - The value to check\n * @param type - The data type to check against\n * @returns true if the value matches the type\n */\nexport function matchesDataType(value: string, type: DataType): boolean {\n if (type === \"any\") return true;\n\n const inferred = inferDataType(value);\n if (inferred === type) return true;\n\n // Compatible type pairs\n if (type === \"number\" && inferred === \"integer\") return true;\n if (type === \"image\" && (inferred === \"gradient\" || inferred === \"url\")) return true;\n\n return false;\n}\n\n/**\n * Get all possible data types for a value.\n * Some values can be interpreted as multiple types.\n *\n * @param value - The value to analyze\n * @returns Array of possible data types\n */\nexport function getPossibleDataTypes(value: string): DataType[] {\n const types: DataType[] = [];\n const trimmed = value.trim();\n\n // Numbers can be multiple things\n if (INTEGER_PATTERN.test(trimmed)) {\n types.push(\"integer\", \"number\");\n // 0 is a valid length without unit\n if (trimmed === \"0\") {\n types.push(\"length\", \"angle\", \"time\", \"percentage\");\n }\n }\n\n // Percentages\n if (trimmed.endsWith(\"%\") && NUMBER_WITH_UNIT.test(trimmed)) {\n types.push(\"percentage\");\n }\n\n // Check for various units\n const match = trimmed.match(NUMBER_WITH_UNIT);\n if (match && match[1]) {\n const unit = match[1];\n if (LENGTH_UNITS.has(unit)) types.push(\"length\");\n if (ANGLE_UNITS.has(unit)) types.push(\"angle\");\n if (TIME_UNITS.has(unit)) types.push(\"time\");\n if (FREQUENCY_UNITS.has(unit.toLowerCase())) types.push(\"frequency\");\n if (RESOLUTION_UNITS.has(unit.toLowerCase())) types.push(\"resolution\");\n if (unit === \"fr\") types.push(\"flex\");\n }\n\n // Check for colors\n if (isColor(trimmed)) {\n types.push(\"color\");\n }\n\n // Check for images/gradients\n for (const fn of IMAGE_FUNCTIONS) {\n if (trimmed.startsWith(`${fn}(`)) {\n types.push(\"image\");\n if (GRADIENT_FUNCTIONS.some((g) => trimmed.startsWith(`${g}(`))) {\n types.push(\"gradient\");\n }\n break;\n }\n }\n\n if (trimmed.startsWith(\"url(\")) {\n types.push(\"url\");\n }\n\n // Default\n if (types.length === 0) {\n types.push(\"any\");\n }\n\n return types;\n}\n","/**\n * CSS Dimensions\n *\n * Central dimension/length parser and utilities.\n */\n\n/**\n * CSS length units and their categories.\n */\nexport const LENGTH_UNITS = {\n // Absolute units (convert to px)\n absolute: {\n px: 1,\n cm: 96 / 2.54,\n mm: 96 / 25.4,\n Q: 96 / 101.6,\n in: 96,\n pc: 16,\n pt: 96 / 72,\n },\n // Font-relative units\n fontRelative: [\"em\", \"rem\", \"ex\", \"rex\", \"cap\", \"rcap\", \"ch\", \"rch\", \"ic\", \"ric\", \"lh\", \"rlh\"],\n // Viewport units\n viewport: [\n \"vw\",\n \"vh\",\n \"vi\",\n \"vb\",\n \"vmin\",\n \"vmax\",\n \"svw\",\n \"svh\",\n \"svi\",\n \"svb\",\n \"svmin\",\n \"svmax\",\n \"lvw\",\n \"lvh\",\n \"lvi\",\n \"lvb\",\n \"lvmin\",\n \"lvmax\",\n \"dvw\",\n \"dvh\",\n \"dvi\",\n \"dvb\",\n \"dvmin\",\n \"dvmax\",\n ],\n // Container query units\n container: [\"cqw\", \"cqh\", \"cqi\", \"cqb\", \"cqmin\", \"cqmax\"],\n // Flex unit\n flex: [\"fr\"],\n} as const;\n\n/**\n * All valid CSS length units.\n */\nexport const ALL_LENGTH_UNITS = new Set([\n ...Object.keys(LENGTH_UNITS.absolute),\n ...LENGTH_UNITS.fontRelative,\n ...LENGTH_UNITS.viewport,\n ...LENGTH_UNITS.container,\n ...LENGTH_UNITS.flex,\n]);\n\n// Pre-computed Sets for O(1) unit category lookups (used by getUnitCategory)\nconst FONT_RELATIVE_UNITS: Set<string> = new Set(LENGTH_UNITS.fontRelative);\nconst VIEWPORT_UNITS: Set<string> = new Set(LENGTH_UNITS.viewport);\nconst CONTAINER_UNITS: Set<string> = new Set(LENGTH_UNITS.container);\nconst FLEX_UNITS: Set<string> = new Set(LENGTH_UNITS.flex);\n\n// Pre-compiled regex patterns for number validation (hoisted to avoid recreation)\nconst INTEGER_PATTERN = /^\\d+$/;\nconst DECIMAL_PATTERN = /^\\d+(?:\\.\\d+)?$/;\nconst OPTIONAL_DECIMAL_PATTERN = /^\\d*\\.?\\d+$/;\nconst DIMENSION_PATTERN = /^(-?(?:\\d+\\.?\\d*|\\.\\d+))([a-zA-Z%]*)$/;\n\n/**\n * Parsed dimension value.\n */\nexport interface Dimension {\n value: number;\n unit: string;\n}\n\n/**\n * Parse a CSS dimension string into value and unit.\n *\n * @example\n * ```ts\n * parseDimension(\"10px\") // { value: 10, unit: \"px\" }\n * parseDimension(\"-5rem\") // { value: -5, unit: \"rem\" }\n * parseDimension(\"50%\") // { value: 50, unit: \"%\" }\n * parseDimension(\"0\") // { value: 0, unit: \"\" }\n * parseDimension(\"auto\") // null\n * ```\n */\nexport function parseDimension(input: string): Dimension | null {\n const trimmed = input.trim();\n\n // Match number with optional unit\n const match = trimmed.match(DIMENSION_PATTERN);\n if (!match) return null;\n\n const value = parseFloat(match[1]!);\n const unit = match[2] ?? \"\";\n\n if (isNaN(value)) return null;\n\n return { value, unit };\n}\n\n/**\n * Check if a string is a valid CSS length.\n *\n * @example\n * ```ts\n * isLength(\"10px\") // true\n * isLength(\"5rem\") // true\n * isLength(\"50%\") // true (percentage, not technically a length)\n * isLength(\"auto\") // false\n * ```\n */\nexport function isLength(input: string): boolean {\n const dim = parseDimension(input);\n if (!dim) return false;\n\n // 0 is valid without a unit\n if (dim.value === 0 && dim.unit === \"\") return true;\n\n // Must have a valid unit\n return ALL_LENGTH_UNITS.has(dim.unit) || dim.unit === \"%\";\n}\n\n/**\n * Check if a string is a valid positive integer.\n */\nexport function isPositiveInteger(input: string): boolean {\n const trimmed = input.trim();\n if (!INTEGER_PATTERN.test(trimmed)) return false;\n const num = parseInt(trimmed, 10);\n return num >= 0 && Number.isInteger(num);\n}\n\n/**\n * Check if a string is a valid strictly positive integer (> 0).\n */\nexport function isStrictPositiveInteger(input: string): boolean {\n const trimmed = input.trim();\n if (!INTEGER_PATTERN.test(trimmed)) return false;\n const num = parseInt(trimmed, 10);\n return num > 0 && Number.isInteger(num);\n}\n\n/**\n * Check if a value is a valid spacing multiplier.\n * Valid spacing multipliers are numbers that work with the spacing scale.\n */\nexport function isValidSpacingMultiplier(input: string): boolean {\n const trimmed = input.trim();\n\n // Allow negative values\n const isNegative = trimmed.startsWith(\"-\");\n const value = isNegative ? trimmed.slice(1) : trimmed;\n\n // Must be a number (integer or decimal)\n if (!DECIMAL_PATTERN.test(value)) return false;\n\n const num = parseFloat(value);\n return !isNaN(num) && isFinite(num);\n}\n\n/**\n * Check if a value is a valid opacity value.\n * Valid opacity values are:\n * - decimals between 0 and 1 (e.g. 0, 0.5, 1)\n * - percentages between 0% and 100%\n */\nexport function isValidOpacityValue(input: string): boolean {\n const trimmed = input.trim();\n\n if (trimmed.endsWith(\"%\")) {\n const raw = trimmed.slice(0, -1);\n if (!OPTIONAL_DECIMAL_PATTERN.test(raw)) return false;\n const num = parseFloat(raw);\n return num >= 0 && num <= 100;\n }\n\n if (INTEGER_PATTERN.test(trimmed)) {\n const num = parseInt(trimmed, 10);\n return num >= 0 && num <= 100;\n }\n\n if (!OPTIONAL_DECIMAL_PATTERN.test(trimmed)) return false;\n\n const num = parseFloat(trimmed);\n return num >= 0 && num <= 1;\n}\n\n/**\n * Convert a dimension to pixels.\n * Only works for absolute units; returns null for relative units.\n *\n * @param dim - The dimension to convert\n * @param context - Optional context for relative units (fontSize, rootFontSize in px)\n */\nexport function toPx(dim: Dimension, context?: { fontSize?: number; rootFontSize?: number }): number | null {\n const { value, unit } = dim;\n\n // Zero is always 0px\n if (value === 0) return 0;\n\n // Absolute units\n const absoluteRatio = LENGTH_UNITS.absolute[unit as keyof typeof LENGTH_UNITS.absolute];\n if (absoluteRatio !== undefined) {\n return value * absoluteRatio;\n }\n\n // Font-relative with context\n if (context) {\n if (unit === \"em\" && context.fontSize) {\n return value * context.fontSize;\n }\n if (unit === \"rem\" && context.rootFontSize) {\n return value * context.rootFontSize;\n }\n }\n\n // Can't convert relative units without context\n return null;\n}\n\n/**\n * Compare two dimensions.\n * Only comparable if they have the same unit or are both convertible to px.\n *\n * @returns negative if a < b, 0 if equal, positive if a > b, or null if not comparable\n */\nexport function compareDimensions(\n a: Dimension,\n b: Dimension,\n context?: { fontSize?: number; rootFontSize?: number }\n): number | null {\n // Same unit - direct comparison\n if (a.unit === b.unit) {\n return a.value - b.value;\n }\n\n // Try to convert both to px\n const aPx = toPx(a, context);\n const bPx = toPx(b, context);\n\n if (aPx !== null && bPx !== null) {\n return aPx - bPx;\n }\n\n // Not comparable\n return null;\n}\n\n/**\n * Sort dimensions by their pixel value.\n * Dimensions that can't be converted are placed at the end.\n */\nexport function sortDimensions(dimensions: string[], context?: { fontSize?: number; rootFontSize?: number }): string[] {\n const parsed = dimensions.map((d) => ({\n original: d,\n dim: parseDimension(d),\n }));\n\n return parsed\n .sort((a, b) => {\n // Can't parse - move to end\n if (!a.dim && !b.dim) return 0;\n if (!a.dim) return 1;\n if (!b.dim) return -1;\n\n const result = compareDimensions(a.dim, b.dim, context);\n if (result === null) {\n // Not comparable - sort by unit then value\n if (a.dim.unit !== b.dim.unit) {\n return a.dim.unit.localeCompare(b.dim.unit);\n }\n return a.dim.value - b.dim.value;\n }\n return result;\n })\n .map((p) => p.original);\n}\n\n/**\n * Format a dimension value.\n */\nexport function formatDimension(dim: Dimension): string {\n // Remove unnecessary decimals\n const formatted =\n dim.value === Math.floor(dim.value) ? String(dim.value) : dim.value.toFixed(4).replace(/\\.?0+$/, \"\");\n\n return `${formatted}${dim.unit}`;\n}\n\n/**\n * Get the unit category for a dimension unit.\n */\nexport function getUnitCategory(\n unit: string\n): \"absolute\" | \"font-relative\" | \"viewport\" | \"container\" | \"flex\" | \"percentage\" | \"unknown\" {\n if (unit in LENGTH_UNITS.absolute) return \"absolute\";\n if (FONT_RELATIVE_UNITS.has(unit)) return \"font-relative\";\n if (VIEWPORT_UNITS.has(unit)) return \"viewport\";\n if (CONTAINER_UNITS.has(unit)) return \"container\";\n if (FLEX_UNITS.has(unit)) return \"flex\";\n if (unit === \"%\") return \"percentage\";\n return \"unknown\";\n}\n","/**\n * Utility Trie\n *\n * A segment-based trie data structure for O(k) utility prefix matching.\n * Instead of character-by-character traversal, we split by dashes and\n * traverse segment-by-segment, reducing Map lookups significantly.\n *\n * Example:\n * - \"bg-gradient-to-r-500\" with right-to-left: 5 Map lookups\n * - \"bg-gradient-to-r-500\" with segment trie: 5 segment lookups (same, but left-to-right)\n *\n * The key advantage is we find the LONGEST match in one forward pass,\n * without needing to backtrack.\n */\n\ninterface SegmentTrieNode {\n children: Map<string, SegmentTrieNode>;\n entries: Array<[string, SegmentTrieNode]>;\n isUtility: boolean;\n}\n\n/**\n * A segment-based trie optimized for finding the longest matching utility prefix.\n * Stores dash-separated segments instead of individual characters.\n */\nexport class UtilityTrie {\n private root: SegmentTrieNode = { children: new Map(), entries: [], isUtility: false };\n private size = 0;\n\n /**\n * Insert a utility name into the trie.\n * @param utility - The utility name (e.g., \"bg\", \"bg-gradient-to\")\n */\n insert(utility: string): void {\n const segments = utility.split(\"-\");\n let node = this.root;\n\n for (const segment of segments) {\n let child = node.children.get(segment);\n if (!child) {\n child = { children: new Map(), entries: [], isUtility: false };\n node.children.set(segment, child);\n node.entries.push([segment, child]);\n }\n node = child;\n }\n\n if (!node.isUtility) {\n node.isUtility = true;\n this.size++;\n }\n }\n\n /**\n * Check if a utility exists in the trie.\n * @param utility - The utility name to check\n */\n has(utility: string): boolean {\n // Fast path: no dashes means direct lookup\n const firstDash = utility.indexOf(\"-\");\n if (firstDash === -1) {\n const child = this.root.children.get(utility);\n return !!child?.isUtility;\n }\n\n let node = this.root;\n let segmentStart = 0;\n let pos = 0;\n\n while (pos <= utility.length) {\n if (pos === utility.length || utility.charCodeAt(pos) === 0x2d /* - */) {\n const child = findChild(node, utility, segmentStart, pos);\n if (!child) return false;\n node = child;\n segmentStart = pos + 1;\n }\n pos++;\n }\n\n return node.isUtility;\n }\n\n /**\n * Find the longest matching utility prefix in the input string.\n * Uses inline segment extraction to avoid array allocations.\n *\n * @param input - The candidate string (e.g., \"bg-red-500\")\n * @returns [root, value] tuple if found, null if no match or entire string is a utility\n *\n * @example\n * ```ts\n * trie.insert(\"bg\");\n * trie.insert(\"bg-gradient-to\");\n *\n * trie.findLongestPrefix(\"bg-red-500\")\n * // Returns [\"bg\", \"red-500\"]\n *\n * trie.findLongestPrefix(\"bg-gradient-to-r\")\n * // Returns [\"bg-gradient-to\", \"r\"]\n *\n * trie.findLongestPrefix(\"flex\")\n * // Returns null (entire string is utility or no match)\n * ```\n */\n findLongestPrefix(input: string): [string, string] | null {\n // Handle inputs without dashes specially\n const firstDash = input.indexOf(\"-\");\n if (firstDash === -1) {\n // Check if the entire input is a registered utility\n // This handles functional utilities used without a value (e.g., \"rounded\", \"shadow\")\n const child = this.root.children.get(input);\n if (child?.isUtility) {\n // Return with empty value part to indicate functional utility with default\n return [input, \"\"];\n }\n return null;\n }\n\n let node = this.root;\n let lastMatchPos = -1; // Position of dash after last matched utility\n let segmentStart = 0;\n let pos = 0;\n\n while (pos <= input.length) {\n // Find end of current segment (at dash or end of string)\n if (pos === input.length || input.charCodeAt(pos) === 0x2d /* - */) {\n const child = findChild(node, input, segmentStart, pos);\n\n if (!child) {\n // No more matches, return best found so far\n break;\n }\n\n node = child;\n\n // Record position if this is a valid utility\n if (node.isUtility) {\n lastMatchPos = pos;\n }\n\n segmentStart = pos + 1;\n }\n pos++;\n }\n\n // If we matched the entire string and it's a utility, it's static\n if (lastMatchPos === input.length) {\n return null;\n }\n\n // Return the split if we found a valid prefix\n if (lastMatchPos > 0) {\n return [input.slice(0, lastMatchPos), input.slice(lastMatchPos + 1)];\n }\n\n return null;\n }\n\n /**\n * Find all utilities that match as prefixes of the input.\n * Useful for debugging and testing.\n *\n * @param input - The candidate string\n * @returns Array of matching utility prefixes\n */\n findAllPrefixes(input: string): string[] {\n const matches: string[] = [];\n let node = this.root;\n let segmentStart = 0;\n let pos = 0;\n\n while (pos <= input.length) {\n // Find end of current segment (at dash or end of string)\n if (pos === input.length || input.charCodeAt(pos) === 0x2d /* - */) {\n const child = findChild(node, input, segmentStart, pos);\n\n if (!child) break;\n node = child;\n\n // Record if this is a valid utility\n if (node.isUtility) {\n matches.push(input.slice(0, pos));\n }\n\n segmentStart = pos + 1;\n }\n pos++;\n }\n\n return matches;\n }\n\n /**\n * Get the number of utilities in the trie.\n */\n getSize(): number {\n return this.size;\n }\n\n /**\n * Clear all utilities from the trie.\n */\n clear(): void {\n this.root = { children: new Map(), entries: [], isUtility: false };\n this.size = 0;\n }\n}\n\nfunction findChild(node: SegmentTrieNode, input: string, start: number, end: number): SegmentTrieNode | null {\n const segmentLength = end - start;\n if (segmentLength <= 0) {\n return null;\n }\n\n for (const [segment, child] of node.entries) {\n if (segment.length !== segmentLength) {\n continue;\n }\n\n let isMatch = true;\n for (let i = 0; i < segmentLength; i++) {\n if (segment.charCodeAt(i) !== input.charCodeAt(start + i)) {\n isMatch = false;\n break;\n }\n }\n\n if (isMatch) {\n return child;\n }\n }\n\n return null;\n}\n\n/**\n * Create a trie from an iterable of utility names.\n * @param utilities - Iterable of utility names\n */\nexport function createUtilityTrie(utilities: Iterable<string>): UtilityTrie {\n const trie = new UtilityTrie();\n for (const utility of utilities) {\n trie.insert(utility);\n }\n return trie;\n}\n","/**\n * Utilities Registry\n *\n * Manages utility definitions and compilation.\n * Utilities are functions that convert candidates to CSS declarations.\n */\n\nimport type { AstNode } from \"../ast\";\nimport type { Candidate, FunctionalCandidate, StaticCandidate } from \"../candidate\";\nimport type { Theme, ThemeKey } from \"../theme\";\nimport { inferDataType, type DataType } from \"../utils/infer-data-type\";\nimport { isValidSpacingMultiplier } from \"../utils/dimensions\";\nimport { UtilityTrie } from \"../utils/utility-trie\";\n\n// Data types that can be negated (pre-computed for O(1) lookup)\nconst NEGATABLE_TYPES: Set<DataType> = new Set([\"length\", \"percentage\", \"angle\", \"time\", \"number\", \"integer\"]);\n\n// Pre-compiled regex patterns for isSimpleNegatable (hoisted to avoid recreation on every call)\nconst TRANSFORM_FUNCTIONS_PATTERN = /translate|rotate|scale|skew|matrix|perspective/;\nconst NEGATABLE_FUNCTIONS_PATTERN = /^(?:calc|min|max|clamp|var)\\(/;\n\n// Try to load native findRoot for better performance\nlet nativeFindRoot: ((input: string) => [string, string] | null) | null = null;\nlet nativeLoadAttempted = false;\n\nfunction tryLoadNativeFindRoot(): typeof nativeFindRoot {\n if (nativeLoadAttempted) return nativeFindRoot;\n nativeLoadAttempted = true;\n\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const oxide = require(\"@rainbowindex/oxide\");\n if (oxide && typeof oxide.findRootNative === \"function\" && typeof oxide.isUtilitySetLoaded === \"function\") {\n nativeFindRoot = oxide.findRootNative;\n }\n } catch {\n // Native module not available\n }\n\n return nativeFindRoot;\n}\n\nfunction loadUtilitySetToNative(utilities: Iterable<string>): boolean {\n try {\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n const oxide = require(\"@rainbowindex/oxide\");\n if (oxide && typeof oxide.loadUtilitySet === \"function\") {\n oxide.loadUtilitySet([...utilities]);\n // Verify the load actually succeeded\n if (typeof oxide.isUtilitySetLoaded === \"function\") {\n return oxide.isUtilitySetLoaded();\n }\n }\n } catch {\n // Native module not available\n }\n return false;\n}\n\n// ============================================\n// Types\n// ============================================\n\n/** Options for utility registration */\nexport interface UtilityOptions {\n /** Data types this utility accepts (for Intellisense) */\n types?: string[];\n}\n\n/** Compile function for static utilities */\nexport type StaticCompileFn = (candidate: StaticCandidate, theme: Theme) => AstNode[] | null | undefined;\n\n/** Compile function for functional utilities */\nexport type FunctionalCompileFn = (candidate: FunctionalCandidate, theme: Theme) => AstNode[] | null | undefined;\n\n/**\n * Stored utility definition.\n *\n * PERFORMANCE: All fields are always present (never undefined) to ensure\n * consistent V8 hidden class shapes. This allows the engine to optimize\n * property access without polymorphic inline caches.\n */\ninterface UtilityDef {\n kind: \"static\" | \"functional\";\n /** Static compile function (null for functional utilities) */\n staticFn: StaticCompileFn | null;\n /** Functional compile function (null for static utilities) */\n functionalFn: FunctionalCompileFn | null;\n /** Utility options (null if none) */\n options: UtilityOptions | null;\n}\n\n/** Suggestion group for Intellisense */\nexport interface SuggestionGroup {\n name: string;\n values: string[];\n}\n\n// ============================================\n// Utilities Class\n// ============================================\n\nexport class Utilities {\n /** Registered utilities by name */\n private utilities = new Map<string, UtilityDef[]>();\n\n /** Completion suggestions by utility name */\n private completions = new Map<string, () => SuggestionGroup[]>();\n\n /** Trie for O(n) utility prefix lookup (lazily built) */\n private _trie: UtilityTrie | null = null;\n\n /** Whether native utility set has been loaded */\n private _nativeLoaded = false;\n\n /** Cache for findRoot results (per utilities instance) */\n private _findRootCache: Map<string, [string, string] | null> = new Map();\n\n /**\n * Get or build the utility trie for fast prefix matching.\n * The trie is lazily built on first access and cached.\n * Also loads utility set into native Rust for even faster lookups.\n */\n getTrie(): UtilityTrie {\n if (this._trie === null) {\n this._trie = new UtilityTrie();\n for (const name of this.utilities.keys()) {\n this._trie.insert(name);\n }\n // Load utility set into native Rust for native findRoot\n // Only mark as loaded if it actually succeeded\n if (!this._nativeLoaded) {\n this._nativeLoaded = loadUtilitySetToNative(this.utilities.keys());\n }\n }\n return this._trie;\n }\n\n /**\n * Find the longest matching utility root for a candidate string.\n * Uses native Rust when available, falls back to TypeScript trie.\n *\n * @param input - The utility part of the candidate (without variants)\n * @returns [root, value] tuple if found, null otherwise\n */\n findRoot(input: string): [string, string] | null {\n // Ensure trie is built (and native set is loaded)\n this.getTrie();\n\n const cached = this._findRootCache.get(input);\n if (cached !== undefined) {\n return cached;\n }\n\n // Try native findRoot first (faster for large utility sets)\n const native = tryLoadNativeFindRoot();\n if (native && this._nativeLoaded) {\n const result = native(input);\n if (this._findRootCache.size >= 1024) {\n this._findRootCache.clear();\n }\n this._findRootCache.set(input, result);\n return result;\n }\n\n // Fall back to TypeScript trie\n const result = this._trie!.findLongestPrefix(input);\n if (this._findRootCache.size >= 1024) {\n this._findRootCache.clear();\n }\n this._findRootCache.set(input, result);\n return result;\n }\n\n /**\n * Invalidate the trie cache (call after registering new utilities).\n */\n invalidateTrie(): void {\n this._trie = null;\n this._nativeLoaded = false;\n this._findRootCache.clear();\n }\n\n /**\n * Create a new Utilities instance with the same registered utilities.\n * Keeps caches empty to avoid sharing mutable state.\n */\n clone(): Utilities {\n const next = new Utilities();\n\n for (const [name, defs] of this.utilities) {\n next.utilities.set(name, defs.slice());\n }\n\n for (const [name, getter] of this.completions) {\n next.completions.set(name, getter);\n }\n\n return next;\n }\n\n /**\n * Register a static utility (no value, like \"flex\" or \"hidden\").\n */\n static(name: string, compileFn: StaticCompileFn): void {\n const defs = this.utilities.get(name) ?? [];\n // PERFORMANCE: Consistent object shape for V8 hidden class optimization\n // SAFETY: Object.freeze prevents mutation after clone() creates shallow copies\n const def: UtilityDef = Object.freeze({\n kind: \"static\",\n staticFn: compileFn,\n functionalFn: null,\n options: null,\n });\n defs.push(def);\n this.utilities.set(name, defs);\n }\n\n /**\n * Register a functional utility (with value, like \"bg-*\" or \"p-*\").\n */\n functional(name: string, compileFn: FunctionalCompileFn, options?: UtilityOptions): void {\n const defs = this.utilities.get(name) ?? [];\n // PERFORMANCE: Consistent object shape for V8 hidden class optimization\n // SAFETY: Object.freeze prevents mutation after clone() creates shallow copies\n const def: UtilityDef = Object.freeze({\n kind: \"functional\",\n staticFn: null,\n functionalFn: compileFn,\n options: options ?? null,\n });\n defs.push(def);\n this.utilities.set(name, defs);\n }\n\n /**\n * Check if a utility exists.\n */\n has(name: string, kind?: \"static\" | \"functional\"): boolean {\n const defs = this.utilities.get(name);\n if (!defs) return false;\n if (!kind) return true;\n return defs.some((d) => d.kind === kind);\n }\n\n /**\n * Get utility definitions by name.\n */\n get(name: string): UtilityDef[] {\n return this.utilities.get(name) ?? [];\n }\n\n /**\n * Compile a candidate to AST nodes.\n */\n compile(candidate: Candidate, theme: Theme): AstNode[] | null {\n // Arbitrary candidates don't have a root - they're handled separately\n if (candidate.kind === \"arbitrary\") {\n return null;\n }\n\n // Check if this is a negative utility (root starts with \"-\")\n const isNegative = candidate.root.startsWith(\"-\");\n const positiveRoot = isNegative ? candidate.root.slice(1) : candidate.root;\n\n // Try the actual root first, then the positive root if negative\n const rootsToTry = isNegative ? [candidate.root, positiveRoot] : [candidate.root];\n\n // When a functional candidate has null value, it means the utility was used\n // without a value (e.g., \"rounded\" instead of \"rounded-lg\"). In this case,\n // we should also try matching static utilities as a fallback.\n const isFunctionalWithNoValue =\n candidate.kind === \"functional\" && (candidate as FunctionalCandidate).value === null;\n\n for (const root of rootsToTry) {\n const defs = this.utilities.get(root);\n if (!defs) continue;\n\n for (const def of defs) {\n if (candidate.kind === \"static\" && def.kind === \"static\" && def.staticFn) {\n const result = def.staticFn(candidate, theme);\n if (result) {\n // Negate values if using positive root for negative candidate\n if (isNegative && root === positiveRoot) {\n return this.negateDeclarations(result);\n }\n return result;\n }\n } else if (candidate.kind === \"functional\" && def.kind === \"functional\" && def.functionalFn) {\n // For negative utilities, use a modified candidate with positive root\n const candidateToCompile =\n isNegative && root === positiveRoot\n ? ({ ...candidate, root: positiveRoot } as FunctionalCandidate)\n : candidate;\n\n const result = def.functionalFn(candidateToCompile, theme);\n if (result) {\n // Negate values if using positive root for negative candidate\n if (isNegative && root === positiveRoot) {\n return this.negateDeclarations(result);\n }\n return result;\n }\n } else if (isFunctionalWithNoValue && def.kind === \"static\" && def.staticFn) {\n // Fallback: try static utility when functional candidate has no value\n // This handles cases like \"flex\" being parsed as functional but only\n // registered as static\n const staticCandidate = {\n kind: \"static\" as const,\n root: candidate.root,\n variants: candidate.variants,\n important: candidate.important,\n raw: candidate.raw,\n };\n const result = def.staticFn(staticCandidate, theme);\n if (result) {\n if (isNegative && root === positiveRoot) {\n return this.negateDeclarations(result);\n }\n return result;\n }\n }\n }\n }\n\n return null;\n }\n\n /**\n * Negate numeric values in declarations.\n * Only negates CSS custom properties (--*) and simple numeric values.\n */\n private negateDeclarations(nodes: AstNode[]): AstNode[] {\n return nodes.map((node) => {\n if (node.kind === \"declaration\" && node.value) {\n // Only negate CSS custom properties (--*) which hold numeric values\n if (node.property.startsWith(\"--\")) {\n return decl(node.property, `calc(${node.value} * -1)`, node.important);\n }\n // For regular properties, only negate if it's a simple value\n // (not complex functions like transform)\n const value = node.value;\n if (this.isSimpleNegatable(value)) {\n return decl(node.property, `calc(${value} * -1)`, node.important);\n }\n }\n return node;\n });\n }\n\n /**\n * Check if a value can be simply negated.\n * Returns true for numeric values (length, percentage, angle, time) and calc()/var().\n * Uses inferDataType for robust type detection.\n */\n private isSimpleNegatable(value: string): boolean {\n // Skip complex transform functions\n if (TRANSFORM_FUNCTIONS_PATTERN.test(value)) {\n return false;\n }\n\n // calc(), min(), max(), clamp(), and var() expressions can be negated\n if (NEGATABLE_FUNCTIONS_PATTERN.test(value)) {\n return true;\n }\n\n // Use inferDataType for robust detection of negatable types\n const dataType = inferDataType(value);\n return NEGATABLE_TYPES.has(dataType);\n }\n\n /**\n * Register completion suggestions for a utility.\n */\n suggest(name: string, groups: () => SuggestionGroup[]): void {\n this.completions.set(name, groups);\n }\n\n /**\n * Get completion suggestions for a utility.\n */\n getCompletions(name: string): SuggestionGroup[] {\n const getter = this.completions.get(name);\n return getter?.() ?? [];\n }\n\n /**\n * Get all registered utility names.\n */\n names(): IterableIterator<string> {\n return this.utilities.keys();\n }\n}\n\n// ============================================\n// Utility Helpers\n// ============================================\n\nimport { decl } from \"../ast\";\n\n/**\n * Create a simple declaration utility.\n */\nexport function staticUtility(declarations: [property: string, value: string][]): StaticCompileFn {\n return () => declarations.map(([property, value]) => decl(property, value));\n}\n\n/**\n * Resolve a theme color for a functional utility.\n */\nexport function resolveThemeColor(candidate: FunctionalCandidate, theme: Theme, themeKeys: ThemeKey[]): string | null {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return candidate.value.value;\n }\n\n return theme.resolve(candidate.value.value, themeKeys);\n}\n\n/**\n * Apply opacity modifier to a color value.\n */\nexport function withOpacity(color: string, modifier: FunctionalCandidate[\"modifier\"]): string {\n if (!modifier) return color;\n\n let opacity: string;\n\n if (modifier.kind === \"named\") {\n // Convert 75 to 75%\n const num = Number(modifier.value);\n if (!Number.isNaN(num)) {\n opacity = `${num}%`;\n } else {\n opacity = modifier.value;\n }\n } else {\n opacity = modifier.value;\n }\n\n if (opacity === \"100%\") return color;\n\n return `color-mix(in oklab, ${color} ${opacity}, transparent)`;\n}\n\n/** Special spacing keywords */\nconst SPACING_KEYWORDS: Record<string, string> = {\n px: \"1px\",\n full: \"100%\",\n auto: \"auto\",\n screen: \"100vh\",\n svh: \"100svh\",\n lvh: \"100lvh\",\n dvh: \"100dvh\",\n min: \"min-content\",\n max: \"max-content\",\n fit: \"fit-content\",\n};\n\n/**\n * Resolve spacing value from theme.\n */\nexport function resolveSpacing(value: string, theme: Theme): string | null {\n // Check for numeric value (e.g., \"4\" -> calc(4 * var(--spacing)))\n const num = Number(value);\n if (!Number.isNaN(num)) {\n // Validate spacing multiplier (must be valid number format)\n if (!isValidSpacingMultiplier(value)) return null;\n\n const spacing = theme.get(\"--spacing\");\n if (spacing) {\n if (num === 0) return \"0px\";\n return `calc(${num} * ${spacing})`;\n }\n return `${num * 0.25}rem`;\n }\n\n // Check for fraction (e.g., \"1/2\" -> 50%)\n if (value.includes(\"/\")) {\n const [numerator, denominator] = value.split(\"/\").map(Number);\n if (!Number.isNaN(numerator) && !Number.isNaN(denominator) && denominator !== 0) {\n return `${(numerator! / denominator!) * 100}%`;\n }\n }\n\n // Named spacing values from theme\n const named = theme.get(`--spacing-${value}`);\n if (named) return named;\n\n // Special spacing keywords\n return SPACING_KEYWORDS[value] ?? null;\n}\n\n/**\n * Handle negative values for a utility.\n */\nexport function handleNegative(\n candidate: FunctionalCandidate,\n compileFn: FunctionalCompileFn,\n theme: Theme\n): AstNode[] | null {\n // Check if root starts with \"-\" (negative utility)\n if (!candidate.root.startsWith(\"-\")) {\n return compileFn(candidate, theme) ?? null;\n }\n\n // Create a copy with positive root\n const positiveCandidate: FunctionalCandidate = {\n ...candidate,\n root: candidate.root.slice(1),\n };\n\n const result = compileFn(positiveCandidate, theme);\n if (!result) return null;\n\n // Negate the values\n return result.map((node) => {\n if (node.kind === \"declaration\" && node.value) {\n return decl(node.property, `calc(${node.value} * -1)`, node.important);\n }\n return node;\n });\n}\n","import { parseDimension, toPx } from \"./dimensions\";\nimport { hasMathFunction } from \"./math-operators\";\n\n/**\n * Unit buckets for grouping incompatible units.\n * Values in different buckets cannot be directly compared.\n */\nexport enum UnitBucket {\n /** Absolute units that can be converted to px */\n Absolute = 0,\n /** Viewport-relative units (vw, vh, etc.) */\n Viewport = 1,\n /** Container-relative units (cqw, cqh, etc.) */\n Container = 2,\n /** Font-relative units (em, rem, etc.) */\n FontRelative = 3,\n /** Percentage values */\n Percentage = 4,\n /** Flex units (fr) */\n Flex = 5,\n /** Math functions (calc, min, max, etc.) */\n Function = 6,\n /** Unknown or unparseable */\n Unknown = 7,\n}\n\n/**\n * Get the unit bucket for a CSS value.\n */\nexport function getUnitBucket(value: string): UnitBucket {\n const trimmed = value.trim();\n\n // Check for math functions first\n if (hasMathFunction(trimmed)) {\n return UnitBucket.Function;\n }\n\n const dim = parseDimension(trimmed);\n if (!dim) {\n return UnitBucket.Unknown;\n }\n\n const { unit } = dim;\n\n // Zero is special - compatible with any absolute unit\n if (dim.value === 0) {\n return UnitBucket.Absolute;\n }\n\n switch (unit) {\n case \"px\":\n case \"cm\":\n case \"mm\":\n case \"in\":\n case \"pt\":\n case \"pc\":\n case \"Q\":\n return UnitBucket.Absolute;\n\n case \"vw\":\n case \"vh\":\n case \"vi\":\n case \"vb\":\n case \"vmin\":\n case \"vmax\":\n case \"svw\":\n case \"svh\":\n case \"svi\":\n case \"svb\":\n case \"svmin\":\n case \"svmax\":\n case \"lvw\":\n case \"lvh\":\n case \"lvi\":\n case \"lvb\":\n case \"lvmin\":\n case \"lvmax\":\n case \"dvw\":\n case \"dvh\":\n case \"dvi\":\n case \"dvb\":\n case \"dvmin\":\n case \"dvmax\":\n return UnitBucket.Viewport;\n\n case \"cqw\":\n case \"cqh\":\n case \"cqi\":\n case \"cqb\":\n case \"cqmin\":\n case \"cqmax\":\n return UnitBucket.Container;\n\n case \"em\":\n case \"rem\":\n case \"ex\":\n case \"rex\":\n case \"cap\":\n case \"rcap\":\n case \"ch\":\n case \"rch\":\n case \"ic\":\n case \"ric\":\n case \"lh\":\n case \"rlh\":\n return UnitBucket.FontRelative;\n\n case \"%\":\n return UnitBucket.Percentage;\n\n case \"fr\":\n return UnitBucket.Flex;\n\n default:\n return UnitBucket.Unknown;\n }\n}\n\n/**\n * Context for breakpoint comparison.\n */\nexport interface BreakpointContext {\n /** Root font size in px (for rem conversion) */\n rootFontSize?: number;\n /** Default font size in px (for em conversion) */\n fontSize?: number;\n}\n\n/**\n * Default context values.\n */\nconst DEFAULT_CONTEXT: Required<BreakpointContext> = {\n rootFontSize: 16,\n fontSize: 16,\n};\n\n/**\n * Compare two breakpoint values.\n *\n * Returns:\n * - Negative if a < b\n * - Zero if a === b\n * - Positive if a > b\n * - null if values cannot be compared (different unit buckets)\n *\n * @example\n * ```ts\n * compareBreakpoints(\"640px\", \"768px\") // -128 (640 < 768)\n * compareBreakpoints(\"40rem\", \"640px\") // 0 (both = 640px with 16px root)\n * compareBreakpoints(\"100vw\", \"50%\") // null (incompatible units)\n * ```\n */\nexport function compareBreakpoints(a: string, b: string, context: BreakpointContext = {}): number | null {\n const ctx = { ...DEFAULT_CONTEXT, ...context };\n\n const bucketA = getUnitBucket(a);\n const bucketB = getUnitBucket(b);\n\n // Different buckets cannot be compared, except Absolute and FontRelative\n if (bucketA !== bucketB) {\n const isAbsoluteAndFontRelative =\n (bucketA === UnitBucket.Absolute && bucketB === UnitBucket.FontRelative) ||\n (bucketA === UnitBucket.FontRelative && bucketB === UnitBucket.Absolute);\n\n if (!isAbsoluteAndFontRelative) {\n return null;\n }\n\n const pxA = toAbsolutePx(a, ctx);\n const pxB = toAbsolutePx(b, ctx);\n\n if (pxA !== null && pxB !== null) {\n return pxA - pxB;\n }\n\n return null;\n }\n\n // Same bucket - compare based on bucket type\n switch (bucketA) {\n case UnitBucket.Absolute:\n case UnitBucket.FontRelative: {\n const pxA = toAbsolutePx(a, ctx);\n const pxB = toAbsolutePx(b, ctx);\n\n if (pxA !== null && pxB !== null) {\n return pxA - pxB;\n }\n return null;\n }\n\n case UnitBucket.Viewport:\n case UnitBucket.Container:\n case UnitBucket.Percentage:\n case UnitBucket.Flex: {\n // Same unit type - compare numeric values\n const dimA = parseDimension(a);\n const dimB = parseDimension(b);\n\n if (dimA && dimB) {\n // Same unit - direct comparison\n if (dimA.unit === dimB.unit) {\n return dimA.value - dimB.value;\n }\n // Different units in same bucket - can't compare exactly\n // Fall back to numeric comparison (not perfect but deterministic)\n return dimA.value - dimB.value;\n }\n return null;\n }\n\n case UnitBucket.Function: {\n // Functions can't be compared at build time\n // Use string comparison for deterministic ordering\n return a.localeCompare(b);\n }\n\n default:\n return null;\n }\n}\n\n/**\n * Convert a CSS length to absolute pixels.\n */\nfunction toAbsolutePx(value: string, ctx: Required<BreakpointContext>): number | null {\n const dim = parseDimension(value);\n if (!dim) return null;\n\n return toPx(dim, {\n fontSize: ctx.fontSize,\n rootFontSize: ctx.rootFontSize,\n });\n}\n\n/**\n * Sort breakpoint values in ascending order.\n * Values that can't be compared are placed at the end in original order.\n *\n * @example\n * ```ts\n * sortBreakpoints([\"1024px\", \"640px\", \"768px\"])\n * // [\"640px\", \"768px\", \"1024px\"]\n *\n * sortBreakpoints([\"640px\", \"100vw\", \"768px\"])\n * // [\"640px\", \"768px\", \"100vw\"] (100vw can't be compared, moved to end)\n * ```\n */\nexport function sortBreakpoints(breakpoints: string[], context: BreakpointContext = {}): string[] {\n // Group by bucket\n const groups = new Map<UnitBucket, Array<{ value: string; index: number }>>();\n\n for (let i = 0; i < breakpoints.length; i++) {\n const value = breakpoints[i]!;\n const bucket = getUnitBucket(value);\n let group = groups.get(bucket);\n if (!group) {\n group = [];\n groups.set(bucket, group);\n }\n group.push({ value, index: i });\n }\n\n // Sort each group internally\n for (const items of groups.values()) {\n items.sort((a, b) => {\n const cmp = compareBreakpoints(a.value, b.value, context);\n if (cmp !== null) return cmp;\n return a.index - b.index;\n });\n }\n\n // Collect results in bucket priority order (Absolute first, Unknown last)\n const sortedBuckets = [...groups.keys()].sort((a, b) => a - b);\n const result: string[] = [];\n\n for (const bucket of sortedBuckets) {\n const items = groups.get(bucket)!;\n for (const item of items) {\n result.push(item.value);\n }\n }\n\n return result;\n}\n\n/**\n * Check if two breakpoint values are equivalent.\n */\nexport function breakpointsEqual(a: string, b: string, context: BreakpointContext = {}): boolean {\n const cmp = compareBreakpoints(a, b, context);\n return cmp === 0;\n}\n\n/**\n * Find the minimum breakpoint from a list.\n * Returns null if no comparable values exist.\n */\nexport function minBreakpoint(breakpoints: string[], context: BreakpointContext = {}): string | null {\n if (breakpoints.length === 0) return null;\n\n let min = breakpoints[0]!;\n\n for (let i = 1; i < breakpoints.length; i++) {\n const current = breakpoints[i]!;\n const cmp = compareBreakpoints(current, min, context);\n\n if (cmp !== null && cmp < 0) {\n min = current;\n }\n }\n\n return min;\n}\n\n/**\n * Find the maximum breakpoint from a list.\n * Returns null if no comparable values exist.\n */\nexport function maxBreakpoint(breakpoints: string[], context: BreakpointContext = {}): string | null {\n if (breakpoints.length === 0) return null;\n\n let max = breakpoints[0]!;\n\n for (let i = 1; i < breakpoints.length; i++) {\n const current = breakpoints[i]!;\n const cmp = compareBreakpoints(current, max, context);\n\n if (cmp !== null && cmp > 0) {\n max = current;\n }\n }\n\n return max;\n}\n","/**\n * Layout Utilities\n *\n * Display, flexbox, grid, positioning, and layout utilities.\n */\n\nimport { atRule, decl, type AstNode } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { compareBreakpoints } from \"../utils/compare-breakpoints\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\n// Pre-defined flex-basis fraction values (hoisted to avoid recreating on every call)\nconst FLEX_BASIS_VALUES: Record<string, string> = {\n auto: \"auto\",\n full: \"100%\",\n \"1/2\": \"50%\",\n \"1/3\": \"33.333333%\",\n \"2/3\": \"66.666667%\",\n \"1/4\": \"25%\",\n \"2/4\": \"50%\",\n \"3/4\": \"75%\",\n \"1/5\": \"20%\",\n \"2/5\": \"40%\",\n \"3/5\": \"60%\",\n \"4/5\": \"80%\",\n \"1/6\": \"16.666667%\",\n \"2/6\": \"33.333333%\",\n \"3/6\": \"50%\",\n \"4/6\": \"66.666667%\",\n \"5/6\": \"83.333333%\",\n \"1/12\": \"8.333333%\",\n \"2/12\": \"16.666667%\",\n \"3/12\": \"25%\",\n \"4/12\": \"33.333333%\",\n \"5/12\": \"41.666667%\",\n \"6/12\": \"50%\",\n \"7/12\": \"58.333333%\",\n \"8/12\": \"66.666667%\",\n \"9/12\": \"75%\",\n \"10/12\": \"83.333333%\",\n \"11/12\": \"91.666667%\",\n};\n\n// Pre-defined order values\nconst ORDER_VALUES: Record<string, string> = {\n first: \"-9999\",\n last: \"9999\",\n none: \"0\",\n};\n\n// Pre-defined column width values\nconst COLUMN_WIDTH_VALUES: Record<string, string> = {\n auto: \"auto\",\n \"3xs\": \"16rem\",\n \"2xs\": \"18rem\",\n xs: \"20rem\",\n sm: \"24rem\",\n md: \"28rem\",\n lg: \"32rem\",\n xl: \"36rem\",\n \"2xl\": \"42rem\",\n \"3xl\": \"48rem\",\n \"4xl\": \"56rem\",\n \"5xl\": \"64rem\",\n \"6xl\": \"72rem\",\n \"7xl\": \"80rem\",\n};\n\n// Pre-defined position-try-fallbacks values\nconst POSITION_TRY_VALUES: Record<string, string> = {\n \"flip-block\": \"flip-block\",\n \"flip-inline\": \"flip-inline\",\n \"flip-both\": \"flip-block flip-inline\",\n};\n\nexport function registerLayoutUtilities(utilities: Utilities, _theme: Theme): void {\n // Display\n\n utilities.static(\"block\", staticUtility([[\"display\", \"block\"]]));\n utilities.static(\"inline-block\", staticUtility([[\"display\", \"inline-block\"]]));\n utilities.static(\"inline\", staticUtility([[\"display\", \"inline\"]]));\n utilities.static(\"flex\", staticUtility([[\"display\", \"flex\"]]));\n utilities.static(\"inline-flex\", staticUtility([[\"display\", \"inline-flex\"]]));\n utilities.static(\"table\", staticUtility([[\"display\", \"table\"]]));\n utilities.static(\"inline-table\", staticUtility([[\"display\", \"inline-table\"]]));\n utilities.static(\"table-caption\", staticUtility([[\"display\", \"table-caption\"]]));\n utilities.static(\"table-cell\", staticUtility([[\"display\", \"table-cell\"]]));\n utilities.static(\"table-column\", staticUtility([[\"display\", \"table-column\"]]));\n utilities.static(\"table-column-group\", staticUtility([[\"display\", \"table-column-group\"]]));\n utilities.static(\"table-footer-group\", staticUtility([[\"display\", \"table-footer-group\"]]));\n utilities.static(\"table-header-group\", staticUtility([[\"display\", \"table-header-group\"]]));\n utilities.static(\"table-row-group\", staticUtility([[\"display\", \"table-row-group\"]]));\n utilities.static(\"table-row\", staticUtility([[\"display\", \"table-row\"]]));\n utilities.static(\"flow-root\", staticUtility([[\"display\", \"flow-root\"]]));\n utilities.static(\"grid\", staticUtility([[\"display\", \"grid\"]]));\n utilities.static(\"inline-grid\", staticUtility([[\"display\", \"inline-grid\"]]));\n utilities.static(\"contents\", staticUtility([[\"display\", \"contents\"]]));\n utilities.static(\"list-item\", staticUtility([[\"display\", \"list-item\"]]));\n utilities.static(\"hidden\", staticUtility([[\"display\", \"none\"]]));\n\n // Position\n\n utilities.static(\"static\", staticUtility([[\"position\", \"static\"]]));\n utilities.static(\"fixed\", staticUtility([[\"position\", \"fixed\"]]));\n utilities.static(\"absolute\", staticUtility([[\"position\", \"absolute\"]]));\n utilities.static(\"relative\", staticUtility([[\"position\", \"relative\"]]));\n utilities.static(\"sticky\", staticUtility([[\"position\", \"sticky\"]]));\n\n // Visibility\n\n utilities.static(\"visible\", staticUtility([[\"visibility\", \"visible\"]]));\n utilities.static(\"invisible\", staticUtility([[\"visibility\", \"hidden\"]]));\n utilities.static(\"collapse\", staticUtility([[\"visibility\", \"collapse\"]]));\n\n // Float\n\n utilities.static(\"float-start\", staticUtility([[\"float\", \"inline-start\"]]));\n utilities.static(\"float-end\", staticUtility([[\"float\", \"inline-end\"]]));\n utilities.static(\"float-right\", staticUtility([[\"float\", \"right\"]]));\n utilities.static(\"float-left\", staticUtility([[\"float\", \"left\"]]));\n utilities.static(\"float-none\", staticUtility([[\"float\", \"none\"]]));\n\n // Clear\n\n utilities.static(\"clear-start\", staticUtility([[\"clear\", \"inline-start\"]]));\n utilities.static(\"clear-end\", staticUtility([[\"clear\", \"inline-end\"]]));\n utilities.static(\"clear-left\", staticUtility([[\"clear\", \"left\"]]));\n utilities.static(\"clear-right\", staticUtility([[\"clear\", \"right\"]]));\n utilities.static(\"clear-both\", staticUtility([[\"clear\", \"both\"]]));\n utilities.static(\"clear-none\", staticUtility([[\"clear\", \"none\"]]));\n\n // Isolation\n\n utilities.static(\"isolate\", staticUtility([[\"isolation\", \"isolate\"]]));\n utilities.static(\"isolation-auto\", staticUtility([[\"isolation\", \"auto\"]]));\n\n // Object Fit\n\n utilities.static(\"object-contain\", staticUtility([[\"object-fit\", \"contain\"]]));\n utilities.static(\"object-cover\", staticUtility([[\"object-fit\", \"cover\"]]));\n utilities.static(\"object-fill\", staticUtility([[\"object-fit\", \"fill\"]]));\n utilities.static(\"object-none\", staticUtility([[\"object-fit\", \"none\"]]));\n utilities.static(\"object-scale-down\", staticUtility([[\"object-fit\", \"scale-down\"]]));\n\n // Object Position\n\n utilities.static(\"object-bottom\", staticUtility([[\"object-position\", \"bottom\"]]));\n utilities.static(\"object-center\", staticUtility([[\"object-position\", \"center\"]]));\n utilities.static(\"object-left\", staticUtility([[\"object-position\", \"left\"]]));\n utilities.static(\"object-bottom-left\", staticUtility([[\"object-position\", \"left bottom\"]]));\n utilities.static(\"object-top-left\", staticUtility([[\"object-position\", \"left top\"]]));\n utilities.static(\"object-right\", staticUtility([[\"object-position\", \"right\"]]));\n utilities.static(\"object-bottom-right\", staticUtility([[\"object-position\", \"right bottom\"]]));\n utilities.static(\"object-top-right\", staticUtility([[\"object-position\", \"right top\"]]));\n utilities.static(\"object-top\", staticUtility([[\"object-position\", \"top\"]]));\n\n // Functional object-position for arbitrary values\n utilities.functional(\"object\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"object-position\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Overflow\n\n utilities.static(\"overflow-auto\", staticUtility([[\"overflow\", \"auto\"]]));\n utilities.static(\"overflow-hidden\", staticUtility([[\"overflow\", \"hidden\"]]));\n utilities.static(\"overflow-clip\", staticUtility([[\"overflow\", \"clip\"]]));\n utilities.static(\"overflow-visible\", staticUtility([[\"overflow\", \"visible\"]]));\n utilities.static(\"overflow-scroll\", staticUtility([[\"overflow\", \"scroll\"]]));\n utilities.static(\"overflow-x-auto\", staticUtility([[\"overflow-x\", \"auto\"]]));\n utilities.static(\"overflow-y-auto\", staticUtility([[\"overflow-y\", \"auto\"]]));\n utilities.static(\"overflow-x-hidden\", staticUtility([[\"overflow-x\", \"hidden\"]]));\n utilities.static(\"overflow-y-hidden\", staticUtility([[\"overflow-y\", \"hidden\"]]));\n utilities.static(\"overflow-x-clip\", staticUtility([[\"overflow-x\", \"clip\"]]));\n utilities.static(\"overflow-y-clip\", staticUtility([[\"overflow-y\", \"clip\"]]));\n utilities.static(\"overflow-x-visible\", staticUtility([[\"overflow-x\", \"visible\"]]));\n utilities.static(\"overflow-y-visible\", staticUtility([[\"overflow-y\", \"visible\"]]));\n utilities.static(\"overflow-x-scroll\", staticUtility([[\"overflow-x\", \"scroll\"]]));\n utilities.static(\"overflow-y-scroll\", staticUtility([[\"overflow-y\", \"scroll\"]]));\n\n // Overscroll Behavior\n\n utilities.static(\"overscroll-auto\", staticUtility([[\"overscroll-behavior\", \"auto\"]]));\n utilities.static(\"overscroll-contain\", staticUtility([[\"overscroll-behavior\", \"contain\"]]));\n utilities.static(\"overscroll-none\", staticUtility([[\"overscroll-behavior\", \"none\"]]));\n utilities.static(\"overscroll-y-auto\", staticUtility([[\"overscroll-behavior-y\", \"auto\"]]));\n utilities.static(\"overscroll-y-contain\", staticUtility([[\"overscroll-behavior-y\", \"contain\"]]));\n utilities.static(\"overscroll-y-none\", staticUtility([[\"overscroll-behavior-y\", \"none\"]]));\n utilities.static(\"overscroll-x-auto\", staticUtility([[\"overscroll-behavior-x\", \"auto\"]]));\n utilities.static(\"overscroll-x-contain\", staticUtility([[\"overscroll-behavior-x\", \"contain\"]]));\n utilities.static(\"overscroll-x-none\", staticUtility([[\"overscroll-behavior-x\", \"none\"]]));\n\n // Box Sizing\n\n utilities.static(\"box-border\", staticUtility([[\"box-sizing\", \"border-box\"]]));\n utilities.static(\"box-content\", staticUtility([[\"box-sizing\", \"content-box\"]]));\n\n // Flexbox\n\n // Flex Direction\n utilities.static(\"flex-row\", staticUtility([[\"flex-direction\", \"row\"]]));\n utilities.static(\"flex-row-reverse\", staticUtility([[\"flex-direction\", \"row-reverse\"]]));\n utilities.static(\"flex-col\", staticUtility([[\"flex-direction\", \"column\"]]));\n utilities.static(\"flex-col-reverse\", staticUtility([[\"flex-direction\", \"column-reverse\"]]));\n\n // Flex Wrap\n utilities.static(\"flex-wrap\", staticUtility([[\"flex-wrap\", \"wrap\"]]));\n utilities.static(\"flex-wrap-reverse\", staticUtility([[\"flex-wrap\", \"wrap-reverse\"]]));\n utilities.static(\"flex-nowrap\", staticUtility([[\"flex-wrap\", \"nowrap\"]]));\n\n // Flex\n utilities.static(\"flex-auto\", staticUtility([[\"flex\", \"auto\"]]));\n utilities.static(\"flex-initial\", staticUtility([[\"flex\", \"0 auto\"]]));\n utilities.static(\"flex-none\", staticUtility([[\"flex\", \"none\"]]));\n\n utilities.functional(\"flex\", (candidate) => {\n if (!candidate.value || candidate.modifier) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"flex\", candidate.value.value)];\n }\n\n if (candidate.value.fraction) {\n const [lhs, rhs] = candidate.value.fraction.split(\"/\").map(Number);\n if (!Number.isNaN(lhs) && !Number.isNaN(rhs) && rhs !== 0) {\n return [decl(\"flex\", `calc(${candidate.value.fraction} * 100%)`)];\n }\n }\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num) && Number.isInteger(num) && num > 0) {\n return [decl(\"flex\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Flex Grow\n utilities.static(\"grow\", staticUtility([[\"flex-grow\", \"1\"]]));\n utilities.static(\"grow-0\", staticUtility([[\"flex-grow\", \"0\"]]));\n\n utilities.functional(\"grow\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num) && Number.isInteger(num) && num >= 0) {\n return [decl(\"flex-grow\", String(num))];\n }\n } else {\n return [decl(\"flex-grow\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Flex Shrink\n utilities.static(\"shrink\", staticUtility([[\"flex-shrink\", \"1\"]]));\n utilities.static(\"shrink-0\", staticUtility([[\"flex-shrink\", \"0\"]]));\n\n utilities.functional(\"shrink\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num) && Number.isInteger(num) && num >= 0) {\n return [decl(\"flex-shrink\", String(num))];\n }\n } else {\n return [decl(\"flex-shrink\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Flex Basis\n utilities.static(\"basis-auto\", staticUtility([[\"flex-basis\", \"auto\"]]));\n utilities.static(\"basis-full\", staticUtility([[\"flex-basis\", \"100%\"]]));\n\n utilities.functional(\"basis\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n const value = FLEX_BASIS_VALUES[val];\n if (value) return [decl(\"flex-basis\", value)];\n\n // Numeric spacing values\n const spacing = theme.get(`--spacing-${val}`);\n if (spacing) return [decl(\"flex-basis\", spacing)];\n\n // Raw numbers as rem\n const num = Number(val);\n if (!Number.isNaN(num)) {\n return [decl(\"flex-basis\", `${num * 0.25}rem`)];\n }\n } else {\n return [decl(\"flex-basis\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Order\n\n utilities.functional(\"order\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = ORDER_VALUES[candidate.value.value];\n if (value) return [decl(\"order\", value)];\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"order\", String(num))];\n }\n } else {\n return [decl(\"order\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Z-Index\n\n utilities.functional(\"z\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Direct comparison instead of object lookup for single value\n if (candidate.value.value === \"auto\") {\n return [decl(\"z-index\", \"auto\")];\n }\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"z-index\", String(num))];\n }\n } else {\n return [decl(\"z-index\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid\n\n // Grid Auto Flow\n utilities.static(\"grid-flow-row\", staticUtility([[\"grid-auto-flow\", \"row\"]]));\n utilities.static(\"grid-flow-col\", staticUtility([[\"grid-auto-flow\", \"column\"]]));\n utilities.static(\"grid-flow-dense\", staticUtility([[\"grid-auto-flow\", \"dense\"]]));\n utilities.static(\"grid-flow-row-dense\", staticUtility([[\"grid-auto-flow\", \"row dense\"]]));\n utilities.static(\"grid-flow-col-dense\", staticUtility([[\"grid-auto-flow\", \"column dense\"]]));\n\n // Justify Content\n\n utilities.static(\"justify-normal\", staticUtility([[\"justify-content\", \"normal\"]]));\n utilities.static(\"justify-start\", staticUtility([[\"justify-content\", \"flex-start\"]]));\n utilities.static(\"justify-end\", staticUtility([[\"justify-content\", \"flex-end\"]]));\n utilities.static(\"justify-center\", staticUtility([[\"justify-content\", \"center\"]]));\n utilities.static(\"justify-between\", staticUtility([[\"justify-content\", \"space-between\"]]));\n utilities.static(\"justify-around\", staticUtility([[\"justify-content\", \"space-around\"]]));\n utilities.static(\"justify-evenly\", staticUtility([[\"justify-content\", \"space-evenly\"]]));\n utilities.static(\"justify-stretch\", staticUtility([[\"justify-content\", \"stretch\"]]));\n utilities.static(\"justify-baseline\", staticUtility([[\"justify-content\", \"baseline\"]]));\n\n // Safe alignment values (prevent content overflow)\n utilities.static(\"justify-center-safe\", staticUtility([[\"justify-content\", \"safe center\"]]));\n utilities.static(\"justify-end-safe\", staticUtility([[\"justify-content\", \"safe flex-end\"]]));\n\n // Justify Items\n\n utilities.static(\"justify-items-start\", staticUtility([[\"justify-items\", \"start\"]]));\n utilities.static(\"justify-items-end\", staticUtility([[\"justify-items\", \"end\"]]));\n utilities.static(\"justify-items-center\", staticUtility([[\"justify-items\", \"center\"]]));\n utilities.static(\"justify-items-stretch\", staticUtility([[\"justify-items\", \"stretch\"]]));\n utilities.static(\"justify-items-normal\", staticUtility([[\"justify-items\", \"normal\"]]));\n\n // Safe alignment values\n utilities.static(\"justify-items-center-safe\", staticUtility([[\"justify-items\", \"safe center\"]]));\n utilities.static(\"justify-items-end-safe\", staticUtility([[\"justify-items\", \"safe end\"]]));\n\n // Justify Self\n\n utilities.static(\"justify-self-auto\", staticUtility([[\"justify-self\", \"auto\"]]));\n utilities.static(\"justify-self-start\", staticUtility([[\"justify-self\", \"start\"]]));\n utilities.static(\"justify-self-end\", staticUtility([[\"justify-self\", \"end\"]]));\n utilities.static(\"justify-self-center\", staticUtility([[\"justify-self\", \"center\"]]));\n utilities.static(\"justify-self-stretch\", staticUtility([[\"justify-self\", \"stretch\"]]));\n\n // Safe alignment values\n utilities.static(\"justify-self-center-safe\", staticUtility([[\"justify-self\", \"safe center\"]]));\n utilities.static(\"justify-self-end-safe\", staticUtility([[\"justify-self\", \"safe end\"]]));\n\n // Align Content\n\n utilities.static(\"content-normal\", staticUtility([[\"align-content\", \"normal\"]]));\n utilities.static(\"content-center\", staticUtility([[\"align-content\", \"center\"]]));\n utilities.static(\"content-start\", staticUtility([[\"align-content\", \"flex-start\"]]));\n utilities.static(\"content-end\", staticUtility([[\"align-content\", \"flex-end\"]]));\n utilities.static(\"content-between\", staticUtility([[\"align-content\", \"space-between\"]]));\n utilities.static(\"content-around\", staticUtility([[\"align-content\", \"space-around\"]]));\n utilities.static(\"content-evenly\", staticUtility([[\"align-content\", \"space-evenly\"]]));\n utilities.static(\"content-baseline\", staticUtility([[\"align-content\", \"baseline\"]]));\n utilities.static(\"content-stretch\", staticUtility([[\"align-content\", \"stretch\"]]));\n\n // Safe alignment values (prevent content overflow)\n utilities.static(\"content-center-safe\", staticUtility([[\"align-content\", \"safe center\"]]));\n utilities.static(\"content-end-safe\", staticUtility([[\"align-content\", \"safe flex-end\"]]));\n\n // Align Items\n\n utilities.static(\"items-start\", staticUtility([[\"align-items\", \"flex-start\"]]));\n utilities.static(\"items-end\", staticUtility([[\"align-items\", \"flex-end\"]]));\n utilities.static(\"items-center\", staticUtility([[\"align-items\", \"center\"]]));\n utilities.static(\"items-baseline\", staticUtility([[\"align-items\", \"baseline\"]]));\n utilities.static(\"items-baseline-last\", staticUtility([[\"align-items\", \"last baseline\"]]));\n utilities.static(\"items-stretch\", staticUtility([[\"align-items\", \"stretch\"]]));\n\n // Safe alignment values (prevent content overflow)\n utilities.static(\"items-center-safe\", staticUtility([[\"align-items\", \"safe center\"]]));\n utilities.static(\"items-end-safe\", staticUtility([[\"align-items\", \"safe flex-end\"]]));\n\n // Align Self\n\n utilities.static(\"self-auto\", staticUtility([[\"align-self\", \"auto\"]]));\n utilities.static(\"self-start\", staticUtility([[\"align-self\", \"flex-start\"]]));\n utilities.static(\"self-end\", staticUtility([[\"align-self\", \"flex-end\"]]));\n utilities.static(\"self-center\", staticUtility([[\"align-self\", \"center\"]]));\n utilities.static(\"self-stretch\", staticUtility([[\"align-self\", \"stretch\"]]));\n utilities.static(\"self-baseline\", staticUtility([[\"align-self\", \"baseline\"]]));\n utilities.static(\"self-baseline-last\", staticUtility([[\"align-self\", \"last baseline\"]]));\n\n // Safe alignment values (prevent content overflow)\n utilities.static(\"self-center-safe\", staticUtility([[\"align-self\", \"safe center\"]]));\n utilities.static(\"self-end-safe\", staticUtility([[\"align-self\", \"safe flex-end\"]]));\n\n // Place Content\n\n utilities.static(\"place-content-center\", staticUtility([[\"place-content\", \"center\"]]));\n utilities.static(\"place-content-start\", staticUtility([[\"place-content\", \"start\"]]));\n utilities.static(\"place-content-end\", staticUtility([[\"place-content\", \"end\"]]));\n utilities.static(\"place-content-between\", staticUtility([[\"place-content\", \"space-between\"]]));\n utilities.static(\"place-content-around\", staticUtility([[\"place-content\", \"space-around\"]]));\n utilities.static(\"place-content-evenly\", staticUtility([[\"place-content\", \"space-evenly\"]]));\n utilities.static(\"place-content-baseline\", staticUtility([[\"place-content\", \"baseline\"]]));\n utilities.static(\"place-content-stretch\", staticUtility([[\"place-content\", \"stretch\"]]));\n\n // Safe alignment values\n utilities.static(\"place-content-center-safe\", staticUtility([[\"place-content\", \"safe center\"]]));\n utilities.static(\"place-content-end-safe\", staticUtility([[\"place-content\", \"safe end\"]]));\n\n // Place Items\n\n utilities.static(\"place-items-start\", staticUtility([[\"place-items\", \"start\"]]));\n utilities.static(\"place-items-end\", staticUtility([[\"place-items\", \"end\"]]));\n utilities.static(\"place-items-center\", staticUtility([[\"place-items\", \"center\"]]));\n utilities.static(\"place-items-baseline\", staticUtility([[\"place-items\", \"baseline\"]]));\n utilities.static(\"place-items-stretch\", staticUtility([[\"place-items\", \"stretch\"]]));\n\n // Safe alignment values\n utilities.static(\"place-items-center-safe\", staticUtility([[\"place-items\", \"safe center\"]]));\n utilities.static(\"place-items-end-safe\", staticUtility([[\"place-items\", \"safe end\"]]));\n\n // Place Self\n\n utilities.static(\"place-self-auto\", staticUtility([[\"place-self\", \"auto\"]]));\n utilities.static(\"place-self-start\", staticUtility([[\"place-self\", \"start\"]]));\n utilities.static(\"place-self-end\", staticUtility([[\"place-self\", \"end\"]]));\n utilities.static(\"place-self-center\", staticUtility([[\"place-self\", \"center\"]]));\n utilities.static(\"place-self-stretch\", staticUtility([[\"place-self\", \"stretch\"]]));\n\n // Safe alignment values\n utilities.static(\"place-self-center-safe\", staticUtility([[\"place-self\", \"safe center\"]]));\n utilities.static(\"place-self-end-safe\", staticUtility([[\"place-self\", \"safe end\"]]));\n\n // Field Sizing\n\n utilities.static(\"field-sizing-content\", staticUtility([[\"field-sizing\", \"content\"]]));\n utilities.static(\"field-sizing-fixed\", staticUtility([[\"field-sizing\", \"fixed\"]]));\n\n // CSS Containment (with compound property support)\n\n // Compound containment value using CSS custom properties\n // This allows combining multiple contain values: contain-size contain-layout\n const containValue =\n \"var(--ri-contain-size,) var(--ri-contain-layout,) var(--ri-contain-paint,) var(--ri-contain-style,)\";\n\n utilities.static(\n \"contain-none\",\n staticUtility([\n [\"--ri-contain-size\", \"initial\"],\n [\"--ri-contain-layout\", \"initial\"],\n [\"--ri-contain-paint\", \"initial\"],\n [\"--ri-contain-style\", \"initial\"],\n [\"contain\", \"none\"],\n ])\n );\n\n utilities.static(\n \"contain-content\",\n staticUtility([\n [\"--ri-contain-size\", \"initial\"],\n [\"--ri-contain-layout\", \"initial\"],\n [\"--ri-contain-paint\", \"initial\"],\n [\"--ri-contain-style\", \"initial\"],\n [\"contain\", \"content\"],\n ])\n );\n\n utilities.static(\n \"contain-strict\",\n staticUtility([\n [\"--ri-contain-size\", \"initial\"],\n [\"--ri-contain-layout\", \"initial\"],\n [\"--ri-contain-paint\", \"initial\"],\n [\"--ri-contain-style\", \"initial\"],\n [\"contain\", \"strict\"],\n ])\n );\n\n utilities.static(\n \"contain-size\",\n staticUtility([\n [\"--ri-contain-size\", \"size\"],\n [\"contain\", containValue],\n ])\n );\n\n utilities.static(\n \"contain-inline-size\",\n staticUtility([\n [\"--ri-contain-size\", \"inline-size\"],\n [\"contain\", containValue],\n ])\n );\n\n utilities.static(\n \"contain-layout\",\n staticUtility([\n [\"--ri-contain-layout\", \"layout\"],\n [\"contain\", containValue],\n ])\n );\n\n utilities.static(\n \"contain-style\",\n staticUtility([\n [\"--ri-contain-style\", \"style\"],\n [\"contain\", containValue],\n ])\n );\n\n utilities.static(\n \"contain-paint\",\n staticUtility([\n [\"--ri-contain-paint\", \"paint\"],\n [\"contain\", containValue],\n ])\n );\n\n utilities.functional(\"contain\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"contain\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Content Visibility\n\n utilities.static(\"content-visibility-auto\", staticUtility([[\"content-visibility\", \"auto\"]]));\n utilities.static(\"content-visibility-hidden\", staticUtility([[\"content-visibility\", \"hidden\"]]));\n utilities.static(\"content-visibility-visible\", staticUtility([[\"content-visibility\", \"visible\"]]));\n\n // Scrollbar Gutter\n\n utilities.static(\"scrollbar-gutter-auto\", staticUtility([[\"scrollbar-gutter\", \"auto\"]]));\n utilities.static(\"scrollbar-gutter-stable\", staticUtility([[\"scrollbar-gutter\", \"stable\"]]));\n utilities.static(\"scrollbar-gutter-stable-both\", staticUtility([[\"scrollbar-gutter\", \"stable both-edges\"]]));\n\n // Box Decoration Break\n\n const boxDecorationSlice = staticUtility([\n [\"-webkit-box-decoration-break\", \"slice\"],\n [\"box-decoration-break\", \"slice\"],\n ]);\n const boxDecorationClone = staticUtility([\n [\"-webkit-box-decoration-break\", \"clone\"],\n [\"box-decoration-break\", \"clone\"],\n ]);\n\n utilities.static(\"box-decoration-slice\", boxDecorationSlice);\n utilities.static(\"box-decoration-clone\", boxDecorationClone);\n\n // Columns\n\n utilities.functional(\"columns\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = COLUMN_WIDTH_VALUES[candidate.value.value];\n if (value) return [decl(\"columns\", value)];\n\n // Numeric column count\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"columns\", String(num))];\n }\n } else {\n return [decl(\"columns\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Container\n\n utilities.static(\"container\", (_candidate, theme) => {\n // Get all breakpoints from theme\n const breakpoints = Array.from(theme.namespace(\"--breakpoint\").entries());\n\n // Sort breakpoints by value (ascending)\n breakpoints.sort((a, b) => {\n const cmp = compareBreakpoints(a[1], b[1]);\n if (cmp === null) {\n return a[1].localeCompare(b[1]);\n }\n return cmp;\n });\n\n // Start with width: 100%\n const nodes: AstNode[] = [decl(\"width\", \"100%\")];\n\n // Add media queries for each breakpoint\n for (const [, value] of breakpoints) {\n nodes.push(atRule(\"media\", `(min-width: ${value})`, [decl(\"max-width\", value)]));\n }\n\n return nodes;\n });\n\n // Break Before (Page/Column/Region breaks)\n\n utilities.static(\"break-before-auto\", staticUtility([[\"break-before\", \"auto\"]]));\n utilities.static(\"break-before-avoid\", staticUtility([[\"break-before\", \"avoid\"]]));\n utilities.static(\"break-before-all\", staticUtility([[\"break-before\", \"all\"]]));\n utilities.static(\"break-before-avoid-page\", staticUtility([[\"break-before\", \"avoid-page\"]]));\n utilities.static(\"break-before-page\", staticUtility([[\"break-before\", \"page\"]]));\n utilities.static(\"break-before-left\", staticUtility([[\"break-before\", \"left\"]]));\n utilities.static(\"break-before-right\", staticUtility([[\"break-before\", \"right\"]]));\n utilities.static(\"break-before-column\", staticUtility([[\"break-before\", \"column\"]]));\n\n // Break Inside\n\n utilities.static(\"break-inside-auto\", staticUtility([[\"break-inside\", \"auto\"]]));\n utilities.static(\"break-inside-avoid\", staticUtility([[\"break-inside\", \"avoid\"]]));\n utilities.static(\"break-inside-avoid-page\", staticUtility([[\"break-inside\", \"avoid-page\"]]));\n utilities.static(\"break-inside-avoid-column\", staticUtility([[\"break-inside\", \"avoid-column\"]]));\n\n // Break After\n\n utilities.static(\"break-after-auto\", staticUtility([[\"break-after\", \"auto\"]]));\n utilities.static(\"break-after-avoid\", staticUtility([[\"break-after\", \"avoid\"]]));\n utilities.static(\"break-after-all\", staticUtility([[\"break-after\", \"all\"]]));\n utilities.static(\"break-after-avoid-page\", staticUtility([[\"break-after\", \"avoid-page\"]]));\n utilities.static(\"break-after-page\", staticUtility([[\"break-after\", \"page\"]]));\n utilities.static(\"break-after-left\", staticUtility([[\"break-after\", \"left\"]]));\n utilities.static(\"break-after-right\", staticUtility([[\"break-after\", \"right\"]]));\n utilities.static(\"break-after-column\", staticUtility([[\"break-after\", \"column\"]]));\n\n // Container Queries\n\n utilities.static(\"@container\", staticUtility([[\"container-type\", \"inline-size\"]]));\n utilities.static(\"@container-normal\", staticUtility([[\"container-type\", \"normal\"]]));\n utilities.static(\"@container-size\", staticUtility([[\"container-type\", \"size\"]]));\n\n utilities.functional(\"@container\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // @container/name sets both type and name\n return [decl(\"container-type\", \"inline-size\"), decl(\"container-name\", candidate.value.value)];\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n // @container-[name] sets container-name\n return [decl(\"container-type\", \"inline-size\"), decl(\"container-name\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Container name only (without setting container-type)\n utilities.functional(\"@container-name\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n return [decl(\"container-name\", candidate.value.value)];\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"container-name\", candidate.value.value)];\n }\n\n return null;\n });\n\n // CSS Anchor Positioning\n\n // anchor-name: Names an element as an anchor\n utilities.functional(\"anchor-name\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Convert dashed-ident format\n const name = candidate.value.value.startsWith(\"--\") ? candidate.value.value : `--${candidate.value.value}`;\n return [decl(\"anchor-name\", name)];\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"anchor-name\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"anchor-name-none\", staticUtility([[\"anchor-name\", \"none\"]]));\n\n // position-anchor: Associates an element with its anchor\n utilities.functional(\"position-anchor\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Convert dashed-ident format\n const name = candidate.value.value.startsWith(\"--\") ? candidate.value.value : `--${candidate.value.value}`;\n return [decl(\"position-anchor\", name)];\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"position-anchor\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"position-anchor-auto\", staticUtility([[\"position-anchor\", \"auto\"]]));\n\n // anchor-scope: Scopes anchor names to a subtree\n utilities.functional(\"anchor-scope\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const name = candidate.value.value.startsWith(\"--\") ? candidate.value.value : `--${candidate.value.value}`;\n return [decl(\"anchor-scope\", name)];\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"anchor-scope\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"anchor-scope-none\", staticUtility([[\"anchor-scope\", \"none\"]]));\n utilities.static(\"anchor-scope-all\", staticUtility([[\"anchor-scope\", \"all\"]]));\n\n // inset-area: Positions element in relation to its anchor\n const insetAreaPositions: Record<string, string> = {\n // Single keywords\n top: \"top\",\n bottom: \"bottom\",\n left: \"left\",\n right: \"right\",\n start: \"start\",\n end: \"end\",\n center: \"center\",\n // Two-keyword combinations\n \"top-left\": \"top left\",\n \"top-center\": \"top center\",\n \"top-right\": \"top right\",\n \"bottom-left\": \"bottom left\",\n \"bottom-center\": \"bottom center\",\n \"bottom-right\": \"bottom right\",\n \"left-center\": \"left center\",\n \"right-center\": \"right center\",\n // Span values\n \"span-top\": \"span-top\",\n \"span-bottom\": \"span-bottom\",\n \"span-left\": \"span-left\",\n \"span-right\": \"span-right\",\n \"span-all\": \"span-all\",\n \"span-start\": \"span-start\",\n \"span-end\": \"span-end\",\n };\n\n utilities.functional(\"inset-area\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = insetAreaPositions[candidate.value.value];\n if (value) return [decl(\"inset-area\", value)];\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"inset-area\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"inset-area-none\", staticUtility([[\"inset-area\", \"none\"]]));\n\n // position-visibility: Visibility based on anchor visibility\n utilities.static(\"position-visibility-always\", staticUtility([[\"position-visibility\", \"always\"]]));\n utilities.static(\n \"position-visibility-anchors-visible\",\n staticUtility([[\"position-visibility\", \"anchors-visible\"]])\n );\n utilities.static(\"position-visibility-no-overflow\", staticUtility([[\"position-visibility\", \"no-overflow\"]]));\n\n // position-try-fallbacks: Fallback positions for anchored elements\n utilities.functional(\"position-try\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = POSITION_TRY_VALUES[candidate.value.value];\n if (value) return [decl(\"position-try-fallbacks\", value)];\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"position-try-fallbacks\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"position-try-none\", staticUtility([[\"position-try-fallbacks\", \"none\"]]));\n\n // View Transitions\n\n // view-transition-name: Names an element for view transitions\n utilities.functional(\"view-transition-name\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n return [decl(\"view-transition-name\", candidate.value.value)];\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"view-transition-name\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"view-transition-name-none\", staticUtility([[\"view-transition-name\", \"none\"]]));\n\n // view-transition-class: Classes for view transitions\n utilities.functional(\"view-transition-class\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n return [decl(\"view-transition-class\", candidate.value.value)];\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"view-transition-class\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"view-transition-class-none\", staticUtility([[\"view-transition-class\", \"none\"]]));\n}\n","/**\n * Spacing Utilities\n *\n * Margin, padding, and gap utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport type { FunctionalCandidate } from \"../candidate\";\nimport { resolveSpacing, type Utilities } from \"./utilities\";\n\nfunction createSpacingUtility(property: string) {\n return function (candidate: FunctionalCandidate, theme: Theme) {\n if (!candidate.value) return null;\n const value =\n candidate.value.kind === \"arbitrary\" ? candidate.value.value : resolveSpacing(candidate.value.value, theme);\n if (!value) return null;\n return [decl(property, value)];\n };\n}\n\nexport function registerSpacingUtilities(utilities: Utilities, _theme: Theme): void {\n // Padding utilities\n utilities.functional(\"p\", createSpacingUtility(\"padding\"));\n utilities.functional(\"px\", createSpacingUtility(\"padding-inline\"));\n utilities.functional(\"py\", createSpacingUtility(\"padding-block\"));\n utilities.functional(\"ps\", createSpacingUtility(\"padding-inline-start\"));\n utilities.functional(\"pe\", createSpacingUtility(\"padding-inline-end\"));\n utilities.functional(\"pbs\", createSpacingUtility(\"padding-block-start\"));\n utilities.functional(\"pbe\", createSpacingUtility(\"padding-block-end\"));\n utilities.functional(\"pt\", createSpacingUtility(\"padding-top\"));\n utilities.functional(\"pr\", createSpacingUtility(\"padding-right\"));\n utilities.functional(\"pb\", createSpacingUtility(\"padding-bottom\"));\n utilities.functional(\"pl\", createSpacingUtility(\"padding-left\"));\n\n // Margin utilities\n utilities.functional(\"m\", createSpacingUtility(\"margin\"));\n utilities.functional(\"mx\", createSpacingUtility(\"margin-inline\"));\n utilities.functional(\"my\", createSpacingUtility(\"margin-block\"));\n utilities.functional(\"ms\", createSpacingUtility(\"margin-inline-start\"));\n utilities.functional(\"me\", createSpacingUtility(\"margin-inline-end\"));\n utilities.functional(\"mbs\", createSpacingUtility(\"margin-block-start\"));\n utilities.functional(\"mbe\", createSpacingUtility(\"margin-block-end\"));\n utilities.functional(\"mt\", createSpacingUtility(\"margin-top\"));\n utilities.functional(\"mr\", createSpacingUtility(\"margin-right\"));\n utilities.functional(\"mb\", createSpacingUtility(\"margin-bottom\"));\n utilities.functional(\"ml\", createSpacingUtility(\"margin-left\"));\n\n // Gap utilities\n utilities.functional(\"gap\", createSpacingUtility(\"gap\"));\n utilities.functional(\"gap-x\", createSpacingUtility(\"column-gap\"));\n utilities.functional(\"gap-y\", createSpacingUtility(\"row-gap\"));\n\n // Inset utilities\n utilities.functional(\"inset\", createSpacingUtility(\"inset\"));\n utilities.functional(\"inset-x\", createSpacingUtility(\"inset-inline\"));\n utilities.functional(\"inset-y\", createSpacingUtility(\"inset-block\"));\n utilities.functional(\"inset-s\", createSpacingUtility(\"inset-inline-start\"));\n utilities.functional(\"inset-e\", createSpacingUtility(\"inset-inline-end\"));\n utilities.functional(\"inset-bs\", createSpacingUtility(\"inset-block-start\"));\n utilities.functional(\"inset-be\", createSpacingUtility(\"inset-block-end\"));\n utilities.functional(\"start\", createSpacingUtility(\"inset-inline-start\"));\n utilities.functional(\"end\", createSpacingUtility(\"inset-inline-end\"));\n utilities.functional(\"top\", createSpacingUtility(\"top\"));\n utilities.functional(\"right\", createSpacingUtility(\"right\"));\n utilities.functional(\"bottom\", createSpacingUtility(\"bottom\"));\n utilities.functional(\"left\", createSpacingUtility(\"left\"));\n\n // ============================================\n // Space Between (applies to children via CSS variable)\n // ============================================\n\n utilities.functional(\"space-x\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let value: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n value = candidate.value.value;\n } else if (candidate.value.value === \"reverse\") {\n return [decl(\"--ri-space-x-reverse\", \"1\")];\n } else {\n value = resolveSpacing(candidate.value.value, theme);\n }\n\n if (!value) return null;\n\n return [\n decl(\"--ri-space-x-reverse\", \"0\"),\n decl(\"margin-inline-end\", `calc(${value} * var(--ri-space-x-reverse))`),\n decl(\"margin-inline-start\", `calc(${value} * calc(1 - var(--ri-space-x-reverse)))`),\n ];\n });\n\n utilities.functional(\"space-y\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let value: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n value = candidate.value.value;\n } else if (candidate.value.value === \"reverse\") {\n return [decl(\"--ri-space-y-reverse\", \"1\")];\n } else {\n value = resolveSpacing(candidate.value.value, theme);\n }\n\n if (!value) return null;\n\n return [\n decl(\"--ri-space-y-reverse\", \"0\"),\n decl(\"margin-block-end\", `calc(${value} * var(--ri-space-y-reverse))`),\n decl(\"margin-block-start\", `calc(${value} * calc(1 - var(--ri-space-y-reverse)))`),\n ];\n });\n}\n","/**\n * Sizing Utilities\n *\n * Width, height, min/max sizing utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { FunctionalCandidate } from \"../candidate\";\nimport type { Theme } from \"../theme\";\nimport { resolveSpacing, staticUtility, type Utilities } from \"./utilities\";\n\n// Pre-defined aspect ratio values (hoisted to avoid recreating on every call)\nconst ASPECT_RATIO_VALUES: Record<string, string> = {\n auto: \"auto\",\n square: \"1 / 1\",\n video: \"16 / 9\",\n};\n\nexport function registerSizingUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Shared Helpers\n // ============================================\n\n function resolveSizeValue(\n raw: string,\n theme: Theme,\n namedValues: Record<string, string>,\n options?: { allowContainer?: boolean }\n ): string | null {\n const named = namedValues[raw];\n if (named) return named;\n\n if (options?.allowContainer) {\n const containerValue = theme.get(`--container-${raw}`);\n if (containerValue) return containerValue;\n }\n\n const num = Number(raw);\n if (!Number.isNaN(num)) {\n const spacing = theme.get(\"--spacing\");\n if (spacing) {\n if (num === 0) return \"0px\";\n return `calc(${num} * ${spacing})`;\n }\n return `${num * 0.25}rem`;\n }\n\n if (raw.includes(\"/\")) {\n const parts = raw.split(\"/\").map(Number);\n const numPart = parts[0];\n const denomPart = parts[1];\n if (\n numPart !== undefined &&\n denomPart !== undefined &&\n !Number.isNaN(numPart) &&\n !Number.isNaN(denomPart) &&\n denomPart !== 0\n ) {\n return `${(numPart / denomPart) * 100}%`;\n }\n }\n\n const spacingValue = theme.get(`--spacing-${raw}`);\n if (spacingValue) return spacingValue;\n\n return null;\n }\n\n function createSizeUtility(\n property: string,\n namedValues: Record<string, string>,\n options?: { allowContainer?: boolean }\n ) {\n return (candidate: FunctionalCandidate, theme: Theme) => {\n if (!candidate.value) return null;\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(property, candidate.value.value)];\n }\n const value = resolveSizeValue(candidate.value.value, theme, namedValues, options);\n return value ? [decl(property, value)] : null;\n };\n }\n\n // ============================================\n // Named Value Maps\n // ============================================\n\n // Shared container query units\n const containerQueryUnits: Record<string, string> = {\n cqw: \"100cqw\",\n cqh: \"100cqh\",\n cqmin: \"100cqmin\",\n cqmax: \"100cqmax\",\n cqi: \"100cqi\",\n cqb: \"100cqb\",\n };\n\n // Base values shared across all sizing utilities\n const baseNamed: Record<string, string> = {\n auto: \"auto\",\n full: \"100%\",\n min: \"min-content\",\n max: \"max-content\",\n fit: \"fit-content\",\n ...containerQueryUnits,\n };\n\n // Width/inline named values (viewport width units)\n const widthNamed: Record<string, string> = {\n ...baseNamed,\n screen: \"100vw\",\n svw: \"100svw\",\n lvw: \"100lvw\",\n dvw: \"100dvw\",\n svh: \"100svh\",\n lvh: \"100lvh\",\n dvh: \"100dvh\",\n };\n\n // Height/block named values (viewport height units + lh)\n const heightNamed: Record<string, string> = {\n ...baseNamed,\n screen: \"100vh\",\n svh: \"100svh\",\n lvh: \"100lvh\",\n dvh: \"100dvh\",\n svw: \"100svw\",\n lvw: \"100lvw\",\n dvw: \"100dvw\",\n lh: \"1lh\",\n };\n\n // Max-width specific named values (container sizes)\n const maxWidthNamed: Record<string, string> = {\n ...widthNamed,\n none: \"none\",\n xs: \"20rem\",\n sm: \"24rem\",\n md: \"28rem\",\n lg: \"32rem\",\n xl: \"36rem\",\n \"2xl\": \"42rem\",\n \"3xl\": \"48rem\",\n \"4xl\": \"56rem\",\n \"5xl\": \"64rem\",\n \"6xl\": \"72rem\",\n \"7xl\": \"80rem\",\n prose: \"65ch\",\n \"screen-sm\": \"640px\",\n \"screen-md\": \"768px\",\n \"screen-lg\": \"1024px\",\n \"screen-xl\": \"1280px\",\n \"screen-2xl\": \"1536px\",\n };\n\n // Max variants add \"none\"\n const maxHeightNamed: Record<string, string> = { ...heightNamed, none: \"none\" };\n\n // ============================================\n // Width Utilities\n // ============================================\n\n utilities.functional(\"w\", createSizeUtility(\"width\", widthNamed));\n utilities.functional(\"min-w\", createSizeUtility(\"min-width\", widthNamed));\n utilities.functional(\"max-w\", createSizeUtility(\"max-width\", maxWidthNamed));\n\n // ============================================\n // Inline/Block Size (logical sizing)\n // ============================================\n\n utilities.functional(\"inline\", createSizeUtility(\"inline-size\", widthNamed, { allowContainer: true }));\n utilities.functional(\"min-inline\", createSizeUtility(\"min-inline-size\", widthNamed, { allowContainer: true }));\n utilities.functional(\n \"max-inline\",\n createSizeUtility(\"max-inline-size\", { ...widthNamed, none: \"none\" }, { allowContainer: true })\n );\n utilities.functional(\"block\", createSizeUtility(\"block-size\", heightNamed));\n utilities.functional(\"min-block\", createSizeUtility(\"min-block-size\", heightNamed));\n utilities.functional(\"max-block\", createSizeUtility(\"max-block-size\", maxHeightNamed));\n\n // ============================================\n // Height Utilities\n // ============================================\n\n utilities.functional(\"h\", createSizeUtility(\"height\", heightNamed));\n utilities.functional(\"min-h\", createSizeUtility(\"min-height\", heightNamed));\n utilities.functional(\"max-h\", createSizeUtility(\"max-height\", maxHeightNamed));\n\n // ============================================\n // Size (width and height together)\n // ============================================\n\n utilities.static(\n \"size-auto\",\n staticUtility([\n [\"width\", \"auto\"],\n [\"height\", \"auto\"],\n ])\n );\n utilities.static(\n \"size-full\",\n staticUtility([\n [\"width\", \"100%\"],\n [\"height\", \"100%\"],\n ])\n );\n utilities.static(\n \"size-screen\",\n staticUtility([\n [\"width\", \"100vw\"],\n [\"height\", \"100vh\"],\n ])\n );\n utilities.static(\n \"size-svw\",\n staticUtility([\n [\"width\", \"100svw\"],\n [\"height\", \"100svh\"],\n ])\n );\n utilities.static(\n \"size-lvw\",\n staticUtility([\n [\"width\", \"100lvw\"],\n [\"height\", \"100lvh\"],\n ])\n );\n utilities.static(\n \"size-dvw\",\n staticUtility([\n [\"width\", \"100dvw\"],\n [\"height\", \"100dvh\"],\n ])\n );\n utilities.static(\n \"size-min\",\n staticUtility([\n [\"width\", \"min-content\"],\n [\"height\", \"min-content\"],\n ])\n );\n utilities.static(\n \"size-max\",\n staticUtility([\n [\"width\", \"max-content\"],\n [\"height\", \"max-content\"],\n ])\n );\n utilities.static(\n \"size-fit\",\n staticUtility([\n [\"width\", \"fit-content\"],\n [\"height\", \"fit-content\"],\n ])\n );\n\n utilities.functional(\"size\", (candidate, theme) => {\n if (!candidate.value) return null;\n const value =\n candidate.value.kind === \"arbitrary\" ? candidate.value.value : resolveSpacing(candidate.value.value, theme);\n if (!value) return null;\n return [decl(\"width\", value), decl(\"height\", value)];\n });\n\n // ============================================\n // Aspect Ratio\n // ============================================\n\n utilities.functional(\"aspect\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = ASPECT_RATIO_VALUES[candidate.value.value];\n if (value) return [decl(\"aspect-ratio\", value)];\n\n // Handle fraction notation: aspect-4/3, aspect-16/9\n if (candidate.value.value.includes(\"/\")) {\n const [w, h] = candidate.value.value.split(\"/\");\n if (w && h) {\n return [decl(\"aspect-ratio\", `${w} / ${h}`)];\n }\n }\n } else {\n return [decl(\"aspect-ratio\", candidate.value.value)];\n }\n\n return null;\n });\n}\n","/**\n * Color Utilities\n *\n * Background, text, border, and other color utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme, ThemeKey } from \"../theme\";\nimport { resolveThemeColor, withOpacity, type Utilities } from \"./utilities\";\nimport { inferDataType } from \"../utils/infer-data-type\";\n\n// Pre-defined value maps (hoisted to avoid recreating on every call)\nconst BORDER_WIDTH_VALUES: Record<string, string> = {\n \"0\": \"0px\",\n \"2\": \"2px\",\n \"4\": \"4px\",\n \"8\": \"8px\",\n};\n\nconst OUTLINE_STYLE_VALUES: Record<string, string> = {\n none: \"none\",\n dashed: \"dashed\",\n dotted: \"dotted\",\n double: \"double\",\n};\n\nconst RING_WIDTH_VALUES: Record<string, string> = {\n \"0\": \"0px\",\n \"1\": \"1px\",\n \"2\": \"2px\",\n \"4\": \"4px\",\n \"8\": \"8px\",\n};\n\nexport function registerColorUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Background Color\n // ============================================\n\n utilities.functional(\"bg\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else {\n color = resolveThemeColor(candidate, theme, [\"--background-color\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n color = withOpacity(color, candidate.modifier);\n return [decl(\"background-color\", color)];\n });\n\n // ============================================\n // Text Color\n // ============================================\n\n utilities.functional(\"text\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Check if it's a text size utility\n if (candidate.value.kind === \"named\") {\n const sizeValue = theme.get(`--text-${candidate.value.value}`);\n if (sizeValue) {\n // Support line-height modifier: text-lg/8, text-xl/tight, text-base/[1.5]\n let lineHeight: string | null = null;\n\n if (candidate.modifier) {\n if (candidate.modifier.kind === \"arbitrary\") {\n // text-lg/[1.5] - arbitrary line-height\n lineHeight = candidate.modifier.value;\n } else if (candidate.modifier.kind === \"named\") {\n // text-lg/tight - named line-height from theme\n const namedLineHeight = theme.get(`--leading-${candidate.modifier.value}`);\n if (namedLineHeight) {\n lineHeight = namedLineHeight;\n } else if (candidate.modifier.value === \"none\") {\n // text-lg/none - unitless 1\n lineHeight = \"1\";\n } else {\n // text-lg/8 - numeric spacing multiplier\n const num = Number(candidate.modifier.value);\n if (!Number.isNaN(num)) {\n const spacing = theme.get(\"--spacing\") ?? \"0.25rem\";\n lineHeight = `calc(${num} * ${spacing})`;\n }\n }\n }\n } else {\n // No modifier - use default line-height from theme\n lineHeight = theme.get(`--text-${candidate.value.value}--line-height`);\n }\n\n const result = [decl(\"font-size\", sizeValue)];\n if (lineHeight) {\n result.push(decl(\"line-height\", lineHeight));\n }\n return result;\n }\n }\n\n // Handle arbitrary values with type inference\n if (candidate.value.kind === \"arbitrary\") {\n const dataType = candidate.value.dataType ?? inferDataType(candidate.value.value);\n\n // Length or percentage values are font-size\n if (dataType === \"length\" || dataType === \"percentage\") {\n return [decl(\"font-size\", candidate.value.value)];\n }\n\n // Otherwise treat as color\n const color = withOpacity(candidate.value.value, candidate.modifier);\n return [decl(\"color\", color)];\n }\n\n // Named values - treat as color\n const color = resolveThemeColor(candidate, theme, [\"--text-color\", \"--color\"] as ThemeKey[]);\n if (!color) return null;\n\n return [decl(\"color\", withOpacity(color, candidate.modifier))];\n });\n\n // ============================================\n // Border Color\n // ============================================\n\n utilities.functional(\"border\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Check if it's a border width utility\n if (candidate.value.kind === \"named\") {\n const width = BORDER_WIDTH_VALUES[candidate.value.value];\n if (width) return [decl(\"border-width\", width)];\n }\n\n // Otherwise treat as color\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else {\n color = resolveThemeColor(candidate, theme, [\"--border-color\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n color = withOpacity(color, candidate.modifier);\n return [decl(\"border-color\", color)];\n });\n\n // ============================================\n // Outline Color\n // ============================================\n\n utilities.functional(\"outline\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Check if it's an outline style/width\n if (candidate.value.kind === \"named\") {\n const style = OUTLINE_STYLE_VALUES[candidate.value.value];\n if (style) {\n return [decl(\"outline-style\", style)];\n }\n\n // Numeric width\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"outline-width\", `${num}px`)];\n }\n }\n\n // Otherwise treat as color\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else {\n color = resolveThemeColor(candidate, theme, [\"--outline-color\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n color = withOpacity(color, candidate.modifier);\n return [decl(\"outline-color\", color)];\n });\n\n // ============================================\n // Ring\n // ============================================\n\n utilities.functional(\"ring\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Ring width\n if (candidate.value.kind === \"named\") {\n const width = RING_WIDTH_VALUES[candidate.value.value];\n if (width) {\n return [\n decl(\n \"--ri-ring-offset-shadow\",\n \"var(--ri-ring-inset) 0 0 0 var(--ri-ring-offset-width) var(--ri-ring-offset-color)\"\n ),\n decl(\n \"--ri-ring-shadow\",\n `var(--ri-ring-inset) 0 0 0 calc(${width} + var(--ri-ring-offset-width)) var(--ri-ring-color)`\n ),\n decl(\n \"box-shadow\",\n \"var(--ri-ring-offset-shadow), var(--ri-ring-shadow), var(--ri-shadow, 0 0 #0000)\"\n ),\n ];\n }\n }\n\n // Ring color\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else {\n color = resolveThemeColor(candidate, theme, [\"--ring-color\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n color = withOpacity(color, candidate.modifier);\n return [decl(\"--ri-ring-color\", color)];\n });\n\n // ============================================\n // Divide Color\n // ============================================\n\n utilities.functional(\"divide\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Divide width (handled separately as divide-x, divide-y)\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n if (val === \"x\" || val === \"y\") return null;\n }\n\n // Divide color\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else {\n color = resolveThemeColor(candidate, theme, [\"--divide-color\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n color = withOpacity(color, candidate.modifier);\n return [decl(\"--ri-divide-color\", color)];\n });\n\n // ============================================\n // Accent Color\n // ============================================\n\n utilities.functional(\"accent\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else if (candidate.value.value === \"auto\") {\n color = \"auto\";\n } else {\n color = resolveThemeColor(candidate, theme, [\"--accent-color\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n if (color !== \"auto\") {\n color = withOpacity(color, candidate.modifier);\n }\n return [decl(\"accent-color\", color)];\n });\n\n // ============================================\n // Caret Color\n // ============================================\n\n utilities.functional(\"caret\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else if (candidate.value.value === \"auto\") {\n color = \"auto\";\n } else {\n color = resolveThemeColor(candidate, theme, [\"--caret-color\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n if (color !== \"auto\") {\n color = withOpacity(color, candidate.modifier);\n }\n return [decl(\"caret-color\", color)];\n });\n\n // ============================================\n // Fill (SVG)\n // ============================================\n\n utilities.functional(\"fill\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else if (candidate.value.value === \"none\") {\n color = \"none\";\n } else if (candidate.value.value === \"current\") {\n color = \"currentColor\";\n } else {\n color = resolveThemeColor(candidate, theme, [\"--fill\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n if (color !== \"none\" && color !== \"currentColor\") {\n color = withOpacity(color, candidate.modifier);\n }\n return [decl(\"fill\", color)];\n });\n\n // ============================================\n // Stroke (SVG)\n // ============================================\n\n utilities.functional(\"stroke\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Check for stroke width\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"stroke-width\", String(num))];\n }\n }\n\n // Stroke color\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else if (candidate.value.value === \"none\") {\n color = \"none\";\n } else if (candidate.value.value === \"current\") {\n color = \"currentColor\";\n } else {\n color = resolveThemeColor(candidate, theme, [\"--stroke\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n if (color !== \"none\" && color !== \"currentColor\") {\n color = withOpacity(color, candidate.modifier);\n }\n return [decl(\"stroke\", color)];\n });\n\n // ============================================\n // Placeholder Color\n // ============================================\n\n // Note: This requires a pseudo-element selector, handled in variants\n utilities.functional(\"placeholder\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let color: string | null = null;\n\n if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n } else {\n color = resolveThemeColor(candidate, theme, [\"--placeholder-color\", \"--color\"] as ThemeKey[]);\n }\n\n if (!color) return null;\n\n color = withOpacity(color, candidate.modifier);\n return [decl(\"--ri-placeholder-color\", color)];\n });\n}\n","/**\n * Typography Utilities\n *\n * Font, text, and typography-related utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme, ThemeKey } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\nimport { looksLikeColor } from \"../utils/is-color\";\n\nexport function registerTypographyUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Font Family\n // ============================================\n\n utilities.functional(\"font\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Check for font weight\n const weight = theme.get(`--font-weight-${candidate.value.value}`);\n if (weight) return [decl(\"font-weight\", weight)];\n\n // Check for font family\n const family = theme.resolve(candidate.value.value, [\"--font\"] as ThemeKey[]);\n if (family) return [decl(\"font-family\", family)];\n } else {\n return [decl(\"font-family\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Font Size (text-*)\n // ============================================\n\n // Note: text-* for colors is handled in colors.ts\n // This handles text-sm, text-lg, etc.\n\n // ============================================\n // Font Style\n // ============================================\n\n utilities.static(\"italic\", staticUtility([[\"font-style\", \"italic\"]]));\n utilities.static(\"not-italic\", staticUtility([[\"font-style\", \"normal\"]]));\n\n // ============================================\n // Font Weight\n // ============================================\n\n utilities.static(\"font-thin\", staticUtility([[\"font-weight\", \"100\"]]));\n utilities.static(\"font-extralight\", staticUtility([[\"font-weight\", \"200\"]]));\n utilities.static(\"font-light\", staticUtility([[\"font-weight\", \"300\"]]));\n utilities.static(\"font-normal\", staticUtility([[\"font-weight\", \"400\"]]));\n utilities.static(\"font-medium\", staticUtility([[\"font-weight\", \"500\"]]));\n utilities.static(\"font-semibold\", staticUtility([[\"font-weight\", \"600\"]]));\n utilities.static(\"font-bold\", staticUtility([[\"font-weight\", \"700\"]]));\n utilities.static(\"font-extrabold\", staticUtility([[\"font-weight\", \"800\"]]));\n utilities.static(\"font-black\", staticUtility([[\"font-weight\", \"900\"]]));\n\n // ============================================\n // Letter Spacing\n // ============================================\n\n utilities.functional(\"tracking\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--tracking-${candidate.value.value}`);\n if (value) return [decl(\"letter-spacing\", value)];\n } else {\n return [decl(\"letter-spacing\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Line Height\n // ============================================\n\n utilities.functional(\"leading\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--leading-${candidate.value.value}`);\n if (value) return [decl(\"line-height\", value)];\n\n // Numeric line height\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"line-height\", `${num * 0.25}rem`)];\n }\n } else {\n return [decl(\"line-height\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // List Style Type\n // ============================================\n\n utilities.static(\"list-none\", staticUtility([[\"list-style-type\", \"none\"]]));\n utilities.static(\"list-disc\", staticUtility([[\"list-style-type\", \"disc\"]]));\n utilities.static(\"list-decimal\", staticUtility([[\"list-style-type\", \"decimal\"]]));\n\n utilities.functional(\"list\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--list-style-type-${candidate.value.value}`);\n if (value) return [decl(\"list-style-type\", value)];\n } else {\n return [decl(\"list-style-type\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // List Style Position\n // ============================================\n\n utilities.static(\"list-inside\", staticUtility([[\"list-style-position\", \"inside\"]]));\n utilities.static(\"list-outside\", staticUtility([[\"list-style-position\", \"outside\"]]));\n\n // ============================================\n // List Style Image\n // ============================================\n\n utilities.static(\"list-image-none\", staticUtility([[\"list-style-image\", \"none\"]]));\n\n utilities.functional(\"list-image\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n // Support url() syntax: list-image-[url('/img/bullet.svg')]\n return [decl(\"list-style-image\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Text Alignment\n // ============================================\n\n utilities.static(\"text-left\", staticUtility([[\"text-align\", \"left\"]]));\n utilities.static(\"text-center\", staticUtility([[\"text-align\", \"center\"]]));\n utilities.static(\"text-right\", staticUtility([[\"text-align\", \"right\"]]));\n utilities.static(\"text-justify\", staticUtility([[\"text-align\", \"justify\"]]));\n utilities.static(\"text-start\", staticUtility([[\"text-align\", \"start\"]]));\n utilities.static(\"text-end\", staticUtility([[\"text-align\", \"end\"]]));\n\n // ============================================\n // Text Decoration\n // ============================================\n\n utilities.static(\"underline\", staticUtility([[\"text-decoration-line\", \"underline\"]]));\n utilities.static(\"overline\", staticUtility([[\"text-decoration-line\", \"overline\"]]));\n utilities.static(\"line-through\", staticUtility([[\"text-decoration-line\", \"line-through\"]]));\n utilities.static(\"no-underline\", staticUtility([[\"text-decoration-line\", \"none\"]]));\n\n // ============================================\n // Text Decoration Style\n // ============================================\n\n utilities.static(\"decoration-solid\", staticUtility([[\"text-decoration-style\", \"solid\"]]));\n utilities.static(\"decoration-double\", staticUtility([[\"text-decoration-style\", \"double\"]]));\n utilities.static(\"decoration-dotted\", staticUtility([[\"text-decoration-style\", \"dotted\"]]));\n utilities.static(\"decoration-dashed\", staticUtility([[\"text-decoration-style\", \"dashed\"]]));\n utilities.static(\"decoration-wavy\", staticUtility([[\"text-decoration-style\", \"wavy\"]]));\n\n // ============================================\n // Text Transform\n // ============================================\n\n utilities.static(\"uppercase\", staticUtility([[\"text-transform\", \"uppercase\"]]));\n utilities.static(\"lowercase\", staticUtility([[\"text-transform\", \"lowercase\"]]));\n utilities.static(\"capitalize\", staticUtility([[\"text-transform\", \"capitalize\"]]));\n utilities.static(\"normal-case\", staticUtility([[\"text-transform\", \"none\"]]));\n\n // ============================================\n // Text Overflow\n // ============================================\n\n utilities.static(\n \"truncate\",\n staticUtility([\n [\"overflow\", \"hidden\"],\n [\"text-overflow\", \"ellipsis\"],\n [\"white-space\", \"nowrap\"],\n ])\n );\n utilities.static(\"text-ellipsis\", staticUtility([[\"text-overflow\", \"ellipsis\"]]));\n utilities.static(\"text-clip\", staticUtility([[\"text-overflow\", \"clip\"]]));\n\n // ============================================\n // Text Wrap\n // ============================================\n\n utilities.static(\"text-wrap\", staticUtility([[\"text-wrap\", \"wrap\"]]));\n utilities.static(\"text-nowrap\", staticUtility([[\"text-wrap\", \"nowrap\"]]));\n utilities.static(\"text-balance\", staticUtility([[\"text-wrap\", \"balance\"]]));\n utilities.static(\"text-pretty\", staticUtility([[\"text-wrap\", \"pretty\"]]));\n\n // ============================================\n // Vertical Alignment\n // ============================================\n\n utilities.static(\"align-baseline\", staticUtility([[\"vertical-align\", \"baseline\"]]));\n utilities.static(\"align-top\", staticUtility([[\"vertical-align\", \"top\"]]));\n utilities.static(\"align-middle\", staticUtility([[\"vertical-align\", \"middle\"]]));\n utilities.static(\"align-bottom\", staticUtility([[\"vertical-align\", \"bottom\"]]));\n utilities.static(\"align-text-top\", staticUtility([[\"vertical-align\", \"text-top\"]]));\n utilities.static(\"align-text-bottom\", staticUtility([[\"vertical-align\", \"text-bottom\"]]));\n utilities.static(\"align-sub\", staticUtility([[\"vertical-align\", \"sub\"]]));\n utilities.static(\"align-super\", staticUtility([[\"vertical-align\", \"super\"]]));\n\n utilities.functional(\"align\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"vertical-align\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Whitespace\n // ============================================\n\n utilities.static(\"whitespace-normal\", staticUtility([[\"white-space\", \"normal\"]]));\n utilities.static(\"whitespace-nowrap\", staticUtility([[\"white-space\", \"nowrap\"]]));\n utilities.static(\"whitespace-pre\", staticUtility([[\"white-space\", \"pre\"]]));\n utilities.static(\"whitespace-pre-line\", staticUtility([[\"white-space\", \"pre-line\"]]));\n utilities.static(\"whitespace-pre-wrap\", staticUtility([[\"white-space\", \"pre-wrap\"]]));\n utilities.static(\"whitespace-break-spaces\", staticUtility([[\"white-space\", \"break-spaces\"]]));\n\n // ============================================\n // Word Break\n // ============================================\n\n utilities.static(\n \"break-normal\",\n staticUtility([\n [\"overflow-wrap\", \"normal\"],\n [\"word-break\", \"normal\"],\n ])\n );\n utilities.static(\"break-all\", staticUtility([[\"word-break\", \"break-all\"]]));\n utilities.static(\"break-keep\", staticUtility([[\"word-break\", \"keep-all\"]]));\n\n // ============================================\n // Hyphens\n // ============================================\n\n utilities.static(\"hyphens-none\", staticUtility([[\"hyphens\", \"none\"]]));\n utilities.static(\"hyphens-manual\", staticUtility([[\"hyphens\", \"manual\"]]));\n utilities.static(\"hyphens-auto\", staticUtility([[\"hyphens\", \"auto\"]]));\n\n // ============================================\n // Content (with CSS custom property for theme integration)\n // ============================================\n\n utilities.static(\n \"content-none\",\n staticUtility([\n [\"--ri-content\", \"none\"],\n [\"content\", \"none\"],\n ])\n );\n\n utilities.functional(\"content\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Check for theme content value\n const themeValue = theme.get(`--content-${candidate.value.value}`);\n if (themeValue) {\n return [decl(\"--ri-content\", themeValue), decl(\"content\", \"var(--ri-content)\")];\n }\n }\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"--ri-content\", candidate.value.value), decl(\"content\", \"var(--ri-content)\")];\n }\n\n return null;\n });\n\n // ============================================\n // Line Clamp\n // ============================================\n\n utilities.functional(\"line-clamp\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n if (candidate.value.value === \"none\") {\n return [decl(\"-webkit-line-clamp\", \"unset\"), decl(\"overflow\", \"visible\"), decl(\"display\", \"block\")];\n }\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"overflow\", \"hidden\"),\n decl(\"display\", \"-webkit-box\"),\n decl(\"-webkit-box-orient\", \"vertical\"),\n decl(\"-webkit-line-clamp\", String(num)),\n ];\n }\n } else {\n return [\n decl(\"overflow\", \"hidden\"),\n decl(\"display\", \"-webkit-box\"),\n decl(\"-webkit-box-orient\", \"vertical\"),\n decl(\"-webkit-line-clamp\", candidate.value.value),\n ];\n }\n\n return null;\n });\n\n // ============================================\n // Font Variant Numeric\n // ============================================\n\n utilities.static(\"normal-nums\", staticUtility([[\"font-variant-numeric\", \"normal\"]]));\n utilities.static(\"ordinal\", staticUtility([[\"font-variant-numeric\", \"ordinal\"]]));\n utilities.static(\"slashed-zero\", staticUtility([[\"font-variant-numeric\", \"slashed-zero\"]]));\n utilities.static(\"lining-nums\", staticUtility([[\"font-variant-numeric\", \"lining-nums\"]]));\n utilities.static(\"oldstyle-nums\", staticUtility([[\"font-variant-numeric\", \"oldstyle-nums\"]]));\n utilities.static(\"proportional-nums\", staticUtility([[\"font-variant-numeric\", \"proportional-nums\"]]));\n utilities.static(\"tabular-nums\", staticUtility([[\"font-variant-numeric\", \"tabular-nums\"]]));\n utilities.static(\"diagonal-fractions\", staticUtility([[\"font-variant-numeric\", \"diagonal-fractions\"]]));\n utilities.static(\"stacked-fractions\", staticUtility([[\"font-variant-numeric\", \"stacked-fractions\"]]));\n\n // ============================================\n // Font Stretch\n // ============================================\n\n utilities.static(\"font-stretch-ultra-condensed\", staticUtility([[\"font-stretch\", \"ultra-condensed\"]]));\n utilities.static(\"font-stretch-extra-condensed\", staticUtility([[\"font-stretch\", \"extra-condensed\"]]));\n utilities.static(\"font-stretch-condensed\", staticUtility([[\"font-stretch\", \"condensed\"]]));\n utilities.static(\"font-stretch-semi-condensed\", staticUtility([[\"font-stretch\", \"semi-condensed\"]]));\n utilities.static(\"font-stretch-normal\", staticUtility([[\"font-stretch\", \"normal\"]]));\n utilities.static(\"font-stretch-semi-expanded\", staticUtility([[\"font-stretch\", \"semi-expanded\"]]));\n utilities.static(\"font-stretch-expanded\", staticUtility([[\"font-stretch\", \"expanded\"]]));\n utilities.static(\"font-stretch-extra-expanded\", staticUtility([[\"font-stretch\", \"extra-expanded\"]]));\n utilities.static(\"font-stretch-ultra-expanded\", staticUtility([[\"font-stretch\", \"ultra-expanded\"]]));\n\n utilities.functional(\"font-stretch\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Percentage value\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"font-stretch\", `${num}%`)];\n }\n } else {\n return [decl(\"font-stretch\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Font Feature Settings\n // ============================================\n\n utilities.functional(\"font-features\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n if (candidate.value.value === \"normal\") {\n return [decl(\"font-feature-settings\", \"normal\")];\n }\n } else {\n return [decl(\"font-feature-settings\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Overflow Wrap\n // ============================================\n\n utilities.static(\"wrap-normal\", staticUtility([[\"overflow-wrap\", \"normal\"]]));\n utilities.static(\"wrap-break-word\", staticUtility([[\"overflow-wrap\", \"break-word\"]]));\n utilities.static(\"wrap-anywhere\", staticUtility([[\"overflow-wrap\", \"anywhere\"]]));\n\n // ============================================\n // Text Underline Offset\n // ============================================\n\n utilities.functional(\"underline-offset\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n if (candidate.value.value === \"auto\") {\n return [decl(\"text-underline-offset\", \"auto\")];\n }\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"text-underline-offset\", `${num}px`)];\n }\n } else {\n return [decl(\"text-underline-offset\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Text Decoration Thickness and Color\n // ============================================\n\n utilities.functional(\"decoration\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Thickness values\n if (candidate.value.value === \"auto\") {\n return [decl(\"text-decoration-thickness\", \"auto\")];\n }\n if (candidate.value.value === \"from-font\") {\n return [decl(\"text-decoration-thickness\", \"from-font\")];\n }\n\n // Numeric thickness\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"text-decoration-thickness\", `${num}px`)];\n }\n\n // Special color values\n if (candidate.value.value === \"inherit\") {\n return [decl(\"text-decoration-color\", \"inherit\")];\n }\n if (candidate.value.value === \"current\") {\n return [decl(\"text-decoration-color\", \"currentColor\")];\n }\n if (candidate.value.value === \"transparent\") {\n return [decl(\"text-decoration-color\", \"transparent\")];\n }\n\n // Theme colors (e.g., decoration-red-500)\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) {\n return [decl(\"text-decoration-color\", color)];\n }\n } else {\n // Arbitrary value - detect if it's a color or thickness\n const value = candidate.value.value;\n // Check if it looks like a color\n if (looksLikeColor(value)) {\n return [decl(\"text-decoration-color\", value)];\n }\n // Otherwise treat as thickness\n return [decl(\"text-decoration-thickness\", value)];\n }\n\n return null;\n });\n\n utilities.static(\"decoration-auto\", staticUtility([[\"text-decoration-thickness\", \"auto\"]]));\n utilities.static(\"decoration-from-font\", staticUtility([[\"text-decoration-thickness\", \"from-font\"]]));\n utilities.static(\"decoration-inherit\", staticUtility([[\"text-decoration-color\", \"inherit\"]]));\n utilities.static(\"decoration-current\", staticUtility([[\"text-decoration-color\", \"currentColor\"]]));\n utilities.static(\"decoration-transparent\", staticUtility([[\"text-decoration-color\", \"transparent\"]]));\n\n // ============================================\n // Font Smoothing\n // ============================================\n\n utilities.static(\n \"antialiased\",\n staticUtility([\n [\"-webkit-font-smoothing\", \"antialiased\"],\n [\"-moz-osx-font-smoothing\", \"grayscale\"],\n ])\n );\n\n utilities.static(\n \"subpixel-antialiased\",\n staticUtility([\n [\"-webkit-font-smoothing\", \"auto\"],\n [\"-moz-osx-font-smoothing\", \"auto\"],\n ])\n );\n\n // ============================================\n // Placeholder Color\n // ============================================\n\n utilities.functional(\"placeholder\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) {\n return [decl(\"--ri-placeholder-color\", color)];\n }\n } else {\n return [decl(\"--ri-placeholder-color\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"placeholder-inherit\", staticUtility([[\"--ri-placeholder-color\", \"inherit\"]]));\n utilities.static(\"placeholder-current\", staticUtility([[\"--ri-placeholder-color\", \"currentColor\"]]));\n utilities.static(\"placeholder-transparent\", staticUtility([[\"--ri-placeholder-color\", \"transparent\"]]));\n\n // ============================================\n // Text Indent\n // ============================================\n\n utilities.functional(\"indent\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Check spacing value\n const spacing = theme.get(`--spacing-${candidate.value.value}`);\n if (spacing) return [decl(\"text-indent\", spacing)];\n\n // Numeric values as rem\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"text-indent\", `${num * 0.25}rem`)];\n }\n } else {\n return [decl(\"text-indent\", candidate.value.value)];\n }\n\n return null;\n });\n}\n","/**\n * Border Utilities\n *\n * Border width, color, style, radius, and corner-shape utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport type { FunctionalCandidate } from \"../candidate\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\n// Pre-computed Set for O(1) corner shape lookup (hoisted to avoid recreation on every call)\nconst CORNER_SHAPES = new Set([\"round\", \"squircle\", \"square\", \"bevel\", \"scoop\", \"notch\"]);\n\n// ============================================\n// Helper: Resolve radius value\n// ============================================\n\n/**\n * Resolve a radius value from candidate.\n * Unit-based system: numeric values are multiples of --spacing.\n * Handles: numeric (1, 2, 0.5), special (none, full), arbitrary\n */\nfunction resolveRadius(candidate: FunctionalCandidate, theme: Theme): string | null {\n const spacing = theme.get(\"--spacing\") ?? \"0.25rem\";\n\n if (!candidate.value) {\n return null;\n }\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n // Special values\n if (val === \"none\") return \"0\";\n if (val === \"full\") return \"9999px\";\n\n // Numeric value (unit-based: 1, 2, 0.5, etc.)\n const num = Number(val);\n if (!Number.isNaN(num)) {\n if (num === 0) return \"0\";\n return `calc(${num} * ${spacing})`;\n }\n\n return null;\n }\n\n // Arbitrary value (pass through)\n return candidate.value.value;\n}\n\n/**\n * Resolve radius with squircle scaling.\n * Unit-based system with --ri-squircle-scale multiplier applied.\n */\nfunction resolveSquircleRadius(candidate: FunctionalCandidate, theme: Theme): string | null {\n const spacing = theme.get(\"--spacing\") ?? \"0.25rem\";\n const scale = theme.get(\"--ri-squircle-scale\") ?? \"1.6\";\n\n if (!candidate.value) {\n // Default: 1 unit * scale\n return `calc(${spacing} * ${scale})`;\n }\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n // Special values (no scaling)\n if (val === \"none\") return \"0\";\n if (val === \"full\") return \"9999px\";\n\n // Numeric value with scaling\n const num = Number(val);\n if (!Number.isNaN(num)) {\n if (num === 0) return \"0\";\n return `calc(${num} * ${spacing} * ${scale})`;\n }\n\n return null;\n }\n\n // Arbitrary value (apply scaling)\n return `calc(${candidate.value.value} * ${scale})`;\n}\n\nexport function registerBorderUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Border Radius - All corners\n // ============================================\n\n utilities.functional(\"rounded\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) return [decl(\"border-radius\", value)];\n return null;\n });\n\n // ============================================\n // Border Radius - Physical sides (t, r, b, l)\n // ============================================\n\n utilities.functional(\"rounded-t\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) {\n return [decl(\"border-top-left-radius\", value), decl(\"border-top-right-radius\", value)];\n }\n return null;\n });\n\n utilities.functional(\"rounded-r\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) {\n return [decl(\"border-top-right-radius\", value), decl(\"border-bottom-right-radius\", value)];\n }\n return null;\n });\n\n utilities.functional(\"rounded-b\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) {\n return [decl(\"border-bottom-left-radius\", value), decl(\"border-bottom-right-radius\", value)];\n }\n return null;\n });\n\n utilities.functional(\"rounded-l\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) {\n return [decl(\"border-top-left-radius\", value), decl(\"border-bottom-left-radius\", value)];\n }\n return null;\n });\n\n // ============================================\n // Border Radius - Logical sides (s, e) - RTL aware\n // ============================================\n\n utilities.functional(\"rounded-s\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) {\n return [decl(\"border-start-start-radius\", value), decl(\"border-end-start-radius\", value)];\n }\n return null;\n });\n\n utilities.functional(\"rounded-e\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) {\n return [decl(\"border-start-end-radius\", value), decl(\"border-end-end-radius\", value)];\n }\n return null;\n });\n\n // ============================================\n // Border Radius - Physical corners (tl, tr, br, bl)\n // ============================================\n\n utilities.functional(\"rounded-tl\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) return [decl(\"border-top-left-radius\", value)];\n return null;\n });\n\n utilities.functional(\"rounded-tr\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) return [decl(\"border-top-right-radius\", value)];\n return null;\n });\n\n utilities.functional(\"rounded-br\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) return [decl(\"border-bottom-right-radius\", value)];\n return null;\n });\n\n utilities.functional(\"rounded-bl\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) return [decl(\"border-bottom-left-radius\", value)];\n return null;\n });\n\n // ============================================\n // Border Radius - Logical corners (ss, se, es, ee) - RTL aware\n // ============================================\n\n utilities.functional(\"rounded-ss\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) return [decl(\"border-start-start-radius\", value)];\n return null;\n });\n\n utilities.functional(\"rounded-se\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) return [decl(\"border-start-end-radius\", value)];\n return null;\n });\n\n utilities.functional(\"rounded-es\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) return [decl(\"border-end-start-radius\", value)];\n return null;\n });\n\n utilities.functional(\"rounded-ee\", (candidate, theme) => {\n const value = resolveRadius(candidate, theme);\n if (value) return [decl(\"border-end-end-radius\", value)];\n return null;\n });\n\n // ============================================\n // Corner Shape Utilities\n // ============================================\n\n utilities.functional(\"corner\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const shape = candidate.value.value;\n if (CORNER_SHAPES.has(shape)) {\n return [decl(\"corner-shape\", shape)];\n }\n } else if (candidate.value.kind === \"arbitrary\") {\n // Support arbitrary like corner-[superellipse(2.5)]\n return [decl(\"corner-shape\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Per-corner shape utilities\n utilities.functional(\"corner-tl\", (candidate) => {\n if (!candidate.value) return null;\n if (candidate.value.kind === \"named\" && CORNER_SHAPES.has(candidate.value.value)) {\n return [decl(\"corner-shape-top-left\", candidate.value.value)];\n } else if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"corner-shape-top-left\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"corner-tr\", (candidate) => {\n if (!candidate.value) return null;\n if (candidate.value.kind === \"named\" && CORNER_SHAPES.has(candidate.value.value)) {\n return [decl(\"corner-shape-top-right\", candidate.value.value)];\n } else if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"corner-shape-top-right\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"corner-br\", (candidate) => {\n if (!candidate.value) return null;\n if (candidate.value.kind === \"named\" && CORNER_SHAPES.has(candidate.value.value)) {\n return [decl(\"corner-shape-bottom-right\", candidate.value.value)];\n } else if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"corner-shape-bottom-right\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"corner-bl\", (candidate) => {\n if (!candidate.value) return null;\n if (candidate.value.kind === \"named\" && CORNER_SHAPES.has(candidate.value.value)) {\n return [decl(\"corner-shape-bottom-left\", candidate.value.value)];\n } else if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"corner-shape-bottom-left\", candidate.value.value)];\n }\n return null;\n });\n\n // ============================================\n // Squircle-Rounded Compound Utilities\n // Combines corner-shape: squircle with scaled radius\n // ============================================\n\n utilities.functional(\"squircle\", (candidate, theme) => {\n const value = resolveSquircleRadius(candidate, theme);\n if (value) {\n return [decl(\"border-radius\", value), decl(\"corner-shape\", \"squircle\")];\n }\n return null;\n });\n\n // Squircle directional variants\n utilities.functional(\"squircle-t\", (candidate, theme) => {\n const value = resolveSquircleRadius(candidate, theme);\n if (value) {\n return [\n decl(\"border-top-left-radius\", value),\n decl(\"border-top-right-radius\", value),\n decl(\"corner-shape-top-left\", \"squircle\"),\n decl(\"corner-shape-top-right\", \"squircle\"),\n ];\n }\n return null;\n });\n\n utilities.functional(\"squircle-r\", (candidate, theme) => {\n const value = resolveSquircleRadius(candidate, theme);\n if (value) {\n return [\n decl(\"border-top-right-radius\", value),\n decl(\"border-bottom-right-radius\", value),\n decl(\"corner-shape-top-right\", \"squircle\"),\n decl(\"corner-shape-bottom-right\", \"squircle\"),\n ];\n }\n return null;\n });\n\n utilities.functional(\"squircle-b\", (candidate, theme) => {\n const value = resolveSquircleRadius(candidate, theme);\n if (value) {\n return [\n decl(\"border-bottom-left-radius\", value),\n decl(\"border-bottom-right-radius\", value),\n decl(\"corner-shape-bottom-left\", \"squircle\"),\n decl(\"corner-shape-bottom-right\", \"squircle\"),\n ];\n }\n return null;\n });\n\n utilities.functional(\"squircle-l\", (candidate, theme) => {\n const value = resolveSquircleRadius(candidate, theme);\n if (value) {\n return [\n decl(\"border-top-left-radius\", value),\n decl(\"border-bottom-left-radius\", value),\n decl(\"corner-shape-top-left\", \"squircle\"),\n decl(\"corner-shape-bottom-left\", \"squircle\"),\n ];\n }\n return null;\n });\n\n // Squircle corner-specific\n utilities.functional(\"squircle-tl\", (candidate, theme) => {\n const value = resolveSquircleRadius(candidate, theme);\n if (value) {\n return [decl(\"border-top-left-radius\", value), decl(\"corner-shape-top-left\", \"squircle\")];\n }\n return null;\n });\n\n utilities.functional(\"squircle-tr\", (candidate, theme) => {\n const value = resolveSquircleRadius(candidate, theme);\n if (value) {\n return [decl(\"border-top-right-radius\", value), decl(\"corner-shape-top-right\", \"squircle\")];\n }\n return null;\n });\n\n utilities.functional(\"squircle-br\", (candidate, theme) => {\n const value = resolveSquircleRadius(candidate, theme);\n if (value) {\n return [decl(\"border-bottom-right-radius\", value), decl(\"corner-shape-bottom-right\", \"squircle\")];\n }\n return null;\n });\n\n utilities.functional(\"squircle-bl\", (candidate, theme) => {\n const value = resolveSquircleRadius(candidate, theme);\n if (value) {\n return [decl(\"border-bottom-left-radius\", value), decl(\"corner-shape-bottom-left\", \"squircle\")];\n }\n return null;\n });\n\n // ============================================\n // Border Width\n // ============================================\n\n utilities.functional(\"border\", (candidate, theme) => {\n if (!candidate.value) {\n return [decl(\"border-width\", \"1px\")];\n }\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-width\", `${num}px`)];\n }\n // Check for color\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"border-color\", color)];\n } else {\n return [decl(\"border-width\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.functional(\"border-t\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-top-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-top-width\", `${num}px`)];\n }\n } else {\n return [decl(\"border-top-width\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"border-r\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-right-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-right-width\", `${num}px`)];\n }\n } else {\n return [decl(\"border-right-width\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"border-b\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-bottom-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-bottom-width\", `${num}px`)];\n }\n } else {\n return [decl(\"border-bottom-width\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"border-l\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-left-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-left-width\", `${num}px`)];\n }\n } else {\n return [decl(\"border-left-width\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"border-x\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-left-width\", \"1px\"), decl(\"border-right-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-left-width\", `${num}px`), decl(\"border-right-width\", `${num}px`)];\n }\n } else {\n return [\n decl(\"border-left-width\", candidate.value.value),\n decl(\"border-right-width\", candidate.value.value),\n ];\n }\n return null;\n });\n\n utilities.functional(\"border-y\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-top-width\", \"1px\"), decl(\"border-bottom-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-top-width\", `${num}px`), decl(\"border-bottom-width\", `${num}px`)];\n }\n } else {\n return [\n decl(\"border-top-width\", candidate.value.value),\n decl(\"border-bottom-width\", candidate.value.value),\n ];\n }\n return null;\n });\n\n utilities.functional(\"border-s\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-inline-start-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-inline-start-width\", `${num}px`)];\n }\n } else {\n return [decl(\"border-inline-start-width\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"border-e\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-inline-end-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-inline-end-width\", `${num}px`)];\n }\n } else {\n return [decl(\"border-inline-end-width\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"border-bs\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-block-start-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-block-start-width\", `${num}px`)];\n }\n } else {\n return [decl(\"border-block-start-width\", candidate.value.value)];\n }\n return null;\n });\n\n utilities.functional(\"border-be\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"border-block-end-width\", \"1px\")];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"border-block-end-width\", `${num}px`)];\n }\n } else {\n return [decl(\"border-block-end-width\", candidate.value.value)];\n }\n return null;\n });\n\n // ============================================\n // Border Style\n // ============================================\n\n utilities.static(\"border-solid\", staticUtility([[\"border-style\", \"solid\"]]));\n utilities.static(\"border-dashed\", staticUtility([[\"border-style\", \"dashed\"]]));\n utilities.static(\"border-dotted\", staticUtility([[\"border-style\", \"dotted\"]]));\n utilities.static(\"border-double\", staticUtility([[\"border-style\", \"double\"]]));\n utilities.static(\"border-hidden\", staticUtility([[\"border-style\", \"hidden\"]]));\n utilities.static(\"border-none\", staticUtility([[\"border-style\", \"none\"]]));\n\n // ============================================\n // Divide Width\n // ============================================\n\n utilities.functional(\"divide-x\", (candidate) => {\n if (!candidate.value) {\n return [\n decl(\"--ri-divide-x-reverse\", \"0\"),\n decl(\"border-right-width\", \"calc(1px * var(--ri-divide-x-reverse))\"),\n decl(\"border-left-width\", \"calc(1px * calc(1 - var(--ri-divide-x-reverse)))\"),\n ];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-divide-x-reverse\", \"0\"),\n decl(\"border-right-width\", `calc(${num}px * var(--ri-divide-x-reverse))`),\n decl(\"border-left-width\", `calc(${num}px * calc(1 - var(--ri-divide-x-reverse)))`),\n ];\n }\n }\n return null;\n });\n\n utilities.functional(\"divide-y\", (candidate) => {\n if (!candidate.value) {\n return [\n decl(\"--ri-divide-y-reverse\", \"0\"),\n decl(\"border-bottom-width\", \"calc(1px * var(--ri-divide-y-reverse))\"),\n decl(\"border-top-width\", \"calc(1px * calc(1 - var(--ri-divide-y-reverse)))\"),\n ];\n }\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-divide-y-reverse\", \"0\"),\n decl(\"border-bottom-width\", `calc(${num}px * var(--ri-divide-y-reverse))`),\n decl(\"border-top-width\", `calc(${num}px * calc(1 - var(--ri-divide-y-reverse)))`),\n ];\n }\n }\n return null;\n });\n\n utilities.static(\"divide-x-reverse\", staticUtility([[\"--ri-divide-x-reverse\", \"1\"]]));\n utilities.static(\"divide-y-reverse\", staticUtility([[\"--ri-divide-y-reverse\", \"1\"]]));\n\n // ============================================\n // Divide Color\n // ============================================\n\n utilities.functional(\"divide\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"border-color\", color)];\n } else {\n return [decl(\"border-color\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"divide-inherit\", staticUtility([[\"border-color\", \"inherit\"]]));\n utilities.static(\"divide-current\", staticUtility([[\"border-color\", \"currentColor\"]]));\n utilities.static(\"divide-transparent\", staticUtility([[\"border-color\", \"transparent\"]]));\n\n // ============================================\n // Divide Style\n // ============================================\n\n utilities.static(\"divide-solid\", staticUtility([[\"border-style\", \"solid\"]]));\n utilities.static(\"divide-dashed\", staticUtility([[\"border-style\", \"dashed\"]]));\n utilities.static(\"divide-dotted\", staticUtility([[\"border-style\", \"dotted\"]]));\n utilities.static(\"divide-double\", staticUtility([[\"border-style\", \"double\"]]));\n utilities.static(\"divide-none\", staticUtility([[\"border-style\", \"none\"]]));\n\n // ============================================\n // Outline Width\n // ============================================\n\n utilities.functional(\"outline\", (candidate, theme) => {\n if (!candidate.value) {\n return [decl(\"outline-style\", \"solid\"), decl(\"outline-width\", \"1px\")];\n }\n\n if (candidate.value.kind === \"named\") {\n if (candidate.value.value === \"none\") {\n return [decl(\"outline-style\", \"none\")];\n }\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"outline-style\", \"solid\"), decl(\"outline-width\", `${num}px`)];\n }\n\n // Check for color\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"outline-color\", color)];\n } else {\n return [decl(\"outline-width\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Outline Style\n // ============================================\n\n utilities.static(\"outline-solid\", staticUtility([[\"outline-style\", \"solid\"]]));\n utilities.static(\"outline-dashed\", staticUtility([[\"outline-style\", \"dashed\"]]));\n utilities.static(\"outline-dotted\", staticUtility([[\"outline-style\", \"dotted\"]]));\n utilities.static(\"outline-double\", staticUtility([[\"outline-style\", \"double\"]]));\n // outline-hidden uses transparent color instead of hidden style for forced-colors mode support\n // In forced-colors mode, transparent becomes visible (replaced by system color)\n utilities.static(\n \"outline-hidden\",\n staticUtility([\n [\"outline\", \"2px solid transparent\"],\n [\"outline-offset\", \"2px\"],\n ])\n );\n utilities.static(\"outline-none\", staticUtility([[\"outline-style\", \"none\"]]));\n\n // ============================================\n // Outline Offset\n // ============================================\n\n utilities.functional(\"outline-offset\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"outline-offset\", `${num}px`)];\n }\n } else {\n return [decl(\"outline-offset\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Ring Width\n // ============================================\n\n utilities.functional(\"ring\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Only handle numeric values for ring width\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (Number.isNaN(num)) return null; // Not a number, let color handler take it\n }\n\n const ringWidth = candidate.value.kind === \"named\" ? `${candidate.value.value}px` : candidate.value.value;\n\n const defaultRingColor = theme.get(\"--ring-color\") ?? \"oklch(0.6 0.15 250 / 0.5)\";\n const ringColor = `var(--ri-ring-color, ${defaultRingColor})`;\n const ringOffsetWidth = \"var(--ri-ring-offset-width, 0px)\";\n const ringOffsetColor = \"var(--ri-ring-offset-color, #fff)\";\n\n return [\n decl(\"--ri-ring-offset-shadow\", `0 0 0 ${ringOffsetWidth} ${ringOffsetColor}`),\n decl(\"--ri-ring-shadow\", `0 0 0 calc(${ringWidth} + ${ringOffsetWidth}) ${ringColor}`),\n decl(\"box-shadow\", \"var(--ri-ring-offset-shadow), var(--ri-ring-shadow), var(--ri-shadow, 0 0 #0000)\"),\n ];\n });\n\n utilities.static(\"ring-inset\", staticUtility([[\"--ri-ring-inset\", \"inset\"]]));\n\n // ============================================\n // Ring Color\n // ============================================\n\n utilities.functional(\"ring\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Special color values\n if (candidate.value.value === \"inherit\") {\n return [decl(\"--ri-ring-color\", \"inherit\")];\n }\n if (candidate.value.value === \"current\") {\n return [decl(\"--ri-ring-color\", \"currentColor\")];\n }\n if (candidate.value.value === \"transparent\") {\n return [decl(\"--ri-ring-color\", \"transparent\")];\n }\n\n // Theme colors (e.g., ring-blue-500)\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) {\n // Apply opacity modifier if present\n if (candidate.modifier) {\n const opacity =\n candidate.modifier.kind === \"named\" ? `${candidate.modifier.value}%` : candidate.modifier.value;\n return [decl(\"--ri-ring-color\", `color-mix(in oklab, ${color} ${opacity}, transparent)`)];\n }\n return [decl(\"--ri-ring-color\", color)];\n }\n } else {\n // Arbitrary color value\n return [decl(\"--ri-ring-color\", candidate.value.value)];\n }\n\n return null;\n });\n\n utilities.static(\"ring-inherit\", staticUtility([[\"--ri-ring-color\", \"inherit\"]]));\n utilities.static(\"ring-current\", staticUtility([[\"--ri-ring-color\", \"currentColor\"]]));\n utilities.static(\"ring-transparent\", staticUtility([[\"--ri-ring-color\", \"transparent\"]]));\n\n // ============================================\n // Ring Offset Width\n // ============================================\n\n utilities.functional(\"ring-offset\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-ring-offset-width\", `${num}px`)];\n }\n // Check for color\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"--ri-ring-offset-color\", color)];\n } else {\n return [decl(\"--ri-ring-offset-width\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Inset Ring\n // ============================================\n\n utilities.functional(\"inset-ring\", (candidate, theme) => {\n const ringWidth = candidate.value\n ? candidate.value.kind === \"named\"\n ? `${candidate.value.value}px`\n : candidate.value.value\n : \"1px\";\n\n const ringColor = theme.get(\"--inset-ring-color\") ?? \"currentColor\";\n\n return [\n decl(\"--ri-inset-ring-shadow\", `inset 0 0 0 ${ringWidth} ${ringColor}`),\n decl(\n \"box-shadow\",\n \"var(--ri-inset-shadow, 0 0 #0000), var(--ri-inset-ring-shadow, 0 0 #0000), var(--ri-ring-offset-shadow, 0 0 #0000), var(--ri-ring-shadow, 0 0 #0000), var(--ri-shadow, 0 0 #0000)\"\n ),\n ];\n });\n\n // Inset ring color\n utilities.functional(\"inset-ring\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"--ri-inset-ring-color\", color)];\n } else {\n return [decl(\"--ri-inset-ring-color\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Border Spacing (for tables)\n // ============================================\n\n utilities.functional(\"border-spacing\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let value: string | null = null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n const spacing = theme.get(\"--spacing\");\n if (spacing) {\n value = num === 0 ? \"0px\" : `calc(${num} * ${spacing})`;\n } else {\n value = `${num * 0.25}rem`;\n }\n }\n } else {\n value = candidate.value.value;\n }\n\n if (!value) return null;\n return [decl(\"border-spacing\", value)];\n });\n\n utilities.functional(\"border-spacing-x\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let value: string | null = null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n const spacing = theme.get(\"--spacing\");\n if (spacing) {\n value = num === 0 ? \"0px\" : `calc(${num} * ${spacing})`;\n } else {\n value = `${num * 0.25}rem`;\n }\n }\n } else {\n value = candidate.value.value;\n }\n\n if (!value) return null;\n return [\n decl(\"--ri-border-spacing-x\", value),\n decl(\"border-spacing\", \"var(--ri-border-spacing-x) var(--ri-border-spacing-y, 0px)\"),\n ];\n });\n\n utilities.functional(\"border-spacing-y\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n let value: string | null = null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n const spacing = theme.get(\"--spacing\");\n if (spacing) {\n value = num === 0 ? \"0px\" : `calc(${num} * ${spacing})`;\n } else {\n value = `${num * 0.25}rem`;\n }\n }\n } else {\n value = candidate.value.value;\n }\n\n if (!value) return null;\n return [\n decl(\"--ri-border-spacing-y\", value),\n decl(\"border-spacing\", \"var(--ri-border-spacing-x, 0px) var(--ri-border-spacing-y)\"),\n ];\n });\n}\n","/**\n * Effects Utilities\n *\n * Shadows, opacity, mix-blend-mode, and background-blend-mode utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\nimport { looksLikeColor } from \"../utils/is-color\";\nimport { isValidOpacityValue } from \"../utils/dimensions\";\n\nconst BOX_SHADOW_VALUE = \"var(--ri-ring-offset-shadow, 0 0 #0000), var(--ri-ring-shadow, 0 0 #0000), var(--ri-shadow)\";\nconst INSET_SHADOW_VALUE =\n \"var(--ri-inset-shadow), var(--ri-ring-offset-shadow, 0 0 #0000), var(--ri-ring-shadow, 0 0 #0000), var(--ri-shadow, 0 0 #0000)\";\n\n// Pre-defined text shadow values (hoisted to avoid recreating on every call)\nconst TEXT_SHADOW_VALUES: Record<string, string> = {\n sm: \"0 1px 1px rgb(0 0 0 / 0.05)\",\n md: \"0 1px 2px rgb(0 0 0 / 0.1)\",\n lg: \"0 2px 4px rgb(0 0 0 / 0.1)\",\n xl: \"0 4px 8px rgb(0 0 0 / 0.1)\",\n \"2xl\": \"0 8px 16px rgb(0 0 0 / 0.1)\",\n none: \"none\",\n initial: \"initial\",\n};\n\nexport function registerEffectsUtilities(utilities: Utilities, _theme: Theme): void {\n // Box Shadow\n utilities.functional(\"shadow\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--shadow-${candidate.value.value}`);\n if (value) {\n return [decl(\"--ri-shadow\", value), decl(\"box-shadow\", BOX_SHADOW_VALUE)];\n }\n\n // Special values\n if (candidate.value.value === \"none\") {\n return [decl(\"--ri-shadow\", \"0 0 #0000\"), decl(\"box-shadow\", BOX_SHADOW_VALUE)];\n }\n\n if (candidate.value.value === \"initial\") {\n return [decl(\"box-shadow\", \"initial\")];\n }\n } else {\n return [decl(\"--ri-shadow\", candidate.value.value), decl(\"box-shadow\", BOX_SHADOW_VALUE)];\n }\n\n return null;\n });\n\n // Shadow color\n utilities.functional(\"shadow\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"--ri-shadow-color\", color)];\n } else {\n return [decl(\"--ri-shadow-color\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Inset Shadow\n\n utilities.functional(\"inset-shadow\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--inset-shadow-${candidate.value.value}`);\n if (value) {\n return [decl(\"--ri-inset-shadow\", value), decl(\"box-shadow\", INSET_SHADOW_VALUE)];\n }\n\n if (candidate.value.value === \"none\") {\n return [decl(\"--ri-inset-shadow\", \"0 0 #0000\"), decl(\"box-shadow\", INSET_SHADOW_VALUE)];\n }\n\n if (candidate.value.value === \"initial\") {\n return [decl(\"box-shadow\", \"initial\")];\n }\n }\n\n return null;\n });\n\n // Drop Shadow\n\n utilities.static(\n \"drop-shadow-none\",\n staticUtility([\n [\"--ri-drop-shadow\", \"drop-shadow(0 0 #0000)\"],\n [\"filter\", \"var(--ri-drop-shadow)\"],\n ])\n );\n\n utilities.functional(\"drop-shadow\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--drop-shadow-${candidate.value.value}`);\n if (value) {\n return [decl(\"--ri-drop-shadow\", value), decl(\"filter\", \"var(--ri-drop-shadow)\")];\n }\n\n if (candidate.value.value === \"none\") {\n return [decl(\"--ri-drop-shadow\", \"drop-shadow(0 0 #0000)\"), decl(\"filter\", \"var(--ri-drop-shadow)\")];\n }\n\n // Check for color (drop-shadow-red-500)\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) {\n return [decl(\"--ri-drop-shadow-color\", color)];\n }\n } else {\n // Arbitrary value - detect if it's a color or shadow definition\n const value = candidate.value.value;\n if (looksLikeColor(value)) {\n return [decl(\"--ri-drop-shadow-color\", value)];\n }\n return [decl(\"--ri-drop-shadow\", `drop-shadow(${value})`), decl(\"filter\", \"var(--ri-drop-shadow)\")];\n }\n\n return null;\n });\n\n // Drop shadow color utility\n utilities.functional(\"drop-shadow-color\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n if (candidate.value.value === \"inherit\") {\n return [decl(\"--ri-drop-shadow-color\", \"inherit\")];\n }\n if (candidate.value.value === \"current\") {\n return [decl(\"--ri-drop-shadow-color\", \"currentColor\")];\n }\n if (candidate.value.value === \"transparent\") {\n return [decl(\"--ri-drop-shadow-color\", \"transparent\")];\n }\n\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"--ri-drop-shadow-color\", color)];\n } else {\n return [decl(\"--ri-drop-shadow-color\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Opacity\n\n utilities.functional(\"opacity\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Validate opacity value (must be integer 0-100)\n if (!isValidOpacityValue(candidate.value.value)) return null;\n\n const num = Number(candidate.value.value);\n return [decl(\"opacity\", String(num / 100))];\n } else {\n // Arbitrary values pass through directly\n return [decl(\"opacity\", candidate.value.value)];\n }\n });\n\n // Mix Blend Mode\n\n utilities.static(\"mix-blend-normal\", staticUtility([[\"mix-blend-mode\", \"normal\"]]));\n utilities.static(\"mix-blend-multiply\", staticUtility([[\"mix-blend-mode\", \"multiply\"]]));\n utilities.static(\"mix-blend-screen\", staticUtility([[\"mix-blend-mode\", \"screen\"]]));\n utilities.static(\"mix-blend-overlay\", staticUtility([[\"mix-blend-mode\", \"overlay\"]]));\n utilities.static(\"mix-blend-darken\", staticUtility([[\"mix-blend-mode\", \"darken\"]]));\n utilities.static(\"mix-blend-lighten\", staticUtility([[\"mix-blend-mode\", \"lighten\"]]));\n utilities.static(\"mix-blend-color-dodge\", staticUtility([[\"mix-blend-mode\", \"color-dodge\"]]));\n utilities.static(\"mix-blend-color-burn\", staticUtility([[\"mix-blend-mode\", \"color-burn\"]]));\n utilities.static(\"mix-blend-hard-light\", staticUtility([[\"mix-blend-mode\", \"hard-light\"]]));\n utilities.static(\"mix-blend-soft-light\", staticUtility([[\"mix-blend-mode\", \"soft-light\"]]));\n utilities.static(\"mix-blend-difference\", staticUtility([[\"mix-blend-mode\", \"difference\"]]));\n utilities.static(\"mix-blend-exclusion\", staticUtility([[\"mix-blend-mode\", \"exclusion\"]]));\n utilities.static(\"mix-blend-hue\", staticUtility([[\"mix-blend-mode\", \"hue\"]]));\n utilities.static(\"mix-blend-saturation\", staticUtility([[\"mix-blend-mode\", \"saturation\"]]));\n utilities.static(\"mix-blend-color\", staticUtility([[\"mix-blend-mode\", \"color\"]]));\n utilities.static(\"mix-blend-luminosity\", staticUtility([[\"mix-blend-mode\", \"luminosity\"]]));\n utilities.static(\"mix-blend-plus-darker\", staticUtility([[\"mix-blend-mode\", \"plus-darker\"]]));\n utilities.static(\"mix-blend-plus-lighter\", staticUtility([[\"mix-blend-mode\", \"plus-lighter\"]]));\n\n // Background Blend Mode\n\n utilities.static(\"bg-blend-normal\", staticUtility([[\"background-blend-mode\", \"normal\"]]));\n utilities.static(\"bg-blend-multiply\", staticUtility([[\"background-blend-mode\", \"multiply\"]]));\n utilities.static(\"bg-blend-screen\", staticUtility([[\"background-blend-mode\", \"screen\"]]));\n utilities.static(\"bg-blend-overlay\", staticUtility([[\"background-blend-mode\", \"overlay\"]]));\n utilities.static(\"bg-blend-darken\", staticUtility([[\"background-blend-mode\", \"darken\"]]));\n utilities.static(\"bg-blend-lighten\", staticUtility([[\"background-blend-mode\", \"lighten\"]]));\n utilities.static(\"bg-blend-color-dodge\", staticUtility([[\"background-blend-mode\", \"color-dodge\"]]));\n utilities.static(\"bg-blend-color-burn\", staticUtility([[\"background-blend-mode\", \"color-burn\"]]));\n utilities.static(\"bg-blend-hard-light\", staticUtility([[\"background-blend-mode\", \"hard-light\"]]));\n utilities.static(\"bg-blend-soft-light\", staticUtility([[\"background-blend-mode\", \"soft-light\"]]));\n utilities.static(\"bg-blend-difference\", staticUtility([[\"background-blend-mode\", \"difference\"]]));\n utilities.static(\"bg-blend-exclusion\", staticUtility([[\"background-blend-mode\", \"exclusion\"]]));\n utilities.static(\"bg-blend-hue\", staticUtility([[\"background-blend-mode\", \"hue\"]]));\n utilities.static(\"bg-blend-saturation\", staticUtility([[\"background-blend-mode\", \"saturation\"]]));\n utilities.static(\"bg-blend-color\", staticUtility([[\"background-blend-mode\", \"color\"]]));\n utilities.static(\"bg-blend-luminosity\", staticUtility([[\"background-blend-mode\", \"luminosity\"]]));\n\n // Text Shadow\n\n utilities.functional(\"text-shadow\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--text-shadow-${candidate.value.value}`);\n if (value) return [decl(\"text-shadow\", value)];\n\n // Named sizes\n const namedValue = TEXT_SHADOW_VALUES[candidate.value.value];\n if (namedValue) return [decl(\"text-shadow\", namedValue)];\n } else {\n return [decl(\"text-shadow\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Text shadow color (with opacity modifier support)\n utilities.functional(\"text-shadow\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Special color values\n if (candidate.value.value === \"inherit\") {\n return [decl(\"--ri-text-shadow-color\", \"inherit\")];\n }\n if (candidate.value.value === \"current\") {\n return [decl(\"--ri-text-shadow-color\", \"currentColor\")];\n }\n if (candidate.value.value === \"transparent\") {\n return [decl(\"--ri-text-shadow-color\", \"transparent\")];\n }\n\n // Theme colors (e.g., text-shadow-blue-500)\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) {\n // Apply opacity modifier if present (e.g., text-shadow-blue-500/50)\n if (candidate.modifier) {\n const opacity =\n candidate.modifier.kind === \"named\" ? `${candidate.modifier.value}%` : candidate.modifier.value;\n return [decl(\"--ri-text-shadow-color\", `color-mix(in oklab, ${color} ${opacity}, transparent)`)];\n }\n return [decl(\"--ri-text-shadow-color\", color)];\n }\n } else {\n // Arbitrary color value\n return [decl(\"--ri-text-shadow-color\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Static text shadow color utilities\n utilities.static(\"text-shadow-inherit\", staticUtility([[\"--ri-text-shadow-color\", \"inherit\"]]));\n utilities.static(\"text-shadow-current\", staticUtility([[\"--ri-text-shadow-color\", \"currentColor\"]]));\n utilities.static(\"text-shadow-transparent\", staticUtility([[\"--ri-text-shadow-color\", \"transparent\"]]));\n\n // Shadow Reset Utilities\n\n utilities.static(\n \"shadow-initial\",\n staticUtility([\n [\"--ri-shadow\", \"initial\"],\n [\"--ri-shadow-color\", \"initial\"],\n [\"box-shadow\", \"initial\"],\n ])\n );\n\n utilities.static(\n \"inset-shadow-initial\",\n staticUtility([\n [\"--ri-inset-shadow\", \"initial\"],\n [\"box-shadow\", \"initial\"],\n ])\n );\n\n utilities.static(\n \"text-shadow-initial\",\n staticUtility([\n [\"--ri-text-shadow-color\", \"initial\"],\n [\"text-shadow\", \"initial\"],\n ])\n );\n}\n","/**\n * Transform Utilities\n *\n * Scale, rotate, translate, skew, and transform origin utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\n/** Composable 2D transform value using CSS custom properties */\nconst TRANSFORM_2D =\n \"translate(var(--ri-translate-x, 0), var(--ri-translate-y, 0)) rotate(var(--ri-rotate, 0)) skewX(var(--ri-skew-x, 0)) skewY(var(--ri-skew-y, 0)) scaleX(var(--ri-scale-x, 1)) scaleY(var(--ri-scale-y, 1))\";\n\n/** Pre-compiled regex for fraction values (hoisted to avoid recreation on every call) */\nconst FRACTION_PATTERN = /^(\\d+)\\/(\\d+)$/;\n\nexport function registerTransformUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Scale\n // ============================================\n\n utilities.functional(\"scale\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n const value = String(num / 100);\n return [decl(\"--ri-scale-x\", value), decl(\"--ri-scale-y\", value), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [\n decl(\"--ri-scale-x\", candidate.value.value),\n decl(\"--ri-scale-y\", candidate.value.value),\n decl(\"transform\", TRANSFORM_2D),\n ];\n }\n\n return null;\n });\n\n utilities.functional(\"scale-x\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-scale-x\", String(num / 100)), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-scale-x\", candidate.value.value), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n\n utilities.functional(\"scale-y\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-scale-y\", String(num / 100)), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-scale-y\", candidate.value.value), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n\n // ============================================\n // Rotate\n // ============================================\n\n utilities.functional(\"rotate\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-rotate\", `${num}deg`), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-rotate\", candidate.value.value), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n\n // ============================================\n // Transform (arbitrary)\n // ============================================\n\n utilities.functional(\"transform\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"transform\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Translate\n // ============================================\n\n utilities.functional(\"translate\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--spacing-${candidate.value.value}`);\n if (value) {\n return [\n decl(\"--ri-translate-x\", value),\n decl(\"--ri-translate-y\", value),\n decl(\"transform\", TRANSFORM_2D),\n ];\n }\n\n // Fraction values\n if (candidate.value.value === \"full\") {\n return [\n decl(\"--ri-translate-x\", \"100%\"),\n decl(\"--ri-translate-y\", \"100%\"),\n decl(\"transform\", TRANSFORM_2D),\n ];\n }\n\n const fractionMatch = candidate.value.value.match(FRACTION_PATTERN);\n if (fractionMatch) {\n const [, num, denom] = fractionMatch;\n const percentage = (Number(num) / Number(denom)) * 100;\n return [\n decl(\"--ri-translate-x\", `${percentage}%`),\n decl(\"--ri-translate-y\", `${percentage}%`),\n decl(\"transform\", TRANSFORM_2D),\n ];\n }\n\n // Numeric value (spacing scale)\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-translate-x\", `${num * 0.25}rem`),\n decl(\"--ri-translate-y\", `${num * 0.25}rem`),\n decl(\"transform\", TRANSFORM_2D),\n ];\n }\n } else {\n return [\n decl(\"--ri-translate-x\", candidate.value.value),\n decl(\"--ri-translate-y\", candidate.value.value),\n decl(\"transform\", TRANSFORM_2D),\n ];\n }\n\n return null;\n });\n\n utilities.functional(\"translate-x\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--spacing-${candidate.value.value}`);\n if (value) {\n return [decl(\"--ri-translate-x\", value), decl(\"transform\", TRANSFORM_2D)];\n }\n\n // Fraction values\n if (candidate.value.value === \"full\") {\n return [decl(\"--ri-translate-x\", \"100%\"), decl(\"transform\", TRANSFORM_2D)];\n }\n\n const fractionMatch = candidate.value.value.match(FRACTION_PATTERN);\n if (fractionMatch) {\n const [, num, denom] = fractionMatch;\n const percentage = (Number(num) / Number(denom)) * 100;\n return [decl(\"--ri-translate-x\", `${percentage}%`), decl(\"transform\", TRANSFORM_2D)];\n }\n\n // Numeric value (spacing scale)\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-translate-x\", `${num * 0.25}rem`), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-translate-x\", candidate.value.value), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n\n utilities.functional(\"translate-y\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--spacing-${candidate.value.value}`);\n if (value) {\n return [decl(\"--ri-translate-y\", value), decl(\"transform\", TRANSFORM_2D)];\n }\n\n // Fraction values\n if (candidate.value.value === \"full\") {\n return [decl(\"--ri-translate-y\", \"100%\"), decl(\"transform\", TRANSFORM_2D)];\n }\n\n const fractionMatch = candidate.value.value.match(FRACTION_PATTERN);\n if (fractionMatch) {\n const [, num, denom] = fractionMatch;\n const percentage = (Number(num) / Number(denom)) * 100;\n return [decl(\"--ri-translate-y\", `${percentage}%`), decl(\"transform\", TRANSFORM_2D)];\n }\n\n // Numeric value (spacing scale)\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-translate-y\", `${num * 0.25}rem`), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-translate-y\", candidate.value.value), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n\n // ============================================\n // Skew\n // ============================================\n\n // Compound skew (applies same value to both X and Y)\n utilities.functional(\"skew\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-skew-x\", `${num}deg`),\n decl(\"--ri-skew-y\", `${num}deg`),\n decl(\"transform\", TRANSFORM_2D),\n ];\n }\n } else {\n return [\n decl(\"--ri-skew-x\", candidate.value.value),\n decl(\"--ri-skew-y\", candidate.value.value),\n decl(\"transform\", TRANSFORM_2D),\n ];\n }\n\n return null;\n });\n\n utilities.functional(\"skew-x\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-skew-x\", `${num}deg`), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-skew-x\", candidate.value.value), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n\n utilities.functional(\"skew-y\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-skew-y\", `${num}deg`), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-skew-y\", candidate.value.value), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n\n // ============================================\n // Transform Origin\n // ============================================\n\n utilities.static(\"origin-center\", staticUtility([[\"transform-origin\", \"center\"]]));\n utilities.static(\"origin-top\", staticUtility([[\"transform-origin\", \"top\"]]));\n utilities.static(\"origin-top-right\", staticUtility([[\"transform-origin\", \"top right\"]]));\n utilities.static(\"origin-right\", staticUtility([[\"transform-origin\", \"right\"]]));\n utilities.static(\"origin-bottom-right\", staticUtility([[\"transform-origin\", \"bottom right\"]]));\n utilities.static(\"origin-bottom\", staticUtility([[\"transform-origin\", \"bottom\"]]));\n utilities.static(\"origin-bottom-left\", staticUtility([[\"transform-origin\", \"bottom left\"]]));\n utilities.static(\"origin-left\", staticUtility([[\"transform-origin\", \"left\"]]));\n utilities.static(\"origin-top-left\", staticUtility([[\"transform-origin\", \"top left\"]]));\n\n utilities.functional(\"origin\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--transform-origin-${candidate.value.value}`);\n if (value) return [decl(\"transform-origin\", value)];\n } else {\n return [decl(\"transform-origin\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Perspective\n // ============================================\n\n utilities.functional(\"perspective\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--perspective-${candidate.value.value}`);\n if (value) return [decl(\"perspective\", value)];\n\n if (candidate.value.value === \"none\") {\n return [decl(\"perspective\", \"none\")];\n }\n } else {\n return [decl(\"perspective\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Perspective Origin\n // ============================================\n\n utilities.static(\"perspective-origin-center\", staticUtility([[\"perspective-origin\", \"center\"]]));\n utilities.static(\"perspective-origin-top\", staticUtility([[\"perspective-origin\", \"top\"]]));\n utilities.static(\"perspective-origin-top-right\", staticUtility([[\"perspective-origin\", \"top right\"]]));\n utilities.static(\"perspective-origin-right\", staticUtility([[\"perspective-origin\", \"right\"]]));\n utilities.static(\"perspective-origin-bottom-right\", staticUtility([[\"perspective-origin\", \"bottom right\"]]));\n utilities.static(\"perspective-origin-bottom\", staticUtility([[\"perspective-origin\", \"bottom\"]]));\n utilities.static(\"perspective-origin-bottom-left\", staticUtility([[\"perspective-origin\", \"bottom left\"]]));\n utilities.static(\"perspective-origin-left\", staticUtility([[\"perspective-origin\", \"left\"]]));\n utilities.static(\"perspective-origin-top-left\", staticUtility([[\"perspective-origin\", \"top left\"]]));\n\n utilities.functional(\"perspective-origin\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--perspective-origin-${candidate.value.value}`);\n if (value) return [decl(\"perspective-origin\", value)];\n } else {\n return [decl(\"perspective-origin\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Transform Style\n // ============================================\n\n utilities.static(\"transform-3d\", staticUtility([[\"transform-style\", \"preserve-3d\"]]));\n utilities.static(\"transform-flat\", staticUtility([[\"transform-style\", \"flat\"]]));\n\n // ============================================\n // Backface Visibility\n // ============================================\n\n utilities.static(\"backface-visible\", staticUtility([[\"backface-visibility\", \"visible\"]]));\n utilities.static(\"backface-hidden\", staticUtility([[\"backface-visibility\", \"hidden\"]]));\n\n // ============================================\n // Transform Box\n // ============================================\n\n utilities.static(\"transform-content\", staticUtility([[\"transform-box\", \"content-box\"]]));\n utilities.static(\"transform-border\", staticUtility([[\"transform-box\", \"border-box\"]]));\n utilities.static(\"transform-fill\", staticUtility([[\"transform-box\", \"fill-box\"]]));\n utilities.static(\"transform-stroke\", staticUtility([[\"transform-box\", \"stroke-box\"]]));\n utilities.static(\"transform-view\", staticUtility([[\"transform-box\", \"view-box\"]]));\n\n // ============================================\n // Transform None / GPU / CPU\n // ============================================\n\n utilities.static(\"transform-none\", staticUtility([[\"transform\", \"none\"]]));\n utilities.static(\"transform-gpu\", staticUtility([[\"transform\", \"translateZ(0)\"]]));\n utilities.static(\"transform-cpu\", staticUtility([[\"transform\", \"translateX(0)\"]]));\n\n // ============================================\n // Translate Shortcuts\n // ============================================\n\n utilities.static(\n \"translate-none\",\n staticUtility([\n [\"--ri-translate-x\", \"0\"],\n [\"--ri-translate-y\", \"0\"],\n [\"transform\", TRANSFORM_2D],\n ])\n );\n\n utilities.static(\n \"translate-full\",\n staticUtility([\n [\"--ri-translate-x\", \"100%\"],\n [\"--ri-translate-y\", \"100%\"],\n [\"transform\", TRANSFORM_2D],\n ])\n );\n\n utilities.static(\n \"-translate-full\",\n staticUtility([\n [\"--ri-translate-x\", \"-100%\"],\n [\"--ri-translate-y\", \"-100%\"],\n [\"transform\", TRANSFORM_2D],\n ])\n );\n\n utilities.static(\n \"translate-3d\",\n staticUtility([\n [\"transform\", \"translate3d(var(--ri-translate-x, 0), var(--ri-translate-y, 0), var(--ri-translate-z, 0))\"],\n ])\n );\n\n // ============================================\n // Scale Shortcuts\n // ============================================\n\n utilities.static(\n \"scale-none\",\n staticUtility([\n [\"--ri-scale-x\", \"1\"],\n [\"--ri-scale-y\", \"1\"],\n [\"transform\", TRANSFORM_2D],\n ])\n );\n\n utilities.static(\n \"scale-3d\",\n staticUtility([[\"transform\", \"scale3d(var(--ri-scale-x, 1), var(--ri-scale-y, 1), var(--ri-scale-z, 1))\"]])\n );\n\n // ============================================\n // Rotate Shortcuts\n // ============================================\n\n utilities.static(\n \"rotate-none\",\n staticUtility([\n [\"--ri-rotate\", \"0\"],\n [\"transform\", TRANSFORM_2D],\n ])\n );\n\n // ============================================\n // 3D Transform Utilities\n // ============================================\n\n utilities.functional(\"translate-z\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--spacing-${candidate.value.value}`);\n if (value) {\n return [\n decl(\"--ri-translate-z\", value),\n decl(\n \"transform\",\n \"translate3d(var(--ri-translate-x, 0), var(--ri-translate-y, 0), var(--ri-translate-z, 0))\"\n ),\n ];\n }\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-translate-z\", `${num * 0.25}rem`),\n decl(\n \"transform\",\n \"translate3d(var(--ri-translate-x, 0), var(--ri-translate-y, 0), var(--ri-translate-z, 0))\"\n ),\n ];\n }\n } else {\n return [\n decl(\"--ri-translate-z\", candidate.value.value),\n decl(\n \"transform\",\n \"translate3d(var(--ri-translate-x, 0), var(--ri-translate-y, 0), var(--ri-translate-z, 0))\"\n ),\n ];\n }\n\n return null;\n });\n\n utilities.functional(\"rotate-x\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"transform\", `rotateX(${num}deg)`)];\n }\n } else {\n return [decl(\"transform\", `rotateX(${candidate.value.value})`)];\n }\n\n return null;\n });\n\n utilities.functional(\"rotate-y\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"transform\", `rotateY(${num}deg)`)];\n }\n } else {\n return [decl(\"transform\", `rotateY(${candidate.value.value})`)];\n }\n\n return null;\n });\n\n utilities.functional(\"rotate-z\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"transform\", `rotateZ(${num}deg)`)];\n }\n } else {\n return [decl(\"transform\", `rotateZ(${candidate.value.value})`)];\n }\n\n return null;\n });\n\n utilities.functional(\"scale-z\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-scale-z\", String(num / 100)),\n decl(\"transform\", \"scale3d(var(--ri-scale-x, 1), var(--ri-scale-y, 1), var(--ri-scale-z, 1))\"),\n ];\n }\n } else {\n return [\n decl(\"--ri-scale-z\", candidate.value.value),\n decl(\"transform\", \"scale3d(var(--ri-scale-x, 1), var(--ri-scale-y, 1), var(--ri-scale-z, 1))\"),\n ];\n }\n\n return null;\n });\n\n // ============================================\n // Negative Scale\n // ============================================\n\n utilities.functional(\"-scale\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n const value = String(-num / 100);\n return [decl(\"--ri-scale-x\", value), decl(\"--ri-scale-y\", value), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [\n decl(\"--ri-scale-x\", `calc(-1 * ${candidate.value.value})`),\n decl(\"--ri-scale-y\", `calc(-1 * ${candidate.value.value})`),\n decl(\"transform\", TRANSFORM_2D),\n ];\n }\n\n return null;\n });\n\n utilities.functional(\"-scale-x\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-scale-x\", String(-num / 100)), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-scale-x\", `calc(-1 * ${candidate.value.value})`), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n\n utilities.functional(\"-scale-y\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-scale-y\", String(-num / 100)), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-scale-y\", `calc(-1 * ${candidate.value.value})`), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n\n // ============================================\n // Negative Rotate\n // ============================================\n\n utilities.functional(\"-rotate\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-rotate\", `${-num}deg`), decl(\"transform\", TRANSFORM_2D)];\n }\n } else {\n return [decl(\"--ri-rotate\", `calc(-1 * ${candidate.value.value})`), decl(\"transform\", TRANSFORM_2D)];\n }\n\n return null;\n });\n}\n","/**\n * Filter Utilities\n *\n * Blur, brightness, contrast, grayscale, and other filter utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\n/** Composable filter value using CSS custom properties */\nconst FILTER_VALUE =\n \"var(--ri-blur, ) var(--ri-brightness, ) var(--ri-contrast, ) var(--ri-grayscale, ) var(--ri-hue-rotate, ) var(--ri-invert, ) var(--ri-saturate, ) var(--ri-sepia, ) var(--ri-drop-shadow, )\";\n\n/** Composable backdrop-filter value using CSS custom properties */\nconst BACKDROP_FILTER_VALUE =\n \"var(--ri-backdrop-blur, ) var(--ri-backdrop-brightness, ) var(--ri-backdrop-contrast, ) var(--ri-backdrop-grayscale, ) var(--ri-backdrop-hue-rotate, ) var(--ri-backdrop-invert, ) var(--ri-backdrop-opacity, ) var(--ri-backdrop-saturate, ) var(--ri-backdrop-sepia, )\";\n\nexport function registerFilterUtilities(utilities: Utilities, _theme: Theme): void {\n // Blur\n\n utilities.functional(\"blur\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--blur-${candidate.value.value}`);\n if (value) {\n return [decl(\"--ri-blur\", `blur(${value})`), decl(\"filter\", FILTER_VALUE)];\n }\n\n if (candidate.value.value === \"none\") {\n return [decl(\"--ri-blur\", \"\"), decl(\"filter\", FILTER_VALUE)];\n }\n } else {\n return [decl(\"--ri-blur\", `blur(${candidate.value.value})`), decl(\"filter\", FILTER_VALUE)];\n }\n\n return null;\n });\n\n // Brightness\n\n utilities.functional(\"brightness\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-brightness\", `brightness(${num / 100})`), decl(\"filter\", FILTER_VALUE)];\n }\n } else {\n return [decl(\"--ri-brightness\", `brightness(${candidate.value.value})`), decl(\"filter\", FILTER_VALUE)];\n }\n\n return null;\n });\n\n // Contrast\n\n utilities.functional(\"contrast\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-contrast\", `contrast(${num / 100})`), decl(\"filter\", FILTER_VALUE)];\n }\n } else {\n return [decl(\"--ri-contrast\", `contrast(${candidate.value.value})`), decl(\"filter\", FILTER_VALUE)];\n }\n\n return null;\n });\n\n // Grayscale\n\n utilities.functional(\"grayscale\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"--ri-grayscale\", \"grayscale(100%)\"), decl(\"filter\", FILTER_VALUE)];\n }\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-grayscale\", `grayscale(${num}%)`), decl(\"filter\", FILTER_VALUE)];\n }\n } else {\n return [decl(\"--ri-grayscale\", `grayscale(${candidate.value.value})`), decl(\"filter\", FILTER_VALUE)];\n }\n\n return null;\n });\n\n // Hue Rotate\n\n utilities.functional(\"hue-rotate\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-hue-rotate\", `hue-rotate(${num}deg)`), decl(\"filter\", FILTER_VALUE)];\n }\n } else {\n return [decl(\"--ri-hue-rotate\", `hue-rotate(${candidate.value.value})`), decl(\"filter\", FILTER_VALUE)];\n }\n\n return null;\n });\n\n // Invert\n\n utilities.functional(\"invert\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"--ri-invert\", \"invert(100%)\"), decl(\"filter\", FILTER_VALUE)];\n }\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-invert\", `invert(${num}%)`), decl(\"filter\", FILTER_VALUE)];\n }\n } else {\n return [decl(\"--ri-invert\", `invert(${candidate.value.value})`), decl(\"filter\", FILTER_VALUE)];\n }\n\n return null;\n });\n\n // Saturate\n\n utilities.functional(\"saturate\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-saturate\", `saturate(${num / 100})`), decl(\"filter\", FILTER_VALUE)];\n }\n } else {\n return [decl(\"--ri-saturate\", `saturate(${candidate.value.value})`), decl(\"filter\", FILTER_VALUE)];\n }\n\n return null;\n });\n\n // Sepia\n\n utilities.functional(\"sepia\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"--ri-sepia\", \"sepia(100%)\"), decl(\"filter\", FILTER_VALUE)];\n }\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-sepia\", `sepia(${num}%)`), decl(\"filter\", FILTER_VALUE)];\n }\n } else {\n return [decl(\"--ri-sepia\", `sepia(${candidate.value.value})`), decl(\"filter\", FILTER_VALUE)];\n }\n\n return null;\n });\n\n // Backdrop Blur\n\n utilities.functional(\"backdrop-blur\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--blur-${candidate.value.value}`);\n if (value) {\n return [decl(\"--ri-backdrop-blur\", `blur(${value})`), decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE)];\n }\n\n if (candidate.value.value === \"none\") {\n return [decl(\"--ri-backdrop-blur\", \"\"), decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE)];\n }\n } else {\n return [\n decl(\"--ri-backdrop-blur\", `blur(${candidate.value.value})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n\n return null;\n });\n\n // Backdrop Brightness\n\n utilities.functional(\"backdrop-brightness\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-backdrop-brightness\", `brightness(${num / 100})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n } else {\n return [\n decl(\"--ri-backdrop-brightness\", `brightness(${candidate.value.value})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n\n return null;\n });\n\n // Backdrop Contrast\n\n utilities.functional(\"backdrop-contrast\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-backdrop-contrast\", `contrast(${num / 100})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n } else {\n return [\n decl(\"--ri-backdrop-contrast\", `contrast(${candidate.value.value})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n\n return null;\n });\n\n // Backdrop Grayscale\n\n utilities.functional(\"backdrop-grayscale\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"--ri-backdrop-grayscale\", \"grayscale(100%)\"), decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE)];\n }\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-backdrop-grayscale\", `grayscale(${num}%)`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n } else {\n return [\n decl(\"--ri-backdrop-grayscale\", `grayscale(${candidate.value.value})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n\n return null;\n });\n\n // Backdrop Hue Rotate\n\n utilities.functional(\"backdrop-hue-rotate\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-backdrop-hue-rotate\", `hue-rotate(${num}deg)`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n } else {\n return [\n decl(\"--ri-backdrop-hue-rotate\", `hue-rotate(${candidate.value.value})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n\n return null;\n });\n\n // Backdrop Invert\n\n utilities.functional(\"backdrop-invert\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"--ri-backdrop-invert\", \"invert(100%)\"), decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE)];\n }\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-backdrop-invert\", `invert(${num}%)`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n } else {\n return [\n decl(\"--ri-backdrop-invert\", `invert(${candidate.value.value})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n\n return null;\n });\n\n // Backdrop Opacity\n\n utilities.functional(\"backdrop-opacity\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-backdrop-opacity\", `opacity(${num / 100})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n } else {\n return [\n decl(\"--ri-backdrop-opacity\", `opacity(${candidate.value.value})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n\n return null;\n });\n\n // Backdrop Saturate\n\n utilities.functional(\"backdrop-saturate\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\"--ri-backdrop-saturate\", `saturate(${num / 100})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n } else {\n return [\n decl(\"--ri-backdrop-saturate\", `saturate(${candidate.value.value})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n\n return null;\n });\n\n // Backdrop Sepia\n\n utilities.functional(\"backdrop-sepia\", (candidate) => {\n if (!candidate.value) {\n return [decl(\"--ri-backdrop-sepia\", \"sepia(100%)\"), decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE)];\n }\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-backdrop-sepia\", `sepia(${num}%)`), decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE)];\n }\n } else {\n return [\n decl(\"--ri-backdrop-sepia\", `sepia(${candidate.value.value})`),\n decl(\"backdrop-filter\", BACKDROP_FILTER_VALUE),\n ];\n }\n\n return null;\n });\n\n // Filter (direct/arbitrary)\n\n utilities.static(\"filter-none\", staticUtility([[\"filter\", \"none\"]]));\n\n utilities.functional(\"filter\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"filter\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Backdrop Filter (direct/arbitrary)\n\n utilities.static(\"backdrop-filter-none\", staticUtility([[\"backdrop-filter\", \"none\"]]));\n\n utilities.functional(\"backdrop-filter\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"backdrop-filter\", candidate.value.value)];\n }\n\n return null;\n });\n}\n","/**\n * Interactivity Utilities\n *\n * Cursor, user-select, pointer-events, resize, scroll, and touch utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { FunctionalCandidate } from \"../candidate\";\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\nexport function registerInteractivityUtilities(utilities: Utilities, _theme: Theme): void {\n // Accent Color\n\n utilities.static(\"accent-auto\", staticUtility([[\"accent-color\", \"auto\"]]));\n\n utilities.functional(\"accent\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n if (candidate.value.value === \"auto\") {\n return [decl(\"accent-color\", \"auto\")];\n }\n\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"accent-color\", color)];\n } else {\n return [decl(\"accent-color\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Appearance\n\n utilities.static(\"appearance-none\", staticUtility([[\"appearance\", \"none\"]]));\n utilities.static(\"appearance-auto\", staticUtility([[\"appearance\", \"auto\"]]));\n\n // Cursor\n\n utilities.static(\"cursor-auto\", staticUtility([[\"cursor\", \"auto\"]]));\n utilities.static(\"cursor-default\", staticUtility([[\"cursor\", \"default\"]]));\n utilities.static(\"cursor-pointer\", staticUtility([[\"cursor\", \"pointer\"]]));\n utilities.static(\"cursor-wait\", staticUtility([[\"cursor\", \"wait\"]]));\n utilities.static(\"cursor-text\", staticUtility([[\"cursor\", \"text\"]]));\n utilities.static(\"cursor-move\", staticUtility([[\"cursor\", \"move\"]]));\n utilities.static(\"cursor-help\", staticUtility([[\"cursor\", \"help\"]]));\n utilities.static(\"cursor-not-allowed\", staticUtility([[\"cursor\", \"not-allowed\"]]));\n utilities.static(\"cursor-none\", staticUtility([[\"cursor\", \"none\"]]));\n utilities.static(\"cursor-context-menu\", staticUtility([[\"cursor\", \"context-menu\"]]));\n utilities.static(\"cursor-progress\", staticUtility([[\"cursor\", \"progress\"]]));\n utilities.static(\"cursor-cell\", staticUtility([[\"cursor\", \"cell\"]]));\n utilities.static(\"cursor-crosshair\", staticUtility([[\"cursor\", \"crosshair\"]]));\n utilities.static(\"cursor-vertical-text\", staticUtility([[\"cursor\", \"vertical-text\"]]));\n utilities.static(\"cursor-alias\", staticUtility([[\"cursor\", \"alias\"]]));\n utilities.static(\"cursor-copy\", staticUtility([[\"cursor\", \"copy\"]]));\n utilities.static(\"cursor-no-drop\", staticUtility([[\"cursor\", \"no-drop\"]]));\n utilities.static(\"cursor-grab\", staticUtility([[\"cursor\", \"grab\"]]));\n utilities.static(\"cursor-grabbing\", staticUtility([[\"cursor\", \"grabbing\"]]));\n utilities.static(\"cursor-all-scroll\", staticUtility([[\"cursor\", \"all-scroll\"]]));\n utilities.static(\"cursor-col-resize\", staticUtility([[\"cursor\", \"col-resize\"]]));\n utilities.static(\"cursor-row-resize\", staticUtility([[\"cursor\", \"row-resize\"]]));\n utilities.static(\"cursor-n-resize\", staticUtility([[\"cursor\", \"n-resize\"]]));\n utilities.static(\"cursor-e-resize\", staticUtility([[\"cursor\", \"e-resize\"]]));\n utilities.static(\"cursor-s-resize\", staticUtility([[\"cursor\", \"s-resize\"]]));\n utilities.static(\"cursor-w-resize\", staticUtility([[\"cursor\", \"w-resize\"]]));\n utilities.static(\"cursor-ne-resize\", staticUtility([[\"cursor\", \"ne-resize\"]]));\n utilities.static(\"cursor-nw-resize\", staticUtility([[\"cursor\", \"nw-resize\"]]));\n utilities.static(\"cursor-se-resize\", staticUtility([[\"cursor\", \"se-resize\"]]));\n utilities.static(\"cursor-sw-resize\", staticUtility([[\"cursor\", \"sw-resize\"]]));\n utilities.static(\"cursor-ew-resize\", staticUtility([[\"cursor\", \"ew-resize\"]]));\n utilities.static(\"cursor-ns-resize\", staticUtility([[\"cursor\", \"ns-resize\"]]));\n utilities.static(\"cursor-nesw-resize\", staticUtility([[\"cursor\", \"nesw-resize\"]]));\n utilities.static(\"cursor-nwse-resize\", staticUtility([[\"cursor\", \"nwse-resize\"]]));\n utilities.static(\"cursor-zoom-in\", staticUtility([[\"cursor\", \"zoom-in\"]]));\n utilities.static(\"cursor-zoom-out\", staticUtility([[\"cursor\", \"zoom-out\"]]));\n\n utilities.functional(\"cursor\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"cursor\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Caret Color\n\n utilities.functional(\"caret\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"caret-color\", color)];\n\n if (candidate.value.value === \"transparent\") {\n return [decl(\"caret-color\", \"transparent\")];\n }\n } else {\n return [decl(\"caret-color\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Pointer Events\n\n utilities.static(\"pointer-events-none\", staticUtility([[\"pointer-events\", \"none\"]]));\n utilities.static(\"pointer-events-auto\", staticUtility([[\"pointer-events\", \"auto\"]]));\n\n // Resize\n\n utilities.static(\"resize-none\", staticUtility([[\"resize\", \"none\"]]));\n utilities.static(\"resize-y\", staticUtility([[\"resize\", \"vertical\"]]));\n utilities.static(\"resize-x\", staticUtility([[\"resize\", \"horizontal\"]]));\n utilities.static(\"resize\", staticUtility([[\"resize\", \"both\"]]));\n\n // Scroll Behavior\n\n utilities.static(\"scroll-auto\", staticUtility([[\"scroll-behavior\", \"auto\"]]));\n utilities.static(\"scroll-smooth\", staticUtility([[\"scroll-behavior\", \"smooth\"]]));\n\n // Scroll Margin\n\n const resolveScrollSpacing = (candidate: FunctionalCandidate, theme: Theme): string | null => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--spacing-${candidate.value.value}`);\n if (value) return value;\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return `${num * 0.25}rem`;\n }\n return null;\n }\n\n return candidate.value.value;\n };\n\n utilities.functional(\"scroll-m\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin\", value)];\n });\n\n utilities.functional(\"scroll-mx\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-left\", value), decl(\"scroll-margin-right\", value)];\n });\n\n utilities.functional(\"scroll-my\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-top\", value), decl(\"scroll-margin-bottom\", value)];\n });\n\n utilities.functional(\"scroll-ms\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-inline-start\", value)];\n });\n\n utilities.functional(\"scroll-me\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-inline-end\", value)];\n });\n\n utilities.functional(\"scroll-mbs\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-block-start\", value)];\n });\n\n utilities.functional(\"scroll-mbe\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-block-end\", value)];\n });\n\n utilities.functional(\"scroll-mt\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-top\", value)];\n });\n\n utilities.functional(\"scroll-mr\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-right\", value)];\n });\n\n utilities.functional(\"scroll-mb\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-bottom\", value)];\n });\n\n utilities.functional(\"scroll-ml\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-margin-left\", value)];\n });\n\n // Scroll Padding\n\n utilities.functional(\"scroll-p\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding\", value)];\n });\n\n utilities.functional(\"scroll-px\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-left\", value), decl(\"scroll-padding-right\", value)];\n });\n\n utilities.functional(\"scroll-py\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-top\", value), decl(\"scroll-padding-bottom\", value)];\n });\n\n utilities.functional(\"scroll-ps\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-inline-start\", value)];\n });\n\n utilities.functional(\"scroll-pe\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-inline-end\", value)];\n });\n\n utilities.functional(\"scroll-pbs\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-block-start\", value)];\n });\n\n utilities.functional(\"scroll-pbe\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-block-end\", value)];\n });\n\n utilities.functional(\"scroll-pt\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-top\", value)];\n });\n\n utilities.functional(\"scroll-pr\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-right\", value)];\n });\n\n utilities.functional(\"scroll-pb\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-bottom\", value)];\n });\n\n utilities.functional(\"scroll-pl\", (candidate, theme) => {\n const value = resolveScrollSpacing(candidate, theme);\n if (!value) return null;\n return [decl(\"scroll-padding-left\", value)];\n });\n\n // Scroll Snap Align\n\n utilities.static(\"snap-start\", staticUtility([[\"scroll-snap-align\", \"start\"]]));\n utilities.static(\"snap-end\", staticUtility([[\"scroll-snap-align\", \"end\"]]));\n utilities.static(\"snap-center\", staticUtility([[\"scroll-snap-align\", \"center\"]]));\n utilities.static(\"snap-align-none\", staticUtility([[\"scroll-snap-align\", \"none\"]]));\n\n // Scroll Snap Stop\n\n utilities.static(\"snap-normal\", staticUtility([[\"scroll-snap-stop\", \"normal\"]]));\n utilities.static(\"snap-always\", staticUtility([[\"scroll-snap-stop\", \"always\"]]));\n\n // Scroll Snap Type\n\n utilities.static(\"snap-none\", staticUtility([[\"scroll-snap-type\", \"none\"]]));\n utilities.static(\"snap-x\", staticUtility([[\"scroll-snap-type\", \"x var(--ri-scroll-snap-strictness)\"]]));\n utilities.static(\"snap-y\", staticUtility([[\"scroll-snap-type\", \"y var(--ri-scroll-snap-strictness)\"]]));\n utilities.static(\"snap-both\", staticUtility([[\"scroll-snap-type\", \"both var(--ri-scroll-snap-strictness)\"]]));\n utilities.static(\"snap-mandatory\", staticUtility([[\"--ri-scroll-snap-strictness\", \"mandatory\"]]));\n utilities.static(\"snap-proximity\", staticUtility([[\"--ri-scroll-snap-strictness\", \"proximity\"]]));\n\n // Touch Action\n\n utilities.static(\"touch-auto\", staticUtility([[\"touch-action\", \"auto\"]]));\n utilities.static(\"touch-none\", staticUtility([[\"touch-action\", \"none\"]]));\n utilities.static(\"touch-pan-x\", staticUtility([[\"touch-action\", \"pan-x\"]]));\n utilities.static(\"touch-pan-left\", staticUtility([[\"touch-action\", \"pan-left\"]]));\n utilities.static(\"touch-pan-right\", staticUtility([[\"touch-action\", \"pan-right\"]]));\n utilities.static(\"touch-pan-y\", staticUtility([[\"touch-action\", \"pan-y\"]]));\n utilities.static(\"touch-pan-up\", staticUtility([[\"touch-action\", \"pan-up\"]]));\n utilities.static(\"touch-pan-down\", staticUtility([[\"touch-action\", \"pan-down\"]]));\n utilities.static(\"touch-pinch-zoom\", staticUtility([[\"touch-action\", \"pinch-zoom\"]]));\n utilities.static(\"touch-manipulation\", staticUtility([[\"touch-action\", \"manipulation\"]]));\n\n // User Select\n\n utilities.static(\"select-none\", staticUtility([[\"user-select\", \"none\"]]));\n utilities.static(\"select-text\", staticUtility([[\"user-select\", \"text\"]]));\n utilities.static(\"select-all\", staticUtility([[\"user-select\", \"all\"]]));\n utilities.static(\"select-auto\", staticUtility([[\"user-select\", \"auto\"]]));\n\n // Will Change\n\n utilities.static(\"will-change-auto\", staticUtility([[\"will-change\", \"auto\"]]));\n utilities.static(\"will-change-scroll\", staticUtility([[\"will-change\", \"scroll-position\"]]));\n utilities.static(\"will-change-contents\", staticUtility([[\"will-change\", \"contents\"]]));\n utilities.static(\"will-change-transform\", staticUtility([[\"will-change\", \"transform\"]]));\n\n utilities.functional(\"will-change\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"will-change\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Color Scheme\n\n utilities.static(\"scheme-normal\", staticUtility([[\"color-scheme\", \"normal\"]]));\n utilities.static(\"scheme-light\", staticUtility([[\"color-scheme\", \"light\"]]));\n utilities.static(\"scheme-dark\", staticUtility([[\"color-scheme\", \"dark\"]]));\n utilities.static(\"scheme-light-dark\", staticUtility([[\"color-scheme\", \"light dark\"]]));\n utilities.static(\"scheme-only-light\", staticUtility([[\"color-scheme\", \"only light\"]]));\n utilities.static(\"scheme-only-dark\", staticUtility([[\"color-scheme\", \"only dark\"]]));\n\n // Forced Color Adjust\n\n utilities.static(\"forced-color-adjust-auto\", staticUtility([[\"forced-color-adjust\", \"auto\"]]));\n utilities.static(\"forced-color-adjust-none\", staticUtility([[\"forced-color-adjust\", \"none\"]]));\n}\n","/**\n * Transition and Animation Utilities\n *\n * Transition property, duration, timing, delay, and animation utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\nexport function registerTransitionUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Transition Property\n // ============================================\n\n utilities.static(\"transition-none\", staticUtility([[\"transition-property\", \"none\"]]));\n\n utilities.static(\n \"transition-all\",\n staticUtility([\n [\"transition-property\", \"all\"],\n [\"transition-timing-function\", \"cubic-bezier(0.4, 0, 0.2, 1)\"],\n [\"transition-duration\", \"150ms\"],\n ])\n );\n\n utilities.static(\n \"transition\",\n staticUtility([\n [\n \"transition-property\",\n \"color, background-color, border-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter, content-visibility, overlay\",\n ],\n [\"transition-timing-function\", \"cubic-bezier(0.4, 0, 0.2, 1)\"],\n [\"transition-duration\", \"150ms\"],\n ])\n );\n\n utilities.static(\n \"transition-colors\",\n staticUtility([\n [\"transition-property\", \"color, background-color, border-color, text-decoration-color, fill, stroke\"],\n [\"transition-timing-function\", \"cubic-bezier(0.4, 0, 0.2, 1)\"],\n [\"transition-duration\", \"150ms\"],\n ])\n );\n\n utilities.static(\n \"transition-opacity\",\n staticUtility([\n [\"transition-property\", \"opacity\"],\n [\"transition-timing-function\", \"cubic-bezier(0.4, 0, 0.2, 1)\"],\n [\"transition-duration\", \"150ms\"],\n ])\n );\n\n utilities.static(\n \"transition-shadow\",\n staticUtility([\n [\"transition-property\", \"box-shadow\"],\n [\"transition-timing-function\", \"cubic-bezier(0.4, 0, 0.2, 1)\"],\n [\"transition-duration\", \"150ms\"],\n ])\n );\n\n utilities.static(\n \"transition-transform\",\n staticUtility([\n [\"transition-property\", \"transform\"],\n [\"transition-timing-function\", \"cubic-bezier(0.4, 0, 0.2, 1)\"],\n [\"transition-duration\", \"150ms\"],\n ])\n );\n\n utilities.functional(\"transition\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"transition-property\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Transition Duration\n // ============================================\n\n utilities.functional(\"duration\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n // Handle initial keyword\n if (candidate.value.value === \"initial\") {\n return [decl(\"transition-duration\", \"initial\")];\n }\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"transition-duration\", `${num}ms`)];\n }\n } else {\n return [decl(\"transition-duration\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Transition Timing Function\n // ============================================\n\n utilities.static(\"ease-linear\", staticUtility([[\"transition-timing-function\", \"linear\"]]));\n utilities.static(\"ease-in\", staticUtility([[\"transition-timing-function\", \"cubic-bezier(0.4, 0, 1, 1)\"]]));\n utilities.static(\"ease-out\", staticUtility([[\"transition-timing-function\", \"cubic-bezier(0, 0, 0.2, 1)\"]]));\n utilities.static(\"ease-in-out\", staticUtility([[\"transition-timing-function\", \"cubic-bezier(0.4, 0, 0.2, 1)\"]]));\n\n utilities.functional(\"ease\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"transition-timing-function\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Transition Delay\n // ============================================\n\n utilities.functional(\"delay\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"transition-delay\", `${num}ms`)];\n }\n } else {\n return [decl(\"transition-delay\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Animation\n // ============================================\n\n utilities.static(\"animate-none\", staticUtility([[\"animation\", \"none\"]]));\n\n utilities.static(\"animate-spin\", staticUtility([[\"animation\", \"spin 1s linear infinite\"]]));\n\n utilities.static(\"animate-ping\", staticUtility([[\"animation\", \"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite\"]]));\n\n utilities.static(\"animate-pulse\", staticUtility([[\"animation\", \"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite\"]]));\n\n utilities.static(\"animate-bounce\", staticUtility([[\"animation\", \"bounce 1s infinite\"]]));\n\n utilities.functional(\"animate\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = theme.get(`--animate-${candidate.value.value}`);\n if (value) return [decl(\"animation\", value)];\n } else {\n return [decl(\"animation\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Animation Duration\n // ============================================\n\n utilities.functional(\"animation-duration\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"animation-duration\", `${num}ms`)];\n }\n } else {\n return [decl(\"animation-duration\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Animation Timing Function\n // ============================================\n\n utilities.static(\"animation-ease-linear\", staticUtility([[\"animation-timing-function\", \"linear\"]]));\n utilities.static(\"animation-ease-in\", staticUtility([[\"animation-timing-function\", \"cubic-bezier(0.4, 0, 1, 1)\"]]));\n utilities.static(\n \"animation-ease-out\",\n staticUtility([[\"animation-timing-function\", \"cubic-bezier(0, 0, 0.2, 1)\"]])\n );\n utilities.static(\n \"animation-ease-in-out\",\n staticUtility([[\"animation-timing-function\", \"cubic-bezier(0.4, 0, 0.2, 1)\"]])\n );\n\n // ============================================\n // Animation Delay\n // ============================================\n\n utilities.functional(\"animation-delay\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"animation-delay\", `${num}ms`)];\n }\n } else {\n return [decl(\"animation-delay\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Animation Iteration Count\n // ============================================\n\n utilities.static(\"animate-infinite\", staticUtility([[\"animation-iteration-count\", \"infinite\"]]));\n utilities.static(\"animate-once\", staticUtility([[\"animation-iteration-count\", \"1\"]]));\n\n utilities.functional(\"animation-iteration\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"animation-iteration-count\", String(num))];\n }\n } else {\n return [decl(\"animation-iteration-count\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Animation Direction\n // ============================================\n\n utilities.static(\"animation-normal\", staticUtility([[\"animation-direction\", \"normal\"]]));\n utilities.static(\"animation-reverse\", staticUtility([[\"animation-direction\", \"reverse\"]]));\n utilities.static(\"animation-alternate\", staticUtility([[\"animation-direction\", \"alternate\"]]));\n utilities.static(\"animation-alternate-reverse\", staticUtility([[\"animation-direction\", \"alternate-reverse\"]]));\n\n // ============================================\n // Animation Fill Mode\n // ============================================\n\n utilities.static(\"animation-fill-none\", staticUtility([[\"animation-fill-mode\", \"none\"]]));\n utilities.static(\"animation-fill-forwards\", staticUtility([[\"animation-fill-mode\", \"forwards\"]]));\n utilities.static(\"animation-fill-backwards\", staticUtility([[\"animation-fill-mode\", \"backwards\"]]));\n utilities.static(\"animation-fill-both\", staticUtility([[\"animation-fill-mode\", \"both\"]]));\n\n // ============================================\n // Animation Play State\n // ============================================\n\n utilities.static(\"animation-running\", staticUtility([[\"animation-play-state\", \"running\"]]));\n utilities.static(\"animation-paused\", staticUtility([[\"animation-play-state\", \"paused\"]]));\n\n // ============================================\n // Transition Behavior\n // ============================================\n\n utilities.static(\"transition-discrete\", staticUtility([[\"transition-behavior\", \"allow-discrete\"]]));\n utilities.static(\"transition-normal\", staticUtility([[\"transition-behavior\", \"normal\"]]));\n}\n","/**\n * Enter/Exit Animation Utilities\n *\n * Derived from tw-animate-css by Wombosvideo (Luca Bosin)\n * https://github.com/Wombosvideo/tw-animate-css\n * Licensed under MIT License\n *\n * CSS variable-driven animations for enter/exit transitions.\n * Compose utilities to build complex animations:\n * class=\"animate-in fade-in zoom-in-95 slide-in-from-bottom-4\"\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport type { Utilities } from \"./utilities\";\n\n// ============================================\n// Spacing multiplier for slide utilities\n// ============================================\nconst SPACING_VAR = \"var(--spacing, 0.25rem)\";\n\n// Pre-compiled regex patterns for slide utilities (hoisted to avoid recreation on every call)\nconst SLIDE_IN_PATTERN = /^in-from-(top|bottom|left|right)-(\\d+)$/;\nconst SLIDE_OUT_PATTERN = /^out-to-(top|bottom|left|right)-(\\d+)$/;\n\n// ============================================\n// Duration/Delay scale values (ms)\n// ============================================\nconst durationScale: Record<string, string> = {\n \"0\": \"0ms\",\n \"75\": \"75ms\",\n \"100\": \"100ms\",\n \"150\": \"150ms\",\n \"200\": \"200ms\",\n \"300\": \"300ms\",\n \"500\": \"500ms\",\n \"700\": \"700ms\",\n \"1000\": \"1000ms\",\n};\n\nexport function registerAnimationUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Animate utility (handles in/out + theme lookup + control)\n // Parses: animate-in, animate-out, animate-duration-200, etc.\n // ============================================\n\n utilities.functional(\"animate\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n // Handle animate-in\n if (val === \"in\") {\n return [\n decl(\"animation-name\", \"ri-enter\"),\n decl(\"animation-duration\", \"var(--ri-animate-duration, 150ms)\"),\n decl(\"--ri-enter-opacity\", \"initial\"),\n decl(\"--ri-enter-scale\", \"initial\"),\n decl(\"--ri-enter-rotate\", \"initial\"),\n decl(\"--ri-enter-translate-x\", \"initial\"),\n decl(\"--ri-enter-translate-y\", \"initial\"),\n decl(\"--ri-enter-blur\", \"initial\"),\n ];\n }\n\n // Handle animate-out\n if (val === \"out\") {\n return [\n decl(\"animation-name\", \"ri-exit\"),\n decl(\"animation-duration\", \"var(--ri-animate-duration, 150ms)\"),\n decl(\"--ri-exit-opacity\", \"initial\"),\n decl(\"--ri-exit-scale\", \"initial\"),\n decl(\"--ri-exit-rotate\", \"initial\"),\n decl(\"--ri-exit-translate-x\", \"initial\"),\n decl(\"--ri-exit-translate-y\", \"initial\"),\n decl(\"--ri-exit-blur\", \"initial\"),\n ];\n }\n\n // Handle animate-duration-*\n if (val.startsWith(\"duration-\")) {\n const durVal = val.slice(9);\n const ms = durationScale[durVal] ?? `${durVal}ms`;\n return [decl(\"--ri-animate-duration\", ms), decl(\"animation-duration\", ms)];\n }\n\n // Handle animate-delay-*\n if (val.startsWith(\"delay-\")) {\n const delVal = val.slice(6);\n const ms = durationScale[delVal] ?? `${delVal}ms`;\n return [decl(\"animation-delay\", ms)];\n }\n\n // Handle animation direction\n if (val === \"normal\") return [decl(\"animation-direction\", \"normal\")];\n if (val === \"reverse\") return [decl(\"animation-direction\", \"reverse\")];\n if (val === \"alternate\") return [decl(\"animation-direction\", \"alternate\")];\n if (val === \"alternate-reverse\") return [decl(\"animation-direction\", \"alternate-reverse\")];\n\n // Handle animation fill mode\n if (val === \"fill-none\") return [decl(\"animation-fill-mode\", \"none\")];\n if (val === \"fill-forwards\") return [decl(\"animation-fill-mode\", \"forwards\")];\n if (val === \"fill-backwards\") return [decl(\"animation-fill-mode\", \"backwards\")];\n if (val === \"fill-both\") return [decl(\"animation-fill-mode\", \"both\")];\n\n // Handle animation iteration\n if (val === \"once\") return [decl(\"animation-iteration-count\", \"1\")];\n if (val === \"twice\") return [decl(\"animation-iteration-count\", \"2\")];\n if (val === \"infinite\") return [decl(\"animation-iteration-count\", \"infinite\")];\n\n // Handle animation play state\n if (val === \"running\") return [decl(\"animation-play-state\", \"running\")];\n if (val === \"paused\") return [decl(\"animation-play-state\", \"paused\")];\n\n // Handle animation easing\n if (val === \"ease-linear\") return [decl(\"animation-timing-function\", \"linear\")];\n if (val === \"ease-in\") return [decl(\"animation-timing-function\", \"cubic-bezier(0.4, 0, 1, 1)\")];\n if (val === \"ease-out\") return [decl(\"animation-timing-function\", \"cubic-bezier(0, 0, 0.2, 1)\")];\n if (val === \"ease-in-out\") return [decl(\"animation-timing-function\", \"cubic-bezier(0.4, 0, 0.2, 1)\")];\n\n // Fall back to theme lookup for named animations (e.g., animate-spin, animate-accordion-down)\n const themeValue = theme.get(`--animate-${val}`);\n if (themeValue) return [decl(\"animation\", themeValue)];\n } else if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"animation\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Fade utilities\n // Parses: fade-in, fade-out, fade-in-50, fade-out-75\n // ============================================\n\n utilities.functional(\"fade\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"in\") return [decl(\"--ri-enter-opacity\", \"0\")];\n if (val === \"out\") return [decl(\"--ri-exit-opacity\", \"0\")];\n\n // fade-in-50 -> val = \"in-50\"\n if (val.startsWith(\"in-\")) {\n const num = Number(val.slice(3));\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-enter-opacity\", `${num / 100}`)];\n }\n }\n\n // fade-out-50\n if (val.startsWith(\"out-\")) {\n const num = Number(val.slice(4));\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-exit-opacity\", `${num / 100}`)];\n }\n }\n } else if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"--ri-enter-opacity\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Zoom utilities\n // Parses: zoom-in, zoom-out, zoom-in-95, zoom-out-50\n // ============================================\n\n utilities.functional(\"zoom\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"in\") return [decl(\"--ri-enter-scale\", \"0\")];\n if (val === \"out\") return [decl(\"--ri-exit-scale\", \"0\")];\n\n if (val.startsWith(\"in-\")) {\n const num = Number(val.slice(3));\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-enter-scale\", `${num / 100}`)];\n }\n }\n\n if (val.startsWith(\"out-\")) {\n const num = Number(val.slice(4));\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-exit-scale\", `${num / 100}`)];\n }\n }\n } else if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"--ri-enter-scale\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Spin utilities (for rotation in enter/exit animations)\n // Parses: spin-in, spin-out, spin-in-180, spin-out-90\n // ============================================\n\n utilities.functional(\"spin\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"in\") return [decl(\"--ri-enter-rotate\", \"-180deg\")];\n if (val === \"out\") return [decl(\"--ri-exit-rotate\", \"180deg\")];\n\n if (val.startsWith(\"in-\")) {\n const num = Number(val.slice(3));\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-enter-rotate\", `${num}deg`)];\n }\n }\n\n if (val.startsWith(\"out-\")) {\n const num = Number(val.slice(4));\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-exit-rotate\", `${num}deg`)];\n }\n }\n } else if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"--ri-enter-rotate\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Slide utilities\n // Parses: slide-in-from-top, slide-in-from-bottom-4, slide-out-to-left, etc.\n // ============================================\n\n utilities.functional(\"slide\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n // Slide in directions\n if (val === \"in-from-top\" || val === \"in-from-top-full\") {\n return [decl(\"--ri-enter-translate-y\", \"-100%\")];\n }\n if (val === \"in-from-bottom\" || val === \"in-from-bottom-full\") {\n return [decl(\"--ri-enter-translate-y\", \"100%\")];\n }\n if (val === \"in-from-left\" || val === \"in-from-left-full\") {\n return [decl(\"--ri-enter-translate-x\", \"-100%\")];\n }\n if (val === \"in-from-right\" || val === \"in-from-right-full\") {\n return [decl(\"--ri-enter-translate-x\", \"100%\")];\n }\n\n // Slide in with numeric value\n const slideInMatch = val.match(SLIDE_IN_PATTERN);\n if (slideInMatch) {\n const [, direction, numStr] = slideInMatch;\n const num = Number(numStr);\n if (!Number.isNaN(num)) {\n const isNegative = direction === \"top\" || direction === \"left\";\n const prop =\n direction === \"top\" || direction === \"bottom\"\n ? \"--ri-enter-translate-y\"\n : \"--ri-enter-translate-x\";\n const value = isNegative ? `calc(${num} * ${SPACING_VAR} * -1)` : `calc(${num} * ${SPACING_VAR})`;\n return [decl(prop, value)];\n }\n }\n\n // Slide out directions\n if (val === \"out-to-top\" || val === \"out-to-top-full\") {\n return [decl(\"--ri-exit-translate-y\", \"-100%\")];\n }\n if (val === \"out-to-bottom\" || val === \"out-to-bottom-full\") {\n return [decl(\"--ri-exit-translate-y\", \"100%\")];\n }\n if (val === \"out-to-left\" || val === \"out-to-left-full\") {\n return [decl(\"--ri-exit-translate-x\", \"-100%\")];\n }\n if (val === \"out-to-right\" || val === \"out-to-right-full\") {\n return [decl(\"--ri-exit-translate-x\", \"100%\")];\n }\n\n // Slide out with numeric value\n const slideOutMatch = val.match(SLIDE_OUT_PATTERN);\n if (slideOutMatch) {\n const [, direction, numStr] = slideOutMatch;\n const num = Number(numStr);\n if (!Number.isNaN(num)) {\n const isNegative = direction === \"top\" || direction === \"left\";\n const prop =\n direction === \"top\" || direction === \"bottom\"\n ? \"--ri-exit-translate-y\"\n : \"--ri-exit-translate-x\";\n const value = isNegative ? `calc(${num} * ${SPACING_VAR} * -1)` : `calc(${num} * ${SPACING_VAR})`;\n return [decl(prop, value)];\n }\n }\n }\n\n return null;\n });\n\n // ============================================\n // Blur utilities for enter/exit animations\n // Parses: blur-in, blur-out, blur-in-lg, blur-out-2xl\n // Note: These extend the existing blur functional but only handle in/out\n // ============================================\n\n utilities.functional(\"blur\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n // blur-in variants\n if (val === \"in\") return [decl(\"--ri-enter-blur\", \"4px\")];\n if (val === \"in-none\") return [decl(\"--ri-enter-blur\", \"0\")];\n if (val === \"in-sm\") return [decl(\"--ri-enter-blur\", \"4px\")];\n if (val === \"in-md\") return [decl(\"--ri-enter-blur\", \"8px\")];\n if (val === \"in-lg\") return [decl(\"--ri-enter-blur\", \"12px\")];\n if (val === \"in-xl\") return [decl(\"--ri-enter-blur\", \"16px\")];\n if (val === \"in-2xl\") return [decl(\"--ri-enter-blur\", \"24px\")];\n if (val === \"in-3xl\") return [decl(\"--ri-enter-blur\", \"40px\")];\n\n // blur-out variants\n if (val === \"out\") return [decl(\"--ri-exit-blur\", \"4px\")];\n if (val === \"out-none\") return [decl(\"--ri-exit-blur\", \"0\")];\n if (val === \"out-sm\") return [decl(\"--ri-exit-blur\", \"4px\")];\n if (val === \"out-md\") return [decl(\"--ri-exit-blur\", \"8px\")];\n if (val === \"out-lg\") return [decl(\"--ri-exit-blur\", \"12px\")];\n if (val === \"out-xl\") return [decl(\"--ri-exit-blur\", \"16px\")];\n if (val === \"out-2xl\") return [decl(\"--ri-exit-blur\", \"24px\")];\n if (val === \"out-3xl\") return [decl(\"--ri-exit-blur\", \"40px\")];\n }\n\n // Don't return anything for other blur values - let the filter blur handle them\n return null;\n });\n}\n","/**\n * SVG Utilities\n *\n * Comprehensive SVG utilities including:\n * - Fill (color, opacity, rule)\n * - Stroke (color, width, linecap, linejoin, dash, opacity)\n * - Paint order\n * - Vector effects\n * - Clip rule\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\n// Pre-compiled pattern for underscore-to-space conversion (hoisted to avoid recreation)\nconst UNDERSCORE_PATTERN = /_/g;\n\n// Pre-defined opacity values (0-100 in steps of 5)\nconst SVG_OPACITY_VALUES: Record<string, string> = {\n \"0\": \"0\",\n \"5\": \"0.05\",\n \"10\": \"0.1\",\n \"15\": \"0.15\",\n \"20\": \"0.2\",\n \"25\": \"0.25\",\n \"30\": \"0.3\",\n \"35\": \"0.35\",\n \"40\": \"0.4\",\n \"45\": \"0.45\",\n \"50\": \"0.5\",\n \"55\": \"0.55\",\n \"60\": \"0.6\",\n \"65\": \"0.65\",\n \"70\": \"0.7\",\n \"75\": \"0.75\",\n \"80\": \"0.8\",\n \"85\": \"0.85\",\n \"90\": \"0.9\",\n \"95\": \"0.95\",\n \"100\": \"1\",\n};\n\nexport function registerSvgUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Fill\n // ============================================\n\n utilities.static(\"fill-none\", staticUtility([[\"fill\", \"none\"]]));\n\n utilities.functional(\"fill\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n if (candidate.value.value === \"none\") {\n return [decl(\"fill\", \"none\")];\n }\n\n if (candidate.value.value === \"current\") {\n return [decl(\"fill\", \"currentColor\")];\n }\n\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"fill\", color)];\n } else {\n return [decl(\"fill\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Stroke Color\n // ============================================\n\n utilities.static(\"stroke-none\", staticUtility([[\"stroke\", \"none\"]]));\n\n utilities.functional(\"stroke\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n if (candidate.value.value === \"none\") {\n return [decl(\"stroke\", \"none\")];\n }\n\n if (candidate.value.value === \"current\") {\n return [decl(\"stroke\", \"currentColor\")];\n }\n\n // Check for stroke width (numeric)\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"stroke-width\", String(num))];\n }\n\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return [decl(\"stroke\", color)];\n } else {\n return [decl(\"stroke\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Stroke Linecap\n // ============================================\n\n utilities.static(\"stroke-cap-butt\", staticUtility([[\"stroke-linecap\", \"butt\"]]));\n utilities.static(\"stroke-cap-round\", staticUtility([[\"stroke-linecap\", \"round\"]]));\n utilities.static(\"stroke-cap-square\", staticUtility([[\"stroke-linecap\", \"square\"]]));\n\n // ============================================\n // Stroke Linejoin\n // ============================================\n\n utilities.static(\"stroke-join-arcs\", staticUtility([[\"stroke-linejoin\", \"arcs\"]]));\n utilities.static(\"stroke-join-bevel\", staticUtility([[\"stroke-linejoin\", \"bevel\"]]));\n utilities.static(\"stroke-join-miter\", staticUtility([[\"stroke-linejoin\", \"miter\"]]));\n utilities.static(\"stroke-join-miter-clip\", staticUtility([[\"stroke-linejoin\", \"miter-clip\"]]));\n utilities.static(\"stroke-join-round\", staticUtility([[\"stroke-linejoin\", \"round\"]]));\n\n // ============================================\n // Stroke Dash Array\n // ============================================\n\n utilities.static(\"stroke-dash-none\", staticUtility([[\"stroke-dasharray\", \"none\"]]));\n utilities.static(\"stroke-dash-dotted\", staticUtility([[\"stroke-dasharray\", \"1 3\"]]));\n utilities.static(\"stroke-dash-dashed\", staticUtility([[\"stroke-dasharray\", \"4 4\"]]));\n utilities.static(\"stroke-dash-long\", staticUtility([[\"stroke-dasharray\", \"8 4\"]]));\n utilities.static(\"stroke-dash-dense\", staticUtility([[\"stroke-dasharray\", \"2 2\"]]));\n utilities.static(\"stroke-dash-loose\", staticUtility([[\"stroke-dasharray\", \"6 6\"]]));\n utilities.static(\"stroke-dash-dot-dash\", staticUtility([[\"stroke-dasharray\", \"8 4 2 4\"]]));\n\n // Arbitrary stroke dash: stroke-dash-[4_2]\n utilities.functional(\"stroke-dash\", (candidate) => {\n if (!candidate.value) return null;\n if (candidate.value.kind === \"arbitrary\") {\n // Replace underscores with spaces for dasharray values\n const value = candidate.value.value.replace(UNDERSCORE_PATTERN, \" \");\n return [decl(\"stroke-dasharray\", value)];\n }\n return null;\n });\n\n // ============================================\n // Stroke Dash Offset\n // ============================================\n\n utilities.static(\"stroke-offset-0\", staticUtility([[\"stroke-dashoffset\", \"0\"]]));\n utilities.static(\"stroke-offset-1\", staticUtility([[\"stroke-dashoffset\", \"1\"]]));\n utilities.static(\"stroke-offset-2\", staticUtility([[\"stroke-dashoffset\", \"2\"]]));\n utilities.static(\"stroke-offset-4\", staticUtility([[\"stroke-dashoffset\", \"4\"]]));\n utilities.static(\"stroke-offset-8\", staticUtility([[\"stroke-dashoffset\", \"8\"]]));\n\n utilities.functional(\"stroke-offset\", (candidate) => {\n if (!candidate.value) return null;\n return [decl(\"stroke-dashoffset\", candidate.value.value)];\n });\n\n // ============================================\n // Stroke Miter Limit\n // ============================================\n\n utilities.static(\"stroke-miter-1\", staticUtility([[\"stroke-miterlimit\", \"1\"]]));\n utilities.static(\"stroke-miter-2\", staticUtility([[\"stroke-miterlimit\", \"2\"]]));\n utilities.static(\"stroke-miter-4\", staticUtility([[\"stroke-miterlimit\", \"4\"]]));\n utilities.static(\"stroke-miter-8\", staticUtility([[\"stroke-miterlimit\", \"8\"]]));\n\n utilities.functional(\"stroke-miter\", (candidate) => {\n if (!candidate.value) return null;\n return [decl(\"stroke-miterlimit\", candidate.value.value)];\n });\n\n // ============================================\n // Stroke Opacity\n // ============================================\n\n utilities.functional(\"stroke-opacity\", (candidate) => {\n if (!candidate.value) return null;\n if (candidate.value.kind === \"named\") {\n const opacity = SVG_OPACITY_VALUES[candidate.value.value];\n if (opacity) return [decl(\"stroke-opacity\", opacity)];\n } else {\n return [decl(\"stroke-opacity\", candidate.value.value)];\n }\n return null;\n });\n\n // ============================================\n // Fill Opacity\n // ============================================\n\n utilities.functional(\"fill-opacity\", (candidate) => {\n if (!candidate.value) return null;\n if (candidate.value.kind === \"named\") {\n const opacity = SVG_OPACITY_VALUES[candidate.value.value];\n if (opacity) return [decl(\"fill-opacity\", opacity)];\n } else {\n return [decl(\"fill-opacity\", candidate.value.value)];\n }\n return null;\n });\n\n // ============================================\n // Fill Rule\n // ============================================\n\n utilities.static(\"fill-rule-nonzero\", staticUtility([[\"fill-rule\", \"nonzero\"]]));\n utilities.static(\"fill-rule-evenodd\", staticUtility([[\"fill-rule\", \"evenodd\"]]));\n\n // ============================================\n // Clip Rule\n // ============================================\n\n utilities.static(\"clip-rule-nonzero\", staticUtility([[\"clip-rule\", \"nonzero\"]]));\n utilities.static(\"clip-rule-evenodd\", staticUtility([[\"clip-rule\", \"evenodd\"]]));\n\n // ============================================\n // Paint Order\n // ============================================\n\n utilities.static(\"paint-normal\", staticUtility([[\"paint-order\", \"normal\"]]));\n utilities.static(\"paint-stroke\", staticUtility([[\"paint-order\", \"stroke\"]]));\n utilities.static(\"paint-fill\", staticUtility([[\"paint-order\", \"fill\"]]));\n utilities.static(\"paint-markers\", staticUtility([[\"paint-order\", \"markers\"]]));\n\n // Two-value combinations\n utilities.static(\"paint-stroke-fill\", staticUtility([[\"paint-order\", \"stroke fill\"]]));\n utilities.static(\"paint-stroke-markers\", staticUtility([[\"paint-order\", \"stroke markers\"]]));\n utilities.static(\"paint-fill-stroke\", staticUtility([[\"paint-order\", \"fill stroke\"]]));\n utilities.static(\"paint-fill-markers\", staticUtility([[\"paint-order\", \"fill markers\"]]));\n utilities.static(\"paint-markers-stroke\", staticUtility([[\"paint-order\", \"markers stroke\"]]));\n utilities.static(\"paint-markers-fill\", staticUtility([[\"paint-order\", \"markers fill\"]]));\n\n // Three-value combinations\n utilities.static(\"paint-stroke-fill-markers\", staticUtility([[\"paint-order\", \"stroke fill markers\"]]));\n utilities.static(\"paint-stroke-markers-fill\", staticUtility([[\"paint-order\", \"stroke markers fill\"]]));\n utilities.static(\"paint-fill-stroke-markers\", staticUtility([[\"paint-order\", \"fill stroke markers\"]]));\n utilities.static(\"paint-fill-markers-stroke\", staticUtility([[\"paint-order\", \"fill markers stroke\"]]));\n utilities.static(\"paint-markers-stroke-fill\", staticUtility([[\"paint-order\", \"markers stroke fill\"]]));\n utilities.static(\"paint-markers-fill-stroke\", staticUtility([[\"paint-order\", \"markers fill stroke\"]]));\n\n // ============================================\n // Vector Effect\n // ============================================\n\n utilities.static(\"vector-none\", staticUtility([[\"vector-effect\", \"none\"]]));\n utilities.static(\"vector-non-scaling-stroke\", staticUtility([[\"vector-effect\", \"non-scaling-stroke\"]]));\n utilities.static(\"vector-non-scaling-size\", staticUtility([[\"vector-effect\", \"non-scaling-size\"]]));\n utilities.static(\"vector-non-rotation\", staticUtility([[\"vector-effect\", \"non-rotation\"]]));\n utilities.static(\"vector-fixed-position\", staticUtility([[\"vector-effect\", \"fixed-position\"]]));\n}\n","/**\n * Accessibility Utilities\n *\n * Screen reader only, focus visible, and other accessibility utilities.\n */\n\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\nexport function registerAccessibilityUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Screen Reader Only\n // ============================================\n\n utilities.static(\n \"sr-only\",\n staticUtility([\n [\"position\", \"absolute\"],\n [\"width\", \"1px\"],\n [\"height\", \"1px\"],\n [\"padding\", \"0\"],\n [\"margin\", \"-1px\"],\n [\"overflow\", \"hidden\"],\n [\"clip\", \"rect(0, 0, 0, 0)\"],\n [\"white-space\", \"nowrap\"],\n [\"border-width\", \"0\"],\n ])\n );\n\n utilities.static(\n \"not-sr-only\",\n staticUtility([\n [\"position\", \"static\"],\n [\"width\", \"auto\"],\n [\"height\", \"auto\"],\n [\"padding\", \"0\"],\n [\"margin\", \"0\"],\n [\"overflow\", \"visible\"],\n [\"clip\", \"auto\"],\n [\"white-space\", \"normal\"],\n ])\n );\n\n // ============================================\n // Forced Color Adjust\n // ============================================\n\n utilities.static(\"forced-color-adjust-auto\", staticUtility([[\"forced-color-adjust\", \"auto\"]]));\n utilities.static(\"forced-color-adjust-none\", staticUtility([[\"forced-color-adjust\", \"none\"]]));\n}\n","/**\n * Table Utilities\n *\n * Table layout, border collapse, and caption utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport type { FunctionalCandidate } from \"../candidate\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\nfunction resolveBorderSpacingValue(candidate: FunctionalCandidate, theme: Theme): string | null {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return candidate.value.value;\n }\n\n const themeValue = theme.get(`--spacing-${candidate.value.value}`);\n if (themeValue) return themeValue;\n\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return `${num * 0.25}rem`;\n }\n\n return null;\n}\n\nconst BORDER_SPACING_DECL = \"var(--ri-border-spacing-x) var(--ri-border-spacing-y)\";\n\nexport function registerTableUtilities(utilities: Utilities, _theme: Theme): void {\n utilities.static(\"border-collapse\", staticUtility([[\"border-collapse\", \"collapse\"]]));\n utilities.static(\"border-separate\", staticUtility([[\"border-collapse\", \"separate\"]]));\n\n utilities.functional(\"border-spacing\", (candidate, theme) => {\n const value = resolveBorderSpacingValue(candidate, theme);\n if (!value) return null;\n\n return [\n decl(\"--ri-border-spacing-x\", value),\n decl(\"--ri-border-spacing-y\", value),\n decl(\"border-spacing\", BORDER_SPACING_DECL),\n ];\n });\n\n utilities.functional(\"border-spacing-x\", (candidate, theme) => {\n const value = resolveBorderSpacingValue(candidate, theme);\n if (!value) return null;\n\n return [decl(\"--ri-border-spacing-x\", value), decl(\"border-spacing\", BORDER_SPACING_DECL)];\n });\n\n utilities.functional(\"border-spacing-y\", (candidate, theme) => {\n const value = resolveBorderSpacingValue(candidate, theme);\n if (!value) return null;\n\n return [decl(\"--ri-border-spacing-y\", value), decl(\"border-spacing\", BORDER_SPACING_DECL)];\n });\n\n // ============================================\n // Table Layout\n // ============================================\n\n utilities.static(\"table-auto\", staticUtility([[\"table-layout\", \"auto\"]]));\n utilities.static(\"table-fixed\", staticUtility([[\"table-layout\", \"fixed\"]]));\n\n // ============================================\n // Caption Side\n // ============================================\n\n utilities.static(\"caption-top\", staticUtility([[\"caption-side\", \"top\"]]));\n utilities.static(\"caption-bottom\", staticUtility([[\"caption-side\", \"bottom\"]]));\n}\n","/**\n * Background Utilities\n *\n * Background attachment, clip, origin, position, repeat, size, and gradient utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\n// Pre-defined gradient direction values (hoisted to avoid recreating on every call)\nconst LINEAR_GRADIENT_DIRECTIONS: Record<string, string> = {\n \"to-t\": \"to top\",\n \"to-tr\": \"to top right\",\n \"to-r\": \"to right\",\n \"to-br\": \"to bottom right\",\n \"to-b\": \"to bottom\",\n \"to-bl\": \"to bottom left\",\n \"to-l\": \"to left\",\n \"to-tl\": \"to top left\",\n};\n\n// Pre-defined radial gradient position values\nconst RADIAL_GRADIENT_POSITIONS: Record<string, string> = {\n \"at-t\": \"at top\",\n \"at-tr\": \"at top right\",\n \"at-r\": \"at right\",\n \"at-br\": \"at bottom right\",\n \"at-b\": \"at bottom\",\n \"at-bl\": \"at bottom left\",\n \"at-l\": \"at left\",\n \"at-tl\": \"at top left\",\n \"at-c\": \"at center\",\n};\n\n// ============================================\n// Gradient Helper Functions\n// ============================================\n\n/**\n * Build gradient color stops with position support.\n * Uses CSS custom properties for color and position values.\n *\n * Each stop includes:\n * - Color variable with fallback\n * - Position variable (empty by default, allowing CSS to auto-distribute)\n *\n * The --ri-gradient-interpolation variable stores the color interpolation mode\n * (e.g., \"in oklab\") for use with @supports queries or future enhancements.\n */\nfunction buildGradientStops(): string {\n return [\n \"var(--ri-gradient-from, transparent) var(--ri-gradient-from-position,)\",\n \"var(--ri-gradient-via, var(--ri-gradient-from, transparent)) var(--ri-gradient-via-position,)\",\n \"var(--ri-gradient-to, transparent) var(--ri-gradient-to-position,)\",\n ].join(\", \");\n}\n\n/**\n * Resolve gradient interpolation method from modifier.\n *\n * Supports:\n * - oklab (default)\n * - oklch\n * - srgb\n * - hsl\n * - longer (oklch longer hue)\n * - shorter (oklch shorter hue)\n * - increasing (oklch increasing hue)\n * - decreasing (oklch decreasing hue)\n */\nfunction resolveInterpolationMethod(modifier: { kind: string; value: string } | null): string {\n if (!modifier) return \"in oklab\";\n\n if (modifier.kind === \"named\") {\n switch (modifier.value) {\n case \"longer\":\n case \"shorter\":\n case \"increasing\":\n case \"decreasing\":\n return `in oklch ${modifier.value} hue`;\n case \"oklab\":\n case \"oklch\":\n case \"srgb\":\n case \"hsl\":\n case \"hwb\":\n case \"lch\":\n case \"lab\":\n case \"srgb-linear\":\n case \"display-p3\":\n case \"a98-rgb\":\n case \"prophoto-rgb\":\n case \"rec2020\":\n case \"xyz\":\n case \"xyz-d50\":\n case \"xyz-d65\":\n return `in ${modifier.value}`;\n default:\n return \"in oklab\";\n }\n } else if (modifier.kind === \"arbitrary\") {\n return modifier.value;\n }\n\n return \"in oklab\";\n}\n\nexport function registerBackgroundUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Background Attachment\n // ============================================\n\n utilities.static(\"bg-fixed\", staticUtility([[\"background-attachment\", \"fixed\"]]));\n utilities.static(\"bg-local\", staticUtility([[\"background-attachment\", \"local\"]]));\n utilities.static(\"bg-scroll\", staticUtility([[\"background-attachment\", \"scroll\"]]));\n\n // ============================================\n // Background Clip\n // ============================================\n\n utilities.static(\"bg-clip-border\", staticUtility([[\"background-clip\", \"border-box\"]]));\n utilities.static(\"bg-clip-padding\", staticUtility([[\"background-clip\", \"padding-box\"]]));\n utilities.static(\"bg-clip-content\", staticUtility([[\"background-clip\", \"content-box\"]]));\n utilities.static(\"bg-clip-text\", staticUtility([[\"background-clip\", \"text\"]]));\n\n // ============================================\n // Background Origin\n // ============================================\n\n utilities.static(\"bg-origin-border\", staticUtility([[\"background-origin\", \"border-box\"]]));\n utilities.static(\"bg-origin-padding\", staticUtility([[\"background-origin\", \"padding-box\"]]));\n utilities.static(\"bg-origin-content\", staticUtility([[\"background-origin\", \"content-box\"]]));\n\n // ============================================\n // Background Position\n // ============================================\n\n utilities.static(\"bg-bottom\", staticUtility([[\"background-position\", \"bottom\"]]));\n utilities.static(\"bg-center\", staticUtility([[\"background-position\", \"center\"]]));\n utilities.static(\"bg-left\", staticUtility([[\"background-position\", \"left\"]]));\n utilities.static(\"bg-bottom-left\", staticUtility([[\"background-position\", \"left bottom\"]]));\n utilities.static(\"bg-top-left\", staticUtility([[\"background-position\", \"left top\"]]));\n utilities.static(\"bg-right\", staticUtility([[\"background-position\", \"right\"]]));\n utilities.static(\"bg-bottom-right\", staticUtility([[\"background-position\", \"right bottom\"]]));\n utilities.static(\"bg-top-right\", staticUtility([[\"background-position\", \"right top\"]]));\n utilities.static(\"bg-top\", staticUtility([[\"background-position\", \"top\"]]));\n\n utilities.functional(\"bg-position\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"background-position\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Background Repeat\n // ============================================\n\n utilities.static(\"bg-repeat\", staticUtility([[\"background-repeat\", \"repeat\"]]));\n utilities.static(\"bg-no-repeat\", staticUtility([[\"background-repeat\", \"no-repeat\"]]));\n utilities.static(\"bg-repeat-x\", staticUtility([[\"background-repeat\", \"repeat-x\"]]));\n utilities.static(\"bg-repeat-y\", staticUtility([[\"background-repeat\", \"repeat-y\"]]));\n utilities.static(\"bg-repeat-round\", staticUtility([[\"background-repeat\", \"round\"]]));\n utilities.static(\"bg-repeat-space\", staticUtility([[\"background-repeat\", \"space\"]]));\n\n // ============================================\n // Background Size\n // ============================================\n\n utilities.static(\"bg-auto\", staticUtility([[\"background-size\", \"auto\"]]));\n utilities.static(\"bg-cover\", staticUtility([[\"background-size\", \"cover\"]]));\n utilities.static(\"bg-contain\", staticUtility([[\"background-size\", \"contain\"]]));\n\n utilities.functional(\"bg-size\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"background-size\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Background Image / Gradient\n // ============================================\n\n utilities.static(\"bg-none\", staticUtility([[\"background-image\", \"none\"]]));\n\n // Gradient directions (with position modifier support)\n const gradientStops = buildGradientStops();\n\n utilities.static(\n \"bg-gradient-to-t\",\n staticUtility([\n [\"--ri-gradient-position\", \"to top\"],\n [\"background-image\", `linear-gradient(var(--ri-gradient-position), ${gradientStops})`],\n ])\n );\n utilities.static(\n \"bg-gradient-to-tr\",\n staticUtility([\n [\"--ri-gradient-position\", \"to top right\"],\n [\"background-image\", `linear-gradient(var(--ri-gradient-position), ${gradientStops})`],\n ])\n );\n utilities.static(\n \"bg-gradient-to-r\",\n staticUtility([\n [\"--ri-gradient-position\", \"to right\"],\n [\"background-image\", `linear-gradient(var(--ri-gradient-position), ${gradientStops})`],\n ])\n );\n utilities.static(\n \"bg-gradient-to-br\",\n staticUtility([\n [\"--ri-gradient-position\", \"to bottom right\"],\n [\"background-image\", `linear-gradient(var(--ri-gradient-position), ${gradientStops})`],\n ])\n );\n utilities.static(\n \"bg-gradient-to-b\",\n staticUtility([\n [\"--ri-gradient-position\", \"to bottom\"],\n [\"background-image\", `linear-gradient(var(--ri-gradient-position), ${gradientStops})`],\n ])\n );\n utilities.static(\n \"bg-gradient-to-bl\",\n staticUtility([\n [\"--ri-gradient-position\", \"to bottom left\"],\n [\"background-image\", `linear-gradient(var(--ri-gradient-position), ${gradientStops})`],\n ])\n );\n utilities.static(\n \"bg-gradient-to-l\",\n staticUtility([\n [\"--ri-gradient-position\", \"to left\"],\n [\"background-image\", `linear-gradient(var(--ri-gradient-position), ${gradientStops})`],\n ])\n );\n utilities.static(\n \"bg-gradient-to-tl\",\n staticUtility([\n [\"--ri-gradient-position\", \"to top left\"],\n [\"background-image\", `linear-gradient(var(--ri-gradient-position), ${gradientStops})`],\n ])\n );\n\n // Radial gradients\n utilities.static(\"bg-gradient-radial\", staticUtility([[\"background-image\", `radial-gradient(${gradientStops})`]]));\n\n // Conic gradients\n utilities.static(\"bg-gradient-conic\", staticUtility([[\"background-image\", `conic-gradient(${gradientStops})`]]));\n\n // ============================================\n // Modern Gradient Utilities (bg-linear, bg-radial, bg-conic)\n // ============================================\n\n // Linear gradient with direction support and interpolation method modifiers\n // Usage: bg-linear-45, bg-linear-to-r, bg-linear-45/oklch, bg-linear-to-r/longer\n utilities.functional(\"bg-linear\", (candidate) => {\n const stops = buildGradientStops();\n const interpolation = resolveInterpolationMethod(candidate.modifier);\n\n if (!candidate.value) {\n // Default: to bottom\n return [\n decl(\"--ri-gradient-position\", \"to bottom\"),\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `linear-gradient(${interpolation}, var(--ri-gradient-position), ${stops})`),\n ];\n }\n\n if (candidate.value.kind === \"named\") {\n const dir = LINEAR_GRADIENT_DIRECTIONS[candidate.value.value];\n if (dir) {\n return [\n decl(\"--ri-gradient-position\", dir),\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\n \"background-image\",\n `linear-gradient(${interpolation}, var(--ri-gradient-position), ${stops})`\n ),\n ];\n }\n\n // Angle in degrees\n const deg = Number(candidate.value.value);\n if (!Number.isNaN(deg)) {\n return [\n decl(\"--ri-gradient-position\", `${deg}deg`),\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\n \"background-image\",\n `linear-gradient(${interpolation}, var(--ri-gradient-position), ${stops})`\n ),\n ];\n }\n } else {\n return [\n decl(\"--ri-gradient-position\", candidate.value.value),\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `linear-gradient(${interpolation}, var(--ri-gradient-position), ${stops})`),\n ];\n }\n\n return null;\n });\n\n // Radial gradient with position support and interpolation method modifiers\n // Usage: bg-radial, bg-radial-at-t, bg-radial/oklch, bg-radial-at-c/longer\n utilities.functional(\"bg-radial\", (candidate) => {\n const stops = buildGradientStops();\n const interpolation = resolveInterpolationMethod(candidate.modifier);\n\n if (!candidate.value) {\n return [\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `radial-gradient(${interpolation}, ${stops})`),\n ];\n }\n\n if (candidate.value.kind === \"named\") {\n const pos = RADIAL_GRADIENT_POSITIONS[candidate.value.value];\n if (pos) {\n return [\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `radial-gradient(${interpolation}, ${pos}, ${stops})`),\n ];\n }\n } else {\n return [\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `radial-gradient(${interpolation}, ${candidate.value.value}, ${stops})`),\n ];\n }\n\n return null;\n });\n\n // Conic gradient with angle/position support and interpolation method modifiers\n // Usage: bg-conic, bg-conic-90, bg-conic/oklch, bg-conic-45/longer\n utilities.functional(\"bg-conic\", (candidate) => {\n const stops = buildGradientStops();\n const interpolation = resolveInterpolationMethod(candidate.modifier);\n\n if (!candidate.value) {\n return [\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `conic-gradient(${interpolation}, ${stops})`),\n ];\n }\n\n if (candidate.value.kind === \"named\") {\n // Angle in degrees\n const deg = Number(candidate.value.value);\n if (!Number.isNaN(deg)) {\n return [\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `conic-gradient(${interpolation}, from ${deg}deg, ${stops})`),\n ];\n }\n } else {\n return [\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `conic-gradient(${interpolation}, ${candidate.value.value}, ${stops})`),\n ];\n }\n\n return null;\n });\n\n // ============================================\n // Negative Linear Gradient (counter-clockwise angle)\n // ============================================\n\n utilities.functional(\"-bg-linear\", (candidate) => {\n const stops = buildGradientStops();\n const interpolation = resolveInterpolationMethod(candidate.modifier);\n\n if (!candidate.value) {\n return [\n decl(\"--ri-gradient-position\", \"to top\"),\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `linear-gradient(${interpolation}, var(--ri-gradient-position), ${stops})`),\n ];\n }\n\n if (candidate.value.kind === \"named\") {\n // Angle in degrees (negated)\n const deg = Number(candidate.value.value);\n if (!Number.isNaN(deg)) {\n return [\n decl(\"--ri-gradient-position\", `${-deg}deg`),\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\n \"background-image\",\n `linear-gradient(${interpolation}, var(--ri-gradient-position), ${stops})`\n ),\n ];\n }\n } else {\n return [\n decl(\"--ri-gradient-position\", `calc(-1 * ${candidate.value.value})`),\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `linear-gradient(${interpolation}, var(--ri-gradient-position), ${stops})`),\n ];\n }\n\n return null;\n });\n\n // ============================================\n // Negative Conic Gradient (counter-clockwise angle)\n // ============================================\n\n utilities.functional(\"-bg-conic\", (candidate) => {\n const stops = buildGradientStops();\n const interpolation = resolveInterpolationMethod(candidate.modifier);\n\n if (!candidate.value) {\n return [\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `conic-gradient(${interpolation}, ${stops})`),\n ];\n }\n\n if (candidate.value.kind === \"named\") {\n // Angle in degrees (negated)\n const deg = Number(candidate.value.value);\n if (!Number.isNaN(deg)) {\n return [\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\"background-image\", `conic-gradient(${interpolation}, from ${-deg}deg, ${stops})`),\n ];\n }\n } else {\n return [\n decl(\"--ri-gradient-interpolation\", interpolation),\n decl(\n \"background-image\",\n `conic-gradient(${interpolation}, from calc(-1 * ${candidate.value.value}), ${stops})`\n ),\n ];\n }\n\n return null;\n });\n\n // ============================================\n // Gradient Color Stops\n // ============================================\n\n // Static via-none utility\n utilities.static(\"via-none\", staticUtility([[\"--ri-gradient-via\", \"initial\"]]));\n\n utilities.functional(\"from\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Helper to resolve position from modifier\n const resolvePosition = (): string | null => {\n if (!candidate.modifier) return null;\n if (candidate.modifier.kind === \"arbitrary\") {\n return candidate.modifier.value;\n }\n if (candidate.modifier.kind === \"named\") {\n // Named position: from-red-500/50 → 50%\n const num = Number(candidate.modifier.value);\n if (!Number.isNaN(num)) {\n return `${num}%`;\n }\n }\n return null;\n };\n\n if (candidate.value.kind === \"named\") {\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-from\", color)];\n result.push(decl(\"--ri-gradient-from-position\", position ?? \"\"));\n return result;\n }\n\n if (candidate.value.value === \"transparent\") {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-from\", \"transparent\")];\n result.push(decl(\"--ri-gradient-from-position\", position ?? \"\"));\n return result;\n }\n\n if (candidate.value.value === \"current\") {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-from\", \"currentColor\")];\n result.push(decl(\"--ri-gradient-from-position\", position ?? \"\"));\n return result;\n }\n\n // Check for percentage (position-only)\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-gradient-from-position\", `${num}%`)];\n }\n } else {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-from\", candidate.value.value)];\n result.push(decl(\"--ri-gradient-from-position\", position ?? \"\"));\n return result;\n }\n\n return null;\n });\n\n utilities.functional(\"via\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Helper to resolve position from modifier\n const resolvePosition = (): string | null => {\n if (!candidate.modifier) return null;\n if (candidate.modifier.kind === \"arbitrary\") {\n return candidate.modifier.value;\n }\n if (candidate.modifier.kind === \"named\") {\n // Named position: via-red-500/50 → 50%\n const num = Number(candidate.modifier.value);\n if (!Number.isNaN(num)) {\n return `${num}%`;\n }\n }\n return null;\n };\n\n if (candidate.value.kind === \"named\") {\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-via\", color)];\n result.push(decl(\"--ri-gradient-via-position\", position ?? \"\"));\n return result;\n }\n\n if (candidate.value.value === \"transparent\") {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-via\", \"transparent\")];\n result.push(decl(\"--ri-gradient-via-position\", position ?? \"\"));\n return result;\n }\n\n if (candidate.value.value === \"current\") {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-via\", \"currentColor\")];\n result.push(decl(\"--ri-gradient-via-position\", position ?? \"\"));\n return result;\n }\n\n if (candidate.value.value === \"none\") {\n return [decl(\"--ri-gradient-via\", \"initial\"), decl(\"--ri-gradient-via-position\", \"\")];\n }\n\n // Check for percentage (position-only)\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-gradient-via-position\", `${num}%`)];\n }\n } else {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-via\", candidate.value.value)];\n result.push(decl(\"--ri-gradient-via-position\", position ?? \"\"));\n return result;\n }\n\n return null;\n });\n\n utilities.functional(\"to\", (candidate, theme) => {\n if (!candidate.value) return null;\n\n // Helper to resolve position from modifier\n const resolvePosition = (): string | null => {\n if (!candidate.modifier) return null;\n if (candidate.modifier.kind === \"arbitrary\") {\n return candidate.modifier.value;\n }\n if (candidate.modifier.kind === \"named\") {\n // Named position: to-red-500/50 → 50%\n const num = Number(candidate.modifier.value);\n if (!Number.isNaN(num)) {\n return `${num}%`;\n }\n }\n return null;\n };\n\n if (candidate.value.kind === \"named\") {\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-to\", color)];\n result.push(decl(\"--ri-gradient-to-position\", position ?? \"\"));\n return result;\n }\n\n if (candidate.value.value === \"transparent\") {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-to\", \"transparent\")];\n result.push(decl(\"--ri-gradient-to-position\", position ?? \"\"));\n return result;\n }\n\n if (candidate.value.value === \"current\") {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-to\", \"currentColor\")];\n result.push(decl(\"--ri-gradient-to-position\", position ?? \"\"));\n return result;\n }\n\n // Check for percentage (position-only)\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [decl(\"--ri-gradient-to-position\", `${num}%`)];\n }\n } else {\n const position = resolvePosition();\n const result = [decl(\"--ri-gradient-to\", candidate.value.value)];\n result.push(decl(\"--ri-gradient-to-position\", position ?? \"\"));\n return result;\n }\n\n return null;\n });\n\n // ============================================\n // Background Image (URL)\n // ============================================\n\n utilities.functional(\"bg\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n const value = candidate.value.value;\n // Check if it's a URL or gradient\n if (value.startsWith(\"url(\") || value.includes(\"gradient(\")) {\n return [decl(\"background-image\", value)];\n }\n }\n\n return null;\n });\n}\n","/**\n * Masking Utilities\n *\n * CSS mask-image, mask-position, mask-size, mask-repeat, mask-origin,\n * mask-clip, mask-composite, and mask-mode utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\n// Pre-defined edge list for mask utilities (hoisted to avoid recreation on every call)\nconst MASK_EDGES = [\"top\", \"right\", \"bottom\", \"left\"] as const;\n\nexport function registerMaskingUtilities(utilities: Utilities, _theme: Theme): void {\n // ============================================\n // Mask Type (mask-type)\n // ============================================\n\n utilities.static(\"mask-type-alpha\", staticUtility([[\"mask-type\", \"alpha\"]]));\n utilities.static(\"mask-type-luminance\", staticUtility([[\"mask-type\", \"luminance\"]]));\n\n // ============================================\n // Mask Image\n // ============================================\n\n utilities.static(\"mask-none\", staticUtility([[\"mask-image\", \"none\"]]));\n\n utilities.functional(\"mask\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"mask-image\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Mask Composite\n // ============================================\n\n utilities.static(\"mask-add\", staticUtility([[\"mask-composite\", \"add\"]]));\n utilities.static(\"mask-subtract\", staticUtility([[\"mask-composite\", \"subtract\"]]));\n utilities.static(\"mask-intersect\", staticUtility([[\"mask-composite\", \"intersect\"]]));\n utilities.static(\"mask-exclude\", staticUtility([[\"mask-composite\", \"exclude\"]]));\n\n // ============================================\n // Mask Mode\n // ============================================\n\n utilities.static(\"mask-match\", staticUtility([[\"mask-mode\", \"match-source\"]]));\n utilities.static(\"mask-alpha\", staticUtility([[\"mask-mode\", \"alpha\"]]));\n utilities.static(\"mask-luminance\", staticUtility([[\"mask-mode\", \"luminance\"]]));\n\n // ============================================\n // Mask Position\n // ============================================\n\n utilities.static(\"mask-bottom\", staticUtility([[\"mask-position\", \"bottom\"]]));\n utilities.static(\"mask-center\", staticUtility([[\"mask-position\", \"center\"]]));\n utilities.static(\"mask-left\", staticUtility([[\"mask-position\", \"left\"]]));\n utilities.static(\"mask-bottom-left\", staticUtility([[\"mask-position\", \"left bottom\"]]));\n utilities.static(\"mask-top-left\", staticUtility([[\"mask-position\", \"left top\"]]));\n utilities.static(\"mask-right\", staticUtility([[\"mask-position\", \"right\"]]));\n utilities.static(\"mask-bottom-right\", staticUtility([[\"mask-position\", \"right bottom\"]]));\n utilities.static(\"mask-top-right\", staticUtility([[\"mask-position\", \"right top\"]]));\n utilities.static(\"mask-top\", staticUtility([[\"mask-position\", \"top\"]]));\n\n utilities.functional(\"mask-position\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"mask-position\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Mask Repeat\n // ============================================\n\n utilities.static(\"mask-repeat\", staticUtility([[\"mask-repeat\", \"repeat\"]]));\n utilities.static(\"mask-no-repeat\", staticUtility([[\"mask-repeat\", \"no-repeat\"]]));\n utilities.static(\"mask-repeat-x\", staticUtility([[\"mask-repeat\", \"repeat-x\"]]));\n utilities.static(\"mask-repeat-y\", staticUtility([[\"mask-repeat\", \"repeat-y\"]]));\n utilities.static(\"mask-repeat-round\", staticUtility([[\"mask-repeat\", \"round\"]]));\n utilities.static(\"mask-repeat-space\", staticUtility([[\"mask-repeat\", \"space\"]]));\n\n // ============================================\n // Mask Size\n // ============================================\n\n utilities.static(\"mask-auto\", staticUtility([[\"mask-size\", \"auto\"]]));\n utilities.static(\"mask-cover\", staticUtility([[\"mask-size\", \"cover\"]]));\n utilities.static(\"mask-contain\", staticUtility([[\"mask-size\", \"contain\"]]));\n\n utilities.functional(\"mask-size\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [decl(\"mask-size\", candidate.value.value)];\n }\n\n return null;\n });\n\n // ============================================\n // Mask Origin\n // ============================================\n\n utilities.static(\"mask-origin-border\", staticUtility([[\"mask-origin\", \"border-box\"]]));\n utilities.static(\"mask-origin-padding\", staticUtility([[\"mask-origin\", \"padding-box\"]]));\n utilities.static(\"mask-origin-content\", staticUtility([[\"mask-origin\", \"content-box\"]]));\n utilities.static(\"mask-origin-fill\", staticUtility([[\"mask-origin\", \"fill-box\"]]));\n utilities.static(\"mask-origin-stroke\", staticUtility([[\"mask-origin\", \"stroke-box\"]]));\n utilities.static(\"mask-origin-view\", staticUtility([[\"mask-origin\", \"view-box\"]]));\n\n // ============================================\n // Mask Clip\n // ============================================\n\n utilities.static(\"mask-clip-border\", staticUtility([[\"mask-clip\", \"border-box\"]]));\n utilities.static(\"mask-clip-padding\", staticUtility([[\"mask-clip\", \"padding-box\"]]));\n utilities.static(\"mask-clip-content\", staticUtility([[\"mask-clip\", \"content-box\"]]));\n utilities.static(\"mask-clip-fill\", staticUtility([[\"mask-clip\", \"fill-box\"]]));\n utilities.static(\"mask-clip-stroke\", staticUtility([[\"mask-clip\", \"stroke-box\"]]));\n utilities.static(\"mask-clip-view\", staticUtility([[\"mask-clip\", \"view-box\"]]));\n utilities.static(\"mask-no-clip\", staticUtility([[\"mask-clip\", \"no-clip\"]]));\n\n // ============================================\n // Mask Gradient Shapes (radial masks)\n // ============================================\n\n utilities.static(\n \"mask-radial\",\n staticUtility([[\"mask-image\", \"radial-gradient(var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"]])\n );\n\n utilities.functional(\"mask-radial\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [\n decl(\n \"mask-image\",\n `radial-gradient(${candidate.value.value}, var(--ri-mask-from, black), var(--ri-mask-to, transparent))`\n ),\n ];\n }\n\n return null;\n });\n\n utilities.static(\n \"mask-circle\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(circle, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-ellipse\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(ellipse, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n // Radial size keywords\n utilities.static(\n \"mask-radial-closest-side\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(closest-side, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n utilities.static(\n \"mask-radial-closest-corner\",\n staticUtility([\n [\n \"mask-image\",\n \"radial-gradient(closest-corner, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\",\n ],\n ])\n );\n utilities.static(\n \"mask-radial-farthest-side\",\n staticUtility([\n [\n \"mask-image\",\n \"radial-gradient(farthest-side, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\",\n ],\n ])\n );\n utilities.static(\n \"mask-radial-farthest-corner\",\n staticUtility([\n [\n \"mask-image\",\n \"radial-gradient(farthest-corner, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\",\n ],\n ])\n );\n\n // Radial position variants\n utilities.static(\n \"mask-radial-at-center\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(at center, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-radial-at-top\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(at top, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-radial-at-bottom\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(at bottom, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-radial-at-left\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(at left, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-radial-at-right\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(at right, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-radial-at-top-left\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(at top left, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-radial-at-top-right\",\n staticUtility([\n [\"mask-image\", \"radial-gradient(at top right, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-radial-at-bottom-left\",\n staticUtility([\n [\n \"mask-image\",\n \"radial-gradient(at bottom left, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\",\n ],\n ])\n );\n\n utilities.static(\n \"mask-radial-at-bottom-right\",\n staticUtility([\n [\n \"mask-image\",\n \"radial-gradient(at bottom right, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\",\n ],\n ])\n );\n\n // ============================================\n // Mask Linear Gradients\n // ============================================\n\n utilities.static(\n \"mask-linear-to-t\",\n staticUtility([\n [\"mask-image\", \"linear-gradient(to top, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-linear-to-tr\",\n staticUtility([\n [\"mask-image\", \"linear-gradient(to top right, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-linear-to-r\",\n staticUtility([\n [\"mask-image\", \"linear-gradient(to right, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-linear-to-br\",\n staticUtility([\n [\n \"mask-image\",\n \"linear-gradient(to bottom right, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\",\n ],\n ])\n );\n\n utilities.static(\n \"mask-linear-to-b\",\n staticUtility([\n [\"mask-image\", \"linear-gradient(to bottom, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-linear-to-bl\",\n staticUtility([\n [\n \"mask-image\",\n \"linear-gradient(to bottom left, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\",\n ],\n ])\n );\n\n utilities.static(\n \"mask-linear-to-l\",\n staticUtility([\n [\"mask-image\", \"linear-gradient(to left, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n utilities.static(\n \"mask-linear-to-tl\",\n staticUtility([\n [\"mask-image\", \"linear-gradient(to top left, var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"],\n ])\n );\n\n // Functional mask-linear for arbitrary angles\n utilities.functional(\"mask-linear\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\n \"mask-image\",\n `linear-gradient(${num}deg, var(--ri-mask-from, black), var(--ri-mask-to, transparent))`\n ),\n ];\n }\n } else {\n return [\n decl(\n \"mask-image\",\n `linear-gradient(${candidate.value.value}, var(--ri-mask-from, black), var(--ri-mask-to, transparent))`\n ),\n ];\n }\n\n return null;\n });\n\n // ============================================\n // Mask Conic Gradient\n // ============================================\n\n utilities.static(\n \"mask-conic\",\n staticUtility([[\"mask-image\", \"conic-gradient(var(--ri-mask-from, black), var(--ri-mask-to, transparent))\"]])\n );\n\n utilities.functional(\"mask-conic\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n return [\n decl(\n \"mask-image\",\n `conic-gradient(from ${num}deg, var(--ri-mask-from, black), var(--ri-mask-to, transparent))`\n ),\n ];\n }\n } else {\n return [\n decl(\n \"mask-image\",\n `conic-gradient(${candidate.value.value}, var(--ri-mask-from, black), var(--ri-mask-to, transparent))`\n ),\n ];\n }\n\n return null;\n });\n\n // ============================================\n // Mask Radial Position (functional)\n // ============================================\n\n utilities.functional(\"mask-radial-at\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"arbitrary\") {\n return [\n decl(\n \"mask-image\",\n `radial-gradient(at ${candidate.value.value}, var(--ri-mask-from, black), var(--ri-mask-to, transparent))`\n ),\n ];\n }\n\n return null;\n });\n\n // ============================================\n // Advanced Mask Edge Utilities\n // ============================================\n\n // Common mask properties for composable masks\n const maskComposite = \"intersect\";\n const maskLayers =\n \"var(--ri-mask-linear, linear-gradient(#fff, #fff)), var(--ri-mask-radial, linear-gradient(#fff, #fff)), var(--ri-mask-conic, linear-gradient(#fff, #fff))\";\n\n // Helper to create edge mask utilities\n function createEdgeMaskUtility(\n edges: { top?: boolean; right?: boolean; bottom?: boolean; left?: boolean },\n stop: \"from\" | \"to\"\n ) {\n return (candidate: Parameters<Parameters<typeof utilities.functional>[1]>[0], theme: Theme) => {\n if (!candidate.value) return null;\n\n // Resolve color from value\n let color: string | null = null;\n let position: string | null = null;\n\n if (candidate.value.kind === \"named\") {\n // Check for theme color\n color = theme.get(`--color-${candidate.value.value}`);\n\n // Check for special values\n if (!color) {\n if (candidate.value.value === \"transparent\") color = \"transparent\";\n else if (candidate.value.value === \"current\") color = \"currentColor\";\n else if (candidate.value.value === \"black\") color = \"black\";\n else if (candidate.value.value === \"white\") color = \"white\";\n }\n\n // Check for percentage (position only)\n if (!color) {\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) {\n position = `${num}%`;\n }\n }\n } else if (candidate.value.kind === \"arbitrary\") {\n color = candidate.value.value;\n }\n\n const result: ReturnType<typeof decl>[] = [\n decl(\"mask-image\", maskLayers),\n decl(\"mask-composite\", maskComposite),\n ];\n\n // Build edge-specific gradients\n const activeEdges = MASK_EDGES.filter((e) => edges[e]);\n\n // Set up the linear mask variable with all edge gradients\n const edgeGradients = activeEdges\n .map((edge) => `var(--ri-mask-${edge}, linear-gradient(#fff, #fff))`)\n .join(\", \");\n result.push(decl(\"--ri-mask-linear\", edgeGradients));\n\n // Set color or position for each active edge\n for (const edge of activeEdges) {\n result.push(\n decl(\n `--ri-mask-${edge}`,\n `linear-gradient(to ${edge}, var(--ri-mask-${edge}-from-color, black) var(--ri-mask-${edge}-from-position, 0%), var(--ri-mask-${edge}-to-color, transparent) var(--ri-mask-${edge}-to-position, 100%))`\n )\n );\n\n if (color) {\n result.push(decl(`--ri-mask-${edge}-${stop}-color`, color));\n }\n if (position) {\n result.push(decl(`--ri-mask-${edge}-${stop}-position`, position));\n }\n }\n\n return result;\n };\n }\n\n // Horizontal edges (left + right)\n utilities.functional(\"mask-x-from\", createEdgeMaskUtility({ left: true, right: true }, \"from\"));\n utilities.functional(\"mask-x-to\", createEdgeMaskUtility({ left: true, right: true }, \"to\"));\n\n // Vertical edges (top + bottom)\n utilities.functional(\"mask-y-from\", createEdgeMaskUtility({ top: true, bottom: true }, \"from\"));\n utilities.functional(\"mask-y-to\", createEdgeMaskUtility({ top: true, bottom: true }, \"to\"));\n\n // Individual edges\n utilities.functional(\"mask-t-from\", createEdgeMaskUtility({ top: true }, \"from\"));\n utilities.functional(\"mask-t-to\", createEdgeMaskUtility({ top: true }, \"to\"));\n utilities.functional(\"mask-r-from\", createEdgeMaskUtility({ right: true }, \"from\"));\n utilities.functional(\"mask-r-to\", createEdgeMaskUtility({ right: true }, \"to\"));\n utilities.functional(\"mask-b-from\", createEdgeMaskUtility({ bottom: true }, \"from\"));\n utilities.functional(\"mask-b-to\", createEdgeMaskUtility({ bottom: true }, \"to\"));\n utilities.functional(\"mask-l-from\", createEdgeMaskUtility({ left: true }, \"from\"));\n utilities.functional(\"mask-l-to\", createEdgeMaskUtility({ left: true }, \"to\"));\n\n // ============================================\n // Mask Linear From/To Utilities\n // ============================================\n\n // Helper to resolve mask color or position\n function resolveMaskStopValue(\n candidate: Parameters<Parameters<typeof utilities.functional>[1]>[0],\n theme: Theme\n ): { color?: string; position?: string } {\n if (!candidate.value) return {};\n\n if (candidate.value.kind === \"named\") {\n // Check for theme color\n const color = theme.get(`--color-${candidate.value.value}`);\n if (color) return { color };\n\n // Special values\n if (candidate.value.value === \"transparent\") return { color: \"transparent\" };\n if (candidate.value.value === \"current\") return { color: \"currentColor\" };\n if (candidate.value.value === \"black\") return { color: \"black\" };\n if (candidate.value.value === \"white\") return { color: \"white\" };\n\n // Percentage position\n const num = Number(candidate.value.value);\n if (!Number.isNaN(num)) return { position: `${num}%` };\n\n // Percentage with % suffix\n if (candidate.value.value.endsWith(\"%\")) return { position: candidate.value.value };\n } else if (candidate.value.kind === \"arbitrary\") {\n // Determine if it's a color or position\n const value = candidate.value.value;\n if (value.endsWith(\"%\") || value.endsWith(\"px\") || value.endsWith(\"rem\") || value.endsWith(\"em\")) {\n return { position: value };\n }\n return { color: value };\n }\n\n return {};\n }\n\n const linearGradient =\n \"linear-gradient(var(--ri-mask-linear-position, 0deg), var(--ri-mask-linear-from-color, black) var(--ri-mask-linear-from-position, 0%), var(--ri-mask-linear-to-color, transparent) var(--ri-mask-linear-to-position, 100%))\";\n const radialGradient =\n \"radial-gradient(var(--ri-mask-radial-shape,) var(--ri-mask-radial-position,), var(--ri-mask-radial-from-color, black) var(--ri-mask-radial-from-position, 0%), var(--ri-mask-radial-to-color, transparent) var(--ri-mask-radial-to-position, 100%))\";\n const conicGradient =\n \"conic-gradient(from var(--ri-mask-conic-angle, 0deg) at var(--ri-mask-conic-position, center), var(--ri-mask-conic-from-color, black) var(--ri-mask-conic-from-position, 0%), var(--ri-mask-conic-to-color, transparent) var(--ri-mask-conic-to-position, 100%))\";\n\n function createMaskGradientUtility(\n variablePrefix: string,\n gradientVariable: string,\n gradientValue: string,\n stop: \"from\" | \"to\"\n ) {\n return function (candidate: Parameters<Parameters<typeof utilities.functional>[1]>[0], theme: Theme) {\n const { color, position } = resolveMaskStopValue(candidate, theme);\n\n const result: ReturnType<typeof decl>[] = [\n decl(\"mask-image\", maskLayers),\n decl(\"mask-composite\", maskComposite),\n decl(gradientVariable, gradientValue),\n ];\n\n if (color) result.push(decl(`${variablePrefix}-${stop}-color`, color));\n if (position) result.push(decl(`${variablePrefix}-${stop}-position`, position));\n\n return result;\n };\n }\n\n // Linear mask from/to utilities\n utilities.functional(\n \"mask-linear-from\",\n createMaskGradientUtility(\"--ri-mask-linear\", \"--ri-mask-linear\", linearGradient, \"from\")\n );\n utilities.functional(\n \"mask-linear-to\",\n createMaskGradientUtility(\"--ri-mask-linear\", \"--ri-mask-linear\", linearGradient, \"to\")\n );\n\n // Radial mask from/to utilities\n utilities.functional(\n \"mask-radial-from\",\n createMaskGradientUtility(\"--ri-mask-radial\", \"--ri-mask-radial\", radialGradient, \"from\")\n );\n utilities.functional(\n \"mask-radial-to\",\n createMaskGradientUtility(\"--ri-mask-radial\", \"--ri-mask-radial\", radialGradient, \"to\")\n );\n\n // Conic mask from/to utilities\n utilities.functional(\n \"mask-conic-from\",\n createMaskGradientUtility(\"--ri-mask-conic\", \"--ri-mask-conic\", conicGradient, \"from\")\n );\n utilities.functional(\n \"mask-conic-to\",\n createMaskGradientUtility(\"--ri-mask-conic\", \"--ri-mask-conic\", conicGradient, \"to\")\n );\n}\n","/**\n * Grid Utilities\n *\n * CSS Grid layout utilities including grid-template-columns, grid-template-rows,\n * grid-auto-columns, grid-auto-rows, and grid placement utilities.\n */\n\nimport { decl } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { staticUtility, type Utilities } from \"./utilities\";\n\n// Pre-defined grid auto values (hoisted to avoid recreating on every call)\nconst GRID_AUTO_VALUES: Record<string, string> = {\n auto: \"auto\",\n min: \"min-content\",\n max: \"max-content\",\n fr: \"minmax(0, 1fr)\",\n};\n\nexport function registerGridUtilities(utilities: Utilities, _theme: Theme): void {\n // Grid Template Columns\n\n utilities.functional(\"grid-cols\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"none\") {\n return [decl(\"grid-template-columns\", \"none\")];\n }\n\n if (val === \"subgrid\") {\n return [decl(\"grid-template-columns\", \"subgrid\")];\n }\n\n // Numeric: grid-cols-1 through grid-cols-12\n const num = Number(val);\n if (!Number.isNaN(num) && num >= 1 && num <= 12) {\n return [decl(\"grid-template-columns\", `repeat(${num}, minmax(0, 1fr))`)];\n }\n } else {\n return [decl(\"grid-template-columns\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid Template Rows\n\n utilities.functional(\"grid-rows\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"none\") {\n return [decl(\"grid-template-rows\", \"none\")];\n }\n\n if (val === \"subgrid\") {\n return [decl(\"grid-template-rows\", \"subgrid\")];\n }\n\n // Numeric: grid-rows-1 through grid-rows-12\n const num = Number(val);\n if (!Number.isNaN(num) && num >= 1 && num <= 12) {\n return [decl(\"grid-template-rows\", `repeat(${num}, minmax(0, 1fr))`)];\n }\n } else {\n return [decl(\"grid-template-rows\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid Auto Columns\n\n utilities.functional(\"auto-cols\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = GRID_AUTO_VALUES[candidate.value.value];\n if (value) return [decl(\"grid-auto-columns\", value)];\n } else {\n return [decl(\"grid-auto-columns\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid Auto Rows\n\n utilities.functional(\"auto-rows\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const value = GRID_AUTO_VALUES[candidate.value.value];\n if (value) return [decl(\"grid-auto-rows\", value)];\n } else {\n return [decl(\"grid-auto-rows\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid Column Span\n\n utilities.functional(\"col-span\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"full\") {\n return [decl(\"grid-column\", \"1 / -1\")];\n }\n\n const num = Number(val);\n if (!Number.isNaN(num) && num >= 1 && num <= 12) {\n return [decl(\"grid-column\", `span ${num} / span ${num}`)];\n }\n } else {\n return [decl(\"grid-column\", `span ${candidate.value.value} / span ${candidate.value.value}`)];\n }\n\n return null;\n });\n\n // col-auto\n utilities.static(\"col-auto\", staticUtility([[\"grid-column\", \"auto\"]]));\n\n // Direct grid-column shorthand: col-1, col-2, col-[1/3], etc.\n utilities.functional(\"col\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n // Numeric: col-1 through col-12\n const num = Number(val);\n if (!Number.isNaN(num) && num >= 1 && num <= 12) {\n return [decl(\"grid-column\", String(num))];\n }\n } else {\n // Arbitrary: col-[1/3], col-[span_2]\n return [decl(\"grid-column\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid Column Start\n\n utilities.functional(\"col-start\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"auto\") {\n return [decl(\"grid-column-start\", \"auto\")];\n }\n\n const num = Number(val);\n if (!Number.isNaN(num)) {\n return [decl(\"grid-column-start\", String(num))];\n }\n } else {\n return [decl(\"grid-column-start\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid Column End\n\n utilities.functional(\"col-end\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"auto\") {\n return [decl(\"grid-column-end\", \"auto\")];\n }\n\n const num = Number(val);\n if (!Number.isNaN(num)) {\n return [decl(\"grid-column-end\", String(num))];\n }\n } else {\n return [decl(\"grid-column-end\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid Row Span\n\n utilities.functional(\"row-span\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"full\") {\n return [decl(\"grid-row\", \"1 / -1\")];\n }\n\n const num = Number(val);\n if (!Number.isNaN(num) && num >= 1 && num <= 12) {\n return [decl(\"grid-row\", `span ${num} / span ${num}`)];\n }\n } else {\n return [decl(\"grid-row\", `span ${candidate.value.value} / span ${candidate.value.value}`)];\n }\n\n return null;\n });\n\n // row-auto\n utilities.static(\"row-auto\", staticUtility([[\"grid-row\", \"auto\"]]));\n\n // Direct grid-row shorthand: row-1, row-2, row-[1/3], etc.\n utilities.functional(\"row\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n // Numeric: row-1 through row-12\n const num = Number(val);\n if (!Number.isNaN(num) && num >= 1 && num <= 12) {\n return [decl(\"grid-row\", String(num))];\n }\n } else {\n // Arbitrary: row-[1/3], row-[span_2]\n return [decl(\"grid-row\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid Row Start\n\n utilities.functional(\"row-start\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"auto\") {\n return [decl(\"grid-row-start\", \"auto\")];\n }\n\n const num = Number(val);\n if (!Number.isNaN(num)) {\n return [decl(\"grid-row-start\", String(num))];\n }\n } else {\n return [decl(\"grid-row-start\", candidate.value.value)];\n }\n\n return null;\n });\n\n // Grid Row End\n\n utilities.functional(\"row-end\", (candidate) => {\n if (!candidate.value) return null;\n\n if (candidate.value.kind === \"named\") {\n const val = candidate.value.value;\n\n if (val === \"auto\") {\n return [decl(\"grid-row-end\", \"auto\")];\n }\n\n const num = Number(val);\n if (!Number.isNaN(num)) {\n return [decl(\"grid-row-end\", String(num))];\n }\n } else {\n return [decl(\"grid-row-end\", candidate.value.value)];\n }\n\n return null;\n });\n}\n","/**\n * Utilities Module\n *\n * Core utility system and default utility registrations.\n */\n\nexport * from \"./utilities\";\nexport * from \"./layout\";\nexport * from \"./spacing\";\nexport * from \"./sizing\";\nexport * from \"./colors\";\nexport * from \"./typography\";\nexport * from \"./borders\";\nexport * from \"./effects\";\nexport * from \"./transforms\";\nexport * from \"./filters\";\nexport * from \"./interactivity\";\nexport * from \"./transitions\";\nexport * from \"./animations\";\nexport * from \"./svg\";\nexport * from \"./accessibility\";\nexport * from \"./tables\";\nexport * from \"./backgrounds\";\nexport * from \"./masking\";\nexport * from \"./grid\";\n\nimport type { Theme } from \"../theme\";\nimport { Utilities } from \"./utilities\";\nimport { registerLayoutUtilities } from \"./layout\";\nimport { registerSpacingUtilities } from \"./spacing\";\nimport { registerSizingUtilities } from \"./sizing\";\nimport { registerColorUtilities } from \"./colors\";\nimport { registerTypographyUtilities } from \"./typography\";\nimport { registerBorderUtilities } from \"./borders\";\nimport { registerEffectsUtilities } from \"./effects\";\nimport { registerTransformUtilities } from \"./transforms\";\nimport { registerFilterUtilities } from \"./filters\";\nimport { registerInteractivityUtilities } from \"./interactivity\";\nimport { registerTransitionUtilities } from \"./transitions\";\nimport { registerAnimationUtilities } from \"./animations\";\nimport { registerSvgUtilities } from \"./svg\";\nimport { registerAccessibilityUtilities } from \"./accessibility\";\nimport { registerTableUtilities } from \"./tables\";\nimport { registerBackgroundUtilities } from \"./backgrounds\";\nimport { registerMaskingUtilities } from \"./masking\";\nimport { registerGridUtilities } from \"./grid\";\n\nlet _cachedDefaultUtilities: Utilities | null = null;\n\n/**\n * Create a Utilities instance with all default utilities registered.\n */\nexport function createDefaultUtilities(theme: Theme): Utilities {\n if (_cachedDefaultUtilities === null) {\n const utilities = new Utilities();\n\n registerLayoutUtilities(utilities, theme);\n registerSpacingUtilities(utilities, theme);\n registerSizingUtilities(utilities, theme);\n registerColorUtilities(utilities, theme);\n registerTypographyUtilities(utilities, theme);\n registerBorderUtilities(utilities, theme);\n registerEffectsUtilities(utilities, theme);\n registerTransformUtilities(utilities, theme);\n registerFilterUtilities(utilities, theme);\n registerInteractivityUtilities(utilities, theme);\n registerTransitionUtilities(utilities, theme);\n registerAnimationUtilities(utilities, theme);\n registerSvgUtilities(utilities, theme);\n registerAccessibilityUtilities(utilities, theme);\n registerTableUtilities(utilities, theme);\n registerBackgroundUtilities(utilities, theme);\n registerMaskingUtilities(utilities, theme);\n registerGridUtilities(utilities, theme);\n\n _cachedDefaultUtilities = utilities;\n }\n\n return _cachedDefaultUtilities.clone();\n}\n","/**\n * Segment Utility\n *\n * Splits a string on a top-level character, respecting nested brackets.\n */\n\nconst BACKSLASH = 0x5c;\nconst OPEN_CURLY = 0x7b;\nconst CLOSE_CURLY = 0x7d;\nconst OPEN_PAREN = 0x28;\nconst CLOSE_PAREN = 0x29;\nconst OPEN_BRACKET = 0x5b;\nconst CLOSE_BRACKET = 0x5d;\nconst DOUBLE_QUOTE = 0x22;\nconst SINGLE_QUOTE = 0x27;\n\n// Shared buffer for tracking nesting level (performance optimization)\nconst closingBracketStack = new Uint8Array(256);\n\n/**\n * Split a string on a top-level character.\n *\n * Respects nested parentheses, brackets, braces, and strings.\n *\n * Example with comma separator:\n * \"var(--a, 0 0 1px rgb(0, 0, 0)), 0 0 1px rgb(0, 0, 0)\"\n * Splits only at the top-level comma, not commas inside parens.\n */\nexport function segment(input: string, separator: string): string[] {\n let stackPos = 0;\n const parts: string[] = [];\n let lastPos = 0;\n const len = input.length;\n const separatorCode = separator.charCodeAt(0);\n\n for (let idx = 0; idx < len; idx++) {\n const char = input.charCodeAt(idx);\n\n if (stackPos === 0 && char === separatorCode) {\n parts.push(input.slice(lastPos, idx));\n lastPos = idx + 1;\n continue;\n }\n\n switch (char) {\n case BACKSLASH:\n // Skip escaped character\n idx += 1;\n break;\n\n case SINGLE_QUOTE:\n case DOUBLE_QUOTE:\n // Skip string content until closing quote\n while (++idx < len) {\n const nextChar = input.charCodeAt(idx);\n if (nextChar === BACKSLASH) {\n idx += 1;\n continue;\n }\n if (nextChar === char) {\n break;\n }\n }\n break;\n\n case OPEN_PAREN:\n closingBracketStack[stackPos] = CLOSE_PAREN;\n stackPos++;\n break;\n\n case OPEN_BRACKET:\n closingBracketStack[stackPos] = CLOSE_BRACKET;\n stackPos++;\n break;\n\n case OPEN_CURLY:\n closingBracketStack[stackPos] = CLOSE_CURLY;\n stackPos++;\n break;\n\n case CLOSE_BRACKET:\n case CLOSE_CURLY:\n case CLOSE_PAREN:\n if (stackPos > 0 && char === closingBracketStack[stackPos - 1]) {\n stackPos--;\n }\n break;\n }\n }\n\n parts.push(input.slice(lastPos));\n return parts;\n}\n","/**\n * Negation Utilities for the `not` Variant\n *\n * Provides functions to negate CSS at-rules and selectors\n * for the compound `not` variant (e.g., not-hover, not-motion-safe).\n */\n\n// Pre-compiled pattern for nesting selector replacement (hoisted to avoid recreation on every call)\nconst NESTING_SELECTOR_PATTERN = /&/g;\n\nimport { segment } from \"../utils/segment\";\nimport { atRule, type AtRule, type AstNode, type StyleRule } from \"../ast/types\";\n\n/**\n * Negate conditions in an at-rule.\n *\n * Handles @media, @supports, and @container conditions.\n * For @container, special handling is required for named containers.\n *\n * @param ruleName - The at-rule name (e.g., \"@media\", \"@supports\", \"@container\")\n * @param conditions - Array of condition strings to negate\n * @returns Array of negated condition strings\n */\nexport function negateConditions(ruleName: string, conditions: string[]): string[] {\n return conditions.map((condition) => {\n const trimmed = condition.trim();\n const parts = segment(trimmed, \" \");\n\n // Already negated - remove negation (double negative)\n if (parts[0] === \"not\") {\n return parts.slice(1).join(\" \");\n }\n\n // @container has special handling for named containers\n if (ruleName === \"@container\") {\n // @container (query) → @container not (query)\n if (parts[0]?.[0] === \"(\") {\n return `not ${trimmed}`;\n }\n // @container name not (query) → @container name (query)\n if (parts[1] === \"not\") {\n return `${parts[0]} ${parts.slice(2).join(\" \")}`;\n }\n // @container name (query) → @container name not (query)\n return `${parts[0]} not ${parts.slice(1).join(\" \")}`;\n }\n\n // @media and @supports: prepend \"not all and\" or \"not\"\n // For @media, we need \"not all and\" to properly negate\n if (ruleName === \"@media\") {\n return `not all and ${trimmed}`;\n }\n\n // For @supports, just prepend \"not\"\n return `not ${trimmed}`;\n });\n}\n\n/**\n * Negate an at-rule node.\n *\n * Validates that the at-rule can be negated (single condition only)\n * and returns a new at-rule with negated conditions.\n *\n * @param node - The at-rule node to negate\n * @returns A new at-rule with negated params, or null if cannot be negated\n */\nexport function negateAtRule(node: AtRule): AtRule | null {\n // Split on comma to get individual conditions\n const conditions = segment(node.params, \",\");\n\n // Cannot negate comma-separated media queries (e.g., \"screen, print\")\n if (conditions.length > 1) {\n return null;\n }\n\n const negated = negateConditions(node.name, conditions);\n return atRule(node.name, negated.join(\", \"), node.nodes);\n}\n\n/**\n * Negate a selector string.\n *\n * Wraps the selector in :not() and replaces & with *.\n * Cannot negate pseudo-elements (::before, ::after, etc.).\n *\n * @param selector - The selector string to negate\n * @returns A negated selector string, or null if cannot be negated\n */\nexport function negateSelector(selector: string): string | null {\n // Cannot negate pseudo-elements\n if (selector.includes(\"::\")) {\n return null;\n }\n\n // Split on comma and process each selector\n const selectors = segment(selector, \",\").map((s) => {\n // Replace & with * so :not() targets the element\n return s.replace(NESTING_SELECTOR_PATTERN, \"*\").trim();\n });\n\n // Wrap in :not()\n return `&:not(${selectors.join(\", \")})`;\n}\n\n/**\n * Collect all at-rules and style rules from an AST node and its children.\n *\n * Used to validate that a rule tree can be negated (max 1 at-rule, max 1 style rule).\n */\nexport function collectRulesInPath(node: AstNode): { atRules: AtRule[]; styleRules: StyleRule[] } {\n const atRules: AtRule[] = [];\n const styleRules: StyleRule[] = [];\n\n function collect(n: AstNode): void {\n if (n.kind === \"at-rule\") {\n atRules.push(n);\n for (const child of n.nodes) {\n collect(child);\n }\n } else if (n.kind === \"rule\") {\n styleRules.push(n);\n for (const child of n.nodes) {\n collect(child);\n }\n } else if (n.kind === \"context\" || n.kind === \"at-root\") {\n for (const child of n.nodes) {\n collect(child);\n }\n }\n }\n\n collect(node);\n return { atRules, styleRules };\n}\n\n/**\n * Check if a rule can be negated.\n *\n * A rule can be negated if it has at most 1 at-rule and at most 1 style rule\n * in its path. More complex nesting is not supported.\n */\nexport function canNegate(node: AstNode): boolean {\n const { atRules, styleRules } = collectRulesInPath(node);\n return atRules.length <= 1 && styleRules.length <= 1;\n}\n","/**\n * Variants Registry\n *\n * Manages variant definitions for conditional styling.\n * Variants wrap utilities in selectors or at-rules.\n */\n\nimport type { AstNode, StyleRule, AtRule } from \"../ast\";\nimport { atRule, styleRule } from \"../ast\";\nimport type { CompoundVariant, FunctionalVariant, StaticVariant, Variant } from \"../candidate\";\nimport type { Theme } from \"../theme\";\nimport { compareBreakpoints } from \"../utils/compare-breakpoints\";\nimport { negateAtRule, negateSelector } from \"./negate\";\n\n// Pre-compiled regex for numeric variant matching (hoisted to avoid recreation on every comparison)\nconst NUMERIC_VARIANT_PATTERN = /^\\d+$/;\n\n// Pre-compiled pattern for nesting selector replacement (hoisted to avoid recreation on every call)\nconst NESTING_SELECTOR_PATTERN = /&/g;\n\n// ============================================\n// Types\n// ============================================\n\n/** Compound behavior flags */\nexport const enum Compounds {\n /** Cannot compound with other variants */\n Never = 0,\n /** Can compound with at-rules (media, supports, etc.) */\n AtRules = 1 << 0,\n /** Can compound with style rules (selectors) */\n StyleRules = 1 << 1,\n}\n\n/** Apply function for static variants */\nexport type StaticApplyFn = (rule: StyleRule, variant: StaticVariant, theme: Theme) => void | null;\n\n/** Apply function for functional variants */\nexport type FunctionalApplyFn = (rule: StyleRule, variant: FunctionalVariant, theme: Theme) => void | null;\n\n/** Variant configuration */\ninterface VariantConfig {\n kind: \"static\" | \"functional\";\n order: number;\n applyFn: StaticApplyFn | FunctionalApplyFn;\n compoundsWith: Compounds;\n}\n\n// Common pseudo-class variants used by compound variants.\nconst COMPOUND_PSEUDO_MAP: Record<string, string> = {\n hover: \":hover\",\n focus: \":focus\",\n \"focus-within\": \":focus-within\",\n \"focus-visible\": \":focus-visible\",\n active: \":active\",\n visited: \":visited\",\n checked: \":checked\",\n disabled: \":disabled\",\n enabled: \":enabled\",\n required: \":required\",\n valid: \":valid\",\n invalid: \":invalid\",\n first: \":first-child\",\n last: \":last-child\",\n odd: \":nth-child(odd)\",\n even: \":nth-child(even)\",\n open: \"[open]\",\n};\n\n// ============================================\n// Variants Class\n// ============================================\n\nexport class Variants {\n /** Registered variants */\n private variants = new Map<string, VariantConfig>();\n\n /** Special pattern-based variants (like numeric breakpoints) */\n private patterns: Array<{ pattern: RegExp; config: VariantConfig }> = [];\n\n /** Optional class prefix (e.g., \"tw-\") for compound marker classes */\n classPrefix: string | null = null;\n\n /** Current ordering index */\n private orderIndex = 0;\n\n /** Current group comparison function */\n private currentCompareFn?: (a: string, b: string) => number;\n\n /**\n * Pre-computed order map for bitmask operations.\n * PERFORMANCE: Updated incrementally during registration to avoid\n * rebuilding the entire map on each access.\n */\n private _orderMap = new Map<string, number>();\n\n /** Tracks if order map needs rebuilding (variants registered out of order) */\n private _orderMapDirty = false;\n\n /**\n * Register a static variant.\n */\n static(name: string, applyFn: StaticApplyFn, options?: { compoundsWith?: Compounds; order?: number }): void {\n const order = options?.order ?? this.orderIndex++;\n\n this.variants.set(name, {\n kind: \"static\",\n order,\n applyFn,\n compoundsWith: options?.compoundsWith ?? Compounds.AtRules | Compounds.StyleRules,\n });\n\n // PERFORMANCE: Incrementally update order map during registration.\n // If custom order is specified, mark dirty for later rebuild.\n if (options?.order !== undefined) {\n this._orderMapDirty = true;\n } else {\n this._orderMap.set(name, this._orderMap.size);\n }\n }\n\n /**\n * Register a functional variant.\n */\n functional(\n name: string | RegExp,\n applyFn: FunctionalApplyFn,\n options?: { compoundsWith?: Compounds; order?: number }\n ): void {\n const order = options?.order ?? this.orderIndex++;\n\n const config: VariantConfig = {\n kind: \"functional\",\n order,\n applyFn,\n compoundsWith: options?.compoundsWith ?? Compounds.AtRules | Compounds.StyleRules,\n };\n\n if (name instanceof RegExp) {\n this.patterns.push({ pattern: name, config });\n } else {\n this.variants.set(name, config);\n\n // PERFORMANCE: Incrementally update order map during registration.\n // If custom order is specified, mark dirty for later rebuild.\n if (options?.order !== undefined) {\n this._orderMapDirty = true;\n } else {\n this._orderMap.set(name, this._orderMap.size);\n }\n }\n }\n\n /**\n * Check if a variant exists.\n */\n has(name: string): boolean {\n if (this.variants.has(name)) return true;\n\n // Check patterns\n for (const { pattern } of this.patterns) {\n if (pattern.test(name)) return true;\n }\n\n return false;\n }\n\n /**\n * Get variant configuration.\n */\n get(name: string): VariantConfig | undefined {\n const config = this.variants.get(name);\n if (config) return config;\n\n // Check patterns\n for (const { pattern, config } of this.patterns) {\n if (pattern.test(name)) return config;\n }\n\n return undefined;\n }\n\n /**\n * Apply a variant to a rule.\n */\n apply(rule: StyleRule, variant: Variant, theme: Theme): AstNode[] | null {\n let config: VariantConfig | undefined;\n let _name: string;\n\n if (variant.kind === \"static\") {\n _name = variant.root;\n config = this.get(variant.root);\n } else if (variant.kind === \"functional\") {\n _name = variant.root;\n config = this.get(variant.root);\n } else if (variant.kind === \"arbitrary\") {\n // Arbitrary variant: [&_p], [&:hover]\n if (variant.relative) {\n return null;\n }\n const selector = variant.selector.replace(NESTING_SELECTOR_PATTERN, rule.selector);\n return [styleRule(selector, rule.nodes)];\n } else if (variant.kind === \"compound\") {\n // Compound variant: group-hover, peer-focus\n return this.applyCompoundVariant(rule, variant, theme);\n } else {\n return null;\n }\n\n if (!config) return null;\n\n // Create a copy of the rule to modify\n const modifiedRule = styleRule(rule.selector, [...rule.nodes]);\n\n if (variant.kind === \"static\" && config.kind === \"static\") {\n const result = (config.applyFn as StaticApplyFn)(modifiedRule, variant, theme);\n if (result === null) return null;\n } else if (variant.kind === \"functional\" && config.kind === \"functional\") {\n const result = (config.applyFn as FunctionalApplyFn)(modifiedRule, variant, theme);\n if (result === null) return null;\n } else {\n return null;\n }\n\n return [modifiedRule];\n }\n\n /**\n * Apply a non-compound variant to a rule.\n * Used internally by applyCompoundVariant for the `not` variant.\n */\n private applyInnerVariant(\n rule: StyleRule,\n variant: StaticVariant | FunctionalVariant,\n theme: Theme\n ): AstNode[] | null {\n const config = this.get(variant.root);\n if (!config) return null;\n\n // Create a copy of the rule to modify\n const modifiedRule = styleRule(rule.selector, [...rule.nodes]);\n\n if (variant.kind === \"static\" && config.kind === \"static\") {\n const result = (config.applyFn as StaticApplyFn)(modifiedRule, variant, theme);\n if (result === null) return null;\n } else if (variant.kind === \"functional\" && config.kind === \"functional\") {\n const result = (config.applyFn as FunctionalApplyFn)(modifiedRule, variant, theme);\n if (result === null) return null;\n } else {\n return null;\n }\n\n return [modifiedRule];\n }\n\n /**\n * Get the sort order for a variant.\n */\n getOrder(variant: Variant): number {\n if (variant.kind === \"static\" || variant.kind === \"functional\") {\n const config = this.get(variant.root);\n return config?.order ?? Infinity;\n }\n return Infinity;\n }\n\n /**\n * Compare two variants for sorting.\n * Uses breakpoint comparison for media query variants.\n *\n * @returns negative if a < b, 0 if equal, positive if a > b\n */\n compareVariants(a: Variant, b: Variant, theme?: Theme): number {\n const orderA = this.getOrder(a);\n const orderB = this.getOrder(b);\n\n // If orders are different, use them\n if (orderA !== orderB) {\n return orderA - orderB;\n }\n\n // For numeric breakpoint variants, compare by value\n if (\n a.kind === \"functional\" &&\n NUMERIC_VARIANT_PATTERN.test(a.root) &&\n b.kind === \"functional\" &&\n NUMERIC_VARIANT_PATTERN.test(b.root)\n ) {\n const valueA = `${a.root}rem`;\n const valueB = `${b.root}rem`;\n const comparison = compareBreakpoints(valueA, valueB);\n if (comparison !== null) {\n return comparison;\n }\n }\n\n // For named breakpoints, try to compare their theme values\n if (theme && a.kind === \"static\" && b.kind === \"static\") {\n const breakpointA = theme.get(`--breakpoint-${a.root}`);\n const breakpointB = theme.get(`--breakpoint-${b.root}`);\n\n if (breakpointA && breakpointB) {\n const comparison = compareBreakpoints(breakpointA, breakpointB);\n if (comparison !== null) {\n return comparison;\n }\n }\n }\n\n return 0;\n }\n\n /**\n * Get all registered variant names.\n */\n names(): IterableIterator<string> {\n return this.variants.keys();\n }\n\n /**\n * Create a new Variants instance with the same registered variants.\n * Keeps caches empty to avoid sharing mutable state.\n */\n clone(): Variants {\n const next = new Variants();\n\n next.variants = new Map(this.variants);\n next.patterns = this.patterns.slice();\n next.orderIndex = this.orderIndex;\n next.currentCompareFn = this.currentCompareFn;\n next._orderMap = new Map(this._orderMap);\n next._orderMapDirty = this._orderMapDirty;\n next.classPrefix = this.classPrefix;\n\n return next;\n }\n\n /**\n * Get a map of variant names to their order indices.\n * Used for bitmask-based sorting (O(1) comparisons).\n *\n * PERFORMANCE: Pre-computed during registration for most cases.\n * Only rebuilds when custom order values were specified.\n */\n getOrderMap(): Map<string, number> {\n // Fast path: order map was built incrementally during registration\n if (!this._orderMapDirty) {\n return this._orderMap;\n }\n\n // Slow path: rebuild when custom orders were specified\n // Build sorted list of variants by order\n const entries = Array.from(this.variants.entries()).sort((a, b) => a[1].order - b[1].order);\n\n // Assign sequential indices (0, 1, 2, ...) for bitmask positions\n this._orderMap.clear();\n for (let i = 0; i < entries.length; i++) {\n this._orderMap.set(entries[i]![0], i);\n }\n\n this._orderMapDirty = false;\n return this._orderMap;\n }\n\n /**\n * Invalidate the order map (call after registering new variants with custom order).\n */\n invalidateOrderMap(): void {\n this._orderMapDirty = true;\n }\n\n /**\n * Group variants for ordering.\n */\n group(fn: () => void): void {\n const _startIndex = this.orderIndex;\n fn();\n // All variants registered within the group share the same base order\n }\n\n /**\n * Apply a compound variant (group-hover, peer-focus, etc.)\n *\n * Compound variants create selectors that target elements based on\n * the state of a parent/sibling with a matching marker class.\n *\n * Examples:\n * - group-hover:text-paper -> .group:hover .group-hover\\:text-paper\n * - peer-focus:text-paper -> .peer:focus ~ .peer-focus\\:text-paper\n * - group/sidebar-hover:text-paper -> .group\\/sidebar:hover .group\\/sidebar-hover\\:text-paper\n */\n private applyCompoundVariant(rule: StyleRule, variant: CompoundVariant, _theme: Theme): AstNode[] | null {\n const { root, modifier, variant: innerVariant } = variant;\n\n // Build the marker class name\n let markerClass = root;\n if (modifier?.kind === \"named\") {\n markerClass = `${root}/${modifier.value}`;\n } else if (modifier?.kind === \"arbitrary\") {\n markerClass = `${root}/[${modifier.value}]`;\n }\n\n if (this.classPrefix) {\n markerClass = `${this.classPrefix}${markerClass}`;\n }\n\n // Escape the marker class for use in selector\n const escapedMarker = escapeSelector(markerClass);\n\n // Get the inner variant's selector modifier\n let stateSelector = \"\";\n\n if (innerVariant.kind === \"static\") {\n if (innerVariant.root.startsWith(\"aria-\")) {\n const attr = innerVariant.root.slice(5);\n stateSelector = `[aria-${attr}=\"true\"]`;\n } else if (innerVariant.root === \"data-open\") {\n stateSelector = `[data-state=\"open\"]`;\n } else if (innerVariant.root === \"data-closed\") {\n stateSelector = `[data-state=\"closed\"]`;\n } else if (innerVariant.root.startsWith(\"data-\")) {\n const attr = innerVariant.root.slice(5);\n stateSelector = `[data-${attr}]`;\n } else {\n // Map common variant names to their pseudo-class selectors\n stateSelector = COMPOUND_PSEUDO_MAP[innerVariant.root] ?? `:${innerVariant.root}`;\n }\n } else if (innerVariant.kind === \"functional\") {\n if (!innerVariant.value) return null;\n\n if (innerVariant.root === \"aria\") {\n if (innerVariant.value.kind === \"arbitrary\") {\n stateSelector = `[aria-${innerVariant.value.value}]`;\n } else {\n stateSelector = `[aria-${innerVariant.value.value}=\"true\"]`;\n }\n } else if (innerVariant.root === \"data\") {\n stateSelector = `[data-${innerVariant.value.value}]`;\n } else if (innerVariant.root === \"nth\") {\n stateSelector = `:nth-child(${innerVariant.value.value})`;\n } else if (innerVariant.root === \"nth-last\") {\n stateSelector = `:nth-last-child(${innerVariant.value.value})`;\n } else if (innerVariant.root === \"nth-of-type\") {\n stateSelector = `:nth-of-type(${innerVariant.value.value})`;\n } else if (innerVariant.root === \"nth-last-of-type\") {\n stateSelector = `:nth-last-of-type(${innerVariant.value.value})`;\n } else if (innerVariant.root === \"is\") {\n stateSelector = `:is(${innerVariant.value.value})`;\n } else if (innerVariant.root === \"where\") {\n stateSelector = `:where(${innerVariant.value.value})`;\n } else if (innerVariant.root === \"has\") {\n if (innerVariant.value.kind === \"arbitrary\") {\n stateSelector = `:has(${innerVariant.value.value})`;\n } else {\n stateSelector = `:has(:${innerVariant.value.value})`;\n }\n } else if (innerVariant.root === \"not\") {\n if (innerVariant.value.kind === \"arbitrary\") {\n stateSelector = `:not(${innerVariant.value.value})`;\n } else {\n stateSelector = `:not(:${innerVariant.value.value})`;\n }\n } else {\n stateSelector = `:${innerVariant.root}`;\n }\n } else if (innerVariant.kind === \"arbitrary\") {\n // Arbitrary selector within compound\n stateSelector = innerVariant.selector.replace(NESTING_SELECTOR_PATTERN, \"\");\n } else {\n return null;\n }\n\n // Build the final selector based on the compound root type\n let newSelector: string;\n\n if (root === \"peer\") {\n // peer uses general sibling combinator\n newSelector = `.${escapedMarker}${stateSelector} ~ ${rule.selector}`;\n } else if (root === \"has\") {\n // has uses the :has() pseudo-class on the element itself\n // has-hover:text-paper -> .has-hover\\:text-paper:has(:hover)\n // has-[>img]:text-paper -> .has-[>img]\\:text-paper:has(> img)\n // Static variants already include the colon from pseudoMap\n // Arbitrary selectors (like \">img\", \".foo\") should be used as-is\n newSelector = `${rule.selector}:has(${stateSelector})`;\n } else if (root === \"in\") {\n // in checks if element is inside a parent matching the state\n // in-hover:text-paper -> :hover .in-hover\\:text-paper\n newSelector = `${stateSelector} ${rule.selector}`;\n } else if (root === \"not\") {\n // not negates the inner variant's condition\n // For at-rule variants (hover, motion-safe, etc.), we need to negate the at-rule\n // For selector-only variants, we negate via :not()\n\n // Only try at-rule negation for static and functional variants\n if (innerVariant.kind === \"static\" || innerVariant.kind === \"functional\") {\n // Apply the inner variant to get the full result with any at-rules\n const innerResult = this.applyInnerVariant(rule, innerVariant, _theme);\n if (innerResult && innerResult.length > 0) {\n // Check if the result contains an at-rule that needs negation\n const firstNode = innerResult[0];\n if (firstNode && firstNode.kind === \"at-rule\") {\n // Negate the at-rule\n const negated = negateAtRule(firstNode as AtRule);\n if (negated) {\n return [negated];\n }\n // Cannot negate (e.g., comma-separated media queries)\n return null;\n } else if (firstNode && firstNode.kind === \"rule\") {\n // Check if the rule itself was wrapped (selector changed)\n // If so, negate the selector\n const ruleNode = firstNode as StyleRule;\n if (ruleNode.selector !== rule.selector) {\n const negatedSelector = negateSelector(ruleNode.selector);\n if (negatedSelector) {\n return [styleRule(negatedSelector, ruleNode.nodes)];\n }\n // Cannot negate (e.g., pseudo-elements)\n return null;\n }\n }\n }\n }\n\n // Fallback to simple selector negation for arbitrary variants\n // or when the inner variant doesn't produce at-rules\n newSelector = `${rule.selector}:not(${stateSelector})`;\n } else {\n // group (and others) use descendant combinator\n newSelector = `.${escapedMarker}${stateSelector} ${rule.selector}`;\n }\n\n return [styleRule(newSelector, [...rule.nodes])];\n }\n}\n\n// ============================================\n// Variant Helpers\n// ============================================\n\n/**\n * Escape special characters in a CSS selector.\n */\nfunction escapeSelector(str: string): string {\n return str.replace(/([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~])/g, \"\\\\$1\");\n}\n\n/**\n * Create a simple selector variant.\n */\nexport function selectorVariant(selector: string): StaticApplyFn {\n return (rule) => {\n rule.selector = `${rule.selector}${selector}`;\n };\n}\n\n/**\n * Create a media query variant.\n */\nexport function mediaVariant(query: string): StaticApplyFn {\n return (rule) => {\n const mediaRule = atRule(\"media\", query, rule.nodes);\n rule.nodes = [mediaRule];\n };\n}\n","/**\n * Pseudo-class and Pseudo-element Variants\n */\n\nimport { atRule } from \"../ast\";\nimport { Compounds, selectorVariant, type Variants } from \"./variants\";\n\nexport function registerPseudoVariants(variants: Variants): void {\n // ============================================\n // Interactive States\n // ============================================\n\n // Hover with media query guard for touch devices\n variants.static(\n \"hover\",\n (rule) => {\n rule.selector = `${rule.selector}:hover`;\n const mediaRule = atRule(\"media\", \"(hover: hover)\", rule.nodes);\n rule.nodes = [mediaRule];\n },\n { compoundsWith: Compounds.StyleRules }\n );\n\n variants.static(\"focus\", selectorVariant(\":focus\"));\n variants.static(\"focus-within\", selectorVariant(\":focus-within\"));\n variants.static(\"focus-visible\", selectorVariant(\":focus-visible\"));\n variants.static(\"active\", selectorVariant(\":active\"));\n variants.static(\"visited\", selectorVariant(\":visited\"));\n variants.static(\"target\", selectorVariant(\":target\"));\n\n // ============================================\n // Form States\n // ============================================\n\n variants.static(\"enabled\", selectorVariant(\":enabled\"));\n variants.static(\"disabled\", selectorVariant(\":disabled\"));\n variants.static(\"checked\", selectorVariant(\":checked\"));\n variants.static(\"indeterminate\", selectorVariant(\":indeterminate\"));\n variants.static(\"default\", selectorVariant(\":default\"));\n variants.static(\"required\", selectorVariant(\":required\"));\n variants.static(\"optional\", selectorVariant(\":optional\"));\n variants.static(\"valid\", selectorVariant(\":valid\"));\n variants.static(\"invalid\", selectorVariant(\":invalid\"));\n variants.static(\"user-valid\", selectorVariant(\":user-valid\"));\n variants.static(\"user-invalid\", selectorVariant(\":user-invalid\"));\n variants.static(\"in-range\", selectorVariant(\":in-range\"));\n variants.static(\"out-of-range\", selectorVariant(\":out-of-range\"));\n variants.static(\"placeholder-shown\", selectorVariant(\":placeholder-shown\"));\n variants.static(\"autofill\", selectorVariant(\":autofill\"));\n variants.static(\"read-only\", selectorVariant(\":read-only\"));\n\n // ============================================\n // Structural\n // ============================================\n\n variants.static(\"first\", selectorVariant(\":first-child\"));\n variants.static(\"last\", selectorVariant(\":last-child\"));\n variants.static(\"only\", selectorVariant(\":only-child\"));\n variants.static(\"odd\", selectorVariant(\":nth-child(odd)\"));\n variants.static(\"even\", selectorVariant(\":nth-child(even)\"));\n variants.static(\"first-of-type\", selectorVariant(\":first-of-type\"));\n variants.static(\"last-of-type\", selectorVariant(\":last-of-type\"));\n variants.static(\"only-of-type\", selectorVariant(\":only-of-type\"));\n variants.static(\"empty\", selectorVariant(\":empty\"));\n\n // ============================================\n // Pseudo-elements\n // ============================================\n\n variants.static(\"before\", (rule) => {\n rule.selector = `${rule.selector}::before`;\n });\n\n variants.static(\"after\", (rule) => {\n rule.selector = `${rule.selector}::after`;\n });\n\n variants.static(\"first-letter\", (rule) => {\n rule.selector = `${rule.selector}::first-letter`;\n });\n\n variants.static(\"first-line\", (rule) => {\n rule.selector = `${rule.selector}::first-line`;\n });\n\n // Marker with child element support\n variants.static(\"marker\", (rule) => {\n rule.selector = `:is(${rule.selector}::marker, ${rule.selector} *::marker)`;\n });\n\n // Selection with child element support\n variants.static(\"selection\", (rule) => {\n rule.selector = `:is(${rule.selector}::selection, ${rule.selector} *::selection)`;\n });\n\n variants.static(\"file\", (rule) => {\n rule.selector = `${rule.selector}::file-selector-button`;\n });\n\n variants.static(\"backdrop\", (rule) => {\n rule.selector = `${rule.selector}::backdrop`;\n });\n\n variants.static(\"placeholder\", (rule) => {\n rule.selector = `${rule.selector}::placeholder`;\n });\n\n // ============================================\n // Child Selectors (with :is() wrapper for proper specificity)\n // ============================================\n\n variants.static(\"*\", (rule) => {\n rule.selector = `:is(${rule.selector} > *)`;\n });\n\n // All descendants selector (**)\n variants.static(\"**\", (rule) => {\n rule.selector = `:is(${rule.selector} *)`;\n });\n\n // ============================================\n // State Modifiers\n // ============================================\n\n // Open state with popover and dialog support (includes :open pseudo-class for dialogs)\n variants.static(\"open\", (rule) => {\n rule.selector = `${rule.selector}:is([open], :popover-open, :open)`;\n });\n\n variants.static(\"closed\", selectorVariant(\":not([open])\"));\n\n // Inert with child element support\n variants.static(\"inert\", (rule) => {\n rule.selector = `:is(${rule.selector}[inert], [inert] ${rule.selector})`;\n });\n\n // Starting style uses @starting-style at-rule\n variants.static(\n \"starting\",\n (rule) => {\n const startingRule = atRule(\"starting-style\", \"\", rule.nodes);\n rule.nodes = [startingRule];\n },\n { compoundsWith: Compounds.StyleRules }\n );\n\n // Popover API states\n variants.static(\"popover-open\", selectorVariant(\":popover-open\"));\n\n // Details element content\n variants.static(\"details-content\", (rule) => {\n rule.selector = `${rule.selector}::details-content`;\n });\n\n // Modal state\n variants.static(\"modal\", selectorVariant(\":modal\"));\n\n // Fullscreen state\n variants.static(\"fullscreen\", selectorVariant(\":fullscreen\"));\n\n // ============================================\n // Direction (with :dir() and :where() for better support)\n // ============================================\n\n variants.static(\"ltr\", (rule) => {\n rule.selector = `:where(:dir(ltr), [dir=\"ltr\"], [dir=\"ltr\"] *) ${rule.selector}`;\n });\n\n variants.static(\"rtl\", (rule) => {\n rule.selector = `:where(:dir(rtl), [dir=\"rtl\"], [dir=\"rtl\"] *) ${rule.selector}`;\n });\n\n // ============================================\n // nth-child Variants (functional)\n // ============================================\n\n variants.functional(\"nth\", (rule, variant) => {\n if (!variant.value) return null;\n rule.selector = `${rule.selector}:nth-child(${variant.value.value})`;\n });\n\n variants.functional(\"nth-last\", (rule, variant) => {\n if (!variant.value) return null;\n rule.selector = `${rule.selector}:nth-last-child(${variant.value.value})`;\n });\n\n variants.functional(\"nth-of-type\", (rule, variant) => {\n if (!variant.value) return null;\n rule.selector = `${rule.selector}:nth-of-type(${variant.value.value})`;\n });\n\n variants.functional(\"nth-last-of-type\", (rule, variant) => {\n if (!variant.value) return null;\n rule.selector = `${rule.selector}:nth-last-of-type(${variant.value.value})`;\n });\n}\n","/**\n * Media Query Variants\n *\n * Responsive breakpoints, dark mode, and other media-based variants.\n * Includes numeric breakpoint support (e.g., 64:bg-black applies at 64rem).\n */\n\nimport { atRule } from \"../ast\";\nimport { Compounds, type Variants } from \"./variants\";\n\n/** Default breakpoint values */\nconst BREAKPOINT_DEFAULTS: Record<string, string> = {\n sm: \"40rem\",\n md: \"48rem\",\n lg: \"64rem\",\n xl: \"80rem\",\n \"2xl\": \"96rem\",\n};\n\nexport function registerMediaVariants(variants: Variants): void {\n // ============================================\n // Named Breakpoints (from theme)\n // ============================================\n\n // Register min-width and max-width breakpoint variants\n for (const [name, defaultValue] of Object.entries(BREAKPOINT_DEFAULTS)) {\n // Min-width: sm, md, lg, xl, 2xl\n variants.static(name, (rule, _variant, theme) => {\n const breakpoint = theme.get(`--breakpoint-${name}`) ?? defaultValue;\n rule.nodes = [atRule(\"media\", `(min-width: ${breakpoint})`, rule.nodes)];\n });\n\n // Max-width: max-sm, max-md, max-lg, max-xl, max-2xl\n variants.static(`max-${name}`, (rule, _variant, theme) => {\n const breakpoint = theme.get(`--breakpoint-${name}`) ?? defaultValue;\n rule.nodes = [atRule(\"media\", `(max-width: calc(${breakpoint} - 1px))`, rule.nodes)];\n });\n }\n\n // ============================================\n // Numeric Breakpoints (Rainbow Index enhancement)\n // ============================================\n\n // Pattern matches any numeric variant like \"64\", \"48\", \"80\"\n // Usage: 64:bg-black applies at min-width: 64rem\n variants.functional(/^\\d+$/, (rule, variant) => {\n const remValue = variant.root;\n const mediaRule = atRule(\"media\", `(min-width: ${remValue}rem)`, rule.nodes);\n rule.nodes = [mediaRule];\n });\n\n // ============================================\n // Color Scheme\n // ============================================\n\n variants.static(\n \"dark\",\n (rule) => {\n rule.nodes = [atRule(\"media\", \"(prefers-color-scheme: dark)\", rule.nodes)];\n },\n { compoundsWith: Compounds.StyleRules }\n );\n\n variants.static(\n \"light\",\n (rule) => {\n rule.nodes = [atRule(\"media\", \"(prefers-color-scheme: light)\", rule.nodes)];\n },\n { compoundsWith: Compounds.StyleRules }\n );\n\n // ============================================\n // User Preferences\n // ============================================\n\n const mediaPreferences: Array<[string, string]> = [\n [\"motion-safe\", \"(prefers-reduced-motion: no-preference)\"],\n [\"motion-reduce\", \"(prefers-reduced-motion: reduce)\"],\n [\"contrast-more\", \"(prefers-contrast: more)\"],\n [\"contrast-less\", \"(prefers-contrast: less)\"],\n [\"print\", \"print\"],\n [\"portrait\", \"(orientation: portrait)\"],\n [\"landscape\", \"(orientation: landscape)\"],\n ];\n\n for (const [name, query] of mediaPreferences) {\n variants.static(name, (rule) => {\n rule.nodes = [atRule(\"media\", query, rule.nodes)];\n });\n }\n\n // ============================================\n // Container Queries\n // ============================================\n\n // @container variant for container queries\n variants.functional(\"container\", (rule, variant) => {\n if (!variant.value) return null;\n\n const size = variant.value.kind === \"arbitrary\" ? variant.value.value : `${variant.value.value}rem`;\n\n const containerRule = atRule(\"container\", `(min-width: ${size})`, rule.nodes);\n rule.nodes = [containerRule];\n });\n\n // ============================================\n // Container Query Variants (@ syntax)\n // ============================================\n\n // Theme-based container values from --container-*\n // Usage: @sm:flex applies at --container-sm (default 40rem)\n // Named containers: @sm/sidebar:flex applies to container named \"sidebar\"\n for (const [name, defaultValue] of Object.entries(BREAKPOINT_DEFAULTS)) {\n variants.static(`@${name}`, (rule, _variant, theme) => {\n const size = theme.get(`--container-${name}`) ?? theme.get(`--breakpoint-${name}`) ?? defaultValue;\n rule.nodes = [atRule(\"container\", `(min-width: ${size})`, rule.nodes)];\n });\n }\n\n // @ variant for arbitrary/named container queries\n // Usage: @[500px]:flex, @64:flex (64rem)\n // With container name: @[500px]/sidebar:flex\n variants.functional(\"@\", (rule, variant) => {\n if (!variant.value) return null;\n\n const size = variant.value.kind === \"arbitrary\" ? variant.value.value : `${variant.value.value}rem`;\n\n const containerName = variant.modifier?.kind === \"named\" ? variant.modifier.value : null;\n const query = containerName ? `${containerName} (min-width: ${size})` : `(min-width: ${size})`;\n\n rule.nodes = [atRule(\"container\", query, rule.nodes)];\n });\n\n // @min and @max with theme-based container values\n // Usage: @min-sm:flex, @max-lg:hidden\n for (const [name, defaultValue] of Object.entries(BREAKPOINT_DEFAULTS)) {\n variants.static(`@min-${name}`, (rule, _variant, theme) => {\n const size = theme.get(`--container-${name}`) ?? theme.get(`--breakpoint-${name}`) ?? defaultValue;\n rule.nodes = [atRule(\"container\", `(min-width: ${size})`, rule.nodes)];\n });\n\n variants.static(`@max-${name}`, (rule, _variant, theme) => {\n const size = theme.get(`--container-${name}`) ?? theme.get(`--breakpoint-${name}`) ?? defaultValue;\n rule.nodes = [atRule(\"container\", `(max-width: calc(${size} - 1px))`, rule.nodes)];\n });\n }\n\n // ============================================\n // Supports\n // ============================================\n\n variants.functional(\"supports\", (rule, variant) => {\n if (!variant.value || variant.value.kind !== \"arbitrary\") return null;\n\n const condition = variant.value.value;\n const supportsRule = atRule(\"supports\", condition, rule.nodes);\n rule.nodes = [supportsRule];\n });\n\n // ============================================\n // Pointer and Hover Capability\n // ============================================\n\n const pointerVariants: Array<[string, string]> = [\n [\"pointer-fine\", \"(pointer: fine)\"],\n [\"pointer-coarse\", \"(pointer: coarse)\"],\n [\"pointer-none\", \"(pointer: none)\"],\n [\"any-pointer-fine\", \"(any-pointer: fine)\"],\n [\"any-pointer-coarse\", \"(any-pointer: coarse)\"],\n [\"any-pointer-none\", \"(any-pointer: none)\"],\n [\"can-hover\", \"(hover: hover)\"],\n [\"no-hover\", \"(hover: none)\"],\n [\"noscript\", \"(scripting: none)\"],\n [\"scripting\", \"(scripting: enabled)\"],\n ];\n\n for (const [name, query] of pointerVariants) {\n variants.static(name, (rule) => {\n rule.nodes = [atRule(\"media\", query, rule.nodes)];\n });\n }\n\n // ============================================\n // Color Scheme Preference\n // ============================================\n\n // Styles applied when element has color-scheme: light\n variants.static(\n \"scheme-light\",\n (rule) => {\n rule.selector = `:where([style*=\"color-scheme: light\"], [style*=\"color-scheme:light\"]) ${rule.selector}`;\n },\n { compoundsWith: Compounds.StyleRules }\n );\n\n // Styles applied when element has color-scheme: dark\n variants.static(\n \"scheme-dark\",\n (rule) => {\n rule.selector = `:where([style*=\"color-scheme: dark\"], [style*=\"color-scheme:dark\"]) ${rule.selector}`;\n },\n { compoundsWith: Compounds.StyleRules }\n );\n\n // Only light (no dark fallback)\n variants.static(\n \"scheme-only-light\",\n (rule) => {\n rule.selector = `:where([style*=\"color-scheme: light only\"], [style*=\"color-scheme:light only\"]) ${rule.selector}`;\n },\n { compoundsWith: Compounds.StyleRules }\n );\n\n // Only dark (no light fallback)\n variants.static(\n \"scheme-only-dark\",\n (rule) => {\n rule.selector = `:where([style*=\"color-scheme: dark only\"], [style*=\"color-scheme:dark only\"]) ${rule.selector}`;\n },\n { compoundsWith: Compounds.StyleRules }\n );\n\n // ============================================\n // Arbitrary Min/Max Width Breakpoints\n // ============================================\n\n variants.functional(\"min\", (rule, variant) => {\n if (!variant.value) return null;\n const value = variant.value.kind === \"arbitrary\" ? variant.value.value : `${variant.value.value}px`;\n rule.nodes = [atRule(\"media\", `(min-width: ${value})`, rule.nodes)];\n });\n\n variants.functional(\"max\", (rule, variant) => {\n if (!variant.value) return null;\n const value = variant.value.kind === \"arbitrary\" ? variant.value.value : `${variant.value.value}px`;\n rule.nodes = [atRule(\"media\", `(max-width: ${value})`, rule.nodes)];\n });\n\n // ============================================\n // Container Query Min/Max Variants (functional)\n // ============================================\n\n // @min-[value] and @max-[value] for arbitrary container queries\n // Also supports theme-based values like @min-sm (handled by static variants above)\n variants.functional(\"@min\", (rule, variant, theme) => {\n if (!variant.value) return null;\n const value = resolveContainerValue(variant, theme);\n const containerName = variant.modifier?.kind === \"named\" ? variant.modifier.value : null;\n const query = containerName ? `${containerName} (min-width: ${value})` : `(min-width: ${value})`;\n rule.nodes = [atRule(\"container\", query, rule.nodes)];\n });\n\n variants.functional(\"@max\", (rule, variant, theme) => {\n if (!variant.value) return null;\n const value = resolveContainerValue(variant, theme);\n const containerName = variant.modifier?.kind === \"named\" ? variant.modifier.value : null;\n const query = containerName ? `${containerName} (max-width: ${value})` : `(max-width: ${value})`;\n rule.nodes = [atRule(\"container\", query, rule.nodes)];\n });\n\n // ============================================\n // Forced and Inverted Colors\n // ============================================\n\n variants.static(\"forced-colors\", (rule) => {\n rule.nodes = [atRule(\"media\", \"(forced-colors: active)\", rule.nodes)];\n });\n\n variants.static(\"inverted-colors\", (rule) => {\n rule.nodes = [atRule(\"media\", \"(inverted-colors: inverted)\", rule.nodes)];\n });\n}\n\n/**\n * Resolve container value from variant, checking theme for named values.\n */\nfunction resolveContainerValue(\n variant: { value: { kind: string; value: string } | null },\n theme: { get(key: string): string | null }\n): string {\n if (!variant.value) return \"\";\n\n if (variant.value.kind === \"arbitrary\") {\n return variant.value.value;\n }\n\n // Check for theme-based container/breakpoint value\n const themeValue =\n theme.get(`--container-${variant.value.value}`) ?? theme.get(`--breakpoint-${variant.value.value}`);\n return themeValue ?? `${variant.value.value}rem`;\n}\n","/**\n * Data and ARIA Attribute Variants\n */\n\nimport type { Theme } from \"../theme\";\nimport type { Variants } from \"./variants\";\n\nexport function registerDataVariants(variants: Variants, _theme: Theme): void {\n // ============================================\n // Data Attribute Variants\n // ============================================\n\n // data-* variant: data-active, data-[state=open]\n // Both arbitrary and named values produce the same selector format\n variants.functional(\"data\", (rule, variant) => {\n if (!variant.value) return null;\n rule.selector = `${rule.selector}[data-${variant.value.value}]`;\n });\n\n // ============================================\n // ARIA Attribute Variants\n // ============================================\n\n // aria-* variant: aria-disabled, aria-[hidden=true]\n variants.functional(\"aria\", (rule, variant) => {\n if (!variant.value) return null;\n\n // Arbitrary values are used as-is, named values default to \"true\"\n const attrValue = variant.value.kind === \"arbitrary\" ? variant.value.value : `${variant.value.value}=\"true\"`;\n rule.selector = `${rule.selector}[aria-${attrValue}]`;\n });\n\n // ============================================\n // Common ARIA States (shortcuts)\n // ============================================\n\n const ariaShortcuts = [\"checked\", \"disabled\", \"expanded\", \"hidden\", \"pressed\", \"readonly\", \"required\", \"selected\"];\n for (const attr of ariaShortcuts) {\n variants.static(`aria-${attr}`, (rule) => {\n rule.selector = `${rule.selector}[aria-${attr}=\"true\"]`;\n });\n }\n\n // ============================================\n // Common Data States (shortcuts)\n // ============================================\n\n const dataShortcuts = [\"active\", \"disabled\", \"loading\"];\n for (const attr of dataShortcuts) {\n variants.static(`data-${attr}`, (rule) => {\n rule.selector = `${rule.selector}[data-${attr}]`;\n });\n }\n\n // Special data-state shortcuts\n variants.static(\"data-open\", (rule) => {\n rule.selector = `${rule.selector}[data-state=\"open\"]`;\n });\n\n variants.static(\"data-closed\", (rule) => {\n rule.selector = `${rule.selector}[data-state=\"closed\"]`;\n });\n\n // ============================================\n // Group and Peer Variants (compound)\n // ============================================\n\n // Compound variants (group-hover, peer-focus, etc.) are handled automatically\n // in the Variants class via the `applyCompoundVariant` method.\n //\n // Examples:\n // - group-hover:text-paper -> .group:hover .group-hover\\:text-paper\n // - peer-focus:text-paper -> .peer:focus ~ .peer-focus\\:text-paper\n // - group/sidebar-hover:text-paper -> .group\\/sidebar:hover .group\\/sidebar-hover\\:text-paper\n\n // ============================================\n // Has Variant (CSS :has() selector)\n // ============================================\n\n variants.functional(\"has\", (rule, variant) => {\n if (!variant.value) return null;\n\n // Arbitrary values are used as-is, named values become pseudo-classes\n const inner = variant.value.kind === \"arbitrary\" ? variant.value.value : `:${variant.value.value}`;\n rule.selector = `${rule.selector}:has(${inner})`;\n });\n\n // ============================================\n // Not Variant\n // ============================================\n\n variants.functional(\"not\", (rule, variant) => {\n if (!variant.value) return null;\n\n // Arbitrary values are used as-is, named values become pseudo-classes\n const inner = variant.value.kind === \"arbitrary\" ? variant.value.value : `:${variant.value.value}`;\n rule.selector = `${rule.selector}:not(${inner})`;\n });\n\n // ============================================\n // Where Variant (zero specificity)\n // ============================================\n\n variants.functional(\"where\", (rule, variant) => {\n if (!variant.value || variant.value.kind !== \"arbitrary\") return null;\n rule.selector = `:where(${variant.value.value}) ${rule.selector}`;\n });\n\n // ============================================\n // Is Variant\n // ============================================\n\n variants.functional(\"is\", (rule, variant) => {\n if (!variant.value || variant.value.kind !== \"arbitrary\") return null;\n rule.selector = `:is(${variant.value.value}) ${rule.selector}`;\n });\n}\n","/**\n * Variants Module\n *\n * Core variant system and default variant registrations.\n */\n\nexport * from \"./variants\";\nexport * from \"./pseudo\";\nexport * from \"./media\";\nexport * from \"./data\";\n\nimport type { Theme } from \"../theme\";\nimport { Variants } from \"./variants\";\nimport { registerPseudoVariants } from \"./pseudo\";\nimport { registerMediaVariants } from \"./media\";\nimport { registerDataVariants } from \"./data\";\n\nlet _cachedDefaultVariants: Variants | null = null;\n\n/**\n * Create a Variants instance with all default variants registered.\n */\nexport function createDefaultVariants(theme: Theme): Variants {\n if (_cachedDefaultVariants === null) {\n const variants = new Variants();\n\n registerPseudoVariants(variants);\n registerMediaVariants(variants);\n registerDataVariants(variants, theme);\n\n _cachedDefaultVariants = variants;\n }\n\n return _cachedDefaultVariants.clone();\n}\n","/**\n * Plugin API\n *\n * The API passed to plugin functions for extending the design system.\n */\n\nimport type { AstNode } from \"../ast\";\nimport { decl, styleRule } from \"../ast\";\nimport type { FunctionalCandidate } from \"../candidate\";\nimport type { Theme } from \"../theme\";\nimport type { Utilities } from \"../utilities\";\nimport type { Variants } from \"../variants\";\n\n/**\n * The API object passed to plugin functions.\n */\nexport interface PluginAPI {\n /**\n * Add a static utility class.\n * @example\n * addUtility('truncate', {\n * overflow: 'hidden',\n * 'text-overflow': 'ellipsis',\n * 'white-space': 'nowrap',\n * })\n */\n addUtility(name: string, declarations: Record<string, string>): void;\n\n /**\n * Add a functional utility that accepts values.\n * @example\n * addFunctionalUtility('custom-spacing', (value, theme) => ({\n * '--custom-spacing': theme.get(`--spacing-${value}`) ?? `${value}rem`,\n * }))\n */\n addFunctionalUtility(name: string, handler: (value: string, theme: Theme) => Record<string, string> | null): void;\n\n /**\n * Add a static variant.\n * @example\n * addVariant('hocus', '&:hover, &:focus')\n */\n addVariant(name: string, selector: string | ((selector: string) => string)): void;\n\n /**\n * Add a functional variant that accepts values.\n * @example\n * addFunctionalVariant('nth', (value) => `&:nth-child(${value})`)\n */\n addFunctionalVariant(name: string, handler: (value: string) => string | null): void;\n\n /**\n * Extend the theme with custom values.\n * @example\n * extendTheme({\n * '--color-brand': '#ff0000',\n * '--spacing-huge': '100rem',\n * })\n */\n extendTheme(values: Record<string, string>): void;\n\n /**\n * Add raw CSS to the output.\n * This CSS will be included in the final output.\n * @example\n * addBase({\n * 'html': { 'font-size': '16px' },\n * 'body': { 'line-height': '1.5' },\n * })\n */\n addBase(styles: Record<string, Record<string, string>>): void;\n\n /**\n * Add component styles.\n * Similar to addBase but intended for component-level styles.\n * @example\n * addComponents({\n * '.btn': {\n * padding: '0.5rem 1rem',\n * 'border-radius': '0.25rem',\n * },\n * })\n */\n addComponents(styles: Record<string, Record<string, string>>): void;\n\n /**\n * Get a value from the theme.\n * @example\n * theme('--color-red-500') // => 'oklch(0.637 0.237 25.331)'\n */\n theme(key: string): string | undefined;\n\n /**\n * Access the design system's theme instance.\n */\n readonly themeInstance: Theme;\n\n /**\n * Access the design system's utilities instance.\n */\n readonly utilitiesInstance: Utilities;\n\n /**\n * Access the design system's variants instance.\n */\n readonly variantsInstance: Variants;\n}\n\n/**\n * Create a plugin API instance for a design system.\n */\nexport function createPluginAPI(\n theme: Theme,\n utilities: Utilities,\n variants: Variants,\n baseStyles: AstNode[],\n componentStyles: AstNode[]\n): PluginAPI {\n return {\n addUtility(name: string, declarations: Record<string, string>) {\n const nodes = Object.entries(declarations).map(([prop, value]) => decl(prop, value));\n utilities.static(name, () => nodes);\n },\n\n addFunctionalUtility(name: string, handler: (value: string, theme: Theme) => Record<string, string> | null) {\n utilities.functional(name, (candidate: FunctionalCandidate, themeRef: Theme) => {\n if (!candidate.value) return null;\n\n const result = handler(candidate.value.value, themeRef);\n if (!result) return null;\n\n return Object.entries(result).map(([prop, val]) => decl(prop, val));\n });\n },\n\n addVariant(name: string, selector: string | ((selector: string) => string)) {\n if (typeof selector === \"string\") {\n // Simple selector replacement\n variants.static(name, (rule) => {\n rule.selector = selector.replace(/&/g, rule.selector);\n });\n } else {\n // Function-based selector\n variants.static(name, (rule) => {\n rule.selector = selector(rule.selector);\n });\n }\n },\n\n addFunctionalVariant(name: string, handler: (value: string) => string | null) {\n variants.functional(name, (rule, variant) => {\n if (!variant.value) return null;\n\n const result = handler(variant.value.value);\n if (!result) return null;\n\n rule.selector = result.replace(/&/g, rule.selector);\n });\n },\n\n extendTheme(values: Record<string, string>) {\n for (const [key, value] of Object.entries(values)) {\n theme.add(key, value);\n }\n },\n\n addBase(styles: Record<string, Record<string, string>>) {\n for (const [selector, declarations] of Object.entries(styles)) {\n const nodes = Object.entries(declarations).map(([prop, value]) => decl(prop, value));\n baseStyles.push(styleRule(selector, nodes));\n }\n },\n\n addComponents(styles: Record<string, Record<string, string>>) {\n for (const [selector, declarations] of Object.entries(styles)) {\n const nodes = Object.entries(declarations).map(([prop, value]) => decl(prop, value));\n componentStyles.push(styleRule(selector, nodes));\n }\n },\n\n theme(key: string): string | undefined {\n return theme.get(key) ?? undefined;\n },\n\n get themeInstance() {\n return theme;\n },\n\n get utilitiesInstance() {\n return utilities;\n },\n\n get variantsInstance() {\n return variants;\n },\n };\n}\n","/**\n * Plugin System\n *\n * Core plugin types and loading functionality.\n */\n\nimport type { AstNode } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport type { Utilities } from \"../utilities\";\nimport type { Variants } from \"../variants\";\nimport { createPluginAPI, type PluginAPI } from \"./api\";\n\n/**\n * A plugin function that extends the design system.\n */\nexport type PluginFunction = (api: PluginAPI) => void;\n\n/**\n * A plugin with configuration options.\n */\nexport interface PluginWithOptions<T = Record<string, unknown>> {\n (options?: T): PluginFunction;\n __isPluginWithOptions: true;\n}\n\n/**\n * A plugin can be either a function or a plugin with options.\n */\n// eslint-disable-next-line @typescript-eslint/no-explicit-any\nexport type Plugin = PluginFunction | PluginWithOptions<any>;\n\n/**\n * Plugin configuration for the design system.\n */\nexport interface PluginConfig {\n /** List of plugins to load */\n plugins?: Plugin[];\n /** Plugin options by plugin name */\n pluginOptions?: Record<string, unknown>;\n}\n\n/**\n * Create a simple plugin.\n *\n * @example\n * const myPlugin = plugin((api) => {\n * api.addUtility('custom', { color: 'red' })\n * })\n */\nexport function plugin(fn: PluginFunction): PluginFunction {\n return fn;\n}\n\n/**\n * Create a plugin that accepts configuration options.\n *\n * @example\n * const myPlugin = pluginWithOptions<{ prefix: string }>((options = {}) => {\n * return (api) => {\n * const prefix = options.prefix ?? 'my'\n * api.addUtility(`${prefix}-custom`, { color: 'red' })\n * }\n * })\n *\n * // Usage:\n * myPlugin({ prefix: 'custom' })\n */\nexport function pluginWithOptions<T = Record<string, unknown>>(\n fn: (options?: T) => PluginFunction\n): PluginWithOptions<T> {\n const wrapper = (options?: T) => fn(options);\n (wrapper as PluginWithOptions<T>).__isPluginWithOptions = true;\n return wrapper as PluginWithOptions<T>;\n}\n\n/**\n * Check if a value is a plugin with options.\n */\nexport function isPluginWithOptions(value: unknown): value is PluginWithOptions {\n return typeof value === \"function\" && \"__isPluginWithOptions\" in value && value.__isPluginWithOptions === true;\n}\n\n/**\n * Result of loading plugins.\n */\nexport interface LoadPluginsResult {\n /** Base styles added by plugins */\n baseStyles: AstNode[];\n /** Component styles added by plugins */\n componentStyles: AstNode[];\n}\n\n/**\n * Load and execute plugins against a design system.\n *\n * @param plugins - List of plugins to load\n * @param theme - The theme instance\n * @param utilities - The utilities instance\n * @param variants - The variants instance\n * @returns The styles added by plugins\n */\nexport function loadPlugins(\n plugins: Plugin[],\n theme: Theme,\n utilities: Utilities,\n variants: Variants\n): LoadPluginsResult {\n const baseStyles: AstNode[] = [];\n const componentStyles: AstNode[] = [];\n\n const api = createPluginAPI(theme, utilities, variants, baseStyles, componentStyles);\n\n for (const pluginItem of plugins) {\n if (isPluginWithOptions(pluginItem)) {\n // Plugin with options - call with undefined to get default options\n const fn = pluginItem();\n fn(api);\n } else {\n // Regular plugin function\n pluginItem(api);\n }\n }\n\n return { baseStyles, componentStyles };\n}\n\n/**\n * Built-in plugin for CSS container queries.\n * Adds the @container variant and container utilities.\n */\nexport const containerQueriesPlugin = plugin((api) => {\n // Container utility\n api.addUtility(\"container\", {\n \"container-type\": \"inline-size\",\n });\n\n // Container name utility\n api.addFunctionalUtility(\"container-name\", (value) => ({\n \"container-name\": value,\n }));\n\n // Container type utilities\n api.addUtility(\"container-normal\", {\n \"container-type\": \"normal\",\n });\n\n api.addUtility(\"container-size\", {\n \"container-type\": \"size\",\n });\n\n api.addUtility(\"container-inline-size\", {\n \"container-type\": \"inline-size\",\n });\n});\n\n/**\n * Built-in plugin for aspect ratio utilities.\n * Adds additional aspect ratio values beyond the defaults.\n */\nexport const aspectRatioPlugin = plugin((api) => {\n // Extended aspect ratios\n api.extendTheme({\n \"--aspect-portrait\": \"3 / 4\",\n \"--aspect-landscape\": \"4 / 3\",\n \"--aspect-wide\": \"21 / 9\",\n \"--aspect-ultrawide\": \"32 / 9\",\n });\n});\n\n/**\n * Built-in plugin for forms styling.\n * Resets form element styling for better cross-browser consistency.\n */\nexport const formsPlugin = plugin((api) => {\n api.addBase({\n \"[type='text']\": {\n appearance: \"none\",\n \"background-color\": \"#fff\",\n \"border-color\": \"var(--color-gray-500, #6b7280)\",\n \"border-width\": \"1px\",\n \"border-radius\": \"0\",\n padding: \"0.5rem 0.75rem\",\n \"font-size\": \"1rem\",\n \"line-height\": \"1.5\",\n },\n \"[type='email']\": {\n appearance: \"none\",\n \"background-color\": \"#fff\",\n \"border-color\": \"var(--color-gray-500, #6b7280)\",\n \"border-width\": \"1px\",\n \"border-radius\": \"0\",\n padding: \"0.5rem 0.75rem\",\n \"font-size\": \"1rem\",\n \"line-height\": \"1.5\",\n },\n \"[type='url']\": {\n appearance: \"none\",\n \"background-color\": \"#fff\",\n \"border-color\": \"var(--color-gray-500, #6b7280)\",\n \"border-width\": \"1px\",\n \"border-radius\": \"0\",\n padding: \"0.5rem 0.75rem\",\n \"font-size\": \"1rem\",\n \"line-height\": \"1.5\",\n },\n select: {\n appearance: \"none\",\n \"background-color\": \"#fff\",\n \"border-color\": \"var(--color-gray-500, #6b7280)\",\n \"border-width\": \"1px\",\n \"border-radius\": \"0\",\n padding: \"0.5rem 0.75rem\",\n \"font-size\": \"1rem\",\n \"line-height\": \"1.5\",\n },\n textarea: {\n appearance: \"none\",\n \"background-color\": \"#fff\",\n \"border-color\": \"var(--color-gray-500, #6b7280)\",\n \"border-width\": \"1px\",\n \"border-radius\": \"0\",\n padding: \"0.5rem 0.75rem\",\n \"font-size\": \"1rem\",\n \"line-height\": \"1.5\",\n },\n });\n});\n\n/**\n * Built-in plugin for typography prose styles.\n */\nexport const typographyPlugin = plugin((api) => {\n api.addComponents({\n \".prose\": {\n color: \"var(--color-gray-700, #374151)\",\n \"max-width\": \"65ch\",\n \"line-height\": \"1.75\",\n },\n \".prose p\": {\n \"margin-top\": \"1.25em\",\n \"margin-bottom\": \"1.25em\",\n },\n \".prose h1\": {\n color: \"var(--color-gray-900, #111827)\",\n \"font-weight\": \"800\",\n \"font-size\": \"2.25em\",\n \"margin-top\": \"0\",\n \"margin-bottom\": \"0.889em\",\n \"line-height\": \"1.111\",\n },\n \".prose h2\": {\n color: \"var(--color-gray-900, #111827)\",\n \"font-weight\": \"700\",\n \"font-size\": \"1.5em\",\n \"margin-top\": \"2em\",\n \"margin-bottom\": \"1em\",\n \"line-height\": \"1.333\",\n },\n \".prose h3\": {\n color: \"var(--color-gray-900, #111827)\",\n \"font-weight\": \"600\",\n \"font-size\": \"1.25em\",\n \"margin-top\": \"1.6em\",\n \"margin-bottom\": \"0.6em\",\n \"line-height\": \"1.6\",\n },\n \".prose a\": {\n color: \"var(--color-blue-600, #2563eb)\",\n \"text-decoration\": \"underline\",\n \"font-weight\": \"500\",\n },\n \".prose code\": {\n color: \"var(--color-gray-900, #111827)\",\n \"font-weight\": \"600\",\n \"font-size\": \"0.875em\",\n },\n \".prose pre\": {\n color: \"var(--color-gray-200, #e5e7eb)\",\n \"background-color\": \"var(--color-gray-800, #1f2937)\",\n \"overflow-x\": \"auto\",\n \"font-size\": \"0.875em\",\n \"line-height\": \"1.714\",\n \"margin-top\": \"1.714em\",\n \"margin-bottom\": \"1.714em\",\n \"border-radius\": \"0.375rem\",\n padding: \"0.857em 1.143em\",\n },\n \".prose blockquote\": {\n \"font-weight\": \"500\",\n \"font-style\": \"italic\",\n color: \"var(--color-gray-900, #111827)\",\n \"border-left-width\": \"0.25rem\",\n \"border-left-color\": \"var(--color-gray-300, #d1d5db)\",\n \"margin-top\": \"1.6em\",\n \"margin-bottom\": \"1.6em\",\n \"padding-left\": \"1em\",\n },\n \".prose ul\": {\n \"margin-top\": \"1.25em\",\n \"margin-bottom\": \"1.25em\",\n \"padding-left\": \"1.625em\",\n \"list-style-type\": \"disc\",\n },\n \".prose ol\": {\n \"margin-top\": \"1.25em\",\n \"margin-bottom\": \"1.25em\",\n \"padding-left\": \"1.625em\",\n \"list-style-type\": \"decimal\",\n },\n \".prose li\": {\n \"margin-top\": \"0.5em\",\n \"margin-bottom\": \"0.5em\",\n },\n });\n});\n","/**\n * CSS Escape/Unescape Utilities\n *\n * Functions for escaping and unescaping CSS identifiers and strings.\n */\n\n/**\n * Characters that need escaping in CSS identifiers.\n */\nconst ESCAPE_CHARS = /[!\"#$%&'()*+,./:;<=>?@[\\\\\\]^`{|}~\\s]/;\n\n/**\n * Pattern for non-printable ASCII characters that need escaping.\n */\nconst NON_PRINTABLE_ASCII = /[^\\x20-\\x7e]/;\n\n/**\n * Escape a string for use as a CSS class name.\n *\n * @example\n * ```ts\n * escapeClassName(\"bg-[#ff0000]\") // \"bg-\\\\[\\\\#ff0000\\\\]\"\n * escapeClassName(\"w-1/2\") // \"w-1\\\\/2\"\n * escapeClassName(\"2xl\") // \"\\\\32xl\"\n * ```\n */\nexport function escapeClassName(className: string): string {\n if (!className) return \"\";\n\n let result = \"\";\n\n for (let i = 0; i < className.length; ) {\n const codePoint = className.codePointAt(i)!;\n const char = String.fromCodePoint(codePoint);\n const nextIndex = i + (codePoint > 0xffff ? 2 : 1);\n\n // Escape the first character if it's a digit or dash followed by digit\n if (i === 0) {\n if (codePoint >= 0x30 && codePoint <= 0x39) {\n // Digit: escape as \\3X (hex code point + space)\n result += `\\\\3${char} `;\n i = nextIndex;\n continue;\n }\n if (char === \"-\" && className.length > nextIndex) {\n const nextCode = className.codePointAt(nextIndex) ?? 0;\n if (nextCode >= 0x30 && nextCode <= 0x39) {\n // Dash followed by digit: escape the dash\n result += \"\\\\-\";\n i = nextIndex;\n continue;\n }\n }\n }\n\n // Special characters that need escaping\n if (ESCAPE_CHARS.test(char)) {\n result += `\\\\${char}`;\n i = nextIndex;\n continue;\n }\n\n // Non-ASCII characters (escape as hex)\n if (codePoint > 0x7f) {\n result += `\\\\${codePoint.toString(16)} `;\n i = nextIndex;\n continue;\n }\n\n result += char;\n i = nextIndex;\n }\n\n return result;\n}\n\n/**\n * Unescape a CSS identifier back to its original form.\n *\n * @example\n * ```ts\n * unescape(\"bg-\\\\[\\\\#ff0000\\\\]\") // \"bg-[#ff0000]\"\n * unescape(\"w-1\\\\/2\") // \"w-1/2\"\n * unescape(\"\\\\32xl\") // \"2xl\"\n * ```\n */\nexport function unescape(escaped: string): string {\n if (!escaped) return \"\";\n\n let result = \"\";\n let i = 0;\n\n while (i < escaped.length) {\n const char = escaped[i]!;\n\n if (char !== \"\\\\\") {\n result += char;\n i++;\n continue;\n }\n\n // Escape sequence\n i++; // Skip the backslash\n\n if (i >= escaped.length) {\n // Trailing backslash\n result += \"\\\\\";\n break;\n }\n\n const nextChar = escaped[i]!;\n const nextCode = nextChar.charCodeAt(0);\n\n // Hex escape: \\XXXXXX (1-6 hex digits, optionally followed by space)\n if (isHexDigit(nextCode)) {\n let hex = \"\";\n let j = i;\n\n // Collect up to 6 hex digits\n while (j < escaped.length && hex.length < 6 && isHexDigit(escaped.charCodeAt(j))) {\n hex += escaped[j];\n j++;\n }\n\n // Skip optional trailing space\n if (j < escaped.length && escaped[j] === \" \") {\n j++;\n }\n\n const codePoint = parseInt(hex, 16);\n result += String.fromCodePoint(codePoint);\n i = j;\n continue;\n }\n\n // Simple escape: \\X where X is any character\n result += nextChar;\n i++;\n }\n\n return result;\n}\n\n/**\n * Check if a character code is a hex digit (0-9, a-f, A-F).\n */\nfunction isHexDigit(code: number): boolean {\n return (\n (code >= 0x30 && code <= 0x39) || // 0-9\n (code >= 0x41 && code <= 0x46) || // A-F\n (code >= 0x61 && code <= 0x66) // a-f\n );\n}\n\n/**\n * Escape a string for use in a CSS string value (within quotes).\n *\n * @example\n * ```ts\n * escapeString('hello \"world\"') // 'hello \\\\\"world\\\\\"'\n * escapeString(\"line1\\nline2\") // \"line1\\\\Aline2\"\n * ```\n */\nexport function escapeString(str: string, quote: \"'\" | '\"' = '\"'): string {\n let result = \"\";\n\n for (const char of str) {\n const code = char.charCodeAt(0);\n\n // Escape the quote character\n if (char === quote) {\n result += `\\\\${char}`;\n continue;\n }\n\n // Escape backslash\n if (char === \"\\\\\") {\n result += \"\\\\\\\\\";\n continue;\n }\n\n // Escape newlines\n if (char === \"\\n\") {\n result += \"\\\\A \";\n continue;\n }\n\n // Escape carriage return\n if (char === \"\\r\") {\n result += \"\\\\D \";\n continue;\n }\n\n // Escape form feed\n if (char === \"\\f\") {\n result += \"\\\\C \";\n continue;\n }\n\n // Escape null\n if (code === 0) {\n result += \"\\\\0 \";\n continue;\n }\n\n result += char;\n }\n\n return result;\n}\n\n/**\n * Unescape a CSS string value.\n *\n * @example\n * ```ts\n * unescapeString('hello \\\\\"world\\\\\"') // 'hello \"world\"'\n * unescapeString(\"line1\\\\Aline2\") // \"line1\\nline2\"\n * ```\n */\nexport function unescapeString(escaped: string): string {\n // The unescape function handles both identifier and string escapes\n return unescape(escaped);\n}\n\n/**\n * Check if a string needs escaping for use as a CSS class name.\n */\nexport function needsEscaping(className: string): boolean {\n if (!className) return false;\n\n // Check first character\n const firstCode = className.charCodeAt(0);\n if (firstCode >= 0x30 && firstCode <= 0x39) return true; // Starts with digit\n\n if (className[0] === \"-\" && className.length > 1) {\n const secondCode = className.charCodeAt(1);\n if (secondCode >= 0x30 && secondCode <= 0x39) return true; // -digit\n }\n\n // Check for special characters\n return ESCAPE_CHARS.test(className) || NON_PRINTABLE_ASCII.test(className);\n}\n\n/**\n * Convert a CSS escape sequence to its character.\n *\n * @example\n * ```ts\n * escapeSequenceToChar(\"\\\\31\") // \"1\"\n * ```\n */\nexport function escapeSequenceToChar(escape: string): string {\n return unescape(escape);\n}\n","/**\n * Compare two strings alphanumerically.\n * Numbers within strings are compared numerically, not lexicographically.\n *\n * @example\n * ```ts\n * [\"item2\", \"item10\", \"item1\"].sort(compare)\n * // [\"item1\", \"item2\", \"item10\"]\n *\n * // vs regular sort:\n * [\"item2\", \"item10\", \"item1\"].sort()\n * // [\"item1\", \"item10\", \"item2\"] // Wrong!\n * ```\n */\nexport function compare(a: string, b: string): number {\n const aLen = a.length;\n const bLen = b.length;\n let ai = 0;\n let bi = 0;\n\n while (ai < aLen && bi < bLen) {\n const aChar = a.charCodeAt(ai);\n const bChar = b.charCodeAt(bi);\n\n const aIsDigit = isDigit(aChar);\n const bIsDigit = isDigit(bChar);\n\n // Both are digits - compare as numbers\n if (aIsDigit && bIsDigit) {\n const aNum = extractNumber(a, ai);\n const bNum = extractNumber(b, bi);\n\n if (aNum.value !== bNum.value) {\n return aNum.value - bNum.value;\n }\n\n // Same numeric value, advance past the digits\n ai = aNum.end;\n bi = bNum.end;\n continue;\n }\n\n // One is a digit, one is not\n if (aIsDigit !== bIsDigit) {\n // Digits come before non-digits\n return aIsDigit ? -1 : 1;\n }\n\n // Both are non-digits - compare characters\n if (aChar !== bChar) {\n return aChar - bChar;\n }\n\n ai++;\n bi++;\n }\n\n // Shorter string comes first\n return aLen - bLen;\n}\n\n/**\n * Check if a character code is a digit (0-9).\n */\nfunction isDigit(charCode: number): boolean {\n return charCode >= 0x30 && charCode <= 0x39; // '0' to '9'\n}\n\n/**\n * Extract a number from a string starting at a position.\n * Returns the numeric value and the end position.\n */\nfunction extractNumber(str: string, start: number): { value: number; end: number } {\n let end = start;\n while (end < str.length && isDigit(str.charCodeAt(end))) {\n end++;\n }\n return {\n value: parseInt(str.slice(start, end), 10),\n end,\n };\n}\n\n/**\n * Compare two values with a key extractor.\n *\n * @example\n * ```ts\n * const items = [{ name: \"b\" }, { name: \"a\" }];\n * items.sort(compareBy(item => item.name));\n * // [{ name: \"a\" }, { name: \"b\" }]\n * ```\n */\nexport function compareBy<T>(fn: (item: T) => string): (a: T, b: T) => number {\n return (a, b) => compare(fn(a), fn(b));\n}\n\n/**\n * Compare two numbers.\n */\nexport function compareNumbers(a: number, b: number): number {\n return a - b;\n}\n\n/**\n * Reverse a comparison function.\n */\nexport function descending<T>(compareFn: (a: T, b: T) => number): (a: T, b: T) => number {\n return (a, b) => compareFn(b, a);\n}\n\n/**\n * Chain multiple comparison functions.\n * Falls through to the next comparator when values are equal.\n *\n * @example\n * ```ts\n * const items = [\n * { group: \"a\", value: 2 },\n * { group: \"b\", value: 1 },\n * { group: \"a\", value: 1 },\n * ];\n * items.sort(chainCompare(\n * compareBy(i => i.group),\n * compareBy(i => String(i.value))\n * ));\n * // [{ group: \"a\", value: 1 }, { group: \"a\", value: 2 }, { group: \"b\", value: 1 }]\n * ```\n */\nexport function chainCompare<T>(...compareFns: Array<(a: T, b: T) => number>): (a: T, b: T) => number {\n return (a, b) => {\n for (const fn of compareFns) {\n const result = fn(a, b);\n if (result !== 0) return result;\n }\n return 0;\n };\n}\n\n/**\n * Create a stable sort function that preserves original order for equal elements.\n *\n * @example\n * ```ts\n * const items = [\"a1\", \"b1\", \"a2\"];\n * const sorted = stableSort(items, compare);\n * ```\n */\nexport function stableSort<T>(array: T[], compareFn: (a: T, b: T) => number): T[] {\n // Modern JS engines have stable sort, but this ensures it\n const indexed = array.map((item, index) => ({ item, index }));\n indexed.sort((a, b) => {\n const result = compareFn(a.item, b.item);\n return result !== 0 ? result : a.index - b.index;\n });\n return indexed.map(({ item }) => item);\n}\n","/**\n * CSS Property Sort Module\n *\n * Orders CSS declarations in a canonical order for consistent output.\n * Follows established conventions: positioning > display > box model > typography > visual.\n */\n\nimport type { AstNode, Declaration, StyleRule } from \"../ast\";\nimport { compare } from \"../utils/compare\";\nimport { compareBreakpoints } from \"../utils/compare-breakpoints\";\nimport { hasMathFunction } from \"../utils/math-operators\";\n\n// Pre-compiled regex patterns for breakpoint variant normalization (hoisted to avoid recreation)\nconst NUMERIC_ONLY_PATTERN = /^\\d+(?:\\.\\d+)?$/;\nconst NUMERIC_WITH_UNIT_PATTERN =\n /^\\d+(?:\\.\\d+)?(px|rem|em|vw|vh|vmin|vmax|%|svw|svh|lvw|lvh|dvw|dvh|cqw|cqh|cqi|cqb|cqmin|cqmax)$/;\n\n// ============================================\n// Property Order\n// ============================================\n\n/**\n * CSS property order based on common conventions.\n * Lower numbers appear first in output.\n */\nconst PROPERTY_ORDER: Record<string, number> = {\n // Content generation\n content: 1,\n\n // Position\n position: 10,\n inset: 11,\n \"inset-block\": 12,\n \"inset-block-start\": 13,\n \"inset-block-end\": 14,\n \"inset-inline\": 15,\n \"inset-inline-start\": 16,\n \"inset-inline-end\": 17,\n top: 18,\n right: 19,\n bottom: 20,\n left: 21,\n \"z-index\": 22,\n\n // Display & Box Model\n display: 30,\n visibility: 31,\n float: 32,\n clear: 33,\n\n // Flexbox\n flex: 40,\n \"flex-basis\": 41,\n \"flex-direction\": 42,\n \"flex-flow\": 43,\n \"flex-grow\": 44,\n \"flex-shrink\": 45,\n \"flex-wrap\": 46,\n\n // Grid\n grid: 50,\n \"grid-area\": 51,\n \"grid-auto-columns\": 52,\n \"grid-auto-flow\": 53,\n \"grid-auto-rows\": 54,\n \"grid-column\": 55,\n \"grid-column-end\": 56,\n \"grid-column-gap\": 57,\n \"grid-column-start\": 58,\n \"grid-gap\": 59,\n \"grid-row\": 60,\n \"grid-row-end\": 61,\n \"grid-row-gap\": 62,\n \"grid-row-start\": 63,\n \"grid-template\": 64,\n \"grid-template-areas\": 65,\n \"grid-template-columns\": 66,\n \"grid-template-rows\": 67,\n\n // Alignment\n \"align-content\": 70,\n \"align-items\": 71,\n \"align-self\": 72,\n \"justify-content\": 73,\n \"justify-items\": 74,\n \"justify-self\": 75,\n \"place-content\": 76,\n \"place-items\": 77,\n \"place-self\": 78,\n\n // Order\n order: 80,\n\n // Gap\n gap: 85,\n \"column-gap\": 86,\n \"row-gap\": 87,\n\n // Box sizing\n \"box-sizing\": 90,\n\n // Dimensions\n width: 100,\n \"min-width\": 101,\n \"max-width\": 102,\n height: 110,\n \"min-height\": 111,\n \"max-height\": 112,\n \"inline-size\": 115,\n \"min-inline-size\": 116,\n \"max-inline-size\": 117,\n \"block-size\": 118,\n \"min-block-size\": 119,\n \"max-block-size\": 120,\n \"aspect-ratio\": 125,\n\n // Margin\n margin: 130,\n \"margin-block\": 131,\n \"margin-block-start\": 132,\n \"margin-block-end\": 133,\n \"margin-inline\": 134,\n \"margin-inline-start\": 135,\n \"margin-inline-end\": 136,\n \"margin-top\": 137,\n \"margin-right\": 138,\n \"margin-bottom\": 139,\n \"margin-left\": 140,\n\n // Padding\n padding: 150,\n \"padding-block\": 151,\n \"padding-block-start\": 152,\n \"padding-block-end\": 153,\n \"padding-inline\": 154,\n \"padding-inline-start\": 155,\n \"padding-inline-end\": 156,\n \"padding-top\": 157,\n \"padding-right\": 158,\n \"padding-bottom\": 159,\n \"padding-left\": 160,\n\n // Border\n border: 170,\n \"border-collapse\": 171,\n \"border-spacing\": 172,\n \"border-color\": 173,\n \"border-style\": 174,\n \"border-width\": 175,\n \"border-block\": 176,\n \"border-block-start\": 177,\n \"border-block-end\": 178,\n \"border-inline\": 179,\n \"border-inline-start\": 180,\n \"border-inline-end\": 181,\n \"border-top\": 182,\n \"border-top-color\": 183,\n \"border-top-style\": 184,\n \"border-top-width\": 185,\n \"border-right\": 186,\n \"border-right-color\": 187,\n \"border-right-style\": 188,\n \"border-right-width\": 189,\n \"border-bottom\": 190,\n \"border-bottom-color\": 191,\n \"border-bottom-style\": 192,\n \"border-bottom-width\": 193,\n \"border-left\": 194,\n \"border-left-color\": 195,\n \"border-left-style\": 196,\n \"border-left-width\": 197,\n\n // Border radius\n \"border-radius\": 200,\n \"border-start-start-radius\": 201,\n \"border-start-end-radius\": 202,\n \"border-end-start-radius\": 203,\n \"border-end-end-radius\": 204,\n \"border-top-left-radius\": 205,\n \"border-top-right-radius\": 206,\n \"border-bottom-right-radius\": 207,\n \"border-bottom-left-radius\": 208,\n\n // Outline\n outline: 210,\n \"outline-color\": 211,\n \"outline-offset\": 212,\n \"outline-style\": 213,\n \"outline-width\": 214,\n\n // Background\n background: 220,\n \"background-attachment\": 221,\n \"background-blend-mode\": 222,\n \"background-clip\": 223,\n \"background-color\": 224,\n \"background-image\": 225,\n \"background-origin\": 226,\n \"background-position\": 227,\n \"background-position-x\": 228,\n \"background-position-y\": 229,\n \"background-repeat\": 230,\n \"background-size\": 231,\n\n // Typography\n color: 300,\n font: 310,\n \"font-family\": 311,\n \"font-feature-settings\": 312,\n \"font-kerning\": 313,\n \"font-optical-sizing\": 314,\n \"font-size\": 315,\n \"font-size-adjust\": 316,\n \"font-stretch\": 317,\n \"font-style\": 318,\n \"font-synthesis\": 319,\n \"font-variant\": 320,\n \"font-variant-alternates\": 321,\n \"font-variant-caps\": 322,\n \"font-variant-east-asian\": 323,\n \"font-variant-ligatures\": 324,\n \"font-variant-numeric\": 325,\n \"font-variation-settings\": 326,\n \"font-weight\": 327,\n \"letter-spacing\": 330,\n \"line-break\": 331,\n \"line-height\": 332,\n \"overflow-wrap\": 333,\n \"tab-size\": 334,\n \"text-align\": 335,\n \"text-align-last\": 336,\n \"text-combine-upright\": 337,\n \"text-decoration\": 338,\n \"text-decoration-color\": 339,\n \"text-decoration-line\": 340,\n \"text-decoration-skip-ink\": 341,\n \"text-decoration-style\": 342,\n \"text-decoration-thickness\": 343,\n \"text-emphasis\": 344,\n \"text-emphasis-color\": 345,\n \"text-emphasis-position\": 346,\n \"text-emphasis-style\": 347,\n \"text-indent\": 348,\n \"text-justify\": 349,\n \"text-orientation\": 350,\n \"text-overflow\": 351,\n \"text-rendering\": 352,\n \"text-shadow\": 353,\n \"text-transform\": 354,\n \"text-underline-offset\": 355,\n \"text-underline-position\": 356,\n \"text-wrap\": 357,\n \"white-space\": 360,\n \"word-break\": 361,\n \"word-spacing\": 362,\n \"writing-mode\": 363,\n hyphens: 364,\n\n // List\n \"list-style\": 370,\n \"list-style-image\": 371,\n \"list-style-position\": 372,\n \"list-style-type\": 373,\n\n // Table\n \"table-layout\": 380,\n \"caption-side\": 381,\n \"empty-cells\": 382,\n\n // Visual effects\n \"box-shadow\": 400,\n opacity: 401,\n \"mix-blend-mode\": 402,\n isolation: 403,\n\n // Filters\n filter: 410,\n \"backdrop-filter\": 411,\n\n // Transform\n transform: 420,\n \"transform-box\": 421,\n \"transform-origin\": 422,\n \"transform-style\": 423,\n perspective: 424,\n \"perspective-origin\": 425,\n \"backface-visibility\": 426,\n rotate: 427,\n scale: 428,\n translate: 429,\n\n // Transitions\n transition: 500,\n \"transition-delay\": 501,\n \"transition-duration\": 502,\n \"transition-property\": 503,\n \"transition-timing-function\": 504,\n\n // Animation\n animation: 510,\n \"animation-delay\": 511,\n \"animation-direction\": 512,\n \"animation-duration\": 513,\n \"animation-fill-mode\": 514,\n \"animation-iteration-count\": 515,\n \"animation-name\": 516,\n \"animation-play-state\": 517,\n \"animation-timing-function\": 518,\n\n // Overflow & Scrolling\n overflow: 600,\n \"overflow-x\": 601,\n \"overflow-y\": 602,\n \"overflow-anchor\": 603,\n \"overscroll-behavior\": 604,\n \"overscroll-behavior-x\": 605,\n \"overscroll-behavior-y\": 606,\n \"scroll-behavior\": 607,\n \"scroll-margin\": 608,\n \"scroll-margin-block\": 609,\n \"scroll-margin-block-start\": 610,\n \"scroll-margin-block-end\": 611,\n \"scroll-margin-inline\": 612,\n \"scroll-margin-inline-start\": 613,\n \"scroll-margin-inline-end\": 614,\n \"scroll-margin-top\": 615,\n \"scroll-margin-right\": 616,\n \"scroll-margin-bottom\": 617,\n \"scroll-margin-left\": 618,\n \"scroll-padding\": 620,\n \"scroll-padding-block\": 621,\n \"scroll-padding-block-start\": 622,\n \"scroll-padding-block-end\": 623,\n \"scroll-padding-inline\": 624,\n \"scroll-padding-inline-start\": 625,\n \"scroll-padding-inline-end\": 626,\n \"scroll-padding-top\": 627,\n \"scroll-padding-right\": 628,\n \"scroll-padding-bottom\": 629,\n \"scroll-padding-left\": 630,\n \"scroll-snap-align\": 631,\n \"scroll-snap-stop\": 632,\n \"scroll-snap-type\": 633,\n\n // Clip & Mask\n clip: 700,\n \"clip-path\": 701,\n mask: 710,\n \"mask-border\": 711,\n \"mask-border-mode\": 712,\n \"mask-border-outset\": 713,\n \"mask-border-repeat\": 714,\n \"mask-border-slice\": 715,\n \"mask-border-source\": 716,\n \"mask-border-width\": 717,\n \"mask-clip\": 718,\n \"mask-composite\": 719,\n \"mask-image\": 720,\n \"mask-mode\": 721,\n \"mask-origin\": 722,\n \"mask-position\": 723,\n \"mask-repeat\": 724,\n \"mask-size\": 725,\n \"mask-type\": 726,\n\n // Interactivity\n cursor: 800,\n \"pointer-events\": 801,\n resize: 802,\n \"touch-action\": 803,\n \"user-select\": 804,\n \"caret-color\": 805,\n \"accent-color\": 806,\n appearance: 807,\n\n // SVG\n fill: 850,\n \"fill-opacity\": 851,\n \"fill-rule\": 852,\n stroke: 853,\n \"stroke-dasharray\": 854,\n \"stroke-dashoffset\": 855,\n \"stroke-linecap\": 856,\n \"stroke-linejoin\": 857,\n \"stroke-miterlimit\": 858,\n \"stroke-opacity\": 859,\n \"stroke-width\": 860,\n\n // Columns\n columns: 900,\n \"column-count\": 901,\n \"column-fill\": 902,\n // \"column-gap\" is defined earlier with gap utilities\n \"column-rule\": 904,\n \"column-rule-color\": 905,\n \"column-rule-style\": 906,\n \"column-rule-width\": 907,\n \"column-span\": 908,\n \"column-width\": 909,\n\n // Print\n \"break-after\": 950,\n \"break-before\": 951,\n \"break-inside\": 952,\n \"page-break-after\": 953,\n \"page-break-before\": 954,\n \"page-break-inside\": 955,\n orphans: 956,\n widows: 957,\n\n // Will-change & Contain\n \"will-change\": 990,\n contain: 991,\n container: 992,\n \"container-name\": 993,\n \"container-type\": 994,\n};\n\n// Default order for unknown properties (CSS custom properties go last)\nconst DEFAULT_ORDER = 10000;\nconst CSS_VAR_ORDER = 20000;\n\n// ============================================\n// Sort Functions\n// ============================================\n\n/**\n * Get the sort order for a CSS property.\n */\nexport function getPropertyOrder(property: string): number {\n // CSS custom properties (--*) go last\n if (property.startsWith(\"--\")) {\n return CSS_VAR_ORDER;\n }\n\n return PROPERTY_ORDER[property] ?? DEFAULT_ORDER;\n}\n\n/**\n * Sort CSS declarations by property order.\n *\n * @example\n * const sorted = sortDeclarations([\n * { kind: \"declaration\", property: \"color\", value: \"red\" },\n * { kind: \"declaration\", property: \"display\", value: \"flex\" },\n * { kind: \"declaration\", property: \"position\", value: \"absolute\" },\n * ]);\n * // Returns in order: position, display, color\n */\nexport function sortDeclarations(declarations: Declaration[]): Declaration[] {\n return [...declarations].sort((a, b) => {\n const orderA = getPropertyOrder(a.property);\n const orderB = getPropertyOrder(b.property);\n\n if (orderA !== orderB) {\n return orderA - orderB;\n }\n\n // If same order, use alphanumeric comparison for consistency\n return compare(a.property, b.property);\n });\n}\n\n/**\n * Sort declarations within a style rule.\n *\n * @example\n * const sortedRule = sortRuleDeclarations(rule);\n */\nexport function sortRuleDeclarations(rule: StyleRule): StyleRule {\n const declarations: Declaration[] = [];\n const other: AstNode[] = [];\n\n for (const node of rule.nodes) {\n if (node.kind === \"declaration\") {\n declarations.push(node);\n } else {\n other.push(node);\n }\n }\n\n return {\n ...rule,\n nodes: [...sortDeclarations(declarations), ...other],\n };\n}\n\n/**\n * Sort declarations in all rules within an AST.\n *\n * @example\n * const sortedAST = sortAST(ast);\n */\nexport function sortAST(ast: AstNode[]): AstNode[] {\n return ast.map((node) => {\n if (node.kind === \"rule\") {\n return sortRuleDeclarations(node);\n }\n\n if (node.kind === \"at-rule\" && node.nodes.length > 0) {\n return {\n ...node,\n nodes: sortAST(node.nodes),\n };\n }\n\n return node;\n });\n}\n\n/**\n * Compare two class names for sorting.\n * Handles variant prefixes and orders by:\n * 1. Number of variants (fewer first)\n * 2. Variant order (responsive > state > others)\n * 3. Utility name alphabetically\n *\n * @example\n * const sorted = classes.sort(compareClassNames);\n */\nexport function compareClassNames(a: string, b: string): number {\n const partsA = a.split(\":\");\n const partsB = b.split(\":\");\n\n // Compare by number of variants\n if (partsA.length !== partsB.length) {\n return partsA.length - partsB.length;\n }\n\n // Compare variants\n for (let i = 0; i < partsA.length - 1; i++) {\n const variantA = partsA[i]!;\n const variantB = partsB[i]!;\n\n const breakpointCompare = compareBreakpointVariants(variantA, variantB);\n if (breakpointCompare !== null) {\n if (breakpointCompare !== 0) {\n return breakpointCompare;\n }\n continue;\n }\n\n const orderA = getVariantOrder(variantA);\n const orderB = getVariantOrder(variantB);\n\n if (orderA !== orderB) {\n return orderA - orderB;\n }\n }\n\n // Compare base utility\n const baseA = partsA[partsA.length - 1]!;\n const baseB = partsB[partsB.length - 1]!;\n\n return compare(baseA, baseB);\n}\n\n/**\n * Get sort order for a variant name.\n */\nfunction getVariantOrder(variant: string): number {\n // Responsive variants first (in size order)\n const responsiveOrder: Record<string, number> = {\n sm: 1,\n md: 2,\n lg: 3,\n xl: 4,\n \"2xl\": 5,\n };\n\n if (variant in responsiveOrder) {\n return responsiveOrder[variant]!;\n }\n\n // Numeric/unit breakpoints come before other variants\n if (normalizeBreakpointVariant(variant)) {\n return 6;\n }\n\n // Dark mode\n if (variant === \"dark\") {\n return 10;\n }\n\n // State variants\n const stateVariants = [\n \"hover\",\n \"focus\",\n \"focus-within\",\n \"focus-visible\",\n \"active\",\n \"visited\",\n \"disabled\",\n \"checked\",\n \"required\",\n \"valid\",\n \"invalid\",\n \"first\",\n \"last\",\n \"odd\",\n \"even\",\n ];\n\n const stateIndex = stateVariants.indexOf(variant);\n if (stateIndex >= 0) {\n return 20 + stateIndex;\n }\n\n // Compound variants (group-*, peer-*)\n if (variant.startsWith(\"group-\") || variant.startsWith(\"peer-\")) {\n return 100;\n }\n\n // Others\n return 200;\n}\n\nfunction compareBreakpointVariants(a: string, b: string): number | null {\n const aValue = normalizeBreakpointVariant(a);\n const bValue = normalizeBreakpointVariant(b);\n\n if (!aValue || !bValue) {\n return null;\n }\n\n const cmp = compareBreakpoints(aValue, bValue);\n if (cmp === null) {\n return aValue.localeCompare(bValue);\n }\n\n return cmp;\n}\n\nfunction normalizeBreakpointVariant(variant: string): string | null {\n if (NUMERIC_ONLY_PATTERN.test(variant)) {\n return `${variant}rem`;\n }\n\n if (hasMathFunction(variant)) {\n return variant;\n }\n\n if (NUMERIC_WITH_UNIT_PATTERN.test(variant)) {\n return variant;\n }\n\n return null;\n}\n","/**\n * CSS Value Parser\n *\n * Parses CSS values into structured AST nodes.\n * Handles functions like oklch(), var(), calc(), color-mix(), etc.\n */\n\n/** Base node type */\nexport interface BaseNode {\n /** Start position in the original string */\n start?: number;\n /** End position in the original string */\n end?: number;\n}\n\n/** A simple word/identifier */\nexport interface WordNode extends BaseNode {\n kind: \"word\";\n value: string;\n}\n\n/** A CSS function call */\nexport interface FunctionNode extends BaseNode {\n kind: \"function\";\n name: string;\n args: CSSValueNode[];\n}\n\n/** A string literal */\nexport interface StringNode extends BaseNode {\n kind: \"string\";\n value: string;\n quote: '\"' | \"'\";\n}\n\n/** A number with optional unit */\nexport interface NumberNode extends BaseNode {\n kind: \"number\";\n value: number;\n unit: string;\n raw: string;\n}\n\n/** An operator (+, -, *, /, ,, etc.) */\nexport interface OperatorNode extends BaseNode {\n kind: \"operator\";\n value: string;\n}\n\n/** Whitespace */\nexport interface SpaceNode extends BaseNode {\n kind: \"space\";\n value: string;\n}\n\n/** A comment */\nexport interface CommentNode extends BaseNode {\n kind: \"comment\";\n value: string;\n}\n\n/** All CSS value node types */\nexport type CSSValueNode = WordNode | FunctionNode | StringNode | NumberNode | OperatorNode | SpaceNode | CommentNode;\n\nconst WHITESPACE = /^\\s+/;\nconst NUMBER = /^-?(?:\\d+(?:\\.\\d*)?|\\.\\d+)(?:e[+-]?\\d+)?([a-z%]*)/i;\nconst WORD = /^[a-z_-][a-z0-9_-]*/i;\nconst FUNCTION_START = /^[a-z_-][a-z0-9_-]*\\(/i;\nconst STRING_DOUBLE = /^\"(?:[^\"\\\\]|\\\\.)*\"/;\nconst STRING_SINGLE = /^'(?:[^'\\\\]|\\\\.)*'/;\nconst COMMENT = /^\\/\\*[\\s\\S]*?\\*\\//;\nconst OPERATOR = /^[,/:=<>+*-]/;\n\n/**\n * Tokenize a CSS value string.\n */\nfunction tokenize(input: string): CSSValueNode[] {\n const tokens: CSSValueNode[] = [];\n let pos = 0;\n\n while (pos < input.length) {\n const remaining = input.slice(pos);\n\n // Whitespace\n const wsMatch = remaining.match(WHITESPACE);\n if (wsMatch) {\n tokens.push({\n kind: \"space\",\n value: wsMatch[0],\n start: pos,\n end: pos + wsMatch[0].length,\n });\n pos += wsMatch[0].length;\n continue;\n }\n\n // Comment\n const commentMatch = remaining.match(COMMENT);\n if (commentMatch) {\n tokens.push({\n kind: \"comment\",\n value: commentMatch[0].slice(2, -2),\n start: pos,\n end: pos + commentMatch[0].length,\n });\n pos += commentMatch[0].length;\n continue;\n }\n\n // String (double quote)\n const dqMatch = remaining.match(STRING_DOUBLE);\n if (dqMatch) {\n tokens.push({\n kind: \"string\",\n value: dqMatch[0].slice(1, -1).replace(/\\\\(.)/g, \"$1\"),\n quote: '\"',\n start: pos,\n end: pos + dqMatch[0].length,\n });\n pos += dqMatch[0].length;\n continue;\n }\n\n // String (single quote)\n const sqMatch = remaining.match(STRING_SINGLE);\n if (sqMatch) {\n tokens.push({\n kind: \"string\",\n value: sqMatch[0].slice(1, -1).replace(/\\\\(.)/g, \"$1\"),\n quote: \"'\",\n start: pos,\n end: pos + sqMatch[0].length,\n });\n pos += sqMatch[0].length;\n continue;\n }\n\n // Number (must check before word because of units)\n const numMatch = remaining.match(NUMBER);\n if (numMatch) {\n const raw = numMatch[0];\n const unit = numMatch[1] || \"\";\n const numPart = raw.slice(0, raw.length - unit.length);\n\n tokens.push({\n kind: \"number\",\n value: parseFloat(numPart),\n unit,\n raw,\n start: pos,\n end: pos + raw.length,\n });\n pos += raw.length;\n continue;\n }\n\n // Function call start\n if (remaining.match(FUNCTION_START)) {\n const nameMatch = remaining.match(WORD);\n const name = nameMatch![0];\n\n tokens.push({\n kind: \"word\",\n value: name,\n start: pos,\n end: pos + name.length,\n });\n pos += name.length;\n\n // Add the opening paren as operator\n tokens.push({\n kind: \"operator\",\n value: \"(\",\n start: pos,\n end: pos + 1,\n });\n pos += 1;\n continue;\n }\n\n // Word/identifier\n const wordMatch = remaining.match(WORD);\n if (wordMatch) {\n tokens.push({\n kind: \"word\",\n value: wordMatch[0],\n start: pos,\n end: pos + wordMatch[0].length,\n });\n pos += wordMatch[0].length;\n continue;\n }\n\n // Parentheses and brackets\n if (remaining[0] === \"(\" || remaining[0] === \")\" || remaining[0] === \"[\" || remaining[0] === \"]\") {\n tokens.push({\n kind: \"operator\",\n value: remaining[0],\n start: pos,\n end: pos + 1,\n });\n pos += 1;\n continue;\n }\n\n // Operators\n const opMatch = remaining.match(OPERATOR);\n if (opMatch) {\n tokens.push({\n kind: \"operator\",\n value: opMatch[0],\n start: pos,\n end: pos + opMatch[0].length,\n });\n pos += opMatch[0].length;\n continue;\n }\n\n // Unknown character - treat as word\n tokens.push({\n kind: \"word\",\n value: remaining[0]!,\n start: pos,\n end: pos + 1,\n });\n pos += 1;\n }\n\n return tokens;\n}\n\n/**\n * Parse tokens into nested function structure.\n */\nfunction parseTokens(tokens: CSSValueNode[]): CSSValueNode[] {\n const result: CSSValueNode[] = [];\n let i = 0;\n\n while (i < tokens.length) {\n const token = tokens[i]!;\n\n // Check for function call: word followed by (\n if (token.kind === \"word\" && i + 1 < tokens.length) {\n const next = tokens[i + 1];\n if (next && next.kind === \"operator\" && next.value === \"(\") {\n // Find matching closing paren\n let depth = 1;\n let j = i + 2;\n\n while (j < tokens.length && depth > 0) {\n const t = tokens[j];\n if (t && t.kind === \"operator\") {\n if (t.value === \"(\") depth++;\n else if (t.value === \")\") depth--;\n }\n j++;\n }\n\n // Extract and parse function arguments\n const argTokens = tokens.slice(i + 2, j - 1);\n const args = parseTokens(argTokens);\n\n result.push({\n kind: \"function\",\n name: token.value,\n args,\n start: token.start,\n end: tokens[j - 1]?.end,\n });\n\n i = j;\n continue;\n }\n }\n\n result.push(token);\n i++;\n }\n\n return result;\n}\n\n/**\n * Parse a CSS value string into an AST.\n *\n * @example\n * parseValue(\"oklch(0.6 0.2 250)\")\n * // { kind: \"function\", name: \"oklch\", args: [...] }\n *\n * parseValue(\"var(--color-primary, blue)\")\n * // { kind: \"function\", name: \"var\", args: [...] }\n */\nexport function parseValue(input: string): CSSValueNode[] {\n const tokens = tokenize(input);\n return parseTokens(tokens);\n}\n\n/**\n * Serialize CSS value nodes back to string.\n */\nexport function serializeValue(nodes: CSSValueNode[]): string {\n return nodes.map((node) => serializeNode(node)).join(\"\");\n}\n\n/**\n * Serialize a single node.\n */\nexport function serializeNode(node: CSSValueNode): string {\n switch (node.kind) {\n case \"word\":\n return node.value;\n\n case \"function\":\n return `${node.name}(${serializeValue(node.args)})`;\n\n case \"string\":\n return `${node.quote}${node.value}${node.quote}`;\n\n case \"number\":\n return node.raw;\n\n case \"operator\":\n return node.value;\n\n case \"space\":\n return node.value;\n\n case \"comment\":\n return `/*${node.value}*/`;\n\n default:\n return \"\";\n }\n}\n\n/**\n * Find all function calls in a value.\n *\n * @example\n * findFunctions(parseValue(\"color-mix(in oklab, var(--color) 50%, white)\"), \"var\")\n * // [{ kind: \"function\", name: \"var\", args: [...] }]\n */\nexport function findFunctions(nodes: CSSValueNode[], name?: string): FunctionNode[] {\n const results: FunctionNode[] = [];\n\n function visit(node: CSSValueNode): void {\n if (node.kind === \"function\") {\n if (!name || node.name === name) {\n results.push(node);\n }\n // Also search in function arguments\n for (const arg of node.args) {\n visit(arg);\n }\n }\n }\n\n for (const node of nodes) {\n visit(node);\n }\n\n return results;\n}\n\n/**\n * Check if a value contains a specific function.\n *\n * @example\n * hasFunction(\"var(--color)\", \"var\") // true\n * hasFunction(\"oklch(0.5 0.2 250)\", \"var\") // false\n */\nexport function hasFunction(input: string, name: string): boolean {\n const nodes = parseValue(input);\n return findFunctions(nodes, name).length > 0;\n}\n\n/**\n * Extract var() references from a value.\n *\n * @example\n * extractVarReferences(\"color-mix(in oklab, var(--primary), var(--secondary))\")\n * // [\"--primary\", \"--secondary\"]\n */\nexport function extractVarReferences(input: string): string[] {\n const nodes = parseValue(input);\n const vars = findFunctions(nodes, \"var\");\n\n return vars\n .map((v) => {\n const firstArg = v.args[0];\n if (firstArg && firstArg.kind === \"word\" && firstArg.value.startsWith(\"--\")) {\n return firstArg.value;\n }\n return null;\n })\n .filter((v): v is string => v !== null);\n}\n\n/**\n * Transform a value by replacing functions.\n *\n * @example\n * transformValue(\"var(--color)\", (node) => {\n * if (node.kind === \"function\" && node.name === \"var\") {\n * return { kind: \"word\", value: \"red\" };\n * }\n * return node;\n * })\n * // \"red\"\n */\nexport function transformValue(input: string, transform: (node: CSSValueNode) => CSSValueNode): string {\n const nodes = parseValue(input);\n\n function transformNode(node: CSSValueNode): CSSValueNode {\n const transformed = transform(node);\n\n if (transformed.kind === \"function\") {\n return {\n ...transformed,\n args: transformed.args.map(transformNode),\n };\n }\n\n return transformed;\n }\n\n const transformed = nodes.map(transformNode);\n return serializeValue(transformed);\n}\n","/**\n * CSS Functions\n *\n * Provides custom CSS functions for runtime value transformations:\n * - --alpha(color / opacity) - Apply alpha to a color\n * - --spacing(multiplier) - Calculate spacing value\n * - --theme(variable) - Get a theme variable value\n */\n\nimport type { AstNode } from \"./ast\";\nimport { walk } from \"./ast/walk\";\nimport { parseValue, serializeValue, type CSSValueNode } from \"./parser/advanced/value-parser\";\nimport type { Theme } from \"./theme\";\n\n// ============================================\n// Errors\n// ============================================\n\n/**\n * Error thrown when a CSS function fails to evaluate.\n *\n * This replaces silent console.warn behavior to ensure CSS function errors\n * are surfaced during compilation rather than at runtime.\n */\nexport class CSSFunctionError extends Error {\n functionName: string;\n cause?: Error;\n\n constructor(functionName: string, message: string, cause?: Error) {\n super(`CSS function ${functionName} failed: ${message}`);\n this.name = \"CSSFunctionError\";\n this.functionName = functionName;\n this.cause = cause;\n }\n}\n\n// ============================================\n// Types\n// ============================================\n\n/** Context for CSS function resolution */\nexport interface CSSFunctionContext {\n theme: Theme;\n /** Source node for context-aware resolution */\n source?: AstNode;\n}\n\n/** CSS function implementation */\ntype CSSFunction = (ctx: CSSFunctionContext, ...args: string[]) => string;\n\n// ============================================\n// CSS Function Implementations\n// ============================================\n\n/**\n * --alpha(color / opacity)\n *\n * Apply opacity to a color value using color-mix.\n *\n * @example\n * --alpha(var(--color-red-500) / 50%)\n * --alpha(#ff0000 / 0.5)\n */\nfunction alphaFunction(_ctx: CSSFunctionContext, value: string): string {\n // Split on / to separate color and alpha\n const slashIndex = value.lastIndexOf(\"/\");\n if (slashIndex === -1) {\n throw new Error(\n `The --alpha(…) function requires a color and an alpha value separated by /, e.g.: \\`--alpha(var(--my-color) / 50%)\\``\n );\n }\n\n const color = value.slice(0, slashIndex).trim();\n const alpha = value.slice(slashIndex + 1).trim();\n\n if (!color || !alpha) {\n throw new Error(\n `The --alpha(…) function requires a color and an alpha value, e.g.: \\`--alpha(var(--my-color) / 50%)\\``\n );\n }\n\n return withAlpha(color, alpha);\n}\n\n/**\n * --spacing(multiplier)\n *\n * Calculate spacing value based on theme's --spacing variable.\n *\n * @example\n * --spacing(4) -> calc(4 * 0.25rem)\n * --spacing(1.5) -> calc(1.5 * 0.25rem)\n */\nfunction spacingFunction(ctx: CSSFunctionContext, value: string): string {\n if (!value) {\n throw new Error(`The --spacing(…) function requires an argument, but received none.`);\n }\n\n const base = ctx.theme.get(\"--spacing\");\n if (!base) {\n throw new Error(\n \"The --spacing(…) function requires that the `--spacing` theme variable exists, but it was not found.\"\n );\n }\n\n const num = parseFloat(value);\n if (isNaN(num)) {\n throw new Error(`The --spacing(…) function requires a numeric multiplier, but received: \"${value}\"`);\n }\n\n return calcSpacing(num, base);\n}\n\n/**\n * --theme(variable, fallback?)\n *\n * Get a theme variable value. Optionally inline the value.\n *\n * @example\n * --theme(--color-red-500)\n * --theme(--color-red-500, red)\n * --theme(--breakpoint-md inline)\n */\nfunction themeFunction(ctx: CSSFunctionContext, path: string, ...fallback: string[]): string {\n if (!path.startsWith(\"--\")) {\n throw new Error(\n `The --theme(…) function can only be used with CSS variables from your theme (variables starting with --).`\n );\n }\n\n // Handle `--theme(… inline)` to force inline resolution\n const shouldInline = path.endsWith(\" inline\") || ctx.source?.kind === \"at-rule\";\n const normalizedPath = path.endsWith(\" inline\") ? path.slice(0, -7) : path;\n\n const resolvedValue = ctx.theme.get(normalizedPath);\n\n if (!resolvedValue) {\n if (fallback.length > 0) {\n return fallback.join(\", \");\n }\n throw new Error(\n `Could not resolve value for theme function: \\`--theme(${normalizedPath})\\`. Consider checking if the variable name is correct or provide a fallback value.`\n );\n }\n\n ctx.theme.markUsed(normalizedPath);\n\n if (shouldInline) {\n return resolvedValue;\n }\n\n if (fallback.length > 0) {\n return `var(${normalizedPath}, ${fallback.join(\", \")})`;\n }\n\n return `var(${normalizedPath})`;\n}\n\n// ============================================\n// CSS Function Registry\n// ============================================\n\nconst CSS_FUNCTIONS: Record<string, CSSFunction> = {\n \"--alpha\": alphaFunction,\n \"--spacing\": spacingFunction,\n \"--theme\": themeFunction,\n};\n\n/** Regex to quickly check if a value might contain CSS functions */\nexport const CSS_FUNCTION_PATTERN = /--alpha\\(|--spacing\\(|--theme\\(/;\n\n// ============================================\n// Function Substitution\n// ============================================\n\n/**\n * Check if a value contains any CSS functions.\n */\nexport function hasCSSFunctions(value: string): boolean {\n return CSS_FUNCTION_PATTERN.test(value);\n}\n\n/**\n * Substitute CSS functions in a value string.\n *\n * @example\n * substituteFunctionsInValue(\"--alpha(red / 50%)\", ctx)\n * // \"color-mix(in oklab, red 50%, transparent)\"\n */\nexport function substituteFunctionsInValue(value: string, ctx: CSSFunctionContext): string {\n if (!hasCSSFunctions(value)) {\n return value;\n }\n\n const ast = parseValue(value);\n const transformed = transformNodes(ast, ctx);\n return serializeValue(transformed);\n}\n\n/**\n * Transform CSS value nodes, replacing CSS functions.\n */\nfunction transformNodes(nodes: CSSValueNode[], ctx: CSSFunctionContext): CSSValueNode[] {\n return nodes.map((node) => transformNode(node, ctx));\n}\n\n/**\n * Transform a single CSS value node.\n */\nfunction transformNode(node: CSSValueNode, ctx: CSSFunctionContext): CSSValueNode {\n if (node.kind !== \"function\") {\n return node;\n }\n\n const transformedArgs = transformNodes(node.args, ctx);\n const fn = CSS_FUNCTIONS[node.name];\n\n if (!fn) {\n return { ...node, args: transformedArgs };\n }\n\n const argStrings = splitArgs(transformedArgs);\n\n try {\n const result = fn(ctx, ...argStrings);\n const parsed = parseValue(result);\n\n // Single token: return directly\n // Multi-token (e.g., hex colors): wrap as word node to preserve value\n if (parsed.length === 1) {\n return parsed[0]!;\n }\n return { kind: \"word\", value: result };\n } catch (error) {\n const message = error instanceof Error ? error.message : String(error);\n throw new CSSFunctionError(node.name, message, error instanceof Error ? error : undefined);\n }\n}\n\n/**\n * Split function arguments by comma.\n */\nfunction splitArgs(nodes: CSSValueNode[]): string[] {\n const args: string[] = [];\n let current: CSSValueNode[] = [];\n\n for (const node of nodes) {\n if (node.kind === \"operator\" && node.value === \",\") {\n args.push(serializeValue(current).trim());\n current = [];\n } else {\n current.push(node);\n }\n }\n\n if (current.length > 0) {\n args.push(serializeValue(current).trim());\n }\n\n return args;\n}\n\n// ============================================\n// AST-Level Substitution\n// ============================================\n\n/**\n * Substitute CSS functions throughout an AST.\n *\n * Walks the entire AST and transforms declaration values\n * and at-rule params that contain CSS functions.\n */\nexport function substituteFunctions(ast: AstNode[], theme: Theme): void {\n const ctx: CSSFunctionContext = { theme };\n\n walk(ast, (node) => {\n // Transform declaration values\n if (node.kind === \"declaration\" && node.value && hasCSSFunctions(node.value)) {\n node.value = substituteFunctionsInValue(node.value, ctx);\n return;\n }\n\n // Transform at-rule params (media queries, container queries, etc.)\n if (node.kind === \"at-rule\" && hasCSSFunctions(node.params)) {\n const atRuleCtx: CSSFunctionContext = { ...ctx, source: node };\n node.params = substituteFunctionsInValue(node.params, atRuleCtx);\n }\n });\n}\n\n// ============================================\n// Individual Function Exports\n// ============================================\n\n/**\n * Apply alpha to a color.\n * Standalone function for use in utilities.\n */\nexport function withAlpha(color: string, alpha: string): string {\n // Convert numeric alpha to percentage if needed\n let alphaPercent = alpha;\n if (!alpha.endsWith(\"%\")) {\n const num = parseFloat(alpha);\n if (!isNaN(num)) {\n alphaPercent = num <= 1 ? `${num * 100}%` : `${num}%`;\n }\n }\n\n if (alphaPercent === \"100%\") {\n return color;\n }\n\n return `color-mix(in oklab, ${color} ${alphaPercent}, transparent)`;\n}\n\n/**\n * Calculate spacing value.\n * Standalone function for use in utilities.\n */\nexport function calcSpacing(multiplier: number, base: string): string {\n if (multiplier === 0) {\n return \"0px\";\n }\n return `calc(${multiplier} * ${base})`;\n}\n","/**\n * Constant Folding Optimizer\n *\n * Simplifies calc() expressions at compile time:\n * - calc(2 * 4px) -> 8px\n * - calc(100% - 0px) -> 100%\n * - calc(1rem + 0) -> 1rem\n *\n * ## Supported Operations\n *\n * - **Multiplication**: `calc(N * value)` or `calc(value * N)` where N is unitless\n * - **Division**: `calc(value / N)` where N is unitless and non-zero\n * - **Addition/Subtraction**: `calc(value + value)` with compatible units\n *\n * ## Known Limitations\n *\n * ### Not Folded (Intentionally Preserved)\n *\n * - **`min()`, `max()`, `clamp()`**: CSS comparison functions require runtime\n * viewport/container context and cannot be evaluated at compile time.\n * Example: `calc(min(10px, 20px) + 5px)` is preserved as-is.\n *\n * - **`var()` references**: CSS custom properties cannot be evaluated at compile time.\n * Controlled via `preserveVars` option (default: true).\n *\n * - **Viewport units**: `vw`, `vh`, `vmin`, `vmax`, `svw`, `svh`, `lvw`, `lvh`, `dvw`, `dvh`\n * require runtime viewport dimensions.\n *\n * - **Container query units**: `cqw`, `cqh`, `cqi`, `cqb`, `cqmin`, `cqmax`\n * require runtime container context.\n *\n * - **Percentage + length**: `calc(50% + 10px)` cannot be folded because\n * percentage depends on the containing block.\n *\n * - **Nested calc()**: Complex nested expressions like `calc(calc(1 + 2) * 3)`\n * are not currently supported.\n *\n * ### Tokenizer Constraints\n *\n * The tokenizer uses simple parsing. Some edge cases may not fold:\n * - Expressions with multiple operators: `calc(1px + 2px + 3px)` (3+ operands)\n * - Complex whitespace patterns\n *\n * ## Unit Compatibility\n *\n * - **Length units** (px, rem, em, cm, mm, in, pt, pc) are compatible with each other\n * - **Angle units** (deg, grad, rad, turn) are compatible with each other\n * - **Time units** (s, ms) are compatible with each other\n * - **Percentage + length**: NOT compatible (preserved as-is)\n *\n * @example\n * // Folded\n * foldCalc(\"calc(2 * 4px)\") // \"8px\"\n * foldCalc(\"calc(10px / 2)\") // \"5px\"\n * foldCalc(\"calc(1rem + 1rem)\") // \"2rem\"\n *\n * // Preserved (not folded)\n * foldCalc(\"calc(min(10px, 20px))\") // unchanged\n * foldCalc(\"calc(50% + 10px)\") // unchanged\n * foldCalc(\"calc(100vw - 20px)\") // unchanged\n * foldCalc(\"calc(var(--size) * 2)\") // unchanged (default)\n */\n\nimport type { AstNode, Declaration } from \"../ast\";\nimport { decl } from \"../ast\";\n\nexport interface FoldOptions {\n /** Root font size for rem calculations (default: 16) */\n rem?: number;\n /** Preserve calc() for var() references (default: true) */\n preserveVars?: boolean;\n}\n\ninterface ParsedValue {\n number: number;\n unit: string;\n}\n\n/**\n * Convert units to a common base for calculation.\n * All length units convert to pixels for calculation.\n */\nconst UNIT_CONVERSIONS: Record<string, number> = {\n // Absolute lengths (in pixels)\n px: 1,\n cm: 96 / 2.54,\n mm: 96 / 25.4,\n Q: 96 / (2.54 * 40),\n in: 96,\n pc: 16,\n pt: 96 / 72,\n\n // Relative (need root font size)\n rem: 16, // Default, overridden by options.rem\n em: 16, // Assumes 1em = 16px at root\n\n // Viewport (not foldable - keep as is)\n // \"vw\", \"vh\", \"vmin\", \"vmax\", \"svw\", \"svh\", \"lvw\", \"lvh\", \"dvw\", \"dvh\"\n\n // Percentage (only foldable with same unit)\n \"%\": 1,\n\n // Angles\n deg: 1,\n grad: 0.9,\n rad: 180 / Math.PI,\n turn: 360,\n\n // Time\n s: 1000,\n ms: 1,\n\n // Frequency\n Hz: 1,\n kHz: 1000,\n};\n\n// Pre-computed sets for O(1) unit lookups\nconst FOLDABLE_UNITS = new Set([\n \"px\",\n \"rem\",\n \"em\",\n \"cm\",\n \"mm\",\n \"in\",\n \"pt\",\n \"pc\",\n \"deg\",\n \"grad\",\n \"rad\",\n \"turn\",\n \"s\",\n \"ms\",\n \"Hz\",\n \"kHz\",\n \"\",\n]);\n\n/**\n * Check if a unit is foldable (can be calculated at compile time).\n */\nfunction isFoldableUnit(unit: string): boolean {\n return FOLDABLE_UNITS.has(unit);\n}\n\n// Unit compatibility groups (pre-computed for O(1) lookup)\nconst LENGTH_UNITS = new Set([\"px\", \"rem\", \"em\", \"cm\", \"mm\", \"in\", \"pt\", \"pc\"]);\nconst ANGLE_UNITS = new Set([\"deg\", \"grad\", \"rad\", \"turn\"]);\nconst TIME_UNITS = new Set([\"s\", \"ms\"]);\n\n// Pre-compiled pattern for parsing CSS values (hoisted to avoid recreation on every call)\nconst CSS_VALUE_PATTERN = /^(-?[\\d.]+)([a-z%]*)$/i;\n\n/**\n * Check if two units are compatible for calculation.\n */\nfunction areUnitsCompatible(unit1: string, unit2: string): boolean {\n if (unit1 === unit2) return true;\n if (unit1 === \"\" || unit2 === \"\") return true; // Unitless is compatible with anything\n\n // Length units are compatible\n if (LENGTH_UNITS.has(unit1) && LENGTH_UNITS.has(unit2)) return true;\n\n // Angle units are compatible\n if (ANGLE_UNITS.has(unit1) && ANGLE_UNITS.has(unit2)) return true;\n\n // Time units are compatible\n if (TIME_UNITS.has(unit1) && TIME_UNITS.has(unit2)) return true;\n\n return false;\n}\n\n/**\n * Parse a CSS value with unit.\n */\nfunction parseValue(value: string): ParsedValue | null {\n const match = value.match(CSS_VALUE_PATTERN);\n if (!match) return null;\n\n const number = parseFloat(match[1]!);\n const unit = match[2]!.toLowerCase();\n\n if (isNaN(number)) return null;\n\n return { number, unit };\n}\n\n/**\n * Format a value with unit.\n */\nfunction formatValue(value: ParsedValue): string {\n // Round to avoid floating point issues\n const rounded = Math.round(value.number * 10000) / 10000;\n\n // Remove unnecessary decimals\n const formatted = rounded === Math.floor(rounded) ? rounded.toString() : rounded.toFixed(4).replace(/\\.?0+$/, \"\");\n\n return formatted + value.unit;\n}\n\n/**\n * Convert a value to pixels for calculation.\n */\nfunction toPixels(value: ParsedValue, remSize: number): number {\n if (value.unit === \"rem\" || value.unit === \"em\") {\n return value.number * remSize;\n }\n\n const conversion = UNIT_CONVERSIONS[value.unit];\n if (conversion !== undefined) {\n return value.number * conversion;\n }\n\n return value.number;\n}\n\n/**\n * Convert pixels back to the target unit.\n */\nfunction fromPixels(pixels: number, unit: string, remSize: number): number {\n if (unit === \"rem\" || unit === \"em\") {\n return pixels / remSize;\n }\n\n const conversion = UNIT_CONVERSIONS[unit];\n if (conversion !== undefined) {\n return pixels / conversion;\n }\n\n return pixels;\n}\n\n/**\n * Tokenize a calc expression.\n */\nfunction tokenize(expr: string): string[] {\n const tokens: string[] = [];\n let current = \"\";\n let depth = 0;\n\n const prevNonSpaceChar = (index: number): string | null => {\n for (let i = index - 1; i >= 0; i -= 1) {\n const char = expr[i]!;\n if (char !== \" \") return char;\n }\n return null;\n };\n\n for (let i = 0; i < expr.length; i++) {\n const char = expr[i]!;\n\n if (char === \"(\") {\n depth++;\n current += char;\n } else if (char === \")\") {\n depth--;\n current += char;\n } else if (depth === 0 && (char === \"+\" || char === \"-\")) {\n const prevChar = prevNonSpaceChar(i);\n const isSign =\n !prevChar ||\n prevChar === \"(\" ||\n prevChar === \"+\" ||\n prevChar === \"-\" ||\n prevChar === \"*\" ||\n prevChar === \"/\";\n if (isSign) {\n current += char;\n } else {\n if (current.trim()) tokens.push(current.trim());\n tokens.push(char);\n current = \"\";\n }\n } else if (depth === 0 && (char === \"*\" || char === \"/\")) {\n if (current.trim()) tokens.push(current.trim());\n tokens.push(char);\n current = \"\";\n } else if (char !== \" \") {\n current += char;\n } else if (current.trim()) {\n // Space - could be end of token\n // Don't push yet, wait for operator\n }\n }\n\n if (current.trim()) tokens.push(current.trim());\n\n return tokens;\n}\n\n/**\n * Evaluate a simple calc expression.\n * Only handles expressions with two operands and one operator.\n */\nfunction evaluateSimpleCalc(expr: string, options: FoldOptions): string | null {\n const remSize = options.rem ?? 16;\n\n // Remove outer calc() if present\n let inner = expr.trim();\n if (inner.startsWith(\"calc(\") && inner.endsWith(\")\")) {\n inner = inner.slice(5, -1).trim();\n }\n\n // Check for var() - don't fold if present\n if (options.preserveVars !== false && inner.includes(\"var(\")) {\n return null;\n }\n\n // Check for nested calc() - don't fold complex expressions\n if (inner.includes(\"calc(\")) {\n return null;\n }\n\n // Tokenize\n const tokens = tokenize(inner);\n\n // Only handle simple expressions: value operator value\n if (tokens.length === 3) {\n const [leftStr, operator, rightStr] = tokens;\n const left = parseValue(leftStr!);\n const right = parseValue(rightStr!);\n\n if (!left || !right) return null;\n if (!isFoldableUnit(left.unit) || !isFoldableUnit(right.unit)) return null;\n\n // Handle special cases\n switch (operator) {\n case \"+\":\n case \"-\": {\n // Units must be compatible\n if (!areUnitsCompatible(left.unit, right.unit)) return null;\n\n // If one is zero, return the other\n if (right.number === 0) return formatValue(left);\n if (left.number === 0) {\n if (operator === \"+\") return formatValue(right);\n return formatValue({ number: -right.number, unit: right.unit });\n }\n\n // Same unit - simple arithmetic\n if (left.unit === right.unit || left.unit === \"\" || right.unit === \"\") {\n const resultUnit = left.unit || right.unit;\n const result = operator === \"+\" ? left.number + right.number : left.number - right.number;\n return formatValue({ number: result, unit: resultUnit });\n }\n\n // Convert to common unit (pixels) then back to preferred unit\n const leftPx = toPixels(left, remSize);\n const rightPx = toPixels(right, remSize);\n const resultPx = operator === \"+\" ? leftPx + rightPx : leftPx - rightPx;\n\n // Prefer rem over px\n const preferredUnit =\n left.unit === \"rem\" || right.unit === \"rem\" ? \"rem\" : left.unit || right.unit || \"px\";\n const result = fromPixels(resultPx, preferredUnit, remSize);\n\n return formatValue({ number: result, unit: preferredUnit });\n }\n\n case \"*\": {\n // Multiplication: one must be unitless\n if (left.unit && right.unit) return null;\n\n const result = left.number * right.number;\n const unit = left.unit || right.unit;\n\n // Multiplication by zero\n if (result === 0) return \"0\" + (unit || \"px\");\n\n return formatValue({ number: result, unit });\n }\n\n case \"/\": {\n // Division: divisor must be unitless\n if (right.unit) return null;\n if (right.number === 0) return null; // Division by zero\n\n const result = left.number / right.number;\n return formatValue({ number: result, unit: left.unit });\n }\n }\n }\n\n // Single value - just return it\n if (tokens.length === 1) {\n const value = parseValue(tokens[0]!);\n if (value) return formatValue(value);\n }\n\n return null;\n}\n\n/**\n * Fold calc() expressions in a CSS value.\n *\n * @example\n * foldCalc(\"calc(2 * 4px)\") // \"8px\"\n * foldCalc(\"calc(100% - 0px)\") // \"100%\"\n * foldCalc(\"calc(1rem + 1rem)\") // \"2rem\"\n */\nexport function foldCalc(value: string, options: FoldOptions = {}): string {\n if (!value.includes(\"calc(\")) return value;\n\n let result = \"\";\n let index = 0;\n\n while (index < value.length) {\n const start = value.indexOf(\"calc(\", index);\n if (start === -1) {\n result += value.slice(index);\n break;\n }\n\n result += value.slice(index, start);\n\n let depth = 0;\n let end = start;\n for (; end < value.length; end += 1) {\n const char = value[end]!;\n if (char === \"(\") depth += 1;\n else if (char === \")\") {\n depth -= 1;\n if (depth === 0) {\n end += 1;\n break;\n }\n }\n }\n\n if (depth !== 0) {\n result += value.slice(start);\n break;\n }\n\n const match = value.slice(start, end);\n const rawInner = match.slice(5, -1);\n const inner = rawInner.includes(\"calc(\") ? foldCalc(rawInner, options) : rawInner;\n const processedMatch = `calc(${inner})`;\n\n const folded = evaluateSimpleCalc(match, options);\n result += folded ?? processedMatch;\n\n index = end;\n }\n\n return result;\n}\n\n/**\n * Fold calc() expressions in a declaration.\n */\nexport function foldDeclaration(declaration: Declaration, options: FoldOptions = {}): Declaration {\n if (!declaration.value || !declaration.value.includes(\"calc(\")) {\n return declaration;\n }\n\n const foldedValue = foldCalc(declaration.value, options);\n\n if (foldedValue === declaration.value) {\n return declaration;\n }\n\n return decl(declaration.property, foldedValue, declaration.important);\n}\n\n/**\n * Fold calc() expressions in all declarations in an AST.\n */\nexport function foldAST(ast: AstNode[], options: FoldOptions = {}): AstNode[] {\n return ast.map((node) => {\n if (node.kind === \"declaration\") {\n return foldDeclaration(node, options);\n }\n\n if ((node.kind === \"rule\" || node.kind === \"at-rule\") && node.nodes.length > 0) {\n return {\n ...node,\n nodes: foldAST(node.nodes, options),\n };\n }\n\n return node;\n });\n}\n\n/**\n * Remove unnecessary calc() wrappers around simple values.\n *\n * @example\n * unwrapCalc(\"calc(16px)\") // \"16px\"\n * unwrapCalc(\"calc(100%)\") // \"100%\"\n */\nexport function unwrapCalc(value: string): string {\n return value.replace(/calc\\(([^()+\\-*/]+)\\)/g, \"$1\");\n}\n\n/**\n * Simplify a CSS value by folding calc() and unwrapping.\n */\nexport function simplifyValue(value: string, options: FoldOptions = {}): string {\n return unwrapCalc(foldCalc(value, options));\n}\n","/**\n * AST Optimization - Single Pass\n *\n * Consolidates multiple AST walks into a single traversal for better performance.\n * Previously: 6 separate AST walks\n * Now: 1 combined optimization pass\n */\n\nimport type { AstNode, Declaration, StyleRule, AtRule } from \"../ast\";\nimport type { Theme } from \"../theme\";\nimport { hasCSSFunctions, substituteFunctionsInValue, type CSSFunctionContext } from \"../css-functions\";\nimport { foldCalc, type FoldOptions } from \"../optimize/constant-fold\";\n\n// ============================================\n// Types\n// ============================================\n\nexport interface OptimizeOptions {\n /** Theme for CSS function substitution */\n theme: Theme;\n /** Apply !important to all declarations */\n important?: boolean;\n /** Fold calc() expressions */\n foldConstants?: boolean | FoldOptions;\n /** Sort declarations within rules */\n sortDeclarations?: boolean;\n /** Substitute CSS functions (--alpha, --spacing, --theme) */\n substituteFunctions?: boolean;\n}\n\n// ============================================\n// Single-Pass Optimization\n// ============================================\n\n/**\n * Optimize AST in a single pass.\n *\n * Combines multiple optimization steps into one traversal:\n * - CSS function substitution (--alpha, --spacing, --theme)\n * - calc() expression folding\n * - Declaration sorting\n * - !important application\n *\n * This replaces 4-5 separate AST walks with a single traversal.\n */\nexport function optimizeAst(ast: AstNode[], options: OptimizeOptions): AstNode[] {\n const {\n theme,\n important = false,\n foldConstants = true,\n sortDeclarations = true,\n substituteFunctions = true,\n } = options;\n\n const ctx: CSSFunctionContext = { theme };\n const foldOptions: FoldOptions = typeof foldConstants === \"object\" ? foldConstants : {};\n const shouldFold = foldConstants !== false;\n const shouldSubstitute = substituteFunctions !== false;\n const shouldSort = sortDeclarations !== false;\n\n // Single recursive traversal\n return optimizeNodes(ast, ctx, {\n important,\n shouldFold,\n shouldSubstitute,\n shouldSort,\n foldOptions,\n });\n}\n\ninterface OptimizeContext {\n important: boolean;\n shouldFold: boolean;\n shouldSubstitute: boolean;\n shouldSort: boolean;\n foldOptions: FoldOptions;\n}\n\nfunction optimizeNodes(nodes: AstNode[], ctx: CSSFunctionContext, opts: OptimizeContext): AstNode[] {\n for (let i = 0; i < nodes.length; i++) {\n nodes[i] = optimizeNode(nodes[i]!, ctx, opts);\n }\n\n return nodes;\n}\n\nfunction optimizeNode(node: AstNode, ctx: CSSFunctionContext, opts: OptimizeContext): AstNode {\n switch (node.kind) {\n case \"declaration\":\n return optimizeDeclaration(node, ctx, opts);\n\n case \"rule\":\n return optimizeRule(node, ctx, opts);\n\n case \"at-rule\":\n return optimizeAtRule(node, ctx, opts);\n\n case \"comment\":\n return node;\n\n case \"context\":\n case \"at-root\":\n // PERFORMANCE: In-place mutation instead of object spread\n node.nodes = optimizeNodes(node.nodes, ctx, opts);\n return node;\n\n default:\n return node;\n }\n}\n\nfunction optimizeDeclaration(decl: Declaration, ctx: CSSFunctionContext, opts: OptimizeContext): Declaration {\n let value = decl.value;\n\n if (value) {\n // Step 1: Substitute CSS functions\n if (opts.shouldSubstitute && hasCSSFunctions(value)) {\n value = substituteFunctionsInValue(value, ctx);\n }\n\n // Step 2: Fold calc() expressions\n if (opts.shouldFold && value.includes(\"calc(\")) {\n value = foldCalc(value, opts.foldOptions);\n }\n }\n\n // Step 3: Apply !important\n const isImportant = opts.important || decl.important;\n\n // Return same object if nothing changed (memory optimization)\n if (value === decl.value && isImportant === decl.important) {\n return decl;\n }\n\n // PERFORMANCE: In-place mutation instead of object spread.\n // AST nodes are owned by this compilation pass, so mutation is safe.\n decl.value = value;\n decl.important = isImportant;\n return decl;\n}\n\nfunction optimizeRule(rule: StyleRule, ctx: CSSFunctionContext, opts: OptimizeContext): StyleRule {\n // Optimize child nodes\n let nodes = optimizeNodes(rule.nodes, ctx, opts);\n\n // Sort declarations if enabled\n if (opts.shouldSort) {\n nodes = sortDeclarationsInPlace(nodes);\n }\n\n // Return same object if nothing changed\n if (nodes === rule.nodes) {\n return rule;\n }\n\n // PERFORMANCE: In-place mutation instead of object spread.\n // AST nodes are owned by this compilation pass, so mutation is safe.\n rule.nodes = nodes;\n return rule;\n}\n\nfunction optimizeAtRule(atRule: AtRule, ctx: CSSFunctionContext, opts: OptimizeContext): AtRule {\n let params = atRule.params;\n\n // Substitute CSS functions in at-rule params (media queries, etc.)\n if (opts.shouldSubstitute && params && hasCSSFunctions(params)) {\n const atRuleCtx: CSSFunctionContext = { ...ctx, source: atRule };\n params = substituteFunctionsInValue(params, atRuleCtx);\n }\n\n // Optimize child nodes\n const nodes = atRule.nodes.length > 0 ? optimizeNodes(atRule.nodes, ctx, opts) : atRule.nodes;\n\n // Return same object if nothing changed\n if (params === atRule.params && nodes === atRule.nodes) {\n return atRule;\n }\n\n // PERFORMANCE: In-place mutation instead of object spread.\n // AST nodes are owned by this compilation pass, so mutation is safe.\n atRule.params = params;\n atRule.nodes = nodes;\n return atRule;\n}\n\n/**\n * Sort declarations within a rule's nodes.\n * Preserves order of non-declarations (nested rules, comments, etc.)\n */\nfunction sortDeclarationsInPlace(nodes: AstNode[]): AstNode[] {\n // Find declaration indices\n const declarations: Array<{ index: number; node: Declaration }> = [];\n\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i]!;\n if (node.kind === \"declaration\") {\n declarations.push({ index: i, node });\n }\n }\n\n // If 0 or 1 declarations, nothing to sort\n if (declarations.length <= 1) {\n return nodes;\n }\n\n // Sort declarations by property order\n declarations.sort((a, b) => {\n const orderA = getPropertyOrder(a.node.property);\n const orderB = getPropertyOrder(b.node.property);\n return orderA - orderB;\n });\n\n // Check if order changed\n let changed = false;\n for (let i = 1; i < declarations.length; i++) {\n if (declarations[i]!.index < declarations[i - 1]!.index) {\n changed = true;\n break;\n }\n }\n\n if (!changed) {\n return nodes;\n }\n\n // Rebuild nodes array with sorted declarations\n const result = [...nodes];\n const sortedDecls = declarations.map((d) => d.node);\n const indices = declarations.map((d) => d.index).sort((a, b) => a - b);\n\n for (let i = 0; i < indices.length; i++) {\n result[indices[i]!] = sortedDecls[i]!;\n }\n\n return result;\n}\n\n// Property order map for declaration sorting\n// Lower numbers come first\nconst PROPERTY_ORDER: Record<string, number> = {\n // Box model\n content: 10,\n display: 20,\n visibility: 21,\n position: 30,\n inset: 40,\n top: 41,\n right: 42,\n bottom: 43,\n left: 44,\n \"z-index\": 50,\n\n // Flexbox/Grid\n flex: 100,\n \"flex-grow\": 101,\n \"flex-shrink\": 102,\n \"flex-basis\": 103,\n \"flex-direction\": 104,\n \"flex-wrap\": 105,\n \"flex-flow\": 106,\n \"justify-content\": 110,\n \"align-items\": 111,\n \"align-content\": 112,\n \"align-self\": 113,\n order: 120,\n grid: 130,\n \"grid-template\": 131,\n \"grid-template-columns\": 132,\n \"grid-template-rows\": 133,\n \"grid-column\": 140,\n \"grid-row\": 141,\n gap: 150,\n\n // Dimensions\n width: 200,\n \"min-width\": 201,\n \"max-width\": 202,\n height: 210,\n \"min-height\": 211,\n \"max-height\": 212,\n \"aspect-ratio\": 220,\n\n // Margin & Padding\n margin: 300,\n \"margin-top\": 301,\n \"margin-right\": 302,\n \"margin-bottom\": 303,\n \"margin-left\": 304,\n padding: 310,\n \"padding-top\": 311,\n \"padding-right\": 312,\n \"padding-bottom\": 313,\n \"padding-left\": 314,\n\n // Border\n border: 400,\n \"border-width\": 401,\n \"border-style\": 402,\n \"border-color\": 403,\n \"border-radius\": 410,\n\n // Background\n background: 500,\n \"background-color\": 501,\n \"background-image\": 502,\n \"background-position\": 503,\n \"background-size\": 504,\n\n // Typography\n color: 600,\n font: 610,\n \"font-family\": 611,\n \"font-size\": 612,\n \"font-weight\": 613,\n \"font-style\": 614,\n \"line-height\": 620,\n \"letter-spacing\": 621,\n \"text-align\": 630,\n \"text-decoration\": 631,\n \"text-transform\": 632,\n\n // Effects\n opacity: 700,\n \"box-shadow\": 710,\n filter: 720,\n \"backdrop-filter\": 721,\n transform: 800,\n transition: 900,\n animation: 910,\n};\n\nfunction getPropertyOrder(property: string): number {\n // Check exact match first (most common case)\n const order = PROPERTY_ORDER[property];\n if (order !== undefined) return order;\n\n // Custom properties go last\n if (property.startsWith(\"--\")) return 1000;\n\n // Vendor-prefixed properties inherit order from unprefixed version\n if (property[0] === \"-\") {\n const unprefixed = property.replace(/^-\\w+-/, \"\");\n const prefixOrder = PROPERTY_ORDER[unprefixed];\n if (prefixOrder !== undefined) return prefixOrder - 0.5;\n }\n\n return 999;\n}\n","/**\n * CSS Variable Utilities\n */\n\n// Pre-compiled patterns for CSS variable validation (hoisted to avoid recreation on every call)\nconst CSS_VARIABLE_NAME_PATTERN = /^--[a-zA-Z_][a-zA-Z0-9_-]*$/;\nconst INVALID_VARIABLE_CHARS_PATTERN = /[^a-zA-Z0-9_-]/g;\n\n/** Parse a var() call. Returns null if malformed. */\nfunction parseVarCall(\n value: string,\n start: number\n): { end: number; name: string; fallback?: string; fallbackStart?: number } | null {\n if (value.slice(start, start + 4) !== \"var(\") return null;\n\n let depth = 1;\n let end = -1;\n\n for (let i = start + 4; i < value.length; i++) {\n const char = value[i]!;\n if (char === \"(\") depth++;\n if (char === \")\") depth--;\n if (depth === 0) {\n end = i;\n break;\n }\n }\n\n if (end === -1) return null;\n\n const content = value.slice(start + 4, end);\n let commaIndex = -1;\n depth = 0;\n\n for (let i = 0; i < content.length; i++) {\n const char = content[i]!;\n if (char === \"(\") depth++;\n if (char === \")\") depth--;\n if (char === \",\" && depth === 0) {\n commaIndex = i;\n break;\n }\n }\n\n const nameRaw = commaIndex === -1 ? content : content.slice(0, commaIndex);\n const name = nameRaw.trim();\n\n if (commaIndex === -1) {\n return { end, name };\n }\n\n const fallbackRaw = content.slice(commaIndex + 1);\n const leadingWhitespace = fallbackRaw.match(/^\\s*/)?.[0].length ?? 0;\n\n return {\n end,\n name,\n fallback: fallbackRaw.trim(),\n fallbackStart: start + 4 + commaIndex + 1 + leadingWhitespace,\n };\n}\n\nexport interface VariableReference {\n name: string;\n fallback?: string;\n start: number;\n end: number;\n}\n\n/** Extract all CSS variable references from a value, including nested. */\nexport function extractUsedVariables(value: string): VariableReference[] {\n const results: VariableReference[] = [];\n let index = 0;\n\n while (index < value.length) {\n const start = value.indexOf(\"var(\", index);\n if (start === -1) break;\n\n const parsed = parseVarCall(value, start);\n if (!parsed) {\n index = start + 4;\n continue;\n }\n\n results.push({\n name: parsed.name,\n fallback: parsed.fallback,\n start,\n end: parsed.end + 1,\n });\n\n if (parsed.fallback && parsed.fallbackStart !== undefined) {\n const nestedVars = extractUsedVariables(parsed.fallback);\n for (const nested of nestedVars) {\n results.push({\n ...nested,\n start: parsed.fallbackStart + nested.start,\n end: parsed.fallbackStart + nested.end,\n });\n }\n }\n\n index = parsed.end + 1;\n }\n\n return results;\n}\n\n/** Get unique variable names from a CSS value. */\nexport function getVariableNames(value: string): string[] {\n const refs = extractUsedVariables(value);\n return [...new Set(refs.map((r) => r.name))];\n}\n\n/** Check if a CSS value uses any variables. */\nexport function usesVariables(value: string): boolean {\n return extractUsedVariables(value).length > 0;\n}\n\n/** Replace variable references using a replacer function. */\nexport function replaceVariables(value: string, replacer: (name: string, fallback?: string) => string): string {\n let index = 0;\n let result = \"\";\n\n while (index < value.length) {\n const start = value.indexOf(\"var(\", index);\n if (start === -1) break;\n\n const parsed = parseVarCall(value, start);\n if (!parsed) {\n index = start + 4;\n continue;\n }\n\n result += value.slice(index, start);\n result += replacer(parsed.name, parsed.fallback);\n index = parsed.end + 1;\n }\n\n result += value.slice(index);\n return result;\n}\n\n/** Resolve variable references using a lookup function. Uses fallback if lookup returns undefined. */\nexport function resolveVariables(\n value: string,\n lookup: (name: string) => string | undefined,\n options: { preserveUnresolved?: boolean } = {}\n): string {\n const { preserveUnresolved = false } = options;\n\n return replaceVariables(value, (name, fallback) => {\n const resolved = lookup(name);\n\n if (resolved !== undefined) {\n return resolved;\n }\n\n if (fallback !== undefined) {\n return resolveVariables(fallback, lookup, options);\n }\n\n if (preserveUnresolved) {\n return `var(${name})`;\n }\n\n return \"\";\n });\n}\n\n/** Extract custom property names from CSS declarations (e.g., `--color: red;`). */\nexport function extractCustomProperties(css: string): string[] {\n const results: string[] = [];\n const seen = new Set<string>();\n const declPattern = /(--[a-zA-Z0-9_-]+)\\s*:/g;\n let match: RegExpExecArray | null;\n\n while ((match = declPattern.exec(css)) !== null) {\n const name = match[1]!;\n if (!seen.has(name)) {\n seen.add(name);\n results.push(name);\n }\n }\n\n return results;\n}\n\n/** Build a dependency graph: variable name -> variables it depends on. */\nexport function buildVariableDependencyGraph(\n declarations: Array<{ property: string; value: string }>\n): Map<string, string[]> {\n const graph = new Map<string, string[]>();\n\n for (const { property, value } of declarations) {\n if (property.startsWith(\"--\")) {\n const deps = getVariableNames(value);\n graph.set(property, deps);\n }\n }\n\n return graph;\n}\n\nlet warnedLargeGraph = false;\n\n/** Find variables in circular references using Tarjan's SCC algorithm. O(V+E). */\nexport function findCircularVariables(graph: Map<string, string[]>): string[] {\n if (graph.size === 0) return [];\n\n if (graph.size > 500 && !warnedLargeGraph) {\n console.warn(`[rainbowindex] Large variable graph (${graph.size} variables).`);\n warnedLargeGraph = true;\n }\n\n let index = 0;\n const indices = new Map<string, number>();\n const lowlink = new Map<string, number>();\n const onStack = new Set<string>();\n const stack: string[] = [];\n const sccs: string[][] = [];\n\n function strongconnect(v: string): void {\n indices.set(v, index);\n lowlink.set(v, index);\n index++;\n\n stack.push(v);\n onStack.add(v);\n\n const neighbors = graph.get(v) ?? [];\n for (const w of neighbors) {\n if (!graph.has(w)) continue;\n\n if (!indices.has(w)) {\n strongconnect(w);\n lowlink.set(v, Math.min(lowlink.get(v)!, lowlink.get(w)!));\n } else if (onStack.has(w)) {\n lowlink.set(v, Math.min(lowlink.get(v)!, indices.get(w)!));\n }\n }\n\n if (lowlink.get(v) === indices.get(v)) {\n const scc: string[] = [];\n let w: string;\n do {\n w = stack.pop()!;\n onStack.delete(w);\n scc.push(w);\n } while (w !== v);\n sccs.push(scc);\n }\n }\n\n for (const node of graph.keys()) {\n if (!indices.has(node)) {\n strongconnect(node);\n }\n }\n\n const circular: string[] = [];\n for (const scc of sccs) {\n if (scc.length > 1) {\n circular.push(...scc);\n } else if (scc.length === 1) {\n const node = scc[0]!;\n const deps = graph.get(node) ?? [];\n if (deps.includes(node)) {\n circular.push(node);\n }\n }\n }\n\n return circular;\n}\n\n/** Validate a CSS variable name. */\nexport function isValidVariableName(name: string): boolean {\n return CSS_VARIABLE_NAME_PATTERN.test(name);\n}\n\n/** Normalize a CSS variable name. Ensures -- prefix and valid characters. */\nexport function normalizeVariableName(name: string): string {\n let normalized = name.trim();\n if (!normalized.startsWith(\"--\")) {\n normalized = \"--\" + normalized;\n }\n normalized = normalized.replace(INVALID_VARIABLE_CHARS_PATTERN, \"-\");\n return normalized;\n}\n\n/** Create a CSS var() expression. */\nexport function createVarExpression(name: string, fallback?: string): string {\n if (fallback !== undefined) {\n return `var(${name}, ${fallback})`;\n }\n return `var(${name})`;\n}\n","/**\n * Native Acceleration Layer\n *\n * Provides optional native Rust acceleration for hot paths in the compilation pipeline.\n * Falls back to TypeScript implementations when native module is unavailable.\n *\n * Integration Strategy:\n * - Native parsing is used when no `findRoot` lookup is needed\n * - Native compilation is used for built-in utilities\n * - Native printing is always faster than TypeScript\n * - Custom utilities/variants from plugins use TypeScript fallback\n */\n\nimport type { AstNode } from \"../ast\";\nimport type { Candidate as TsCandidate } from \"../candidate\";\nimport type { Theme as TsTheme } from \"../theme\";\nimport { convertNativeCandidate, type NativeCandidate } from \"../native/conversions\";\n\n// Type guard for native module availability\nlet nativeModule: NativeModule | null = null;\nlet nativeModuleChecked = false;\nconst NATIVE_MOCK_KEY = \"__RAINBOW_NATIVE_MOCK__\";\n\nfunction getInjectedNativeModule(): NativeModule | null | undefined {\n return (globalThis as Record<string, unknown>)[NATIVE_MOCK_KEY] as NativeModule | null | undefined;\n}\n\nfunction isNativeRuntimeAvailable(native: NativeModule | null): boolean {\n if (!native) return false;\n if (typeof native.isNativeAvailable === \"function\") {\n return native.isNativeAvailable();\n }\n return true;\n}\n\nfunction isNativeParserAvailableFor(native: NativeModule | null): boolean {\n if (!native || typeof native.parseCandidate !== \"function\") return false;\n if (typeof native.isParserAvailable === \"function\") {\n return native.isParserAvailable();\n }\n if (typeof native.isNativeAvailable === \"function\") {\n return native.isNativeAvailable();\n }\n return true;\n}\n\nfunction isNativeCompilerAvailableFor(native: NativeModule | null): boolean {\n if (!native || typeof native.compileCandidateString !== \"function\") return false;\n if (typeof native.isCompilerAvailable === \"function\") {\n return native.isCompilerAvailable();\n }\n if (typeof native.isNativeAvailable === \"function\") {\n return native.isNativeAvailable();\n }\n return true;\n}\n\nfunction isNativePrinterAvailableFor(native: NativeModule | null): boolean {\n if (!native || typeof native.toCss !== \"function\") return false;\n if (typeof native.isPrinterAvailable === \"function\") {\n return native.isPrinterAvailable();\n }\n if (typeof native.isNativeAvailable === \"function\") {\n return native.isNativeAvailable();\n }\n return true;\n}\n\ninterface NativeAstNode {\n kind: \"rule\" | \"at-rule\" | \"declaration\" | \"comment\" | \"context\" | \"at-root\";\n selector?: string | null;\n params?: string | null;\n property?: string | null;\n value?: string | null;\n important?: boolean | null;\n nodes?: NativeAstNode[] | null;\n}\n\ninterface NativeTheme {\n values?: Record<string, Record<string, string>>;\n prefix?: string;\n}\n\ninterface NativePrintOptions {\n minify?: boolean;\n indent?: \"2space\" | \"4space\" | \"tab\";\n}\n\ninterface NativeModule {\n // Parser functions\n parseCandidate(input: string): NativeCandidate | null;\n parseCandidatesBatch?(inputs: string[]): (NativeCandidate | null)[];\n\n // Compiler functions\n compileCandidateString(input: string, theme?: NativeTheme): NativeAstNode[] | null;\n compileCandidatesBatch?(inputs: string[], theme?: NativeTheme): (NativeAstNode[] | null)[];\n hasUtility(name: string): boolean;\n hasVariant?(name: string): boolean;\n\n // Printer functions\n toCss(nodes: NativeAstNode[], options?: NativePrintOptions): string;\n toCssMinified(nodes: NativeAstNode[]): string;\n toCssPretty(nodes: NativeAstNode[], indent?: string): string;\n compileToCss?(inputs: string[], theme?: NativeTheme, options?: NativePrintOptions): string;\n\n // Availability checks\n isNativeAvailable?(): boolean;\n isParserAvailable?(): boolean;\n isCompilerAvailable?(): boolean;\n isPrinterAvailable?(): boolean;\n}\n\n/**\n * Try to load the native oxide module.\n * Returns null if not available.\n */\nfunction tryLoadNative(): NativeModule | null {\n const injected = getInjectedNativeModule();\n if (injected !== undefined) {\n nativeModule = injected;\n nativeModuleChecked = true;\n return nativeModule;\n }\n if (nativeModuleChecked) {\n return nativeModule;\n }\n nativeModuleChecked = true;\n\n try {\n // Dynamic import to avoid hard dependency\n // eslint-disable-next-line @typescript-eslint/no-require-imports\n nativeModule = require(\"@rainbowindex/oxide\") as NativeModule;\n return nativeModule;\n } catch {\n // Native module not available\n return null;\n }\n}\n\n/**\n * Check if native acceleration is available.\n */\nexport function isNativeAvailable(): boolean {\n return isNativeRuntimeAvailable(tryLoadNative());\n}\n\n/**\n * Check if native parser is available.\n */\nexport function isNativeParserAvailable(): boolean {\n return isNativeParserAvailableFor(tryLoadNative());\n}\n\n/**\n * Check if native compiler is available.\n */\nexport function isNativeCompilerAvailable(): boolean {\n return isNativeCompilerAvailableFor(tryLoadNative());\n}\n\n/**\n * Check if native printer is available.\n */\nexport function isNativePrinterAvailable(): boolean {\n return isNativePrinterAvailableFor(tryLoadNative());\n}\n\n/**\n * Check if a utility exists in the native registry.\n * Used to determine if native compilation can be used for a candidate.\n */\nexport function hasNativeUtility(name: string): boolean {\n const native = tryLoadNative();\n if (!isNativeCompilerAvailableFor(native)) return false;\n return native!.hasUtility(name);\n}\n\n/**\n * Check if a variant exists in the native registry.\n * Used to determine if native compilation can handle a variant.\n */\nexport function hasNativeVariant(name: string): boolean {\n const native = tryLoadNative();\n if (!isNativeCompilerAvailableFor(native)) return false;\n if (native!.hasVariant) {\n return native!.hasVariant(name);\n }\n return false;\n}\n\n// Candidate conversion is shared via ../native/conversions.\n\n// ============================================\n// AST Conversion\n// ============================================\n\n/**\n * Convert native AST nodes to TypeScript AST format.\n */\nfunction nativeAstToTs(nodes: NativeAstNode[]): AstNode[] {\n return nodes.map((node) => {\n if (node.kind === \"declaration\") {\n return {\n kind: \"declaration\" as const,\n property: node.property ?? \"\",\n value: node.value ?? \"\",\n important: node.important ?? false,\n };\n }\n if (node.kind === \"rule\") {\n return {\n kind: \"rule\" as const,\n selector: node.selector ?? \"\",\n nodes: node.nodes ? nativeAstToTs(node.nodes) : [],\n };\n }\n if (node.kind === \"at-rule\") {\n return {\n kind: \"at-rule\" as const,\n name: node.selector ?? \"\",\n params: node.params ?? \"\",\n nodes: node.nodes ? nativeAstToTs(node.nodes) : [],\n };\n }\n if (node.kind === \"comment\") {\n return {\n kind: \"comment\" as const,\n value: node.value ?? \"\",\n };\n }\n if (node.kind === \"context\") {\n return {\n kind: \"context\" as const,\n context: {},\n nodes: node.nodes ? nativeAstToTs(node.nodes) : [],\n };\n }\n // at-root\n return {\n kind: \"at-root\" as const,\n nodes: node.nodes ? nativeAstToTs(node.nodes) : [],\n };\n });\n}\n\n/**\n * Convert TypeScript AST nodes to native format.\n */\nfunction tsAstToNative(nodes: AstNode[]): NativeAstNode[] {\n return nodes.map((node) => {\n if (node.kind === \"declaration\") {\n return {\n kind: \"declaration\" as const,\n property: node.property,\n value: node.value,\n important: node.important,\n };\n }\n if (node.kind === \"rule\") {\n return {\n kind: \"rule\" as const,\n selector: node.selector,\n nodes: tsAstToNative(node.nodes),\n };\n }\n if (node.kind === \"at-rule\") {\n return {\n kind: \"at-rule\" as const,\n selector: node.name,\n params: node.params,\n nodes: tsAstToNative(node.nodes),\n };\n }\n if (node.kind === \"comment\") {\n return {\n kind: \"comment\" as const,\n value: node.value,\n };\n }\n if (node.kind === \"context\") {\n return {\n kind: \"context\" as const,\n nodes: tsAstToNative(node.nodes),\n };\n }\n // at-root\n return {\n kind: \"at-root\" as const,\n nodes: tsAstToNative((node as { nodes: AstNode[] }).nodes),\n };\n });\n}\n\n// ============================================\n// Native Accelerated Functions\n// ============================================\n\n/**\n * Parse a candidate using native Rust parser.\n * Returns null if native is unavailable or parsing fails.\n *\n * Note: This doesn't use the `findRoot` lookup, so it may not\n * correctly resolve compound utility roots. Use the TypeScript\n * parser when you need utility existence checking.\n */\nexport function nativeParseCandidate(input: string): TsCandidate | null {\n const native = tryLoadNative();\n if (!native) {\n return null;\n }\n if (!isNativeParserAvailableFor(native)) {\n return null;\n }\n\n const result = native.parseCandidate(input);\n if (!result) {\n return null;\n }\n\n return convertNativeCandidate(result);\n}\n\n/**\n * Compile a candidate string using native Rust compiler.\n * Returns null if native is unavailable, the utility doesn't exist\n * in the native registry, or compilation fails.\n *\n * This is most useful for built-in utilities. Custom utilities\n * added via plugins should use the TypeScript compiler.\n *\n * Note: Theme values are not passed to the native compiler since\n * native utilities use built-in default values. For custom theme\n * values, use the TypeScript compiler.\n */\nexport function nativeCompileCandidateString(input: string, _theme?: TsTheme): AstNode[] | null {\n const native = tryLoadNative();\n if (!native) {\n return null;\n }\n if (!isNativeCompilerAvailableFor(native)) {\n return null;\n }\n\n // Native compiler uses built-in theme values\n const result = native.compileCandidateString(input);\n if (!result) {\n return null;\n }\n\n return nativeAstToTs(result);\n}\n\n/**\n * Print AST nodes to CSS using native Rust printer.\n * Returns null if native printer is unavailable.\n */\nexport function nativePrintCss(\n nodes: AstNode[],\n options?: { minify?: boolean; indent?: \"2space\" | \"4space\" | \"tab\" }\n): string | null {\n const native = tryLoadNative();\n if (!native) {\n return null;\n }\n if (!isNativePrinterAvailableFor(native)) {\n return null;\n }\n\n const nativeNodes = tsAstToNative(nodes);\n\n if (options?.minify) {\n return native.toCssMinified(nativeNodes);\n }\n\n return native.toCssPretty(nativeNodes, options?.indent);\n}\n\n/**\n * Compile multiple candidates directly to CSS using native pipeline.\n * This is the fastest path when using only built-in utilities.\n *\n * Returns null if native is unavailable.\n */\nexport function nativeCompileToCss(inputs: string[], options?: { minify?: boolean }): string | null {\n const native = tryLoadNative();\n if (!native || !native.compileToCss) {\n return null;\n }\n\n if (!isNativeCompilerAvailableFor(native) || !isNativePrinterAvailableFor(native)) {\n return null;\n }\n\n return native.compileToCss(inputs, undefined, { minify: options?.minify });\n}\n\n// ============================================\n// Batch Operations\n// ============================================\n\n/**\n * Parse multiple candidates using native batch parser.\n * Returns null for each candidate that fails to parse.\n */\nexport function nativeParseCandidatesBatch(inputs: string[]): (TsCandidate | null)[] {\n const native = tryLoadNative();\n if (!native) {\n return inputs.map(() => null);\n }\n if (!isNativeParserAvailableFor(native)) {\n return inputs.map(() => null);\n }\n\n // Use batch if available, otherwise fall back to sequential\n if (native.parseCandidatesBatch) {\n const results = native.parseCandidatesBatch(inputs);\n return results.map((r) => (r ? convertNativeCandidate(r) : null));\n }\n\n return inputs.map((input) => {\n const result = native.parseCandidate(input);\n return result ? convertNativeCandidate(result) : null;\n });\n}\n\n/**\n * Compile multiple candidates using native batch compiler.\n * Returns null for each candidate that fails to compile.\n *\n * Note: Theme values are not passed to the native compiler since\n * native utilities use built-in default values.\n */\nexport function nativeCompileCandidatesBatch(inputs: string[], _theme?: TsTheme): (AstNode[] | null)[] {\n const native = tryLoadNative();\n if (!native) {\n return inputs.map(() => null);\n }\n if (!isNativeCompilerAvailableFor(native)) {\n return inputs.map(() => null);\n }\n\n if (native.compileCandidatesBatch) {\n const results = native.compileCandidatesBatch(inputs);\n return results.map((r) => (r ? nativeAstToTs(r) : null));\n }\n\n return inputs.map((input) => {\n const result = native.compileCandidateString(input);\n return result ? nativeAstToTs(result) : null;\n });\n}\n\n// ============================================\n// Hybrid Compilation Strategy\n// ============================================\n\nexport interface HybridCompileOptions {\n /** List of candidate strings to compile */\n candidates: string[];\n /** Theme for value resolution */\n theme?: TsTheme;\n /** Whether to use native for known utilities */\n preferNative?: boolean;\n /** Fallback compiler for unknown utilities */\n fallback?: (candidate: string, theme?: TsTheme) => AstNode[] | null;\n}\n\n/**\n * Hybrid compilation that uses native for known utilities\n * and falls back to TypeScript for custom utilities.\n */\nexport function hybridCompileCandidates(options: HybridCompileOptions): Map<string, AstNode[] | null> {\n const { candidates, theme, preferNative = true, fallback } = options;\n const results = new Map<string, AstNode[] | null>();\n\n if (!preferNative || !isNativeCompilerAvailable()) {\n // Fall back to TypeScript for all\n for (const candidate of candidates) {\n results.set(candidate, fallback ? fallback(candidate, theme) : null);\n }\n return results;\n }\n\n const native = tryLoadNative()!;\n\n for (const candidate of candidates) {\n // Try native first\n const nativeResult = native.compileCandidateString(candidate);\n\n if (nativeResult) {\n results.set(candidate, nativeAstToTs(nativeResult));\n } else if (fallback) {\n // Fall back to TypeScript\n results.set(candidate, fallback(candidate, theme));\n } else {\n results.set(candidate, null);\n }\n }\n\n return results;\n}\n","/**\n * CSS Compilation\n *\n * Main compilation pipeline that transforms CSS with utilities.\n */\n\nimport type { AstNode, StyleRule, SourceMap } from \"../ast\";\nimport { decl, printWithSourceMap, styleRule, print } from \"../ast\";\nimport { parseCandidate, type Candidate, type ParseOptions } from \"../candidate\";\nimport { Theme, loadDefaultTheme } from \"../theme\";\nimport { createDefaultUtilities, type Utilities } from \"../utilities\";\nimport { createDefaultVariants, type Variants } from \"../variants\";\nimport { loadPlugins, type Plugin } from \"../plugin\";\nimport { escapeClassName as _escapeClassName } from \"../utils/escape\";\nimport { type FoldOptions } from \"../optimize/constant-fold\";\nimport { compareClassNames } from \"./sort\";\nimport { optimizeAst } from \"./optimize\";\nimport { DefaultMap } from \"../utils/default-map\";\nimport { getVariableNames } from \"../utils/variables\";\nimport { isNativeCompilerAvailable, nativeCompileToCss } from \"./native\";\nimport { LruCache } from \"../utils/lru-cache\";\n\n// ============================================\n// Design System\n// ============================================\n\n// Module-level cached design system for default options.\n// This avoids re-creating the design system for every call to\n// getClassOrder, sortClassList, or compileClasses when no custom options are passed.\n// Tailwindcss uses a similar pattern for performance.\nlet _cachedDefaultDesignSystem: DesignSystem | null = null;\nlet _cachedDefaultTheme: Theme | null = null;\n\n/**\n * Get the cached default design system.\n * Creates one on first call, then returns cached instance.\n * This is safe because the default design system is immutable\n * (no plugins, no prefix, no blocked candidates).\n */\nexport function getDefaultDesignSystem(): DesignSystem {\n if (_cachedDefaultDesignSystem === null) {\n _cachedDefaultDesignSystem = createDesignSystem();\n }\n return _cachedDefaultDesignSystem;\n}\n\n/**\n * Clear the cached default design system.\n * Useful for testing or when theme values change.\n */\nexport function clearDesignSystemCache(): void {\n _cachedDefaultDesignSystem = null;\n _cachedDefaultTheme = null;\n}\n\nfunction getDefaultThemeClone(): Theme {\n if (_cachedDefaultTheme === null) {\n const base = new Theme();\n loadDefaultTheme(base);\n _cachedDefaultTheme = base;\n }\n return _cachedDefaultTheme.clone();\n}\n\nexport interface DesignSystem {\n theme: Theme;\n utilities: Utilities;\n variants: Variants;\n /** Base styles added by plugins */\n baseStyles: AstNode[];\n /** Component styles added by plugins */\n componentStyles: AstNode[];\n /** Optional prefix for all utility classes (e.g., \"tw-\") */\n prefix: string | null;\n /**\n * Whether to apply !important to all generated utilities.\n * Set by @import \"tailwindcss\" important or @media important.\n */\n important: boolean;\n /** Set of candidates that failed to compile (for diagnostics) */\n invalidCandidates: Set<string>;\n /** Set of candidates that are explicitly blocked from use */\n blockedCandidates: Set<string>;\n /** Record a candidate as invalid (failed to compile) */\n recordInvalid(candidate: string): void;\n /** Check if a candidate is valid (not blocked and has prefix if required) */\n isValidCandidate(candidate: string): boolean;\n /** Check if a candidate has the required prefix */\n hasValidPrefix(candidate: string): boolean;\n /** Strip the prefix from a candidate if present */\n stripPrefix(candidate: string): string;\n\n // ============================================\n // Cached parsing methods\n // ============================================\n\n /**\n * Parse a candidate with caching.\n * Returns cached results for repeated calls with the same input.\n */\n parseCandidate(candidate: string): readonly Candidate[];\n\n /**\n * Track CSS variables used in a value.\n * Marks variables as used in the theme for tree-shaking.\n */\n trackUsedVariables(raw: string): void;\n\n /**\n * Get all tracked used variables.\n */\n getUsedVariables(): Set<string>;\n\n // ============================================\n // IntelliSense helpers\n // ============================================\n\n /**\n * Compile a candidate to AST nodes with caching.\n * Returns cached results for repeated calls with the same candidate.\n */\n compileCandidate(candidate: Candidate): AstNode[] | null;\n\n /**\n * Compile classes to AST nodes (for IntelliSense).\n * Returns an array of AST nodes for each class, or empty array if invalid.\n */\n candidatesToAst(classes: string[]): AstNode[][];\n\n /**\n * Compile classes to CSS strings (for IntelliSense).\n * Returns CSS string for each class, or null if invalid.\n */\n candidatesToCss(classes: string[]): (string | null)[];\n\n // ============================================\n // Plugin storage\n // ============================================\n\n /**\n * Symbol-keyed storage for plugin data.\n * Used for plugin extensibility without polluting the main interface.\n */\n storage: Record<symbol, unknown>;\n\n // ============================================\n // Cache management\n // ============================================\n\n /**\n * Clear all internal caches.\n * Call this when theme values change, plugins are reloaded,\n * or when you need to ensure fresh compilation results.\n *\n * This invalidates:\n * - Parsed candidate cache\n * - Compiled AST cache\n * - Invalid candidate tracking\n */\n clearCaches(): void;\n\n /**\n * Get cache statistics for debugging and monitoring.\n * Includes hit/miss ratios for performance analysis.\n */\n getCacheStats(): {\n parsedCandidates: { size: number; hits: number; misses: number; hitRate: number };\n compiledAst: number;\n };\n}\n\nexport interface DesignSystemOptions {\n /** List of plugins to load */\n plugins?: Plugin[];\n /** Optional prefix for all utility classes (e.g., \"tw-\") */\n prefix?: string | null;\n /** Candidates to explicitly block from use */\n blockedCandidates?: string[];\n}\n\n/**\n * Create a design system with default configuration.\n */\nexport function createDesignSystem(options: DesignSystemOptions = {}): DesignSystem {\n const theme = getDefaultThemeClone();\n\n const utilities = createDefaultUtilities(theme);\n const variants = createDefaultVariants(theme);\n\n // Load plugins\n let baseStyles: AstNode[] = [];\n let componentStyles: AstNode[] = [];\n\n if (options.plugins && options.plugins.length > 0) {\n const pluginResult = loadPlugins(options.plugins, theme, utilities, variants);\n baseStyles = pluginResult.baseStyles;\n componentStyles = pluginResult.componentStyles;\n }\n\n // Initialize prefix and candidate tracking\n const prefix = options.prefix ?? null;\n variants.classPrefix = prefix;\n const invalidCandidates = new Set<string>();\n const blockedCandidates = new Set<string>(options.blockedCandidates ?? []);\n\n // ============================================\n // Caching infrastructure (multi-level, inspired by tailwindcss)\n // ============================================\n\n // Parse options with trie-based utility lookup (O(n) instead of O(k))\n const parseOptions: ParseOptions = {\n findRoot: (input: string) => utilities.findRoot(input),\n };\n\n // Cache for parsed candidates: candidate string -> Candidate[]\n // Limit: 5000 entries covers large projects (enterprise apps, component libraries)\n // while keeping memory bounded (~50KB assuming ~10 bytes per entry average).\n // This is higher than parse.ts caches because the design system persists\n // across builds, accumulating all candidates seen during watch mode.\n const parsedCandidates = new LruCache<string, readonly Candidate[]>(5000);\n const getParsedCandidates = (candidate: string): readonly Candidate[] => {\n const cached = parsedCandidates.get(candidate);\n if (cached !== undefined) {\n return cached;\n }\n const parsed = parseCandidate(candidate, parseOptions);\n const frozen = parsed.length === 0 ? parsed : Object.freeze(parsed);\n parsedCandidates.set(candidate, frozen);\n return frozen;\n };\n\n // Compilation flags (bitflags for multi-level caching)\n const enum CompileFlags {\n None = 0,\n RespectImportant = 1 << 0,\n }\n\n // Multi-level cache for compiled AST: flags -> candidate raw -> AstNode[] | null\n // This pattern from tailwindcss allows efficient caching by context (e.g., with/without !important)\n const compiledAstCache = new DefaultMap<CompileFlags, Map<string, AstNode[] | null>>(() => new Map());\n\n function compileCandidateCached(\n candidate: Candidate,\n flags: CompileFlags = CompileFlags.RespectImportant\n ): AstNode[] | null {\n const key = candidate.raw;\n const flagCache = compiledAstCache.get(flags);\n const cached = flagCache.get(key);\n if (cached !== undefined) {\n return cached;\n }\n const result = compileCandidate(candidate, utilities, variants, theme);\n flagCache.set(key, result);\n return result;\n }\n\n // Default compilation function (respects important flag)\n function compileCandidateDefault(candidate: Candidate): AstNode[] | null {\n return compileCandidateCached(candidate, CompileFlags.RespectImportant);\n }\n\n // Track all used variables\n const usedVariables = new Set<string>();\n\n // Cache for variable tracking: raw value -> void (side effect: marks variables)\n const trackedVariables = new DefaultMap<string, void>((raw) => {\n const variables = getVariableNames(raw);\n for (const variable of variables) {\n theme.markUsed(variable);\n usedVariables.add(variable);\n }\n });\n\n // Storage for plugin extensibility\n const storage: Record<symbol, unknown> = {};\n\n const designSystem: DesignSystem = {\n theme,\n utilities,\n variants,\n baseStyles,\n componentStyles,\n prefix,\n important: false,\n invalidCandidates,\n blockedCandidates,\n storage,\n\n recordInvalid(candidate: string): void {\n invalidCandidates.add(candidate);\n },\n\n isValidCandidate(candidate: string): boolean {\n return !blockedCandidates.has(candidate) && this.hasValidPrefix(candidate);\n },\n\n hasValidPrefix(candidate: string): boolean {\n return !prefix || candidate.startsWith(prefix);\n },\n\n stripPrefix(candidate: string): string {\n if (!prefix || !candidate.startsWith(prefix)) {\n return candidate;\n }\n return candidate.slice(prefix.length);\n },\n\n // Cached parsing\n parseCandidate(candidate: string): readonly Candidate[] {\n return getParsedCandidates(candidate);\n },\n\n // Cached compilation\n compileCandidate(candidate: Candidate): AstNode[] | null {\n return compileCandidateDefault(candidate);\n },\n\n // Variable tracking\n trackUsedVariables(raw: string): void {\n trackedVariables.get(raw);\n },\n\n getUsedVariables(): Set<string> {\n return new Set(usedVariables);\n },\n\n // IntelliSense helpers (uses cached compilation)\n candidatesToAst(classes: string[]): AstNode[][] {\n return classes.map((className) => {\n const candidates = this.parseCandidate(className);\n if (candidates.length === 0) return [];\n\n for (const candidate of candidates) {\n const nodes = compileCandidateDefault(candidate);\n if (nodes && nodes.length > 0) {\n return nodes;\n }\n }\n\n return [];\n });\n },\n\n candidatesToCss(classes: string[]): (string | null)[] {\n return this.candidatesToAst(classes).map((nodes) => {\n if (nodes.length === 0) return null;\n return print(nodes);\n });\n },\n\n // Cache management\n clearCaches(): void {\n // Clear the parsed candidates cache\n parsedCandidates.clear();\n\n // Clear the compiled AST cache (all flag levels)\n compiledAstCache.clear();\n\n // Clear tracked variables\n trackedVariables.clear();\n\n // Clear invalid candidates so they can be re-evaluated\n invalidCandidates.clear();\n\n // Clear used variables tracking\n usedVariables.clear();\n },\n\n getCacheStats(): {\n parsedCandidates: { size: number; hits: number; misses: number; hitRate: number };\n compiledAst: number;\n } {\n let compiledAstCount = 0;\n for (const flagCache of compiledAstCache.values()) {\n compiledAstCount += flagCache.size;\n }\n const stats = parsedCandidates.stats;\n return {\n parsedCandidates: {\n size: stats.size,\n hits: stats.hits,\n misses: stats.misses,\n hitRate: stats.hitRate,\n },\n compiledAst: compiledAstCount,\n };\n },\n };\n\n return designSystem;\n}\n\n// ============================================\n// Compilation\n// ============================================\n\nexport interface CompileOptions {\n /** Design system to use (creates default if not provided) */\n designSystem?: DesignSystem;\n /** Whether to minify output */\n minify?: boolean;\n /** Whether to include base styles from plugins */\n includeBase?: boolean;\n /** Whether to include component styles from plugins */\n includeComponents?: boolean;\n /** Generate source map */\n sourceMap?: boolean;\n /** Source file path for source map */\n from?: string;\n /**\n * Fold calc() expressions at compile time.\n * - calc(2 * 4px) -> 8px\n * - calc(100% - 0px) -> 100%\n * - calc(1rem + 1rem) -> 2rem\n */\n foldConstants?: boolean | FoldOptions;\n /**\n * Substitute custom CSS functions:\n * - --alpha(color / opacity) -> color-mix()\n * - --spacing(multiplier) -> calc()\n * - --theme(variable) -> var() or inlined value\n */\n substituteFunctions?: boolean;\n /**\n * Sort CSS declarations by property order for consistent output.\n * (position > display > box model > typography > visual)\n */\n sortDeclarations?: boolean;\n}\n\nexport interface CompileResult {\n /** Generated CSS */\n css: string;\n /** List of generated class names */\n classes: string[];\n /** Source map (when sourceMap option is true) */\n map?: SourceMap;\n}\n\n/**\n * Compile a list of utility classes to CSS.\n */\nexport function compileClasses(classes: string[], options: CompileOptions = {}): CompileResult {\n // Use cached design system for default options (major performance win for cold compile)\n const designSystem = options.designSystem ?? getDefaultDesignSystem();\n const { theme, variants, baseStyles, componentStyles } = designSystem;\n\n const generatedClasses: string[] = [];\n const ast: AstNode[] = [];\n\n // Include base styles if requested\n if (options.includeBase !== false && baseStyles.length > 0) {\n ast.push(...baseStyles);\n }\n\n // Include component styles if requested\n if (options.includeComponents !== false && componentStyles.length > 0) {\n ast.push(...componentStyles);\n }\n\n const descriptors: Array<{\n className: string;\n lookupClassName: string;\n candidates: readonly Candidate[];\n }> = [];\n\n for (const className of classes) {\n // Skip blocked candidates\n if (designSystem.blockedCandidates.has(className)) {\n continue;\n }\n\n // Check prefix requirement and strip prefix for lookup\n let lookupClassName = className;\n if (designSystem.prefix) {\n if (!designSystem.hasValidPrefix(className)) {\n // Record as invalid if prefix is required but not present\n designSystem.recordInvalid(className);\n continue;\n }\n lookupClassName = designSystem.stripPrefix(className);\n }\n\n // Use cached parsing from design system\n const candidates = designSystem.parseCandidate(lookupClassName);\n if (candidates.length === 0) {\n designSystem.recordInvalid(className);\n continue;\n }\n\n descriptors.push({ className, lookupClassName, candidates });\n }\n\n // Pre-compute sort orders BEFORE sorting (major performance optimization)\n // This avoids calling getCandidateOrder() O(n log n) times in the comparator\n const orderCache = new Map<string, bigint>();\n for (const desc of descriptors) {\n orderCache.set(desc.className, getCandidateOrder(desc.candidates[0]!, variants));\n }\n\n descriptors.sort((a, b) => {\n const orderA = orderCache.get(a.className)!;\n const orderB = orderCache.get(b.className)!;\n if (orderA !== orderB) {\n return orderA < orderB ? -1 : 1;\n }\n return compareClassNames(a.lookupClassName, b.lookupClassName);\n });\n\n for (const descriptor of descriptors) {\n let compiled = false;\n for (const candidate of descriptor.candidates) {\n const outputCandidate =\n descriptor.className === descriptor.lookupClassName\n ? candidate\n : { ...candidate, raw: descriptor.className };\n // Use cached compilation from designSystem\n const nodes = designSystem.compileCandidate(outputCandidate);\n\n if (nodes && nodes.length > 0) {\n ast.push(...nodes);\n generatedClasses.push(descriptor.className);\n compiled = true;\n\n // Track custom property candidates as used theme variables\n // When a candidate starts with --, mark it as used for tree-shaking\n if (descriptor.lookupClassName.startsWith(\"--\")) {\n theme.markUsed(descriptor.lookupClassName);\n }\n }\n }\n\n if (!compiled) {\n designSystem.recordInvalid(descriptor.className);\n }\n }\n\n // Single-pass AST optimization (replaces 5 separate AST walks)\n const finalAst = optimizeAst(ast, {\n theme,\n important: designSystem.important,\n foldConstants: options.foldConstants,\n sortDeclarations: options.sortDeclarations,\n substituteFunctions: options.substituteFunctions,\n });\n\n const result = printWithSourceMap(finalAst, {\n minify: options.minify,\n sourceMap: options.sourceMap,\n file: options.from,\n });\n\n return {\n css: result.code,\n classes: generatedClasses,\n map: result.map,\n };\n}\n\n// ============================================\n// Incremental Compiler API\n// ============================================\n\nexport interface Compiler {\n /** The design system used by this compiler */\n designSystem: DesignSystem;\n /**\n * Build CSS from a list of candidate class names.\n * Uses caching for repeated calls with overlapping candidates.\n */\n build(candidates: string[]): CompileResult;\n /**\n * Build CSS incrementally by adding new candidates to existing set.\n * More efficient when candidates are added over time.\n * Uses didChange tracking for early exits when nothing changed.\n */\n buildIncremental(newCandidates: string[]): CompileResult;\n /**\n * Check if the last build produced any changes.\n * Useful for build systems that need to know if output changed.\n */\n readonly didChange: boolean;\n}\n\nexport interface CreateCompilerOptions extends Omit<CompileOptions, \"designSystem\"> {\n /** Design system options */\n designSystemOptions?: DesignSystemOptions;\n /**\n * Use native Rust compiler when available.\n * Provides significant performance improvements for built-in utilities.\n * Falls back to TypeScript when:\n * - Native module is not available\n * - Plugins add custom utilities\n * - Source maps are requested\n * Default: true\n */\n useNative?: boolean;\n /**\n * Cache build results when the candidate list hasn't changed.\n * Disable for benchmarking or one-off builds where caching isn't desired.\n * Default: true\n */\n cache?: boolean;\n}\n\n/**\n * Create a compiler instance for efficient repeated builds.\n *\n * The compiler maintains internal caches for:\n * - Parsed candidates\n * - Compiled AST nodes\n * - Variant ordering\n * - Previous build result (for reference equality checks)\n *\n * Uses the `didChange` pattern from tailwindcss for early exits:\n * - Tracks if any new valid candidates were added\n * - Tracks if AST node count changed\n * - Returns cached result when nothing changed\n *\n * This is more efficient than calling `compileClasses()` repeatedly\n * when the same design system is used.\n *\n * @example\n * const compiler = createCompiler();\n * const result1 = compiler.build(['bg-red-500', 'text-paper']);\n * const result2 = compiler.build(['bg-red-500', 'text-paper', 'p-4']); // Uses cache\n */\nexport function createCompiler(options: CreateCompilerOptions = {}): Compiler {\n const designSystem = createDesignSystem(options.designSystemOptions);\n const useBuildCache = options.cache !== false;\n\n // Accumulate all valid candidates seen across builds (like tailwindcss allValidCandidates)\n const allValidCandidates = new Set<string>();\n\n // Cache the last compiled result for reference equality checks\n let cachedResult: CompileResult | null = null;\n let cachedBuildResult: CompileResult | null = null;\n let cachedBuildCandidates: string[] = [];\n let cachedBuildCandidatesLength = 0;\n let cachedBuildCandidatesFirst: string | undefined;\n let cachedBuildCandidatesMid: string | undefined;\n let cachedBuildCandidatesLast: string | undefined;\n\n // Track previous AST node count for didChange detection\n let previousClassCount = 0;\n\n // Track if the last build produced changes\n let _didChange = false;\n\n const compileOptions: CompileOptions = {\n ...options,\n designSystem,\n };\n\n // Determine if we can use native compilation\n // Native is disabled when:\n // - useNative is explicitly false\n // - Plugins add custom utilities (base/component styles)\n // - Source maps are requested (native doesn't support them)\n const hasPlugins = designSystem.baseStyles.length > 0 || designSystem.componentStyles.length > 0;\n const useNative = options.useNative !== false && !hasPlugins && !options.sourceMap && isNativeCompilerAvailable();\n\n function sameCandidateList(a: string[], b: string[]): boolean {\n if (a === b) {\n if (a.length !== cachedBuildCandidatesLength) return false;\n if (a.length === 0) return true;\n const midIndex = a.length >>> 1;\n return (\n a[0] === cachedBuildCandidatesFirst &&\n a[midIndex] === cachedBuildCandidatesMid &&\n a[a.length - 1] === cachedBuildCandidatesLast\n );\n }\n if (a.length !== b.length) return false;\n for (let i = 0; i < a.length; i++) {\n if (a[i] !== b[i]) return false;\n }\n return true;\n }\n\n return {\n designSystem,\n\n get didChange(): boolean {\n return _didChange;\n },\n\n build(candidates: string[]): CompileResult {\n if (useBuildCache && cachedBuildResult && sameCandidateList(candidates, cachedBuildCandidates)) {\n return cachedBuildResult;\n }\n\n // Try native compilation first (fast path)\n // Native supports: display, spacing, sizing, colors, typography, flexbox,\n // grid, borders, shadows, opacity, and all variants\n if (useNative) {\n const css = nativeCompileToCss(candidates, { minify: options.minify });\n if (css !== null && css.length > 0) {\n const result = { css, classes: candidates };\n if (useBuildCache) {\n cachedBuildResult = result;\n cachedBuildCandidates = candidates;\n cachedBuildCandidatesLength = candidates.length;\n cachedBuildCandidatesMid = candidates[candidates.length >>> 1];\n cachedBuildCandidatesFirst = candidates[0];\n cachedBuildCandidatesLast = candidates[candidates.length - 1];\n }\n return result;\n }\n }\n\n // Fall back to TypeScript compilation for full compatibility\n const result = compileClasses(candidates, compileOptions);\n if (useBuildCache) {\n cachedBuildResult = result;\n cachedBuildCandidates = candidates;\n cachedBuildCandidatesLength = candidates.length;\n cachedBuildCandidatesMid = candidates[candidates.length >>> 1];\n cachedBuildCandidatesFirst = candidates[0];\n cachedBuildCandidatesLast = candidates[candidates.length - 1];\n }\n return result;\n },\n\n buildIncremental(newCandidates: string[]): CompileResult {\n // Track if anything changed (didChange pattern from tailwindcss)\n let didChange = false;\n\n // Add new candidates unless we know they are invalid\n const prevSize = allValidCandidates.size;\n for (const candidate of newCandidates) {\n // Skip known invalid candidates (early exit optimization)\n if (designSystem.invalidCandidates.has(candidate)) {\n continue;\n }\n\n // Skip blocked candidates\n if (designSystem.blockedCandidates.has(candidate)) {\n continue;\n }\n\n // Track custom property candidates as used theme variables\n if (candidate.startsWith(\"--\")) {\n designSystem.theme.markUsed(candidate);\n didChange = true;\n continue;\n }\n\n allValidCandidates.add(candidate);\n // Check if size changed (efficient way to detect new additions)\n didChange = didChange || allValidCandidates.size !== prevSize;\n }\n\n // Early exit: no new candidates added\n if (useBuildCache && !didChange && cachedResult !== null) {\n _didChange = false;\n return cachedResult;\n }\n\n const allCandidates = [...allValidCandidates];\n\n // Fast path: native incremental compilation when available\n if (useNative) {\n const css = nativeCompileToCss(allCandidates, { minify: options.minify });\n if (css !== null) {\n const nativeResult = { css, classes: allCandidates };\n\n // Early exit: same number of classes generated (AST didn't change)\n if (useBuildCache && nativeResult.classes.length === previousClassCount && cachedResult !== null) {\n _didChange = false;\n return cachedResult;\n }\n\n previousClassCount = nativeResult.classes.length;\n if (useBuildCache) {\n cachedResult = nativeResult;\n }\n _didChange = true;\n return nativeResult;\n }\n }\n\n // Compile all accumulated candidates (TypeScript fallback)\n const result = compileClasses(allCandidates, compileOptions);\n\n // Early exit: same number of classes generated (AST didn't change)\n if (useBuildCache && result.classes.length === previousClassCount && cachedResult !== null) {\n _didChange = false;\n return cachedResult;\n }\n\n // Update tracking state\n previousClassCount = result.classes.length;\n if (useBuildCache) {\n cachedResult = result;\n }\n _didChange = true;\n\n return result;\n },\n };\n}\n\n/**\n * Compile a single candidate to AST nodes.\n */\nexport function compileCandidate(\n candidate: Candidate,\n utilities: Utilities,\n variants: Variants,\n theme: Theme\n): AstNode[] | null {\n // Compile the base utility\n let nodes: AstNode[] | null = null;\n\n if (candidate.kind === \"arbitrary\") {\n // Arbitrary property: [color:red] or [--custom-prop:value]\n nodes = [decl(candidate.property, candidate.value, candidate.important)];\n\n // Track custom property names as used theme variables\n // This supports tree-shaking for --* candidates\n if (candidate.property.startsWith(\"--\")) {\n theme.markUsed(candidate.property);\n }\n } else {\n nodes = utilities.compile(candidate, theme);\n }\n\n if (!nodes || nodes.length === 0) {\n return null;\n }\n\n // Apply !important if needed\n if (candidate.important) {\n nodes = applyImportant(nodes);\n }\n\n // Generate the base selector\n const selector = _escapeClassName(candidate.raw);\n let rule = styleRule(`.${selector}`, nodes);\n\n // Apply variants in reverse order (innermost first)\n const variantList = [...candidate.variants].reverse();\n\n for (const variant of variantList) {\n const result = variants.apply(rule, variant, theme);\n\n if (!result || result.length === 0) {\n return null;\n }\n\n // The result should be a single modified rule\n rule = result[0] as StyleRule;\n }\n\n // Return the compiled rule - post-processing (substituteFunctions, foldAST, sortAST)\n // is done once in compileClasses() for the entire AST, not per-candidate.\n // This is a major performance optimization.\n return [rule];\n}\n\n// Re-export escapeClassName for convenience\nexport { escapeClassName } from \"../utils/escape\";\n\n/**\n * Apply !important to all declarations in the AST.\n * Used by both Node compile and browser build when @media important is set.\n */\nexport function applyImportant(nodes: AstNode[]): AstNode[] {\n return nodes.map((node) => {\n if (node.kind === \"declaration\") {\n return { ...node, important: true };\n }\n if (\"nodes\" in node && Array.isArray(node.nodes)) {\n return { ...node, nodes: applyImportant(node.nodes) };\n }\n return node;\n });\n}\n\n// ============================================\n// Candidate Sorting\n// ============================================\n\n// Pre-computed BigInt shifts for performance (avoids BigInt() call in hot path)\n// Covers bit positions 0-63 which is sufficient for all variant orderings\nconst BIGINT_SHIFTS: bigint[] = new Array(64);\nfor (let i = 0; i < 64; i++) {\n BIGINT_SHIFTS[i] = 1n << BigInt(i);\n}\n\n// Constants for special bit positions\nconst UNKNOWN_VARIANT_BIT = BIGINT_SHIFTS[60]!;\nconst ARBITRARY_VARIANT_BIT = BIGINT_SHIFTS[61]!;\nconst IMPORTANT_BIT = BIGINT_SHIFTS[62]!;\n\n/**\n * Get the sort order for a candidate using bitmask operations.\n * Uses pre-computed variant order map for O(1) lookups.\n * Lower numbers come first.\n *\n * Performance optimizations:\n * - Pre-computed BigInt shifts (avoids BigInt() allocation in hot path)\n * - Direct variant.kind comparison\n */\nexport function getCandidateOrder(candidate: Candidate, variants: Variants): bigint {\n // Get cached order map for bitmask operations\n const orderMap = variants.getOrderMap();\n\n // Build bitmask: each variant gets a bit position based on its order\n // This gives O(1) comparison instead of O(n) variant iteration\n let variantMask = 0n;\n for (const variant of candidate.variants) {\n if (variant.kind === \"static\" || variant.kind === \"functional\") {\n const idx = orderMap.get(variant.root);\n if (idx !== undefined && idx < 60) {\n variantMask |= BIGINT_SHIFTS[idx]!;\n } else {\n // Unknown variant - use high bit position\n variantMask |= UNKNOWN_VARIANT_BIT;\n }\n } else {\n // Arbitrary/compound variant - use high bit position\n variantMask |= ARBITRARY_VARIANT_BIT;\n }\n }\n\n // Layer 2: Important flag (uses highest bit position)\n if (candidate.important) {\n variantMask |= IMPORTANT_BIT;\n }\n\n return variantMask;\n}\n\n/**\n * Sort classes by their generated CSS order.\n */\nexport function sortClasses(classes: string[], variants: Variants): string[] {\n const parsed = classes.map((className) => ({\n className,\n candidates: parseCandidate(className),\n }));\n\n return parsed\n .sort((a, b) => {\n const aOrder = a.candidates[0] ? getCandidateOrder(a.candidates[0], variants) : 0n;\n const bOrder = b.candidates[0] ? getCandidateOrder(b.candidates[0], variants) : 0n;\n if (aOrder < bOrder) return -1;\n if (aOrder > bOrder) return 1;\n return 0;\n })\n .map((p) => p.className);\n}\n\n/**\n * Get the sort order for a list of classes.\n * Returns array of [className, order] pairs.\n *\n * Useful for IDE integrations that need to sort classes.\n */\nexport function getClassOrder(classes: string[], options: CompileOptions = {}): Array<[string, bigint | null]> {\n // Use cached design system for default options\n const designSystem = options.designSystem ?? getDefaultDesignSystem();\n const { variants } = designSystem;\n\n // Use the design system's cached parseCandidate instead of creating new parseOptions\n return classes.map((className) => {\n const candidates = designSystem.parseCandidate(className);\n\n if (candidates.length === 0) {\n return [className, null] as [string, bigint | null];\n }\n\n const order = getCandidateOrder(candidates[0]!, variants);\n return [className, order] as [string, bigint | null];\n });\n}\n\n/**\n * Sort a string of space-separated classes.\n * Returns the classes in sorted order.\n */\nexport function sortClassList(classList: string, options: CompileOptions = {}): string {\n // Use cached design system for default options\n const designSystem = options.designSystem ?? getDefaultDesignSystem();\n const { variants } = designSystem;\n\n const classes = classList.split(/\\s+/).filter(Boolean);\n return sortClasses(classes, variants).join(\" \");\n}\n","/**\n * Canonicalize Candidates Module\n *\n * Collapses redundant utility classes into more concise forms:\n * - mt-2 mr-2 mb-2 ml-2 -> m-2\n * - px-4 py-4 -> p-4\n * - text-left -> (removes if default)\n */\n\nimport type { DesignSystem } from \"./compile\";\n\n// ============================================\n// Types\n// ============================================\n\nexport interface CanonicalizeOptions {\n /** Collapse axis utilities (mt, mr, mb, ml -> m) */\n collapse?: boolean;\n /** Convert logical properties to physical (ms -> ml in LTR) */\n logicalToPhysical?: boolean;\n /** Remove default values (text-left, opacity-100) */\n removeDefaults?: boolean;\n /** Root font size for rem calculations (default: 16) */\n rem?: number;\n}\n\ninterface CanonicalizationRule {\n /** The individual utility prefixes that can be collapsed */\n parts: string[];\n /** The canonical utility prefix they collapse to */\n canonical: string;\n /** Type of rule: all (mt+mr+mb+ml), axis (mx+my), or pair (ms+me) */\n type: \"all\" | \"axis\" | \"pair\";\n}\n\n// ============================================\n// Canonicalization Rules\n// ============================================\n\nconst CANONICALIZATION_RULES: CanonicalizationRule[] = [\n // Margin\n { parts: [\"mt\", \"mr\", \"mb\", \"ml\"], canonical: \"m\", type: \"all\" },\n { parts: [\"mx\", \"my\"], canonical: \"m\", type: \"axis\" },\n { parts: [\"mt\", \"mb\"], canonical: \"my\", type: \"pair\" },\n { parts: [\"mr\", \"ml\"], canonical: \"mx\", type: \"pair\" },\n { parts: [\"ms\", \"me\"], canonical: \"mx\", type: \"pair\" },\n\n // Padding\n { parts: [\"pt\", \"pr\", \"pb\", \"pl\"], canonical: \"p\", type: \"all\" },\n { parts: [\"px\", \"py\"], canonical: \"p\", type: \"axis\" },\n { parts: [\"pt\", \"pb\"], canonical: \"py\", type: \"pair\" },\n { parts: [\"pr\", \"pl\"], canonical: \"px\", type: \"pair\" },\n { parts: [\"ps\", \"pe\"], canonical: \"px\", type: \"pair\" },\n\n // Inset\n { parts: [\"top\", \"right\", \"bottom\", \"left\"], canonical: \"inset\", type: \"all\" },\n { parts: [\"inset-x\", \"inset-y\"], canonical: \"inset\", type: \"axis\" },\n { parts: [\"top\", \"bottom\"], canonical: \"inset-y\", type: \"pair\" },\n { parts: [\"left\", \"right\"], canonical: \"inset-x\", type: \"pair\" },\n\n // Border radius\n { parts: [\"rounded-tl\", \"rounded-tr\", \"rounded-bl\", \"rounded-br\"], canonical: \"rounded\", type: \"all\" },\n { parts: [\"rounded-t\", \"rounded-b\"], canonical: \"rounded\", type: \"pair\" },\n { parts: [\"rounded-l\", \"rounded-r\"], canonical: \"rounded\", type: \"pair\" },\n { parts: [\"rounded-tl\", \"rounded-tr\"], canonical: \"rounded-t\", type: \"pair\" },\n { parts: [\"rounded-bl\", \"rounded-br\"], canonical: \"rounded-b\", type: \"pair\" },\n { parts: [\"rounded-tl\", \"rounded-bl\"], canonical: \"rounded-l\", type: \"pair\" },\n { parts: [\"rounded-tr\", \"rounded-br\"], canonical: \"rounded-r\", type: \"pair\" },\n\n // Border width\n { parts: [\"border-t\", \"border-r\", \"border-b\", \"border-l\"], canonical: \"border\", type: \"all\" },\n { parts: [\"border-x\", \"border-y\"], canonical: \"border\", type: \"axis\" },\n { parts: [\"border-t\", \"border-b\"], canonical: \"border-y\", type: \"pair\" },\n { parts: [\"border-r\", \"border-l\"], canonical: \"border-x\", type: \"pair\" },\n\n // Scroll margin\n { parts: [\"scroll-mt\", \"scroll-mr\", \"scroll-mb\", \"scroll-ml\"], canonical: \"scroll-m\", type: \"all\" },\n { parts: [\"scroll-mx\", \"scroll-my\"], canonical: \"scroll-m\", type: \"axis\" },\n { parts: [\"scroll-mt\", \"scroll-mb\"], canonical: \"scroll-my\", type: \"pair\" },\n { parts: [\"scroll-mr\", \"scroll-ml\"], canonical: \"scroll-mx\", type: \"pair\" },\n\n // Scroll padding\n { parts: [\"scroll-pt\", \"scroll-pr\", \"scroll-pb\", \"scroll-pl\"], canonical: \"scroll-p\", type: \"all\" },\n { parts: [\"scroll-px\", \"scroll-py\"], canonical: \"scroll-p\", type: \"axis\" },\n { parts: [\"scroll-pt\", \"scroll-pb\"], canonical: \"scroll-py\", type: \"pair\" },\n { parts: [\"scroll-pr\", \"scroll-pl\"], canonical: \"scroll-px\", type: \"pair\" },\n\n // Gap\n { parts: [\"gap-x\", \"gap-y\"], canonical: \"gap\", type: \"axis\" },\n\n // Size\n { parts: [\"w\", \"h\"], canonical: \"size\", type: \"pair\" },\n];\n\n// Pre-compiled regex for pixel value matching (hoisted to avoid recreation on every call)\nconst PX_VALUE_PATTERN = /^(.+)-\\[(\\d+(?:\\.\\d+)?)px\\]$/;\n\n// Standard spacing values lookup (hoisted to avoid recreating object on every call)\nconst STANDARD_SPACING_VALUES: Record<number, string> = {\n 0: \"0\",\n 0.5: \"0.5\",\n 1: \"1\",\n 1.5: \"1.5\",\n 2: \"2\",\n 2.5: \"2.5\",\n 3: \"3\",\n 3.5: \"3.5\",\n 4: \"4\",\n 5: \"5\",\n 6: \"6\",\n 7: \"7\",\n 8: \"8\",\n 9: \"9\",\n 10: \"10\",\n 11: \"11\",\n 12: \"12\",\n 14: \"14\",\n 16: \"16\",\n 20: \"20\",\n 24: \"24\",\n 28: \"28\",\n 32: \"32\",\n 36: \"36\",\n 40: \"40\",\n 44: \"44\",\n 48: \"48\",\n 52: \"52\",\n 56: \"56\",\n 60: \"60\",\n 64: \"64\",\n 72: \"72\",\n 80: \"80\",\n 96: \"96\",\n};\n\n/**\n * Default values that can be removed (these are browser defaults or common defaults)\n */\nconst DEFAULT_VALUES: Set<string> = new Set([\n \"text-left\", // Default text alignment\n \"opacity-100\", // Default opacity\n \"rotate-0\", // No rotation\n \"scale-100\", // No scaling\n \"translate-x-0\", // No translation\n \"translate-y-0\",\n \"skew-x-0\", // No skew\n \"skew-y-0\",\n \"origin-center\", // Default transform origin\n \"cursor-auto\", // Default cursor\n \"select-auto\", // Default user-select\n \"resize-none\", // Default resize (for most elements)\n \"appearance-none\", // Often intentional, keep it\n]);\n\n// ============================================\n// Canonicalization Functions\n// ============================================\n\n/**\n * Parse a utility class into its prefix and value.\n *\n * @example\n * parseUtility(\"mt-4\") // { prefix: \"mt\", value: \"4\" }\n * parseUtility(\"bg-red-500\") // { prefix: \"bg\", value: \"red-500\" }\n */\nfunction parseUtility(className: string): { prefix: string; value: string } | null {\n // Handle negative utilities\n const isNegative = className.startsWith(\"-\");\n const baseClass = isNegative ? className.slice(1) : className;\n\n // Handle variants (hover:, md:, etc.)\n const colonIndex = baseClass.lastIndexOf(\":\");\n const utility = colonIndex >= 0 ? baseClass.slice(colonIndex + 1) : baseClass;\n const variants = colonIndex >= 0 ? baseClass.slice(0, colonIndex + 1) : \"\";\n\n // Find the value separator\n const dashIndex = utility.indexOf(\"-\");\n if (dashIndex === -1) {\n return { prefix: utility, value: \"\" };\n }\n\n const prefix = utility.slice(0, dashIndex);\n const value = utility.slice(dashIndex + 1);\n\n // Reconstruct with negative and variants\n const fullPrefix = (isNegative ? \"-\" : \"\") + variants + prefix;\n\n return { prefix: fullPrefix, value };\n}\n\n/**\n * Canonicalize a list of utility classes.\n *\n * @example\n * canonicalizeClasses([\"mt-4\", \"mr-4\", \"mb-4\", \"ml-4\"])\n * // Returns: [\"m-4\"]\n *\n * canonicalizeClasses([\"px-4\", \"py-4\"])\n * // Returns: [\"p-4\"]\n */\nexport function canonicalizeClasses(classes: string[], options: CanonicalizeOptions = {}): string[] {\n const { collapse = true, removeDefaults = false } = options;\n\n // Remove duplicates while preserving order\n let result = [...new Set(classes)];\n\n // Remove defaults if requested\n if (removeDefaults) {\n result = result.filter((cls) => !DEFAULT_VALUES.has(cls));\n }\n\n // Early exit if not collapsing\n if (!collapse) {\n return result;\n }\n\n // Group classes by value for potential collapsing\n const valueGroups = new Map<string, Set<string>>();\n\n for (const cls of result) {\n const parsed = parseUtility(cls);\n if (!parsed || !parsed.value) continue;\n\n // Extract the base prefix without variants and negation\n const cleanPrefix = parsed.prefix.replace(/^-/, \"\").replace(/.*:/, \"\");\n\n if (!valueGroups.has(parsed.value)) {\n valueGroups.set(parsed.value, new Set());\n }\n valueGroups.get(parsed.value)!.add(cleanPrefix);\n }\n\n // Check each rule for potential canonicalization\n const toRemove = new Set<string>();\n const toAdd: string[] = [];\n\n for (const [value, prefixes] of valueGroups) {\n for (const rule of CANONICALIZATION_RULES) {\n // Check if all parts of the rule are present\n const allPresent = rule.parts.every((part) => prefixes.has(part));\n\n if (allPresent) {\n // Remove the individual classes\n for (const part of rule.parts) {\n toRemove.add(`${part}-${value}`);\n toRemove.add(`-${part}-${value}`); // Also check negative\n }\n\n // Add the canonical class\n toAdd.push(`${rule.canonical}-${value}`);\n\n // Remove the prefixes from the group to prevent double-canonicalization\n for (const part of rule.parts) {\n prefixes.delete(part);\n }\n }\n }\n }\n\n // Apply removals and additions\n result = result.filter((cls) => !toRemove.has(cls));\n result.push(...toAdd);\n\n // Remove duplicates again\n return [...new Set(result)];\n}\n\n/**\n * Check if two class lists are equivalent after canonicalization.\n */\nexport function classListsEquivalent(a: string[], b: string[]): boolean {\n const canonicalA = canonicalizeClasses(a).sort();\n const canonicalB = canonicalizeClasses(b).sort();\n\n if (canonicalA.length !== canonicalB.length) {\n return false;\n }\n\n return canonicalA.every((cls, i) => cls === canonicalB[i]);\n}\n\n/**\n * Expand a canonical class into its component classes.\n * Inverse of canonicalizeClasses.\n *\n * @example\n * expandCanonical(\"m-4\")\n * // Returns: [\"mt-4\", \"mr-4\", \"mb-4\", \"ml-4\"]\n */\nexport function expandCanonical(className: string): string[] {\n const parsed = parseUtility(className);\n if (!parsed || !parsed.value) {\n return [className];\n }\n\n const cleanPrefix = parsed.prefix.replace(/^-/, \"\").replace(/.*:/, \"\");\n\n // Find a rule where this is the canonical form\n for (const rule of CANONICALIZATION_RULES) {\n if (rule.canonical === cleanPrefix) {\n return rule.parts.map((part) => `${part}-${parsed.value}`);\n }\n }\n\n return [className];\n}\n\n/**\n * Suggest a more canonical form for a class list.\n * Returns suggestions without modifying the original.\n *\n * @example\n * suggestCanonical([\"mt-4\", \"mr-4\", \"mb-4\", \"ml-4\"])\n * // Returns: { original: [...], canonical: [\"m-4\"], savings: 3 }\n */\nexport function suggestCanonical(classes: string[]): {\n original: string[];\n canonical: string[];\n savings: number;\n} {\n const canonical = canonicalizeClasses(classes);\n\n return {\n original: classes,\n canonical,\n savings: classes.length - canonical.length,\n };\n}\n\n/**\n * Normalize a class string to a consistent format.\n * - Removes extra whitespace\n * - Deduplicates classes\n * - Optionally canonicalizes\n *\n * @example\n * normalizeClassString(\"mt-4 mr-4 mb-4 ml-4\", { canonicalize: true })\n * // Returns: \"m-4\"\n */\nexport function normalizeClassString(\n classString: string,\n options: CanonicalizeOptions & { canonicalize?: boolean } = {}\n): string {\n const classes = classString.split(/\\s+/).filter(Boolean);\n\n const normalized = options.canonicalize ? canonicalizeClasses(classes, options) : [...new Set(classes)];\n\n return normalized.join(\" \");\n}\n\n// ============================================\n// Design System Integration\n// ============================================\n\n/**\n * Canonicalize candidates using the design system.\n *\n * This is the primary API for IntelliSense integration, providing:\n * - Validation of candidates against the design system\n * - Collapsing of redundant utilities\n * - px to rem conversion (if rem option is set)\n *\n * @example\n * const ds = createDesignSystem();\n * canonicalizeCandidates(ds, [\"mt-4\", \"mr-4\", \"mb-4\", \"ml-4\"]);\n * // Returns: [\"m-4\"]\n *\n * canonicalizeCandidates(ds, [\"mt-[16px]\"], { rem: 16 });\n * // Returns: [\"mt-4\"]\n */\nexport function canonicalizeCandidates(\n designSystem: DesignSystem,\n candidates: string[],\n options: CanonicalizeOptions = {}\n): string[] {\n const { rem, collapse = true, logicalToPhysical = false, removeDefaults = false } = options;\n\n // Filter to only valid candidates\n const validCandidates = candidates.filter((candidate) => {\n const parsed = designSystem.parseCandidate(candidate);\n return parsed.length > 0;\n });\n\n // Convert px to rem if rem option is set\n let processed = validCandidates;\n if (rem) {\n processed = processed.map((candidate) => convertPxToRem(candidate, rem));\n }\n\n // Canonicalize using the standard function\n return canonicalizeClasses(processed, {\n collapse,\n logicalToPhysical,\n removeDefaults,\n });\n}\n\n/**\n * Convert pixel values to rem-based theme values.\n *\n * @example\n * convertPxToRem(\"mt-[16px]\", 16) // \"mt-4\"\n * convertPxToRem(\"p-[32px]\", 16) // \"p-8\"\n */\nfunction convertPxToRem(candidate: string, rem: number): string {\n // Match arbitrary pixel values: -[NNpx]\n const pxMatch = candidate.match(PX_VALUE_PATTERN);\n if (!pxMatch) return candidate;\n\n const [, prefix, pxValue] = pxMatch;\n const px = parseFloat(pxValue!);\n\n // Convert to spacing scale (1 unit = 0.25rem = 4px at 16px base)\n const remValue = px / rem;\n const spacingUnit = remValue / 0.25;\n\n const standardValue = STANDARD_SPACING_VALUES[spacingUnit];\n if (standardValue !== undefined) {\n return `${prefix}-${standardValue}`;\n }\n\n // Return original if no standard value matches\n return candidate;\n}\n","/**\n * Intellisense Module\n *\n * Provides IDE integration APIs for autocomplete and class suggestions.\n */\n\nimport type { DesignSystem } from \"../compile\";\nimport type { Theme } from \"../theme\";\n\n// Re-export canonicalization functions for IntelliSense\nexport {\n canonicalizeCandidates,\n canonicalizeClasses,\n classListsEquivalent,\n expandCanonical,\n suggestCanonical,\n normalizeClassString,\n type CanonicalizeOptions,\n} from \"../compile/canonicalize\";\n\n// ============================================\n// Types\n// ============================================\n\n/** Information about a utility class */\nexport interface ClassInfo {\n /** The full class name */\n name: string;\n /** Class category (e.g., \"spacing\", \"color\", \"layout\") */\n category?: string;\n /** Whether this is a static or functional utility */\n kind: \"static\" | \"functional\";\n /** Available variants that can be applied */\n variants?: string[];\n /** Whether the utility supports negative values */\n supportsNegative?: boolean;\n}\n\n/** Information about a variant */\nexport interface VariantInfo {\n /** The variant name */\n name: string;\n /** Description of what the variant does */\n description?: string;\n /** Whether this is a media query variant */\n isMedia?: boolean;\n /** Whether this is a pseudo-class variant */\n isPseudo?: boolean;\n /** Whether this variant can compound (group-, peer-) */\n canCompound?: boolean;\n /** The selector this variant applies */\n selector?: string;\n}\n\n/** Options for getting the class list */\nexport interface GetClassListOptions {\n /** Include negative utilities (e.g., -m-4) */\n includeNegative?: boolean;\n /** Filter by category */\n category?: string;\n /** Include variant-prefixed classes */\n includeVariants?: boolean;\n}\n\n/** Options for getting variants */\nexport interface GetVariantsOptions {\n /** Include compound variants (group-, peer-) */\n includeCompound?: boolean;\n}\n\n// ============================================\n// Pre-computed variant classification Sets (O(1) lookup)\n// ============================================\n\nconst PSEUDO_VARIANTS = new Set([\n \"hover\",\n \"focus\",\n \"focus-within\",\n \"focus-visible\",\n \"active\",\n \"visited\",\n \"target\",\n \"first\",\n \"last\",\n \"only\",\n \"odd\",\n \"even\",\n \"first-of-type\",\n \"last-of-type\",\n \"only-of-type\",\n \"empty\",\n \"disabled\",\n \"enabled\",\n \"checked\",\n \"indeterminate\",\n \"default\",\n \"required\",\n \"valid\",\n \"invalid\",\n \"in-range\",\n \"out-of-range\",\n \"placeholder-shown\",\n \"autofill\",\n \"read-only\",\n \"open\",\n]);\n\nconst MEDIA_VARIANTS = new Set([\"sm\", \"md\", \"lg\", \"xl\", \"2xl\", \"dark\", \"motion-safe\", \"motion-reduce\", \"print\"]);\n\nconst COMPOUND_ROOTS = [\"group\", \"peer\", \"has\", \"not\", \"in\"] as const;\nconst COMPOUND_ROOTS_SET: Set<string> = new Set(COMPOUND_ROOTS);\n\n// Pre-computed selector map (avoids creating object per call)\nconst SELECTOR_MAP: Record<string, string> = {\n hover: \"&:hover\",\n focus: \"&:focus\",\n \"focus-within\": \"&:focus-within\",\n \"focus-visible\": \"&:focus-visible\",\n active: \"&:active\",\n visited: \"&:visited\",\n target: \"&:target\",\n first: \"&:first-child\",\n last: \"&:last-child\",\n only: \"&:only-child\",\n odd: \"&:nth-child(odd)\",\n even: \"&:nth-child(even)\",\n \"first-of-type\": \"&:first-of-type\",\n \"last-of-type\": \"&:last-of-type\",\n empty: \"&:empty\",\n disabled: \"&:disabled\",\n enabled: \"&:enabled\",\n checked: \"&:checked\",\n required: \"&:required\",\n valid: \"&:valid\",\n invalid: \"&:invalid\",\n \"placeholder-shown\": \"&:placeholder-shown\",\n autofill: \"&:autofill\",\n \"read-only\": \"&:read-only\",\n open: \"&[open]\",\n dark: \"@media (prefers-color-scheme: dark)\",\n \"motion-safe\": \"@media (prefers-reduced-motion: no-preference)\",\n \"motion-reduce\": \"@media (prefers-reduced-motion: reduce)\",\n print: \"@media print\",\n sm: \"@media (min-width: 640px)\",\n md: \"@media (min-width: 768px)\",\n lg: \"@media (min-width: 1024px)\",\n xl: \"@media (min-width: 1280px)\",\n \"2xl\": \"@media (min-width: 1536px)\",\n};\n\n// Pre-generate all pseudo variants as array for compound generation\nconst PSEUDO_VARIANTS_ARRAY = Array.from(PSEUDO_VARIANTS);\n\n// Pre-computed Sets for isNegatable (O(1) lookup instead of O(n) array.includes())\nconst SPACING_UTILITIES = new Set([\n \"m\",\n \"mt\",\n \"mr\",\n \"mb\",\n \"ml\",\n \"mx\",\n \"my\",\n \"ms\",\n \"me\",\n \"p\",\n \"pt\",\n \"pr\",\n \"pb\",\n \"pl\",\n \"px\",\n \"py\",\n \"ps\",\n \"pe\",\n \"space-x\",\n \"space-y\",\n \"gap\",\n \"gap-x\",\n \"gap-y\",\n \"inset\",\n \"top\",\n \"right\",\n \"bottom\",\n \"left\",\n \"translate-x\",\n \"translate-y\",\n \"scroll-m\",\n \"scroll-mt\",\n \"scroll-mr\",\n \"scroll-mb\",\n \"scroll-ml\",\n \"scroll-p\",\n \"scroll-pt\",\n \"scroll-pr\",\n \"scroll-pb\",\n \"scroll-pl\",\n]);\n\nconst SIZING_UTILITIES = new Set([\"w\", \"h\", \"min-w\", \"max-w\", \"min-h\", \"max-h\"]);\n\nconst ORDER_UTILITIES = new Set([\"order\", \"z\"]);\n\n// Pre-computed Set for getThemeValuesForUtility spacing check\nconst SPACING_UTILITY_NAMES = new Set([\n \"m\",\n \"mt\",\n \"mr\",\n \"mb\",\n \"ml\",\n \"mx\",\n \"my\",\n \"p\",\n \"pt\",\n \"pr\",\n \"pb\",\n \"pl\",\n \"px\",\n \"py\",\n]);\n\n// ============================================\n// Caching Infrastructure (Performance Optimization)\n// ============================================\n\n// Cache getVariants results per DesignSystem (WeakMap allows GC of unused DesignSystems)\nconst variantsCache = new WeakMap<DesignSystem, Map<string, VariantInfo[]>>();\n\nfunction getCachedVariants(designSystem: DesignSystem, cacheKey: string): VariantInfo[] | undefined {\n const dsCache = variantsCache.get(designSystem);\n return dsCache?.get(cacheKey);\n}\n\nfunction setCachedVariants(designSystem: DesignSystem, cacheKey: string, result: VariantInfo[]): void {\n let dsCache = variantsCache.get(designSystem);\n if (!dsCache) {\n dsCache = new Map();\n variantsCache.set(designSystem, dsCache);\n }\n dsCache.set(cacheKey, result);\n}\n\n// ============================================\n// Class List Functions\n// ============================================\n\n/**\n * Get all available utility classes from the design system.\n *\n * @example\n * const classes = getClassList(designSystem);\n * // Returns: [{ name: \"flex\", kind: \"static\" }, { name: \"bg-red-500\", kind: \"functional\" }, ...]\n */\nexport function getClassList(designSystem: DesignSystem, options: GetClassListOptions = {}): ClassInfo[] {\n const { utilities, theme } = designSystem;\n const result: ClassInfo[] = [];\n const seen = new Set<string>();\n\n const includeNegative = options.includeNegative ?? true;\n\n for (const name of utilities.names()) {\n const defs = utilities.get(name);\n\n for (const def of defs) {\n if (def.kind === \"static\") {\n // Static utility (e.g., flex, hidden, block)\n if (!seen.has(name)) {\n seen.add(name);\n result.push({\n name,\n kind: \"static\",\n });\n }\n } else if (def.kind === \"functional\") {\n // Functional utility - enumerate completions\n const completions = utilities.getCompletions(name);\n\n if (completions.length > 0) {\n // Has defined completions\n for (const group of completions) {\n for (const value of group.values) {\n const className = `${name}-${value}`;\n if (!seen.has(className)) {\n seen.add(className);\n result.push({\n name: className,\n kind: \"functional\",\n category: group.name,\n });\n }\n\n // Add negative version if applicable, even if the positive class was already seen.\n if (includeNegative && isNegatable(name, group.name)) {\n const negativeClassName = `-${name}-${value}`;\n if (!seen.has(negativeClassName)) {\n seen.add(negativeClassName);\n result.push({\n name: negativeClassName,\n kind: \"functional\",\n category: group.name,\n supportsNegative: true,\n });\n }\n }\n }\n }\n } else {\n // No completions - add theme-based values\n const themeValues = getThemeValuesForUtility(name, theme);\n for (const value of themeValues) {\n const className = `${name}-${value}`;\n if (!seen.has(className)) {\n seen.add(className);\n result.push({\n name: className,\n kind: \"functional\",\n });\n }\n }\n }\n }\n }\n }\n\n // Sort classes alphabetically\n result.sort((a, b) => a.name.localeCompare(b.name));\n\n return result;\n}\n\n/**\n * Get all available variants from the design system.\n * Results are cached per DesignSystem for performance.\n *\n * @example\n * const variants = getVariants(designSystem);\n * // Returns: [{ name: \"hover\", isPseudo: true }, { name: \"md\", isMedia: true }, ...]\n */\nexport function getVariants(designSystem: DesignSystem, options: GetVariantsOptions = {}): VariantInfo[] {\n const includeCompound = options.includeCompound ?? true;\n const cacheKey = `variants:${includeCompound}`;\n\n // Check cache first (major performance optimization)\n const cached = getCachedVariants(designSystem, cacheKey);\n if (cached) return cached;\n\n const { variants } = designSystem;\n\n // Use Map for O(1) deduplication instead of array.some()\n const resultMap = new Map<string, VariantInfo>();\n\n for (const name of variants.names()) {\n // O(1) Set lookups instead of O(n) array.includes()\n const isPseudo = PSEUDO_VARIANTS.has(name);\n const isMedia = MEDIA_VARIANTS.has(name);\n const canCompound = COMPOUND_ROOTS_SET.has(name);\n\n resultMap.set(name, {\n name,\n isPseudo,\n isMedia,\n canCompound,\n selector: SELECTOR_MAP[name],\n });\n }\n\n // Add compound variants if requested\n if (includeCompound) {\n for (const root of COMPOUND_ROOTS) {\n for (const pseudo of PSEUDO_VARIANTS_ARRAY) {\n const compoundName = `${root}-${pseudo}`;\n // O(1) Map.has() instead of O(n) array.some()\n if (!resultMap.has(compoundName)) {\n resultMap.set(compoundName, {\n name: compoundName,\n description: `Apply when ${root} element is ${pseudo}`,\n canCompound: true,\n });\n }\n }\n }\n }\n\n // Convert to array and sort\n const result = Array.from(resultMap.values());\n result.sort((a, b) => {\n // Media variants first, then pseudo, then others\n if (a.isMedia && !b.isMedia) return -1;\n if (!a.isMedia && b.isMedia) return 1;\n if (a.isPseudo && !b.isPseudo) return -1;\n if (!a.isPseudo && b.isPseudo) return 1;\n return a.name.localeCompare(b.name);\n });\n\n // Cache the result\n setCachedVariants(designSystem, cacheKey, result);\n\n return result;\n}\n\n/**\n * Get autocomplete suggestions for a partial class name.\n *\n * @example\n * const suggestions = getSuggestions(designSystem, \"bg-r\");\n * // Returns: [\"bg-red-50\", \"bg-red-100\", \"bg-red-200\", ...]\n */\nexport function getSuggestions(designSystem: DesignSystem, partial: string, limit = 50): string[] {\n const classes = getClassList(designSystem);\n const lowerPartial = partial.toLowerCase();\n\n const matches = classes\n .filter((c) => c.name.toLowerCase().startsWith(lowerPartial))\n .map((c) => c.name)\n .slice(0, limit);\n\n return matches;\n}\n\n/**\n * Check if a class name is valid in the design system.\n */\nexport function isValidClass(designSystem: DesignSystem, className: string): boolean {\n const { utilities } = designSystem;\n\n // Check for variant prefix\n const colonIndex = className.lastIndexOf(\":\");\n const baseClass = colonIndex >= 0 ? className.slice(colonIndex + 1) : className;\n\n // Handle negative utilities\n const isNegative = baseClass.startsWith(\"-\");\n const positiveClass = isNegative ? baseClass.slice(1) : baseClass;\n\n // Check if it's a static utility\n if (utilities.has(positiveClass, \"static\")) {\n return true;\n }\n\n // Check if it's a functional utility\n const dashIndex = positiveClass.indexOf(\"-\");\n if (dashIndex >= 0) {\n const root = positiveClass.slice(0, dashIndex);\n if (utilities.has(root, \"functional\")) {\n return true;\n }\n }\n\n // Check arbitrary value syntax [property:value]\n if (positiveClass.startsWith(\"[\") && positiveClass.endsWith(\"]\")) {\n return true;\n }\n\n return false;\n}\n\n// ============================================\n// Helper Functions\n// ============================================\n\n/**\n * Check if a utility supports negative values.\n */\nfunction isNegatable(utilityName: string, categoryName?: string): boolean {\n // O(1) Set lookups instead of O(n) array.includes()\n if (SPACING_UTILITIES.has(utilityName)) return true;\n if (SIZING_UTILITIES.has(utilityName)) return true;\n if (ORDER_UTILITIES.has(utilityName)) return true;\n\n // Check category\n if (categoryName === \"spacing\" || categoryName === \"sizing\") {\n return true;\n }\n\n return false;\n}\n\n/**\n * Get theme values applicable to a utility.\n */\nfunction getThemeValuesForUtility(utilityName: string, theme: Theme): string[] {\n // Map utility names to theme namespaces\n const namespaceMap: Record<string, string> = {\n bg: \"--color\",\n text: \"--color\",\n border: \"--color\",\n ring: \"--color\",\n fill: \"--color\",\n stroke: \"--color\",\n shadow: \"--shadow\",\n rounded: \"--radius\",\n font: \"--font\",\n \"text-size\": \"--font-size\",\n tracking: \"--letter-spacing\",\n leading: \"--line-height\",\n blur: \"--blur\",\n brightness: \"--brightness\",\n contrast: \"--contrast\",\n grayscale: \"--grayscale\",\n \"hue-rotate\": \"--hue-rotate\",\n invert: \"--invert\",\n saturate: \"--saturate\",\n sepia: \"--sepia\",\n \"backdrop-blur\": \"--backdrop-blur\",\n };\n\n const namespace = namespaceMap[utilityName];\n if (!namespace) {\n // Return common numeric values for spacing utilities (O(1) Set lookup)\n if (SPACING_UTILITY_NAMES.has(utilityName)) {\n return [\n \"0\",\n \"0.5\",\n \"1\",\n \"1.5\",\n \"2\",\n \"2.5\",\n \"3\",\n \"3.5\",\n \"4\",\n \"5\",\n \"6\",\n \"7\",\n \"8\",\n \"9\",\n \"10\",\n \"11\",\n \"12\",\n \"14\",\n \"16\",\n \"20\",\n \"24\",\n \"28\",\n \"32\",\n \"36\",\n \"40\",\n \"44\",\n \"48\",\n \"52\",\n \"56\",\n \"60\",\n \"64\",\n \"72\",\n \"80\",\n \"96\",\n \"auto\",\n \"px\",\n ];\n }\n return [];\n }\n\n // Get values from theme namespace\n const values = theme.namespace(namespace as `--${string}`);\n return Object.keys(values).map((key) => key.replace(`${namespace}-`, \"\"));\n}\n","/**\n * CSS Parser\n *\n * A character-by-character CSS parser that produces an AST.\n * Handles standard CSS plus special directives (@theme, @apply, @utility).\n *\n * Performance optimizations:\n * - Native Rust parser (3-10x faster) when available\n * - Falls back to TypeScript implementation otherwise\n * - Index-based buffer tracking (avoids intermediate string allocations)\n * - Range-based text collection (slice once instead of char-by-char)\n * - Pre-sized arrays based on input length heuristics\n * - Inline whitespace checks (avoids function call overhead)\n * - Inline trim via trimSlice (avoids extra string creation)\n *\n * Browser Compatibility:\n * - Node.js imports (path, module, url) are loaded lazily inside tryLoadNativeParser()\n * - This ensures the browser bundle doesn't include Node.js built-ins\n * - Native parser loading is skipped entirely in browser environments\n */\n\nimport {\n atRule,\n comment,\n decl,\n styleRule,\n type AstNode,\n type AtRule,\n type Declaration,\n type StyleRule,\n type Comment,\n type Source,\n type SourceLocation,\n} from \"../ast\";\nimport { intern } from \"../utils/intern\";\n\n// Node.js modules - loaded lazily to avoid bundling in browsers\n// These are only used by tryLoadNativeParser() which is a no-op in browsers\nlet _path: typeof import(\"node:path\") | null = null;\nlet _createRequire: typeof import(\"node:module\").createRequire | null = null;\nlet _fileURLToPath: typeof import(\"node:url\").fileURLToPath | null = null;\nlet _nodeModulesLoaded = false;\nlet testGlobalRequireOverride: unknown | undefined;\nlet testLocalRequireOverride: unknown | undefined;\nlet testImportMetaUrlOverride: string | null | undefined;\n\nfunction getGlobalRequire(): NodeRequire | null {\n const globalCandidate =\n testGlobalRequireOverride !== undefined\n ? testGlobalRequireOverride\n : (globalThis as { require?: unknown }).require;\n if (typeof globalCandidate === \"function\") {\n return globalCandidate as NodeRequire;\n }\n let localCandidate = testLocalRequireOverride;\n try {\n if (localCandidate === undefined) {\n localCandidate = require;\n }\n } catch {\n // Ignore\n }\n if (typeof localCandidate === \"function\") {\n return localCandidate as NodeRequire;\n }\n return null;\n}\n\n/**\n * Lazily load Node.js modules for native parser loading.\n * Returns false in browser environments where these modules don't exist.\n */\nfunction loadNodeModules(): boolean {\n if (_nodeModulesLoaded) {\n return _path !== null;\n }\n _nodeModulesLoaded = true;\n\n // Skip in browser environments\n if (typeof window !== \"undefined\" || typeof process === \"undefined\" || !process.versions?.node) {\n return false;\n }\n\n const req = getGlobalRequire();\n // require is always available in the Node test runtime.\n /* c8 ignore next */\n if (!req) {\n return false;\n }\n\n try {\n // Dynamic imports to avoid bundler issues\n _path = req(\"node:path\");\n const nodeModule = req(\"node:module\") as { createRequire: typeof import(\"node:module\").createRequire };\n _createRequire = nodeModule.createRequire;\n const nodeUrl = req(\"node:url\") as { fileURLToPath: typeof import(\"node:url\").fileURLToPath };\n _fileURLToPath = nodeUrl.fileURLToPath;\n return true;\n } catch {\n return false;\n }\n}\n\n// ============================================\n// Native Parser Integration\n// ============================================\n\n// Native parser uses numeric kinds to avoid string allocation overhead\n// 0 = rule, 1 = at-rule, 2 = declaration, 3 = comment\nconst CSS_NODE_RULE = 0;\nconst CSS_NODE_AT_RULE = 1;\nconst CSS_NODE_DECLARATION = 2;\nconst CSS_NODE_COMMENT = 3;\n\ninterface NativeCssNode {\n kind: number | string; // 0=rule, 1=at-rule, 2=declaration, 3=comment (or string equivalents)\n selector?: string | null;\n name?: string | null;\n params?: string | null;\n property?: string | null;\n value?: string | null;\n important?: boolean | null;\n nodes?: NativeCssNode[] | null;\n}\n\ninterface NativeCssParseResult {\n ast: NativeCssNode[];\n licenseComments: string[];\n}\n\ninterface NativeOxide {\n parseCss(input: string): NativeCssParseResult;\n isCssParserAvailable(): boolean;\n}\n\nlet nativeParseCss: ((input: string) => NativeCssParseResult) | null = null;\nlet nativeParserChecked = false;\nlet nodeRequire: NodeRequire | null | undefined = undefined;\n\n/**\n * Get a require function compatible with both CommonJS and ESM.\n * Returns null in browser environments.\n */\nfunction getNodeRequire(): NodeRequire | null {\n // Cached require is not observable in tests.\n /* c8 ignore next */\n if (nodeRequire !== undefined) {\n return nodeRequire;\n }\n\n // Need Node.js modules for createRequire\n if (!loadNodeModules()) {\n nodeRequire = null;\n return null;\n }\n\n const globalRequire = getGlobalRequire();\n // globalRequire is always available in the Node test runtime.\n /* c8 ignore next */\n if (globalRequire) {\n nodeRequire = globalRequire;\n return nodeRequire;\n }\n try {\n // createRequire fallback is not hit in CJS tests.\n /* c8 ignore next */\n if (_createRequire && typeof import.meta?.url === \"string\") {\n nodeRequire = _createRequire(import.meta.url);\n return nodeRequire;\n }\n } catch {\n // Ignore\n }\n nodeRequire = null;\n return null;\n}\n\nfunction getModuleDir(): string | null {\n if (!_path || !_fileURLToPath) {\n return null;\n }\n try {\n const moduleUrl =\n testImportMetaUrlOverride !== undefined ? testImportMetaUrlOverride : (import.meta as { url?: string }).url;\n if (typeof moduleUrl === \"string\") {\n return _path.dirname(_fileURLToPath(moduleUrl));\n }\n } catch {\n // Ignore\n }\n return null;\n}\n\n// Environment variables - safely accessed with fallbacks for browser environments\nconst DEBUG_NATIVE_PARSER = typeof process !== \"undefined\" && process.env?.RI_DEBUG_NATIVE_CSS_PARSER === \"1\";\nconst KEEP_NATIVE_COMMENTS = typeof process !== \"undefined\" && process.env?.RI_CSS_PARSER_KEEP_COMMENTS === \"1\";\nconst DISABLE_NATIVE_PARSER = typeof process !== \"undefined\" && process.env?.RI_DISABLE_NATIVE_CSS_PARSER === \"1\";\n\n/**\n * Load the native Rust CSS parser with intelligent path resolution.\n *\n * Resolution strategy (in order of preference):\n * 1. Environment override (RI_OXIDE_PATH) - for custom deployments\n * 2. Package resolution (@rainbowindex/oxide) - standard npm install\n * 3. Direct .node file paths - monorepo and bundled scenarios\n *\n * The native parser provides 3-10x performance improvement over TypeScript.\n * Returns null in browser environments (no native module available).\n */\nfunction tryLoadNativeParser(): ((input: string) => NativeCssParseResult) | null {\n if (nativeParserChecked) {\n return nativeParseCss;\n }\n nativeParserChecked = true;\n\n // Get require function - returns null in browsers\n const req = getNodeRequire();\n if (!req) {\n if (DEBUG_NATIVE_PARSER) {\n console.log(\"[css-parser] require unavailable; skipping native load\");\n }\n return null;\n }\n\n // Need path module for path resolution\n if (!_path) {\n if (DEBUG_NATIVE_PARSER) {\n console.log(\"[css-parser] path module unavailable; skipping native load\");\n }\n return null;\n }\n\n // Build platform-specific filename (e.g., rainbowindex-oxide.darwin-arm64.node)\n const platformMap: Record<string, string> = {\n \"darwin-arm64\": \"darwin-arm64\",\n \"darwin-x64\": \"darwin-x64\",\n \"linux-x64\": \"linux-x64-gnu\",\n \"linux-arm64\": \"linux-arm64-gnu\",\n \"win32-x64\": \"win32-x64-msvc\",\n };\n const platformSuffix = platformMap[`${process.platform}-${process.arch}`];\n if (!platformSuffix) {\n if (DEBUG_NATIVE_PARSER) {\n console.log(`[css-parser] unsupported platform: ${process.platform}-${process.arch}`);\n }\n return null;\n }\n\n const nativeFileName = `rainbowindex-oxide.${platformSuffix}.node`;\n\n // Strategy 1: Environment override for custom deployments\n const envPath = process.env.RI_OXIDE_PATH;\n if (envPath) {\n const resolved = _path.resolve(envPath.endsWith(\".node\") ? envPath : _path.join(envPath, nativeFileName));\n const result = tryLoadFromPath(resolved, req);\n if (result) return result;\n }\n\n // Strategy 2: Standard package resolution (handles npm, pnpm, yarn workspaces)\n try {\n const oxide = req(\"@rainbowindex/oxide\") as NativeOxide;\n if (oxide.parseCss && oxide.isCssParserAvailable?.()) {\n nativeParseCss = oxide.parseCss.bind(oxide);\n if (DEBUG_NATIVE_PARSER) {\n console.log(\"[css-parser] native loaded via @rainbowindex/oxide\");\n }\n return nativeParseCss;\n }\n } catch {\n // Package not installed or not functional - try direct paths\n }\n\n // Strategy 3: Direct .node file resolution for monorepo/bundled scenarios\n const directPaths = [\n // Monorepo development layout\n _path.resolve(\"packages\", \"@rainbowindex\", \"oxide\", nativeFileName),\n // Standard node_modules\n _path.resolve(\"node_modules\", \"@rainbowindex\", \"oxide\", nativeFileName),\n ];\n\n // Add paths relative to this module's location (for bundled distributions)\n const moduleDir = getModuleDir();\n if (moduleDir) {\n directPaths.push(\n _path.join(moduleDir, \"..\", \"..\", \"@rainbowindex\", \"oxide\", nativeFileName),\n _path.join(moduleDir, nativeFileName)\n );\n }\n\n for (const modulePath of directPaths) {\n const result = tryLoadFromPath(modulePath, req);\n if (result) return result;\n }\n\n if (DEBUG_NATIVE_PARSER) {\n console.log(\"[css-parser] native not available\");\n }\n return null;\n}\n\n/**\n * @internal\n * Test hook to inject a native CSS parser implementation.\n */\nexport function __setNativeCssParser(parser: ((input: string) => NativeCssParseResult) | null): void {\n nativeParseCss = parser;\n nativeParserChecked = true;\n}\n\n/**\n * @internal\n * Test hook to override require resolution paths.\n */\nexport function __setTestRequireOverrides(options: {\n globalRequire?: unknown;\n localRequire?: unknown;\n importMetaUrl?: string | null;\n}): void {\n if (\"globalRequire\" in options) testGlobalRequireOverride = options.globalRequire;\n if (\"localRequire\" in options) testLocalRequireOverride = options.localRequire;\n if (\"importMetaUrl\" in options) testImportMetaUrlOverride = options.importMetaUrl;\n}\n\n/**\n * @internal\n * Reset test override state.\n */\nexport function __resetTestOverrides(): void {\n testGlobalRequireOverride = undefined;\n testLocalRequireOverride = undefined;\n testImportMetaUrlOverride = undefined;\n}\n\n/**\n * @internal\n * Test hook to control node module loading state.\n */\nexport function __setNodeModuleStateForTest(state: {\n loaded?: boolean;\n path?: typeof import(\"node:path\") | null;\n createRequire?: typeof import(\"node:module\").createRequire | null;\n fileURLToPath?: typeof import(\"node:url\").fileURLToPath | null;\n}): void {\n if (state.loaded !== undefined) _nodeModulesLoaded = state.loaded;\n if (\"path\" in state) _path = state.path ?? null;\n if (\"createRequire\" in state) _createRequire = state.createRequire ?? null;\n if (\"fileURLToPath\" in state) _fileURLToPath = state.fileURLToPath ?? null;\n}\n\n/**\n * @internal\n * Reset node module loading state for tests.\n */\nexport function __resetNodeModuleStateForTest(): void {\n _nodeModulesLoaded = false;\n _path = null;\n _createRequire = null;\n _fileURLToPath = null;\n}\n\n/**\n * @internal\n * Test hook to set cached nodeRequire.\n */\nexport function __setNodeRequireForTest(value: NodeRequire | null | undefined): void {\n nodeRequire = value;\n}\n\n/**\n * @internal\n * Test hook to expose module directory resolution.\n */\nexport function __getModuleDirForTest(): string | null {\n return getModuleDir();\n}\n\n/**\n * @internal\n * Reset native CSS parser state for tests.\n */\nexport function __resetNativeCssParser(): void {\n nativeParseCss = null;\n nativeParserChecked = false;\n nodeRequire = undefined;\n}\n\n/**\n * Attempt to load native parser from a specific path.\n */\nfunction tryLoadFromPath(modulePath: string, req: NodeRequire): ((input: string) => NativeCssParseResult) | null {\n try {\n const nativeModule = req(modulePath) as {\n parseCss: (input: string) => NativeCssParseResult;\n };\n if (typeof nativeModule.parseCss === \"function\") {\n nativeParseCss = nativeModule.parseCss.bind(nativeModule);\n if (DEBUG_NATIVE_PARSER) {\n console.log(`[css-parser] native loaded: ${modulePath}`);\n }\n return nativeParseCss;\n }\n } catch {\n // Path not available\n }\n return null;\n}\n\n/**\n * Check if native node kind matches (handles both numeric and string kinds).\n * The native parser can return either numeric kinds (0, 1, 2, 3) or string kinds (\"rule\", \"at-rule\", etc.)\n * depending on whether it's loaded via NAPI directly or through the oxide dist wrapper.\n */\nfunction isNodeKind(kind: number | string, numKind: number, strKind: string): boolean {\n return kind === numKind || kind === strKind;\n}\n\n/**\n * Convert native AST nodes to TypeScript AST format.\n */\nfunction convertNativeAst(nodes: NativeCssNode[]): AstNode[] {\n const out = new Array<AstNode>(nodes.length);\n let outPos = 0;\n for (let i = 0; i < nodes.length; i++) {\n const node = nodes[i]!;\n if (isNodeKind(node.kind, CSS_NODE_RULE, \"rule\")) {\n const childNodes = node.nodes;\n const converted = childNodes && childNodes.length > 0 ? convertNativeAst(childNodes) : [];\n if (converted.length === 0) {\n continue;\n }\n out[outPos++] = {\n kind: \"rule\",\n selector: node.selector ?? \"\",\n nodes: converted,\n };\n continue;\n }\n if (isNodeKind(node.kind, CSS_NODE_AT_RULE, \"at-rule\")) {\n const childNodes = node.nodes;\n const converted = childNodes && childNodes.length > 0 ? convertNativeAst(childNodes) : [];\n const name = node.name ?? \"\";\n out[outPos++] = {\n kind: \"at-rule\",\n name: name.charCodeAt(0) === 64 ? name : `@${name}`,\n params: node.params ?? \"\",\n nodes: converted,\n };\n continue;\n }\n if (isNodeKind(node.kind, CSS_NODE_DECLARATION, \"declaration\")) {\n const property = node.property ?? \"\";\n out[outPos++] = {\n kind: \"declaration\",\n property: intern(property),\n value: node.value ?? undefined,\n important: node.important ?? false,\n };\n continue;\n }\n if (isNodeKind(node.kind, CSS_NODE_COMMENT, \"comment\")) {\n if (!KEEP_NATIVE_COMMENTS) {\n continue;\n }\n out[outPos++] = { kind: \"comment\", value: node.value ?? \"\" };\n continue;\n }\n // Fallback - should not happen\n throw new Error(`Unknown native node kind: ${node.kind}`);\n }\n if (outPos === out.length) return out;\n return out.slice(0, outPos);\n}\n\n/**\n * @internal\n * Exposed for benchmarks and internal tooling only.\n */\nexport function __convertNativeAst(nodes: unknown): AstNode[] {\n return convertNativeAst(nodes as NativeCssNode[]);\n}\n\n/**\n * Check if native CSS parser is available.\n */\nexport function isNativeCssParserAvailable(): boolean {\n return tryLoadNativeParser() !== null;\n}\nimport {\n BACKSLASH,\n SLASH,\n ASTERISK,\n DOUBLE_QUOTE,\n SINGLE_QUOTE,\n COLON,\n SEMICOLON,\n LINE_BREAK,\n CARRIAGE_RETURN,\n SPACE,\n TAB,\n OPEN_CURLY,\n CLOSE_CURLY,\n OPEN_PAREN,\n CLOSE_PAREN,\n AT_SIGN,\n EXCLAMATION_MARK,\n} from \"./char-codes\";\n\nexport interface CSSParseOptions {\n /** Source file path for error messages */\n from?: string;\n /**\n * Force tracking of source locations for source map generation.\n * When true, always uses TypeScript parser (which tracks locations)\n * instead of the faster native Rust parser (which doesn't track locations).\n */\n trackSourceLocations?: boolean;\n}\n\nexport interface ParseResult {\n /** Parsed AST nodes */\n ast: AstNode[];\n /** License comments found in the CSS */\n licenseComments: Comment[];\n /** Source object for source map generation */\n source: Source;\n}\n\n/**\n * CSS syntax error with location information.\n */\nexport class CssSyntaxError extends Error {\n line: number;\n column: number;\n file?: string;\n\n constructor(message: string, line: number, column: number, file?: string) {\n const location = file ? `${file}:${line}:${column}` : `${line}:${column}`;\n super(`${location}: ${message}`);\n this.name = \"CssSyntaxError\";\n this.line = line;\n this.column = column;\n this.file = file;\n }\n}\n\n/**\n * Get line number (1-indexed) for a given offset in the input.\n *\n * Performance: O(offset) - scans from start to offset counting newlines.\n * This is acceptable because:\n * 1. Only called during error reporting (not in the hot path)\n * 2. Errors are rare in valid CSS\n * 3. Most CSS files are small enough that linear scan is fast\n *\n * For very large files (10MB+) with many errors, consider pre-computing\n * a line table. But in practice, CSS files rarely exceed 1MB.\n */\nfunction getLineNumber(input: string, offset: number): number {\n let line = 1;\n for (let i = 0; i < offset && i < input.length; i++) {\n if (input.charCodeAt(i) === LINE_BREAK) line++;\n }\n return line;\n}\n\n/**\n * Get column number (1-indexed) for a given offset in the input.\n */\nfunction getColumnNumber(input: string, offset: number): number {\n let col = 1;\n for (let i = offset - 1; i >= 0; i--) {\n if (input.charCodeAt(i) === LINE_BREAK) break;\n col++;\n }\n return col;\n}\n\n/**\n * Parse CSS string into an AST.\n *\n * Uses native Rust parser when available (3-10x faster),\n * falling back to TypeScript implementation otherwise.\n *\n * Key optimizations:\n * - Native Rust parser with SIMD optimizations\n * - Index-based buffer tracking (single slice at flush time)\n * - Escape sequences tracked separately (rare case)\n * - Inline trim via trimSlice (avoids extra string creation)\n * - Pre-sizes arrays based on input length\n */\nexport function parse(input: string, options: CSSParseOptions = {}): ParseResult {\n // Create source object for source map tracking\n const source: Source = {\n file: options.from ?? null,\n code: input,\n };\n\n // When trackSourceLocations is true, skip native parser (it doesn't track locations)\n // This is needed for proper source map generation\n if (options.trackSourceLocations) {\n return parseTypeScript(input, options, source);\n }\n\n if (DISABLE_NATIVE_PARSER) {\n return parseTypeScript(input, options, source);\n }\n\n // Check if input contains preflight markers that need position-aware parsing\n // The TypeScript parser preserves these in the AST for filtering\n const hasPreflight = input.includes(\"@preflight-module\");\n\n // Try native Rust parser first (3-10x faster) - but not for preflight CSS\n // which requires comments to be preserved in their AST positions\n if (!hasPreflight) {\n const nativeParser = nativeParseCss ?? (nativeParserChecked ? null : tryLoadNativeParser());\n if (nativeParser) {\n try {\n const result = nativeParser(input);\n return {\n ast: convertNativeAst(result.ast),\n licenseComments: result.licenseComments.map((c) => comment(c)),\n source,\n };\n } catch (error) {\n // Fall through to TypeScript parser on error\n if (DEBUG_NATIVE_PARSER) {\n console.warn(\n \"[css-parser] native parser failed, falling back to TypeScript:\",\n error instanceof Error ? error.message : error\n );\n }\n }\n }\n }\n\n // TypeScript fallback (also used for preflight CSS to preserve comment positions)\n return parseTypeScript(input, options, source);\n}\n\n/**\n * TypeScript CSS parser implementation (fallback when native unavailable).\n *\n * Uses simple string concatenation (buffer += ...) which modern JS engines\n * optimize extremely well. This is faster than index-based tracking.\n */\nfunction parseTypeScript(input: string, options: CSSParseOptions, source: Source): ParseResult {\n // Handle BOM\n if (input.charCodeAt(0) === 0xfeff) {\n input = \" \" + input.slice(1);\n }\n\n const ast: AstNode[] = [];\n const licenseComments: Comment[] = [];\n const stack: (StyleRule | AtRule | null)[] = [];\n\n let parent: StyleRule | AtRule | null = null;\n let buffer = \"\";\n let bufferStart = 0;\n // Track bracket nesting for parentheses inside selectors/values\n let closingBracketStack = \"\";\n\n const len = input.length;\n\n function createSourceLocation(start: number, end: number): SourceLocation {\n return [source, start, end];\n }\n\n for (let i = 0; i < len; i++) {\n const char = input.charCodeAt(i);\n\n // Skip CR in CRLF\n if (char === CARRIAGE_RETURN && input.charCodeAt(i + 1) === LINE_BREAK) {\n continue;\n }\n\n // Escape sequence - collect both chars at once\n if (char === BACKSLASH) {\n if (i + 1 >= len) {\n throw new CssSyntaxError(\n \"Invalid escape sequence: trailing backslash at EOF\",\n getLineNumber(input, i),\n getColumnNumber(input, i),\n options.from\n );\n }\n if (buffer === \"\") bufferStart = i;\n buffer += input.slice(i, i + 2);\n i++;\n continue;\n }\n\n // Comment\n if (char === SLASH && input.charCodeAt(i + 1) === ASTERISK) {\n const start = i;\n let closed = false;\n\n for (let j = i + 2; j < len; j++) {\n const c = input.charCodeAt(j);\n if (c === BACKSLASH) {\n j++;\n continue;\n }\n if (c === ASTERISK && input.charCodeAt(j + 1) === SLASH) {\n i = j + 1;\n closed = true;\n break;\n }\n }\n\n if (!closed) {\n throw new CssSyntaxError(\n \"Unclosed comment\",\n getLineNumber(input, start),\n getColumnNumber(input, start),\n options.from\n );\n }\n\n // Preserve license comments (/*! ... */)\n if (input.charCodeAt(start + 2) === EXCLAMATION_MARK) {\n const commentText = input.slice(start + 3, i - 1);\n const node = comment(commentText);\n node.src = createSourceLocation(start, i + 1);\n\n // Inject preflight-module markers directly into AST so they survive parse/print cycles\n if (commentText.includes(\"@preflight-module\")) {\n if (parent) {\n parent.nodes.push(node);\n } else {\n ast.push(node);\n }\n }\n\n licenseComments.push(node);\n }\n continue;\n }\n\n // String - collect entire string at once\n if (char === SINGLE_QUOTE || char === DOUBLE_QUOTE) {\n const [end, unclosed] = parseString(input, i, char);\n if (unclosed) {\n throw new CssSyntaxError(\n \"Unclosed string\",\n getLineNumber(input, i),\n getColumnNumber(input, i),\n options.from\n );\n }\n if (buffer === \"\") bufferStart = i;\n buffer += input.slice(i, end + 1);\n i = end;\n continue;\n }\n\n // Skip consecutive whitespace\n if (\n (char === SPACE || char === LINE_BREAK || char === TAB) &&\n (input.charCodeAt(i + 1) === SPACE ||\n input.charCodeAt(i + 1) === LINE_BREAK ||\n input.charCodeAt(i + 1) === TAB ||\n (input.charCodeAt(i + 1) === CARRIAGE_RETURN && input.charCodeAt(i + 2) === LINE_BREAK))\n ) {\n continue;\n }\n\n // Replace newlines with space if buffer has content\n if (char === LINE_BREAK) {\n if (buffer.length === 0) continue;\n const lastChar = buffer.charCodeAt(buffer.length - 1);\n if (lastChar !== SPACE && lastChar !== LINE_BREAK && lastChar !== TAB) {\n buffer += \" \";\n }\n continue;\n }\n\n // Custom property (--*) needs special handling for balanced brackets\n if (char === 45 /* DASH */ && input.charCodeAt(i + 1) === 45 /* DASH */ && buffer.length === 0) {\n let localBracketStack = \"\";\n const start = i;\n let colonIdx = -1;\n\n for (let j = i + 2; j < len; j++) {\n const c = input.charCodeAt(j);\n\n if (c === BACKSLASH) {\n j++;\n continue;\n }\n\n if (c === SINGLE_QUOTE || c === DOUBLE_QUOTE) {\n j = parseString(input, j, c)[0];\n continue;\n }\n\n if (c === SLASH && input.charCodeAt(j + 1) === ASTERISK) {\n for (let k = j + 2; k < len; k++) {\n if (input.charCodeAt(k) === BACKSLASH) {\n k++;\n continue;\n }\n if (input.charCodeAt(k) === ASTERISK && input.charCodeAt(k + 1) === SLASH) {\n j = k + 1;\n break;\n }\n }\n continue;\n }\n\n if (colonIdx === -1 && c === COLON) {\n colonIdx = buffer.length + j - start;\n }\n\n if (c === SEMICOLON && localBracketStack.length === 0) {\n buffer += input.slice(start, j);\n i = j;\n break;\n }\n\n if (c === OPEN_PAREN) localBracketStack += \")\";\n else if (c === 91 /* OPEN_BRACKET */) localBracketStack += \"]\";\n else if (c === OPEN_CURLY) localBracketStack += \"}\";\n\n if ((c === CLOSE_CURLY || j === len - 1) && localBracketStack.length === 0) {\n i = j - 1;\n buffer += input.slice(start, j);\n break;\n }\n\n if (c === CLOSE_PAREN || c === 93 /* CLOSE_BRACKET */ || c === CLOSE_CURLY) {\n if (localBracketStack.length > 0 && input[j] === localBracketStack[localBracketStack.length - 1]) {\n localBracketStack = localBracketStack.slice(0, -1);\n }\n }\n }\n\n // Parse the custom property declaration\n const declaration = parseDeclarationSimple(buffer, colonIdx);\n if (!declaration) {\n throw new CssSyntaxError(\n `Invalid custom property: \"${buffer.trim()}\"`,\n getLineNumber(input, start),\n getColumnNumber(input, start),\n options.from\n );\n }\n declaration.src = createSourceLocation(start, i);\n if (parent) {\n parent.nodes.push(declaration);\n } else {\n ast.push(declaration);\n }\n buffer = \"\";\n continue;\n }\n\n // End of body-less at-rule (e.g., @charset \"UTF-8\";)\n if (char === SEMICOLON && buffer.charCodeAt(0) === AT_SIGN) {\n const node = parseAtRuleSimple(buffer);\n node.src = createSourceLocation(bufferStart, i);\n if (parent) {\n parent.nodes.push(node);\n } else {\n ast.push(node);\n }\n buffer = \"\";\n continue;\n }\n\n // End of declaration\n if (char === SEMICOLON && closingBracketStack[closingBracketStack.length - 1] !== \")\") {\n const declaration = parseDeclarationSimple(buffer);\n if (!declaration) {\n if (buffer.length === 0) continue;\n throw new CssSyntaxError(\n `Invalid declaration \"${buffer.trim()}\" (missing colon)`,\n getLineNumber(input, bufferStart),\n getColumnNumber(input, bufferStart),\n options.from\n );\n }\n declaration.src = createSourceLocation(bufferStart, i);\n if (parent) {\n parent.nodes.push(declaration);\n } else {\n ast.push(declaration);\n }\n buffer = \"\";\n continue;\n }\n\n // Start of block\n if (char === OPEN_CURLY) {\n // Check for unclosed parenthesis before opening block\n if (closingBracketStack[closingBracketStack.length - 1] === \")\") {\n throw new CssSyntaxError(\n \"Unclosed parenthesis\",\n getLineNumber(input, i),\n getColumnNumber(input, i),\n options.from\n );\n }\n closingBracketStack += \"}\";\n const trimmed = buffer.trim();\n const node = trimmed.charCodeAt(0) === AT_SIGN ? parseAtRuleSimple(trimmed) : styleRule(trimmed, []);\n node.src = createSourceLocation(bufferStart, i);\n if (parent) {\n parent.nodes.push(node);\n }\n stack.push(parent);\n parent = node;\n buffer = \"\";\n continue;\n }\n\n // End of block\n if (char === CLOSE_CURLY && closingBracketStack[closingBracketStack.length - 1] !== \")\") {\n if (closingBracketStack === \"\") {\n throw new CssSyntaxError(\n \"Unexpected closing brace\",\n getLineNumber(input, i),\n getColumnNumber(input, i),\n options.from\n );\n }\n closingBracketStack = closingBracketStack.slice(0, -1);\n\n // Handle leftover buffer (declaration without semicolon)\n if (buffer.length > 0) {\n if (buffer.charCodeAt(0) === AT_SIGN) {\n const node = parseAtRuleSimple(buffer);\n node.src = createSourceLocation(bufferStart, i);\n parent!.nodes.push(node);\n } else {\n const colonIdx = buffer.indexOf(\":\");\n if (colonIdx === -1) {\n throw new CssSyntaxError(\n `Invalid declaration \"${buffer.trim()}\" (missing colon)`,\n getLineNumber(input, bufferStart),\n getColumnNumber(input, bufferStart),\n options.from\n );\n }\n const declaration = parseDeclarationSimple(buffer, colonIdx)!;\n declaration.src = createSourceLocation(bufferStart, i);\n parent!.nodes.push(declaration);\n }\n }\n\n const grandParent = stack.pop() ?? null;\n if (grandParent === null && parent) {\n ast.push(parent);\n }\n parent = grandParent;\n buffer = \"\";\n continue;\n }\n\n // Track parentheses for balanced parsing\n if (char === OPEN_PAREN) {\n closingBracketStack += \")\";\n if (buffer === \"\") bufferStart = i;\n buffer += \"(\";\n continue;\n }\n\n if (char === CLOSE_PAREN) {\n if (closingBracketStack[closingBracketStack.length - 1] !== \")\") {\n throw new CssSyntaxError(\n \"Missing opening (\",\n getLineNumber(input, i),\n getColumnNumber(input, i),\n options.from\n );\n }\n closingBracketStack = closingBracketStack.slice(0, -1);\n buffer += \")\";\n continue;\n }\n\n // Skip leading whitespace\n if (buffer.length === 0 && (char === SPACE || char === LINE_BREAK || char === TAB)) {\n continue;\n }\n\n // Regular character\n if (buffer === \"\") bufferStart = i;\n buffer += String.fromCharCode(char);\n }\n\n // Handle leftover at-rule without semicolon at EOF\n if (buffer.charCodeAt(0) === AT_SIGN) {\n const node = parseAtRuleSimple(buffer);\n node.src = createSourceLocation(bufferStart, len);\n ast.push(node);\n }\n\n // Check for unclosed blocks\n if (closingBracketStack.length > 0 && parent) {\n if (parent.kind === \"rule\") {\n throw new CssSyntaxError(\n `Missing closing } at ${parent.selector}`,\n getLineNumber(input, bufferStart),\n getColumnNumber(input, bufferStart),\n options.from\n );\n } else {\n throw new CssSyntaxError(\n `Missing closing } at @${parent.name} ${parent.params}`,\n getLineNumber(input, bufferStart),\n getColumnNumber(input, bufferStart),\n options.from\n );\n }\n }\n\n return { ast, licenseComments, source };\n}\n\n/**\n * Parse at-rule from buffer (e.g., \"@media (min-width: 640px)\")\n */\nfunction parseAtRuleSimple(buffer: string): AtRule {\n let name = buffer;\n let params = \"\";\n\n // Find first whitespace or paren to split name from params\n for (let i = 5 /* '@page'.length */; i < buffer.length; i++) {\n const c = buffer.charCodeAt(i);\n if (c === SPACE || c === TAB || c === OPEN_PAREN) {\n name = buffer.slice(0, i);\n params = buffer.slice(i);\n break;\n }\n }\n\n return atRule(name.trim(), params.trim(), []);\n}\n\n/**\n * Parse declaration from buffer (e.g., \"color: red !important\")\n */\nfunction parseDeclarationSimple(buffer: string, colonIdx: number = buffer.indexOf(\":\")): Declaration | null {\n if (colonIdx === -1) return null;\n // Case-insensitive search for !important - only lowercase if we find a '!'\n const exclamIdx = buffer.indexOf(\"!\", colonIdx + 1);\n let importantIdx = -1;\n if (exclamIdx !== -1) {\n // Check if followed by \"important\" (case-insensitive)\n const rest = buffer.slice(exclamIdx + 1, exclamIdx + 10).toLowerCase();\n if (rest === \"important\" || rest.startsWith(\"important\")) {\n importantIdx = exclamIdx;\n }\n }\n return decl(\n buffer.slice(0, colonIdx).trim(),\n buffer.slice(colonIdx + 1, importantIdx === -1 ? buffer.length : importantIdx).trim(),\n importantIdx !== -1\n );\n}\n\n/**\n * Parse a string literal.\n * Returns [endIndex, isUnclosed] - if isUnclosed is true, the string was not properly terminated.\n */\nfunction parseString(input: string, start: number, quote: number): [number, boolean] {\n for (let i = start + 1; i < input.length; i++) {\n const char = input.charCodeAt(i);\n\n if (char === BACKSLASH) {\n // Handle trailing backslash at end of input\n if (i + 1 >= input.length) {\n return [input.length - 1, true];\n }\n i++;\n continue;\n }\n\n if (char === quote) {\n return [i, false];\n }\n }\n\n return [input.length - 1, true];\n}\n\n/**\n * Serialize AST back to CSS string.\n */\nexport function stringify(nodes: AstNode[], indent = 0): string {\n const pad = \" \".repeat(indent);\n let result = \"\";\n\n for (const node of nodes) {\n if (node.kind === \"comment\") {\n result += `${pad}/*${node.value}*/\\n`;\n } else if (node.kind === \"declaration\") {\n const important = node.important ? \" !important\" : \"\";\n result += `${pad}${node.property}: ${node.value}${important};\\n`;\n } else if (node.kind === \"rule\") {\n result += `${pad}${node.selector} {\\n`;\n result += stringify(node.nodes, indent + 1);\n result += `${pad}}\\n`;\n } else if (node.kind === \"at-rule\") {\n if (node.nodes.length > 0) {\n result += `${pad}@${node.name}${node.params ? \" \" + node.params : \"\"} {\\n`;\n result += stringify(node.nodes, indent + 1);\n result += `${pad}}\\n`;\n } else {\n result += `${pad}@${node.name}${node.params ? \" \" + node.params : \"\"};\\n`;\n }\n }\n }\n\n return result;\n}\n","/**\n * Topological Sort\n *\n * Implements Kahn's algorithm for topological sorting with cycle detection.\n * Used for ordering @apply directive dependencies.\n */\n\n/**\n * Error thrown when a circular dependency is detected.\n */\nexport class CircularDependencyError extends Error {\n constructor(\n public readonly cycle: string[],\n message?: string\n ) {\n super(message ?? `Circular dependency detected: ${cycle.join(\" → \")}`);\n this.name = \"CircularDependencyError\";\n }\n}\n\n/**\n * Topologically sort items based on their dependencies using Kahn's algorithm.\n *\n * @param items - Array of items to sort\n * @param getId - Function to get a unique identifier for each item\n * @param getDeps - Function to get dependency identifiers for each item\n * @returns Sorted array of items (dependencies come before dependents)\n * @throws CircularDependencyError if a cycle is detected\n *\n * @example\n * ```ts\n * const rules = [\n * { name: \"a\", deps: [\"b\"] },\n * { name: \"b\", deps: [\"c\"] },\n * { name: \"c\", deps: [] },\n * ];\n * const sorted = topologicalSort(rules, r => r.name, r => r.deps);\n * // Result: [{ name: \"c\", ... }, { name: \"b\", ... }, { name: \"a\", ... }]\n * ```\n */\nexport function topologicalSort<T>(items: T[], getId: (item: T) => string, getDeps: (item: T) => string[]): T[] {\n // Build adjacency list and in-degree map\n const itemMap = new Map<string, T>();\n const inDegree = new Map<string, number>();\n const dependents = new Map<string, string[]>(); // dep -> items that depend on it\n\n // Initialize\n for (const item of items) {\n const id = getId(item);\n itemMap.set(id, item);\n inDegree.set(id, 0);\n if (!dependents.has(id)) {\n dependents.set(id, []);\n }\n }\n\n // Count in-degrees and build reverse adjacency\n for (const item of items) {\n const id = getId(item);\n const deps = getDeps(item);\n\n for (const dep of deps) {\n // Only count dependencies that exist in our item set\n if (itemMap.has(dep)) {\n inDegree.set(id, (inDegree.get(id) ?? 0) + 1);\n const depList = dependents.get(dep) ?? [];\n depList.push(id);\n dependents.set(dep, depList);\n }\n }\n }\n\n // Find all items with no dependencies (in-degree 0)\n const queue: string[] = [];\n for (const [id, degree] of inDegree) {\n if (degree === 0) {\n queue.push(id);\n }\n }\n\n // Process queue\n const result: T[] = [];\n\n while (queue.length > 0) {\n const id = queue.shift()!;\n const item = itemMap.get(id);\n\n if (item) {\n result.push(item);\n }\n\n // Reduce in-degree of dependents\n for (const dependent of dependents.get(id) ?? []) {\n const newDegree = (inDegree.get(dependent) ?? 1) - 1;\n inDegree.set(dependent, newDegree);\n\n if (newDegree === 0) {\n queue.push(dependent);\n }\n }\n }\n\n // If we haven't processed all items, there's a cycle\n if (result.length < items.length) {\n const cycle = findCycle(items, getId, getDeps);\n throw new CircularDependencyError(cycle);\n }\n\n return result;\n}\n\n/**\n * Find a cycle in the dependency graph using DFS.\n * Called when topological sort detects remaining items.\n */\nfunction findCycle<T>(items: T[], getId: (item: T) => string, getDeps: (item: T) => string[]): string[] {\n const itemMap = new Map<string, T>();\n for (const item of items) {\n itemMap.set(getId(item), item);\n }\n\n const visited = new Set<string>();\n const inStack = new Set<string>();\n const parent = new Map<string, string>();\n\n function dfs(id: string): string[] | null {\n if (inStack.has(id)) {\n // Found cycle - reconstruct it\n const cycle: string[] = [id];\n let current = parent.get(id);\n while (current && current !== id) {\n cycle.unshift(current);\n current = parent.get(current);\n }\n cycle.unshift(id);\n return cycle;\n }\n\n if (visited.has(id)) {\n return null;\n }\n\n visited.add(id);\n inStack.add(id);\n\n const item = itemMap.get(id);\n if (item) {\n for (const dep of getDeps(item)) {\n if (itemMap.has(dep)) {\n parent.set(dep, id);\n const cycle = dfs(dep);\n if (cycle) return cycle;\n }\n }\n }\n\n inStack.delete(id);\n return null;\n }\n\n for (const item of items) {\n const id = getId(item);\n if (!visited.has(id)) {\n const cycle = dfs(id);\n if (cycle) return cycle;\n }\n }\n\n return [\"unknown cycle\"];\n}\n\n/**\n * Build a dependency graph from items.\n * Useful for debugging or visualization.\n */\nexport function buildDependencyGraph<T>(\n items: T[],\n getId: (item: T) => string,\n getDeps: (item: T) => string[]\n): Map<string, { item: T; deps: string[]; dependents: string[] }> {\n const graph = new Map<string, { item: T; deps: string[]; dependents: string[] }>();\n\n // Initialize nodes\n for (const item of items) {\n const id = getId(item);\n graph.set(id, { item, deps: [], dependents: [] });\n }\n\n // Build edges\n for (const item of items) {\n const id = getId(item);\n const deps = getDeps(item);\n const node = graph.get(id)!;\n\n for (const dep of deps) {\n if (graph.has(dep)) {\n node.deps.push(dep);\n graph.get(dep)!.dependents.push(id);\n }\n }\n }\n\n return graph;\n}\n\n/**\n * Check if there would be a cycle if we added a dependency.\n * Useful for preventing cycles before they occur.\n */\nexport function wouldCreateCycle<T>(\n items: T[],\n getId: (item: T) => string,\n getDeps: (item: T) => string[],\n from: string,\n to: string\n): boolean {\n // A cycle would be created if 'from' is reachable from 'to'\n // (adding from -> to would complete the cycle)\n const itemMap = new Map<string, T>();\n for (const item of items) {\n itemMap.set(getId(item), item);\n }\n\n const visited = new Set<string>();\n\n function canReach(current: string, target: string): boolean {\n if (current === target) return true;\n if (visited.has(current)) return false;\n\n visited.add(current);\n\n const item = itemMap.get(current);\n if (!item) return false;\n\n for (const dep of getDeps(item)) {\n if (canReach(dep, target)) return true;\n }\n\n return false;\n }\n\n return canReach(to, from);\n}\n","/**\n * Directive Error Classes\n *\n * This module contains all error classes used by the directives system.\n * Each error class provides specific context about what went wrong.\n *\n * @module\n */\n\n// ============================================\n// Preflight Module Constants (required by PreflightModuleError)\n// ============================================\n\n/**\n * Available preflight modules.\n *\n * These control which parts of the CSS reset are included:\n * - box-sizing: Universal box-sizing: border-box\n * - document: HTML/body defaults\n * - typography: Text rendering, heading margins\n * - tables: Table border-collapse\n * - forms: Form element normalization\n * - lists: List style reset for ul, ol\n * - media: Image/video responsiveness\n * - spacing: Default margin/padding reset\n * - accessibility: sr-only and reduced-motion\n */\nexport const PREFLIGHT_MODULES = [\n \"box-sizing\",\n \"document\",\n \"typography\",\n \"tables\",\n \"forms\",\n \"lists\",\n \"media\",\n \"spacing\",\n \"accessibility\",\n] as const;\n\nexport type PreflightModule = (typeof PREFLIGHT_MODULES)[number];\n\n// ============================================\n// Preflight Errors\n// ============================================\n\n/**\n * Error thrown when @preflight has an invalid module name.\n */\nexport class PreflightModuleError extends Error {\n /** The invalid module name */\n module: string;\n\n constructor(module: string) {\n const validModules = PREFLIGHT_MODULES.join(\", \");\n super(`\\`@preflight\\`: Invalid module \"${module}\". ` + `Valid modules are: ${validModules}.`);\n this.name = \"PreflightModuleError\";\n this.module = module;\n }\n}\n\n// ============================================\n// Theme Errors\n// ============================================\n\n/**\n * Error thrown when @theme contains invalid content.\n */\nexport class ThemeContentError extends Error {\n /** The type of invalid content */\n contentType: string;\n\n constructor(contentType: string) {\n super(`\\`@theme\\` can only contain custom properties (--*) and \\`@keyframes\\`, but found ${contentType}.`);\n this.name = \"ThemeContentError\";\n this.contentType = contentType;\n }\n}\n\n/**\n * Error thrown when a theme prefix is invalid.\n */\nexport class ThemePrefixError extends Error {\n /** The invalid prefix */\n prefix: string;\n\n constructor(prefix: string) {\n super(\n `\\`@theme prefix(${prefix})\\` defines an invalid prefix. ` +\n `Prefixes must contain only lowercase ASCII letters (a-z).`\n );\n this.name = \"ThemePrefixError\";\n this.prefix = prefix;\n }\n}\n\n// ============================================\n// Color Errors\n// ============================================\n\n/**\n * Error thrown when @color has invalid parameters.\n */\nexport class ColorError extends Error {\n /** The parameter name */\n param: string;\n /** The invalid value */\n value: string;\n\n constructor(param: string, value: string, reason: string) {\n super(`\\`@color\\`: Invalid ${param} value \"${value}\". ${reason}`);\n this.name = \"ColorError\";\n this.param = param;\n this.value = value;\n }\n}\n\n// ============================================\n// Apply Errors\n// ============================================\n\n/**\n * Error thrown when @apply is used in an invalid context.\n */\nexport class ApplyContextError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"ApplyContextError\";\n }\n}\n\n/**\n * Error thrown when @apply references a blocked candidate.\n */\nexport class ApplyBlockedError extends Error {\n /** The blocked candidate that was referenced */\n candidate: string;\n\n constructor(candidate: string, message?: string) {\n super(message ?? `Cannot @apply \"${candidate}\": candidate is blocked.`);\n this.name = \"ApplyBlockedError\";\n this.candidate = candidate;\n }\n}\n\n/**\n * Error thrown when @apply references a candidate with invalid prefix.\n */\nexport class ApplyPrefixError extends Error {\n /** The candidate with invalid prefix */\n candidate: string;\n /** The required prefix */\n prefix: string;\n\n constructor(candidate: string, prefix: string, message?: string) {\n super(message ?? `Cannot @apply \"${candidate}\": candidate must start with prefix \"${prefix}\".`);\n this.name = \"ApplyPrefixError\";\n this.candidate = candidate;\n this.prefix = prefix;\n }\n}\n\n/**\n * Error thrown when @apply uses unknown variants.\n */\nexport class ApplyVariantError extends Error {\n /** The candidate that had variants */\n candidate: string;\n /** The variants that were used */\n variants: string[];\n\n constructor(candidate: string, variants: string[], message?: string) {\n const variantList = variants.join(\":\");\n super(\n message ??\n `Cannot @apply \"${candidate}\": the variant${variants.length > 1 ? \"s\" : \"\"} ` +\n `\"${variantList}\" do${variants.length > 1 ? \"\" : \"es\"} not exist.`\n );\n this.name = \"ApplyVariantError\";\n this.candidate = candidate;\n this.variants = variants;\n }\n}\n\n/**\n * Error thrown when @apply references an invalid candidate (from @source not inline).\n */\nexport class ApplyInvalidCandidateError extends Error {\n /** The invalid candidate that was referenced */\n candidate: string;\n\n constructor(candidate: string, message?: string) {\n super(\n message ?? `Cannot @apply \"${candidate}\": candidate is marked as invalid by \\`@source not inline(...)\\`.`\n );\n this.name = \"ApplyInvalidCandidateError\";\n this.candidate = candidate;\n }\n}\n\n/**\n * Error thrown when @apply references an unknown utility.\n */\nexport class ApplyUnknownUtilityError extends Error {\n /** The unknown utility that was referenced */\n candidate: string;\n\n constructor(candidate: string, message?: string) {\n super(message ?? `Cannot @apply \"${candidate}\": utility does not exist.`);\n this.name = \"ApplyUnknownUtilityError\";\n this.candidate = candidate;\n }\n}\n\n// ============================================\n// Directive Errors\n// ============================================\n\n/**\n * Error thrown when a directive is used in a nested context where it's not allowed.\n */\nexport class DirectiveNestingError extends Error {\n /** The directive name that was nested */\n directive: string;\n\n constructor(directive: string) {\n super(`\\`@${directive}\\` cannot be nested inside other rules.`);\n this.name = \"DirectiveNestingError\";\n this.directive = directive;\n }\n}\n\n/**\n * Error thrown when a directive body is empty when it shouldn't be.\n */\nexport class DirectiveEmptyError extends Error {\n /** The directive name that was empty */\n directive: string;\n /** The params of the directive */\n params: string;\n\n constructor(directive: string, params: string) {\n super(`\\`@${directive} ${params}\\` is empty. Utilities should include at least one property.`);\n this.name = \"DirectiveEmptyError\";\n this.directive = directive;\n this.params = params;\n }\n}\n\n/**\n * Error thrown when a directive has a body when it shouldn't.\n */\nexport class DirectiveBodyError extends Error {\n /** The directive name that had an unexpected body */\n directive: string;\n\n constructor(directive: string) {\n super(`\\`@${directive}\\` cannot have a body.`);\n this.name = \"DirectiveBodyError\";\n this.directive = directive;\n }\n}\n\n/**\n * Error thrown when a directive type is invalid.\n */\nexport class DirectiveTypeError extends Error {\n /** The invalid directive type */\n invalidType: string | undefined;\n /** The valid types expected */\n validTypes: string[];\n\n constructor(directive: string, invalidType: string | undefined, validTypes: string[]) {\n const typeStr = invalidType === undefined ? \"(empty)\" : `\"${invalidType}\"`;\n super(\n `@${directive}: Invalid directive type ${typeStr}. Expected one of: ${validTypes.map((t) => `\"${t}\"`).join(\", \")}.`\n );\n this.name = \"DirectiveTypeError\";\n this.invalidType = invalidType;\n this.validTypes = validTypes;\n }\n}\n\n// ============================================\n// Utility Errors\n// ============================================\n\n/**\n * Error thrown when a utility name is invalid.\n */\nexport class UtilityNameError extends Error {\n /** The invalid utility name */\n utilityName: string;\n /** The reason for invalidity */\n reason: string;\n\n constructor(utilityName: string, reason: string) {\n super(`\\`@utility ${utilityName}\\` defines an invalid utility name. ${reason}`);\n this.name = \"UtilityNameError\";\n this.utilityName = utilityName;\n this.reason = reason;\n }\n}\n\n/**\n * Error thrown when @utility @apply fails.\n */\nexport class UtilityApplyError extends Error {\n /** The utility name */\n utilityName: string;\n /** The original error */\n cause?: Error;\n\n constructor(utilityName: string, message: string, cause?: Error) {\n super(`\\`@utility ${utilityName}\\` failed to process @apply: ${message}`);\n this.name = \"UtilityApplyError\";\n this.utilityName = utilityName;\n this.cause = cause;\n }\n}\n\n// ============================================\n// Source Errors\n// ============================================\n\n/**\n * Error thrown when @source path is invalid.\n */\nexport class SourcePathError extends Error {\n /** The invalid source path */\n path: string;\n\n constructor(path: string, reason: string) {\n super(`\\`@source ${path}\\` is invalid. ${reason}`);\n this.name = \"SourcePathError\";\n this.path = path;\n }\n}\n\n// ============================================\n// Import Errors\n// ============================================\n\n/**\n * Error thrown when @import parameters are in invalid order.\n * CSS spec requires: layer() before supports() before media query.\n */\nexport class ImportOrderError extends Error {\n /** The import path */\n path: string;\n\n constructor(path: string, reason: string) {\n super(`\\`@import \"${path}\"\\` has invalid parameter order. ${reason}`);\n this.name = \"ImportOrderError\";\n this.path = path;\n }\n}\n\n// ============================================\n// Variant Errors\n// ============================================\n\n/**\n * Error thrown when a variant name is invalid.\n */\nexport class VariantNameError extends Error {\n /** The invalid variant name */\n variantName: string;\n /** The reason for invalidity */\n reason: string;\n\n constructor(variantName: string, reason: string) {\n super(`\\`@variant ${variantName}\\` defines an invalid variant name. ${reason}`);\n this.name = \"VariantNameError\";\n this.variantName = variantName;\n this.reason = reason;\n }\n}\n\n/**\n * Error thrown when a variant selector is invalid.\n */\nexport class VariantSelectorError extends Error {\n /** The variant name */\n variantName: string;\n /** The invalid selector */\n selector: string;\n\n constructor(variantName: string, selector: string, reason: string) {\n super(`\\`@variant ${variantName}\\` has an invalid selector \"${selector}\". ${reason}`);\n this.name = \"VariantSelectorError\";\n this.variantName = variantName;\n this.selector = selector;\n }\n}\n\n/**\n * Error thrown when @variant directive cannot be parsed.\n */\nexport class VariantParseError extends Error {\n /** The directive params that couldn't be parsed */\n params: string;\n\n constructor(params: string) {\n super(\n `\\`@variant ${params}\\` could not be parsed. ` +\n `Expected format: @variant name (selector), @variant name { ... }, or @variant name @slot;`\n );\n this.name = \"VariantParseError\";\n this.params = params;\n }\n}\n\n/**\n * Error thrown when @variant body is missing @slot.\n */\nexport class VariantSlotError extends Error {\n /** The variant name */\n variantName: string;\n\n constructor(variantName: string) {\n super(\n `\\`@variant ${variantName}\\` body does not contain @slot. ` +\n `Use @slot to mark where child styles should be placed.`\n );\n this.name = \"VariantSlotError\";\n this.variantName = variantName;\n }\n}\n\n/**\n * Error thrown when @variant references an unknown variant for application.\n */\nexport class VariantApplicationError extends Error {\n /** The variant name that was referenced */\n variantName: string;\n\n constructor(variantName: string, message?: string) {\n super(message ?? `Cannot apply @variant \"${variantName}\": variant does not exist.`);\n this.name = \"VariantApplicationError\";\n this.variantName = variantName;\n }\n}\n\n// ============================================\n// Font Errors\n// ============================================\n\n/**\n * Error thrown when @font directive has invalid syntax.\n */\nexport class FontDirectiveError extends Error {\n param: string;\n value: string;\n\n constructor(param: string, value: string, reason: string) {\n super(`\\`@font\\`: Invalid ${param} \"${value}\". ${reason}`);\n this.name = \"FontDirectiveError\";\n this.param = param;\n this.value = value;\n }\n}\n","/**\n * @rainbowindex Directive\n *\n * Processes the @rainbowindex directive for marking injection points.\n *\n * @module\n */\n\nimport type { AtRule } from \"../../ast\";\nimport { segment } from \"../../utils/segment\";\nimport { DirectiveTypeError, SourcePathError } from \"./errors\";\n\n// ============================================\n// Types\n// ============================================\n\nexport type RainbowIndexDirectiveType = \"base\" | \"utilities\" | \"components\";\n\nexport interface RainbowIndexDirective {\n /** Type of directive: base, utilities, or components */\n type: RainbowIndexDirectiveType;\n /** Source pattern for utilities (optional) */\n source?: { base: string; pattern: string } | \"none\";\n /** The original AST node (used as a placeholder for utility injection) */\n node: AtRule;\n}\n\n// ============================================\n// Processing\n// ============================================\n\n/**\n * Process @rainbowindex directive.\n *\n * @rainbowindex base;\n * @rainbowindex utilities;\n * @rainbowindex utilities source(\"./src/**\\/*.html\");\n * @rainbowindex utilities source(none);\n * @rainbowindex components;\n *\n * These directives mark where to inject:\n * - base: Base/reset styles and CSS variables\n * - utilities: Generated utility classes\n * - components: Component styles from plugins\n */\nexport function processRainbowIndexDirective(node: AtRule, base: string): RainbowIndexDirective {\n const params = node.params.trim();\n\n // Parse the directive type\n const parts = segment(params, \" \");\n const type = parts[0] as RainbowIndexDirectiveType | undefined;\n\n if (!type || ![\"base\", \"utilities\", \"components\"].includes(type)) {\n throw new DirectiveTypeError(\"rainbowindex\", type, [\"base\", \"utilities\", \"components\"]);\n }\n\n let source: { base: string; pattern: string } | \"none\" | undefined;\n\n // Parse source() option (only for utilities)\n for (const part of parts.slice(1)) {\n if (part.startsWith(\"source(\")) {\n const path = part.slice(7, -1);\n\n // Keyword: source(none)\n if (path === \"none\") {\n source = \"none\";\n continue;\n }\n\n // Explicit path: source(\"...\")\n if (\n (path[0] === '\"' && path[path.length - 1] !== '\"') ||\n (path[0] === \"'\" && path[path.length - 1] !== \"'\") ||\n (path[0] !== \"'\" && path[0] !== '\"')\n ) {\n throw new SourcePathError(\n path,\n 'Paths must be quoted with single or double quotes, e.g.: source(\"./src/**/*.html\")'\n );\n }\n\n source = {\n base,\n pattern: path.slice(1, -1),\n };\n }\n }\n\n return {\n type,\n source,\n node,\n };\n}\n","/**\n * @layer Directive\n *\n * Processes CSS @layer declarations and definitions.\n *\n * @module\n */\n\nimport type { AstNode, AtRule } from \"../../ast\";\nimport { atRule } from \"../../ast\";\n\n// ============================================\n// Types\n// ============================================\n\nexport interface LayerDirective {\n /** Layer name(s) */\n names: string[];\n /** Whether this is a layer definition (with body) or declaration (without body) */\n isDefinition: boolean;\n /** Content nodes (for definitions) */\n nodes: AstNode[];\n}\n\n// ============================================\n// Processing\n// ============================================\n\n/**\n * Process @layer directive.\n *\n * Layer declaration (order definition):\n * @layer base, utilities, components;\n *\n * Layer definition (with content):\n * @layer utilities {\n * .foo { color: red; }\n * }\n *\n * Returns the parsed layer directive.\n */\nexport function processLayerDirective(node: AtRule): LayerDirective {\n const params = node.params.trim();\n const isDefinition = node.nodes.length > 0;\n\n // Parse layer names (comma-separated)\n const names = params\n .split(\",\")\n .map((n) => n.trim())\n .filter(Boolean);\n\n return {\n names,\n isDefinition,\n nodes: node.nodes,\n };\n}\n\n/**\n * Wrap content in a @layer at-rule.\n */\nexport function wrapInLayer(layerName: string, nodes: AstNode[]): AtRule {\n return atRule(\"layer\", layerName, nodes);\n}\n","/**\n * @preflight Directive\n *\n * Processes the @preflight directive for CSS reset configuration.\n *\n * @module\n */\n\nimport type { AstNode, AtRule } from \"../../ast\";\nimport { PREFLIGHT_MODULES, type PreflightModule, PreflightModuleError } from \"./errors\";\n\n// ============================================\n// Types\n// ============================================\n\n/**\n * Preflight configuration from @preflight directive.\n *\n * @preflight; // Full preflight (default)\n * @preflight none; // No preflight\n * @preflight not lists; // Exclude specific modules\n * @preflight not lists, media; // Exclude multiple modules\n * @preflight only box-sizing; // Include only specific modules\n * @preflight only box-sizing, forms; // Include only multiple modules\n */\nexport interface PreflightConfig {\n /** Mode: full (default), none, include (only), or exclude (not) */\n mode: \"full\" | \"none\" | \"include\" | \"exclude\";\n /** Modules to include or exclude (depending on mode) */\n modules: PreflightModule[];\n}\n\n// ============================================\n// Processing\n// ============================================\n\n/**\n * Process @preflight directive.\n *\n * @preflight; // Full preflight (all modules)\n * @preflight none; // No preflight\n * @preflight not lists; // Exclude lists module\n * @preflight not lists, media; // Exclude multiple modules\n * @preflight only box-sizing, forms; // Include only specific modules\n *\n * @throws PreflightModuleError if an invalid module name is used\n */\nexport function processPreflightDirective(node: AtRule): PreflightConfig {\n const params = node.params.trim();\n\n // @preflight; or @preflight (no params) - full preflight\n if (!params) {\n return { mode: \"full\", modules: [] };\n }\n\n // @preflight none;\n if (params.toLowerCase() === \"none\") {\n return { mode: \"none\", modules: [] };\n }\n\n // @preflight not module1, module2;\n if (params.toLowerCase().startsWith(\"not \")) {\n const moduleList = params.slice(4).trim();\n const modules = parsePreflightModules(moduleList);\n return { mode: \"exclude\", modules };\n }\n\n // @preflight only module1, module2;\n if (params.toLowerCase().startsWith(\"only \")) {\n const moduleList = params.slice(5).trim();\n const modules = parsePreflightModules(moduleList);\n return { mode: \"include\", modules };\n }\n\n // Fallback: treat as module list to include\n const modules = parsePreflightModules(params);\n return { mode: \"include\", modules };\n}\n\n/**\n * Parse a comma-separated list of preflight module names.\n *\n * @throws PreflightModuleError if an invalid module name is found\n */\nfunction parsePreflightModules(moduleList: string): PreflightModule[] {\n const modules: PreflightModule[] = [];\n\n for (const part of moduleList.split(\",\")) {\n const moduleName = part.trim().toLowerCase();\n if (!moduleName) continue;\n\n if (!PREFLIGHT_MODULES.includes(moduleName as PreflightModule)) {\n throw new PreflightModuleError(moduleName);\n }\n\n modules.push(moduleName as PreflightModule);\n }\n\n return modules;\n}\n\n/**\n * Check if a preflight module should be included based on config.\n */\nexport function shouldIncludePreflightModule(module: PreflightModule, config: PreflightConfig): boolean {\n switch (config.mode) {\n case \"full\":\n return true;\n case \"none\":\n return false;\n case \"include\":\n return config.modules.includes(module);\n case \"exclude\":\n return !config.modules.includes(module);\n }\n}\n\n/**\n * Filter preflight CSS AST nodes based on module configuration.\n *\n * The preflight CSS uses comment markers to identify modules:\n * /* @preflight-module: box-sizing *\\/\n * ... styles ...\n * /* @preflight-module-end: box-sizing *\\/\n *\n * This function filters the AST to only include modules that should be included\n * based on the PreflightConfig.\n */\nexport function filterPreflightModules(nodes: AstNode[], config: PreflightConfig): AstNode[] {\n // Fast path: if mode is \"full\", return all nodes\n if (config.mode === \"full\") {\n return nodes;\n }\n\n // Fast path: if mode is \"none\", return empty\n if (config.mode === \"none\") {\n return [];\n }\n\n const result: AstNode[] = [];\n let currentModule: PreflightModule | null = null;\n let includeCurrentModule = true;\n\n for (const node of nodes) {\n // Check for module marker comments\n if (node.kind === \"comment\") {\n // Fast path: check for marker prefix using indexOf (3-5x faster than regex)\n const startIdx = node.value.indexOf(\"@preflight-module:\");\n const endIdx = node.value.indexOf(\"@preflight-module-end:\");\n\n if (startIdx !== -1) {\n // Extract module name: skip marker and trim\n const afterMarker = node.value.slice(startIdx + 18).trimStart();\n const spaceIdx = afterMarker.search(/\\s/);\n const moduleName = (spaceIdx === -1 ? afterMarker : afterMarker.slice(0, spaceIdx)) as PreflightModule;\n\n if (PREFLIGHT_MODULES.includes(moduleName)) {\n currentModule = moduleName;\n includeCurrentModule = shouldIncludePreflightModule(moduleName, config);\n }\n continue; // Don't include the marker comment itself\n }\n\n if (endIdx !== -1) {\n currentModule = null;\n includeCurrentModule = true;\n continue; // Don't include the marker comment itself\n }\n }\n\n // If we're inside a module section, check if it should be included\n if (currentModule !== null) {\n if (includeCurrentModule) {\n result.push(node);\n }\n } else {\n // Outside any module section - include by default\n result.push(node);\n }\n }\n\n return result;\n}\n\n/**\n * Filter preflight styles in a @layer base block.\n *\n * This handles the case where preflight is wrapped in @layer base { ... }\n * and filters the inner nodes based on the PreflightConfig.\n */\nexport function filterPreflightInLayer(ast: AstNode[], config: PreflightConfig): AstNode[] {\n // Fast paths\n if (config.mode === \"full\") {\n return ast;\n }\n\n if (config.mode === \"none\") {\n // Remove all @layer base blocks that contain preflight markers\n return ast.filter((node) => {\n if (node.kind === \"at-rule\" && node.name === \"@layer\" && node.params === \"base\") {\n // Check if this layer contains preflight markers\n return !hasPreflightMarkers(node.nodes);\n }\n return true;\n });\n }\n\n // For include/exclude modes, filter the contents of @layer base\n return ast.map((node) => {\n if (node.kind === \"at-rule\" && node.name === \"@layer\" && node.params === \"base\") {\n // Check if this layer contains preflight markers\n if (hasPreflightMarkers(node.nodes)) {\n const filteredNodes = filterPreflightModules(node.nodes, config);\n return {\n ...node,\n nodes: filteredNodes,\n };\n }\n }\n return node;\n });\n}\n\n/**\n * Check if AST nodes contain preflight module markers.\n */\nfunction hasPreflightMarkers(nodes: AstNode[]): boolean {\n for (const node of nodes) {\n if (node.kind === \"comment\" && node.value.includes(\"@preflight-module:\")) {\n return true;\n }\n }\n return false;\n}\n","/**\n * Brace Expansion Utility\n *\n * Expands brace patterns like:\n * - \"bg-red-{50,100,200}\" -> [\"bg-red-50\", \"bg-red-100\", \"bg-red-200\"]\n * - \"p-{1..4}\" -> [\"p-1\", \"p-2\", \"p-3\", \"p-4\"]\n * - \"m-{0..10..2}\" -> [\"m-0\", \"m-2\", \"m-4\", \"m-6\", \"m-8\", \"m-10\"]\n *\n * Performance optimizations:\n * - Generator-based lazy expansion to avoid intermediate allocations\n * - Pre-allocated result arrays where size is known\n * - Direct string building instead of flatMap chains\n */\n\nimport { segment } from \"./segment\";\n\n// Pre-compiled regex for sequence detection\nconst NUMERICAL_RANGE = /^(-?\\d+)\\.\\.(-?\\d+)(?:\\.\\.(-?\\d+))?$/;\n// Pre-compiled pattern for integer validation in sequences\nconst INTEGER_PATTERN = /^-?\\d+$/;\n\n// Character codes for fast comparison\nconst OPEN_BRACE = 0x7b; // {\nconst CLOSE_BRACE = 0x7d; // }\n\n/** Options for brace expansion */\nexport interface ExpandOptions {\n /** Maximum number of results to generate (default: 10000) */\n maxResults?: number;\n}\n\n/**\n * Expand a brace pattern into all possible combinations.\n *\n * @example\n * expand(\"bg-{red,blue}-{100,200}\")\n * // Returns: [\"bg-red-100\", \"bg-red-200\", \"bg-blue-100\", \"bg-blue-200\"]\n *\n * @example\n * expand(\"p-{1..3}\")\n * // Returns: [\"p-1\", \"p-2\", \"p-3\"]\n */\nexport function expand(pattern: string, options?: ExpandOptions): string[] {\n const maxResults = options?.maxResults ?? 10000;\n\n // Fast path: no braces\n const braceIdx = pattern.indexOf(\"{\");\n if (braceIdx === -1) return [pattern];\n\n // Use optimized internal expansion\n const result: string[] = [];\n expandInternal(pattern, result, maxResults);\n return result;\n}\n\n/**\n * Generator-based lazy expansion for memory efficiency.\n * Use this when you only need to iterate once or may stop early.\n *\n * @example\n * for (const expanded of expandLazy(\"bg-{red,blue}-{100,200}\")) {\n * console.log(expanded);\n * }\n */\nexport function* expandLazy(pattern: string): Generator<string> {\n const braceIdx = pattern.indexOf(\"{\");\n if (braceIdx === -1) {\n yield pattern;\n return;\n }\n\n const pre = pattern.slice(0, braceIdx);\n const braceContent = findBraceContent(pattern, braceIdx);\n\n if (!braceContent) {\n throw new Error(`The pattern \\`${pattern}\\` is not balanced.`);\n }\n\n const { inside, post } = braceContent;\n\n // Get parts from inside the braces\n const parts = isSequence(inside) ? expandSequenceArray(inside) : segment(inside, \",\");\n\n // Recursively expand and combine\n for (const part of parts) {\n for (const expandedPart of expandLazy(part)) {\n for (const tail of expandLazy(post)) {\n yield pre + expandedPart + tail;\n }\n }\n }\n}\n\n/**\n * Internal expansion with pre-allocated result array.\n * Avoids flatMap overhead by building results directly.\n */\nfunction expandInternal(pattern: string, result: string[], maxResults: number): void {\n const braceIdx = pattern.indexOf(\"{\");\n\n if (braceIdx === -1) {\n if (result.length < maxResults) {\n result.push(pattern);\n }\n return;\n }\n\n const pre = pattern.slice(0, braceIdx);\n const braceContent = findBraceContent(pattern, braceIdx);\n\n if (!braceContent) {\n throw new Error(`The pattern \\`${pattern}\\` is not balanced.`);\n }\n\n const { inside, post } = braceContent;\n\n // Get parts - either from sequence or comma-separated\n const parts = isSequence(inside) ? expandSequenceArray(inside) : segment(inside, \",\");\n\n // Expand each part recursively, then combine with tail\n // Use temporary arrays to avoid redundant recursion\n const expandedParts: string[][] = [];\n for (const part of parts) {\n const partResults: string[] = [];\n expandInternal(part, partResults, maxResults);\n expandedParts.push(partResults);\n }\n\n const expandedTails: string[] = [];\n expandInternal(post, expandedTails, maxResults);\n\n // Combine all parts with all tails\n for (const tail of expandedTails) {\n for (const partArray of expandedParts) {\n for (const part of partArray) {\n if (result.length >= maxResults) return;\n result.push(pre + part + tail);\n }\n }\n }\n}\n\n/**\n * Find matching brace content using charCodeAt for performance.\n */\nfunction findBraceContent(pattern: string, startIdx: number): { inside: string; post: string } | null {\n let depth = 0;\n const len = pattern.length;\n\n for (let i = startIdx; i < len; i++) {\n const char = pattern.charCodeAt(i);\n if (char === OPEN_BRACE) {\n depth++;\n } else if (char === CLOSE_BRACE) {\n depth--;\n if (depth === 0) {\n return {\n inside: pattern.slice(startIdx + 1, i),\n post: pattern.slice(i + 1),\n };\n }\n }\n }\n\n return null;\n}\n\n/**\n * Check if a string is a numeric sequence pattern.\n */\nfunction isSequence(str: string): boolean {\n return NUMERICAL_RANGE.test(str);\n}\n\n/**\n * Expand a numeric sequence like \"1..5\" or \"0..10..2\".\n * Returns pre-allocated array with known size.\n */\nfunction expandSequenceArray(seq: string): string[] {\n const seqMatch = seq.match(NUMERICAL_RANGE);\n if (!seqMatch) {\n return [seq];\n }\n\n const [, startStr, endStr, stepStr] = seqMatch;\n\n if (!INTEGER_PATTERN.test(startStr!) || !INTEGER_PATTERN.test(endStr!)) {\n return [seq];\n }\n\n const startNum = parseInt(startStr!, 10);\n const endNum = parseInt(endStr!, 10);\n let step = stepStr ? parseInt(stepStr, 10) : undefined;\n\n if (step === 0) {\n throw new Error(\"Step cannot be zero in sequence expansion.\");\n }\n\n const increasing = startNum <= endNum;\n\n if (step === undefined) {\n step = increasing ? 1 : -1;\n } else if (increasing && step < 0) {\n step = -step;\n } else if (!increasing && step > 0) {\n step = -step;\n }\n\n // Pre-calculate result size for array allocation\n const count = Math.floor(Math.abs(endNum - startNum) / Math.abs(step)) + 1;\n const result = new Array<string>(count);\n\n let idx = 0;\n for (let i = startNum; increasing ? i <= endNum : i >= endNum; i += step) {\n result[idx++] = i.toString();\n }\n\n return result;\n}\n","/**\n * @source Directive\n *\n * Processes the @source directive for candidate source configuration.\n *\n * @module\n */\n\nimport type { AtRule } from \"../../ast\";\nimport { segment } from \"../../utils/segment\";\nimport { expand } from \"../../utils/brace-expansion\";\nimport { DirectiveBodyError, SourcePathError } from \"./errors\";\n\n// ============================================\n// Types\n// ============================================\n\nexport interface SourceDirective {\n /** Type of source directive */\n kind: \"glob\" | \"inline\" | \"not-inline\";\n /** Glob pattern (for kind: \"glob\") */\n pattern?: string;\n /** Base directory for the pattern */\n base?: string;\n /** Whether this is a negated pattern */\n negated?: boolean;\n /** Inline candidates (for kind: \"inline\" or \"not-inline\") */\n candidates?: string[];\n}\n\n// ============================================\n// Processing\n// ============================================\n\n/**\n * Process @source directive.\n *\n * @source \"./src/**\\/*.html\";\n * @source not \"./node_modules/**\";\n * @source inline(\"underline bg-red-500\");\n * @source not inline(\"deprecated-class\");\n *\n * Returns the parsed source directive for scanner integration.\n *\n * @throws DirectiveBodyError if @source has a body\n * @throws SourcePathError if the path is invalid\n */\nexport function processSourceDirective(node: AtRule, base: string): SourceDirective {\n // @source cannot have a body\n if (node.nodes.length > 0) {\n throw new DirectiveBodyError(\"source\");\n }\n\n let params = node.params.trim();\n let negated = false;\n let inline = false;\n\n // Check for \"not\" prefix\n if (params.startsWith(\"not \")) {\n negated = true;\n params = params.slice(4).trim();\n }\n\n // Check for \"inline(\" syntax\n if (params.startsWith(\"inline(\")) {\n inline = true;\n // Extract content between inline( and )\n const closeIndex = params.lastIndexOf(\")\");\n if (closeIndex === -1) {\n throw new SourcePathError(node.params, \"`inline()` is not properly closed.\");\n }\n params = params.slice(7, closeIndex).trim();\n }\n\n // Extract quoted string\n if (\n (params[0] === '\"' && params[params.length - 1] !== '\"') ||\n (params[0] === \"'\" && params[params.length - 1] !== \"'\") ||\n (params[0] !== \"'\" && params[0] !== '\"')\n ) {\n throw new SourcePathError(node.params, \"Paths must be quoted.\");\n }\n\n const source = params.slice(1, -1);\n\n if (inline) {\n // Parse inline candidates with brace expansion\n const candidates: string[] = [];\n const parts = segment(source, \" \");\n\n for (const part of parts) {\n if (part.trim()) {\n // Expand brace patterns like bg-red-{100,200,300}\n for (const expanded of expand(part.trim())) {\n candidates.push(expanded);\n }\n }\n }\n\n return {\n kind: negated ? \"not-inline\" : \"inline\",\n candidates,\n };\n }\n\n // Glob pattern\n return {\n kind: \"glob\",\n pattern: source,\n base,\n negated,\n };\n}\n","/**\n * @theme Directive\n *\n * Processes the @theme directive for CSS variable registration.\n *\n * @module\n */\n\nimport type { AstNode, AtRule, Declaration } from \"../../ast\";\nimport { decl, styleRule } from \"../../ast\";\nimport { ThemeOptions, type Theme } from \"../../theme\";\nimport { ThemeContentError, ThemePrefixError } from \"./errors\";\nimport { buildVariableDependencyGraph, findCircularVariables } from \"../../utils/variables\";\n\n// ============================================\n// Telemetry (opt-in via RAINBOWINDEX_TELEMETRY=1)\n// ============================================\n\n/**\n * Telemetry data for circular reference detection.\n * Only tracked when RAINBOWINDEX_TELEMETRY=1\n */\nexport interface CircularReferenceTelemetry {\n /** Total @theme blocks processed */\n themeBlocksProcessed: number;\n /** @theme blocks with circular references */\n circularReferencesDetected: number;\n /** Total circular variables found */\n circularVariablesCount: number;\n}\n\n// Global telemetry state (only populated when telemetry is enabled)\nlet telemetryEnabled: boolean | null = null;\nconst telemetryData: CircularReferenceTelemetry = {\n themeBlocksProcessed: 0,\n circularReferencesDetected: 0,\n circularVariablesCount: 0,\n};\n\nfunction isTelemetryEnabled(): boolean {\n if (telemetryEnabled === null) {\n telemetryEnabled = typeof process !== \"undefined\" && process.env?.RAINBOWINDEX_TELEMETRY === \"1\";\n }\n return telemetryEnabled;\n}\n\n/**\n * Get current telemetry data (for testing/debugging).\n * Returns null if telemetry is disabled.\n */\nexport function getCircularReferenceTelemetry(): CircularReferenceTelemetry | null {\n if (!isTelemetryEnabled()) return null;\n return { ...telemetryData };\n}\n\n/**\n * Reset telemetry data (for testing).\n */\nexport function resetCircularReferenceTelemetry(): void {\n telemetryData.themeBlocksProcessed = 0;\n telemetryData.circularReferencesDetected = 0;\n telemetryData.circularVariablesCount = 0;\n}\n\n// ============================================\n// Types\n// ============================================\n\nexport interface ThemeDirectiveOptions {\n /** Theme mode: \"inline\" puts variables in :root, \"reference\" just loads them, \"rainbow\" enables light-dark() */\n mode?: \"inline\" | \"reference\" | \"rainbow\";\n /** Force reference behavior (no output) */\n reference?: boolean;\n /** Force rainbow behavior (light-dark transform) */\n rainbow?: boolean;\n /** Force inline behavior (output variables without @property registration) */\n inline?: boolean;\n /** Force default behavior (can be overridden by later declarations) */\n default?: boolean;\n /** Force static behavior (cannot use var() references) */\n static?: boolean;\n /** Variable prefix (e.g., \"ri\" for --ri-*) */\n prefix?: string;\n}\n\n/**\n * Parsed @theme options.\n */\nexport interface ParsedThemeOptions {\n /** Reference-only mode (no output) */\n reference: boolean;\n /** Rainbow mode (light-dark transform) */\n rainbow: boolean;\n /** Inline mode (output in :root without @property) */\n inline: boolean;\n /** Default mode (can be overridden) */\n default: boolean;\n /** Static mode (no var() references) */\n static: boolean;\n /** Variable prefix */\n prefix: string | null;\n}\n\n// ============================================\n// Processing\n// ============================================\n\n/**\n * Process @theme directive.\n *\n * @theme {\n * --color-primary: oklch(0.6 0.2 250);\n * --spacing-lg: 2rem;\n * }\n *\n * @theme rainbow {\n * --color-surface: oklch(0.98 0 0) / oklch(0.15 0 0);\n * }\n * // Compiles to: --color-surface: light-dark(oklch(0.98 0 0), oklch(0.15 0 0));\n *\n * @theme inline default prefix(tw) {\n * --color-brand: blue;\n * }\n *\n * @theme {\n * @keyframes spin {\n * from { transform: rotate(0deg); }\n * to { transform: rotate(360deg); }\n * }\n * }\n *\n * Extracts CSS variables and registers them with the theme.\n * Also collects @keyframes for the animation system.\n *\n * Validates that @theme only contains:\n * - Custom property declarations (--*)\n * - @keyframes rules\n *\n * @throws ThemeContentError if invalid content is found\n */\nexport function processThemeDirective(node: AtRule, theme: Theme, options: ThemeDirectiveOptions = {}): AstNode[] {\n const parsed = options.mode ? parseThemeOptions(options.mode) : parseThemeOptions(node.params);\n const reference = options.reference ?? parsed.reference;\n const rainbow = options.rainbow ?? parsed.rainbow;\n const inline = options.inline ?? parsed.inline;\n const defaultOpt = options.default ?? parsed.default;\n const staticOpt = options.static ?? parsed.static;\n const prefix = options.prefix ?? parsed.prefix;\n\n // Validate prefix if specified (must be lowercase ASCII letters/numbers/hyphens)\n if (prefix && !isValidThemePrefix(prefix)) {\n throw new ThemePrefixError(prefix);\n }\n\n const output: AstNode[] = [];\n const declarations: Declaration[] = [];\n const keyframeRules: AtRule[] = [];\n\n for (const child of node.nodes) {\n if (child.kind === \"declaration\") {\n // Validate: must be a custom property (starts with --)\n if (!child.property.startsWith(\"--\")) {\n throw new ThemeContentError(`a regular property \"${child.property}\"`);\n }\n\n if (child.value === undefined) {\n continue;\n }\n\n let value = child.value;\n const property = child.property; // Store original property without prefix\n\n // In rainbow mode, transform light/dark values\n if (rainbow) {\n value = transformLightDarkValue(value);\n }\n\n // Build ThemeOptions flags\n let themeOpts = ThemeOptions.NONE;\n if (reference) {\n themeOpts |= ThemeOptions.REFERENCE;\n }\n if (inline) {\n themeOpts |= ThemeOptions.INLINE;\n }\n if (defaultOpt) {\n themeOpts |= ThemeOptions.DEFAULT;\n }\n if (staticOpt) {\n themeOpts |= ThemeOptions.STATIC;\n }\n\n // Register with theme using ORIGINAL key (no prefix applied)\n // The prefix is stored on theme and applied at var() emission time\n theme.add(property, value, themeOpts, child.src);\n\n // For output, apply prefix to the emitted property name\n const outputProperty = prefix ? property.replace(/^--/, `--${prefix}-`) : property;\n declarations.push(decl(outputProperty, value, child.important));\n } else if (child.kind === \"at-rule\" && child.name === \"@keyframes\") {\n // @keyframes are allowed in @theme\n // Register with theme's keyframes collection\n theme.addKeyframes(child.params, child);\n keyframeRules.push(child);\n } else if (child.kind === \"at-rule\") {\n // Other at-rules are not allowed\n throw new ThemeContentError(`an at-rule \"@${child.name}\"`);\n } else if (child.kind === \"rule\") {\n // Style rules are not allowed\n throw new ThemeContentError(`a style rule \"${child.selector}\"`);\n } else if (child.kind === \"comment\") {\n // Comments are allowed but ignored\n } else {\n // Unknown node type\n throw new ThemeContentError(`unknown content`);\n }\n }\n\n // Store prefix on theme if specified\n if (prefix) {\n theme.prefix = prefix;\n }\n\n // Check for circular variable references\n if (declarations.length > 0) {\n const declsForGraph = declarations.map((d) => ({\n property: d.property,\n value: d.value!,\n }));\n const graph = buildVariableDependencyGraph(declsForGraph);\n const circular = findCircularVariables(graph);\n\n // Track telemetry if enabled\n if (isTelemetryEnabled()) {\n telemetryData.themeBlocksProcessed++;\n if (circular.length > 0) {\n telemetryData.circularReferencesDetected++;\n telemetryData.circularVariablesCount += circular.length;\n }\n }\n\n // Warn on circular references\n if (circular.length > 0) {\n console.warn(\n `[rainbowindex] Circular CSS variable references detected in @theme: ${circular.join(\", \")}. ` +\n `These variables may not resolve correctly at runtime.`\n );\n }\n }\n\n // In inline or rainbow mode, output the variables in :root, :host\n // Reference mode does not output anything\n // Using :root, :host enables theme variables in shadow DOM\n if (!reference && declarations.length > 0) {\n // For rainbow mode, also add color-scheme property\n if (rainbow) {\n declarations.unshift(decl(\"color-scheme\", \"light dark\"));\n }\n output.push(styleRule(\":root, :host\", declarations));\n }\n\n // Output @keyframes (unless in reference mode)\n if (!reference && keyframeRules.length > 0) {\n output.push(...keyframeRules);\n }\n\n return output;\n}\n\n// Pre-compiled pattern for theme prefix validation (hoisted to avoid recreation on every call)\nconst THEME_PREFIX_PATTERN = /^[a-z]+$/;\n\n/**\n * Validate a theme prefix.\n *\n * Valid prefixes must contain only lowercase ASCII letters.\n *\n * Design decision: This is intentionally restrictive to match CSS\n * identifier conventions. If broader support is needed (e.g., `tw2`, `v3`),\n * consider updating to: /^[a-z][a-z0-9]*$/\n * Hyphens are excluded to avoid conflicts with CSS property names.\n */\nexport function isValidThemePrefix(prefix: string): boolean {\n if (!prefix || prefix.length === 0) return false;\n\n return THEME_PREFIX_PATTERN.test(prefix);\n}\n\n/**\n * Parse theme mode from @theme params.\n *\n * Supports:\n * - @theme { ... } - default inline mode\n * - @theme reference { ... } - reference-only mode\n * - @theme inline { ... } - explicit inline mode\n * - @theme default { ... } - default values that can be overridden\n * - @theme static { ... } - static values (no var() references)\n * - @theme rainbow { ... } - light-dark() transform mode\n * - @theme prefix(tw) { ... } - custom prefix for variables\n *\n * Multiple options can be combined:\n * - @theme reference default { ... }\n * - @theme inline prefix(ri) { ... }\n */\nexport function parseThemeOptions(params: string): ParsedThemeOptions {\n let reference = false;\n let rainbow = false;\n let inline = false;\n let defaultOpt = false;\n let staticOpt = false;\n let prefix: string | null = null;\n\n // Handle prefix() function first\n const prefixMatch = params.match(/prefix\\s*\\(\\s*([^)\\s]+)\\s*\\)/i);\n if (prefixMatch) {\n prefix = prefixMatch[1] as string;\n // Remove the prefix() from params for further parsing\n params = params.replace(prefixMatch[0], \"\");\n }\n\n const tokens = params.trim().toLowerCase().split(/\\s+/).filter(Boolean);\n\n for (const token of tokens) {\n switch (token) {\n case \"reference\":\n reference = true;\n break;\n case \"rainbow\":\n rainbow = true;\n break;\n case \"inline\":\n inline = true;\n break;\n case \"default\":\n defaultOpt = true;\n break;\n case \"static\":\n staticOpt = true;\n break;\n }\n }\n\n return {\n reference,\n rainbow,\n inline,\n default: defaultOpt,\n static: staticOpt,\n prefix,\n };\n}\n\n/**\n * Transform a CSS value with light/dark syntax to light-dark() function.\n *\n * Input: \"oklch(0.98 0 0) / oklch(0.15 0 0)\"\n * Output: \"light-dark(oklch(0.98 0 0), oklch(0.15 0 0))\"\n */\nexport function transformLightDarkValue(value: string): string {\n // Check if the value contains the light/dark separator\n // We need to be careful not to split on / inside functions like oklch()\n const lightDarkParts = splitLightDark(value);\n\n if (lightDarkParts.length === 2) {\n const [lightValue, darkValue] = lightDarkParts;\n return `light-dark(${lightValue!.trim()}, ${darkValue!.trim()})`;\n }\n\n return value;\n}\n\n/**\n * Split a CSS value on the light/dark separator (/).\n * Handles nested parentheses correctly.\n *\n * \"oklch(0.98 0 0) / oklch(0.15 0 0)\" -> [\"oklch(0.98 0 0)\", \"oklch(0.15 0 0)\"]\n * \"oklch(0.5 0.2 250)\" -> [\"oklch(0.5 0.2 250)\"]\n */\nfunction splitLightDark(value: string): string[] {\n let depth = 0;\n let lastSplit = 0;\n const parts: string[] = [];\n\n for (let i = 0; i < value.length; i++) {\n const char = value[i];\n\n if (char === \"(\") {\n depth++;\n } else if (char === \")\") {\n depth--;\n } else if (char === \"/\" && depth === 0) {\n // Check if this is the light/dark separator (surrounded by spaces)\n const before = value[i - 1];\n const after = value[i + 1];\n\n if ((before === \" \" || before === undefined) && (after === \" \" || after === undefined)) {\n parts.push(value.slice(lastSplit, i).trim());\n lastSplit = i + 1;\n }\n }\n }\n\n // Add the remaining part\n const remaining = value.slice(lastSplit).trim();\n if (remaining) {\n parts.push(remaining);\n }\n\n return parts;\n}\n","/**\n * CSS Declaration Expansion\n *\n * Expands CSS shorthand properties into their longhand equivalents.\n * This is important for proper @apply ordering and logical property support.\n */\n\nimport { splitBalanced } from \"./is-valid-arbitrary\";\n\n// Pre-computed Sets for O(1) lookup in helper functions (hoisted to avoid recreation)\nconst BORDER_STYLES = new Set([\n \"none\",\n \"hidden\",\n \"dotted\",\n \"dashed\",\n \"solid\",\n \"double\",\n \"groove\",\n \"ridge\",\n \"inset\",\n \"outset\",\n]);\nconst BORDER_WIDTH_KEYWORDS = new Set([\"thin\", \"medium\", \"thick\"]);\nconst OUTLINE_STYLES = new Set([\n \"auto\",\n \"none\",\n \"dotted\",\n \"dashed\",\n \"solid\",\n \"double\",\n \"groove\",\n \"ridge\",\n \"inset\",\n \"outset\",\n]);\nconst TEXT_DECORATION_LINES = new Set([\"none\", \"underline\", \"overline\", \"line-through\", \"blink\"]);\nconst TEXT_DECORATION_STYLES = new Set([\"solid\", \"double\", \"dotted\", \"dashed\", \"wavy\"]);\n\n/**\n * An expanded CSS declaration (simple property/value pair).\n */\nexport interface ExpandedDeclaration {\n property: string;\n value: string;\n important?: boolean;\n}\n\n/**\n * Shorthand property expansion rules.\n */\ninterface ExpansionRule {\n properties: string[];\n expand: (value: string) => string[];\n}\n\n/**\n * Expand a CSS declaration into longhand properties.\n *\n * @param property - The CSS property\n * @param value - The CSS value\n * @returns Array of expanded declarations, or the original if no expansion needed\n *\n * @example\n * ```ts\n * expandDeclaration(\"margin\", \"10px 20px\")\n * // [\n * // { property: \"margin-top\", value: \"10px\" },\n * // { property: \"margin-right\", value: \"20px\" },\n * // { property: \"margin-bottom\", value: \"10px\" },\n * // { property: \"margin-left\", value: \"20px\" },\n * // ]\n * ```\n */\nexport function expandDeclaration(property: string, value: string): ExpandedDeclaration[] {\n const rule = EXPANSION_RULES[property];\n if (!rule) {\n return [{ property, value }];\n }\n\n const expandedValues = rule.expand(value);\n\n // If expansion failed, return original\n if (expandedValues.length !== rule.properties.length) {\n return [{ property, value }];\n }\n\n return rule.properties.map((prop, i) => ({\n property: prop,\n value: expandedValues[i]!,\n }));\n}\n\n/**\n * Check if a property is a shorthand that can be expanded.\n */\nexport function isShorthand(property: string): boolean {\n return property in EXPANSION_RULES;\n}\n\n/**\n * Get the longhand properties for a shorthand.\n */\nexport function getLonghandProperties(property: string): string[] | null {\n return EXPANSION_RULES[property]?.properties ?? null;\n}\n\n// ============================================\n// Value Parsing Helpers\n// ============================================\n\n/**\n * Split a value by spaces, respecting parentheses.\n */\nfunction splitBySpace(value: string): string[] {\n return splitBalanced(value, \" \").filter(Boolean);\n}\n\n/**\n * Expand box model values (margin, padding, etc.).\n * 1 value: all sides\n * 2 values: vertical | horizontal\n * 3 values: top | horizontal | bottom\n * 4 values: top | right | bottom | left\n */\nfunction expandBoxModel(value: string): string[] {\n const parts = splitBySpace(value);\n\n switch (parts.length) {\n case 1:\n return [parts[0]!, parts[0]!, parts[0]!, parts[0]!];\n case 2:\n return [parts[0]!, parts[1]!, parts[0]!, parts[1]!];\n case 3:\n return [parts[0]!, parts[1]!, parts[2]!, parts[1]!];\n case 4:\n return [parts[0]!, parts[1]!, parts[2]!, parts[3]!];\n default:\n return [];\n }\n}\n\n/**\n * Expand border-radius values.\n * Similar to box model but corners instead of sides.\n * 1 value: all corners\n * 2 values: top-left+bottom-right | top-right+bottom-left\n * 3 values: top-left | top-right+bottom-left | bottom-right\n * 4 values: top-left | top-right | bottom-right | bottom-left\n */\nfunction expandBorderRadius(value: string): string[] {\n // Handle horizontal / vertical syntax\n const slashIndex = value.indexOf(\"/\");\n if (slashIndex !== -1) {\n // Complex border-radius with / - don't expand\n return [];\n }\n\n const parts = splitBySpace(value);\n\n switch (parts.length) {\n case 1:\n return [parts[0]!, parts[0]!, parts[0]!, parts[0]!];\n case 2:\n return [parts[0]!, parts[1]!, parts[0]!, parts[1]!];\n case 3:\n return [parts[0]!, parts[1]!, parts[2]!, parts[1]!];\n case 4:\n return [parts[0]!, parts[1]!, parts[2]!, parts[3]!];\n default:\n return [];\n }\n}\n\n/**\n * Expand border shorthand.\n * border: <width> <style> <color>\n */\nfunction expandBorder(value: string): string[] {\n const parts = splitBySpace(value);\n\n let width = \"medium\";\n let style = \"none\";\n let color = \"currentColor\";\n\n for (const part of parts) {\n if (isBorderStyle(part)) {\n style = part;\n } else if (isBorderWidth(part)) {\n width = part;\n } else {\n color = part;\n }\n }\n\n return [width, style, color];\n}\n\n/**\n * Expand background shorthand.\n * This is complex - for simplicity, we only handle basic cases.\n */\nfunction expandBackground(value: string): string[] {\n // background is extremely complex - for most cases, don't expand\n // Only handle simple single-value cases\n const parts = splitBySpace(value);\n\n if (parts.length === 1) {\n const part = parts[0]!;\n // Single color\n if (\n !part.includes(\"(\") ||\n part.startsWith(\"rgb\") ||\n part.startsWith(\"hsl\") ||\n part.startsWith(\"oklch\") ||\n part.startsWith(\"oklab\") ||\n part.startsWith(\"color\")\n ) {\n return [\"none\", \"0% 0%\", \"auto auto\", \"padding-box\", \"border-box\", part, \"scroll\", \"none\"];\n }\n }\n\n // Don't expand complex backgrounds\n return [];\n}\n\n/**\n * Expand flex shorthand.\n * flex: <grow> <shrink> <basis>\n */\nfunction expandFlex(value: string): string[] {\n const parts = splitBySpace(value);\n\n // Special keywords\n if (parts.length === 1) {\n switch (parts[0]) {\n case \"none\":\n return [\"0\", \"0\", \"auto\"];\n case \"auto\":\n return [\"1\", \"1\", \"auto\"];\n case \"initial\":\n return [\"0\", \"1\", \"auto\"];\n }\n }\n\n // Default values\n let grow = \"1\";\n let shrink = \"1\";\n let basis = \"0%\";\n\n if (parts.length >= 1) {\n grow = parts[0]!;\n }\n if (parts.length >= 2) {\n shrink = parts[1]!;\n }\n if (parts.length >= 3) {\n basis = parts[2]!;\n }\n\n return [grow, shrink, basis];\n}\n\n/**\n * Expand font shorthand.\n * This is very complex - minimal implementation.\n */\nfunction expandFont(_value: string): string[] {\n // font is extremely complex, don't expand\n return [];\n}\n\n/**\n * Expand gap shorthand.\n */\nfunction expandGap(value: string): string[] {\n const parts = splitBySpace(value);\n\n switch (parts.length) {\n case 1:\n return [parts[0]!, parts[0]!];\n case 2:\n return [parts[0]!, parts[1]!];\n default:\n return [];\n }\n}\n\n/**\n * Expand overflow shorthand.\n */\nfunction expandOverflow(value: string): string[] {\n const parts = splitBySpace(value);\n\n switch (parts.length) {\n case 1:\n return [parts[0]!, parts[0]!];\n case 2:\n return [parts[0]!, parts[1]!];\n default:\n return [];\n }\n}\n\n/**\n * Expand inset shorthand.\n */\nfunction expandInset(value: string): string[] {\n return expandBoxModel(value);\n}\n\n/**\n * Expand place-* shorthands.\n */\nfunction expandPlace(value: string): string[] {\n const parts = splitBySpace(value);\n\n switch (parts.length) {\n case 1:\n return [parts[0]!, parts[0]!];\n case 2:\n return [parts[0]!, parts[1]!];\n default:\n return [];\n }\n}\n\n/**\n * Expand outline shorthand.\n */\nfunction expandOutline(value: string): string[] {\n const parts = splitBySpace(value);\n\n let width = \"medium\";\n let style = \"none\";\n let color = \"currentColor\";\n\n for (const part of parts) {\n if (isOutlineStyle(part)) {\n style = part;\n } else if (isBorderWidth(part)) {\n width = part;\n } else {\n color = part;\n }\n }\n\n return [width, style, color];\n}\n\n/**\n * Expand text-decoration shorthand.\n */\nfunction expandTextDecoration(value: string): string[] {\n const parts = splitBySpace(value);\n\n let line = \"none\";\n let style = \"solid\";\n let color = \"currentColor\";\n let thickness = \"auto\";\n\n for (const part of parts) {\n if (isTextDecorationLine(part)) {\n line = part;\n } else if (isTextDecorationStyle(part)) {\n style = part;\n } else if (\n part.endsWith(\"px\") ||\n part.endsWith(\"em\") ||\n part.endsWith(\"%\") ||\n part === \"auto\" ||\n part === \"from-font\"\n ) {\n thickness = part;\n } else {\n color = part;\n }\n }\n\n return [line, color, style, thickness];\n}\n\n/**\n * Expand transition shorthand.\n * Very complex - minimal implementation.\n */\nfunction expandTransition(_value: string): string[] {\n // Don't expand complex transitions\n return [];\n}\n\n/**\n * Expand animation shorthand.\n * Very complex - minimal implementation.\n */\nfunction expandAnimation(_value: string): string[] {\n // Don't expand complex animations\n return [];\n}\n\n// ============================================\n// Helper Functions\n// ============================================\n\nfunction isBorderStyle(value: string): boolean {\n return BORDER_STYLES.has(value);\n}\n\nfunction isBorderWidth(value: string): boolean {\n return BORDER_WIDTH_KEYWORDS.has(value) || /^\\d/.test(value);\n}\n\nfunction isOutlineStyle(value: string): boolean {\n return OUTLINE_STYLES.has(value);\n}\n\nfunction isTextDecorationLine(value: string): boolean {\n return TEXT_DECORATION_LINES.has(value);\n}\n\nfunction isTextDecorationStyle(value: string): boolean {\n return TEXT_DECORATION_STYLES.has(value);\n}\n\n// ============================================\n// Expansion Rules\n// ============================================\n\nconst EXPANSION_RULES: Record<string, ExpansionRule> = {\n margin: {\n properties: [\"margin-top\", \"margin-right\", \"margin-bottom\", \"margin-left\"],\n expand: expandBoxModel,\n },\n padding: {\n properties: [\"padding-top\", \"padding-right\", \"padding-bottom\", \"padding-left\"],\n expand: expandBoxModel,\n },\n \"border-width\": {\n properties: [\"border-top-width\", \"border-right-width\", \"border-bottom-width\", \"border-left-width\"],\n expand: expandBoxModel,\n },\n \"border-style\": {\n properties: [\"border-top-style\", \"border-right-style\", \"border-bottom-style\", \"border-left-style\"],\n expand: expandBoxModel,\n },\n \"border-color\": {\n properties: [\"border-top-color\", \"border-right-color\", \"border-bottom-color\", \"border-left-color\"],\n expand: expandBoxModel,\n },\n \"border-radius\": {\n properties: [\n \"border-top-left-radius\",\n \"border-top-right-radius\",\n \"border-bottom-right-radius\",\n \"border-bottom-left-radius\",\n ],\n expand: expandBorderRadius,\n },\n border: {\n properties: [\"border-width\", \"border-style\", \"border-color\"],\n expand: expandBorder,\n },\n \"border-top\": {\n properties: [\"border-top-width\", \"border-top-style\", \"border-top-color\"],\n expand: expandBorder,\n },\n \"border-right\": {\n properties: [\"border-right-width\", \"border-right-style\", \"border-right-color\"],\n expand: expandBorder,\n },\n \"border-bottom\": {\n properties: [\"border-bottom-width\", \"border-bottom-style\", \"border-bottom-color\"],\n expand: expandBorder,\n },\n \"border-left\": {\n properties: [\"border-left-width\", \"border-left-style\", \"border-left-color\"],\n expand: expandBorder,\n },\n inset: {\n properties: [\"top\", \"right\", \"bottom\", \"left\"],\n expand: expandInset,\n },\n gap: {\n properties: [\"row-gap\", \"column-gap\"],\n expand: expandGap,\n },\n \"grid-gap\": {\n properties: [\"row-gap\", \"column-gap\"],\n expand: expandGap,\n },\n overflow: {\n properties: [\"overflow-x\", \"overflow-y\"],\n expand: expandOverflow,\n },\n \"overscroll-behavior\": {\n properties: [\"overscroll-behavior-x\", \"overscroll-behavior-y\"],\n expand: expandOverflow,\n },\n flex: {\n properties: [\"flex-grow\", \"flex-shrink\", \"flex-basis\"],\n expand: expandFlex,\n },\n background: {\n properties: [\n \"background-image\",\n \"background-position\",\n \"background-size\",\n \"background-origin\",\n \"background-clip\",\n \"background-color\",\n \"background-attachment\",\n \"background-repeat\",\n ],\n expand: expandBackground,\n },\n font: {\n properties: [\n \"font-style\",\n \"font-variant\",\n \"font-weight\",\n \"font-stretch\",\n \"font-size\",\n \"line-height\",\n \"font-family\",\n ],\n expand: expandFont,\n },\n outline: {\n properties: [\"outline-width\", \"outline-style\", \"outline-color\"],\n expand: expandOutline,\n },\n \"text-decoration\": {\n properties: [\n \"text-decoration-line\",\n \"text-decoration-color\",\n \"text-decoration-style\",\n \"text-decoration-thickness\",\n ],\n expand: expandTextDecoration,\n },\n \"place-content\": {\n properties: [\"align-content\", \"justify-content\"],\n expand: expandPlace,\n },\n \"place-items\": {\n properties: [\"align-items\", \"justify-items\"],\n expand: expandPlace,\n },\n \"place-self\": {\n properties: [\"align-self\", \"justify-self\"],\n expand: expandPlace,\n },\n transition: {\n properties: [\"transition-property\", \"transition-duration\", \"transition-timing-function\", \"transition-delay\"],\n expand: expandTransition,\n },\n animation: {\n properties: [\n \"animation-name\",\n \"animation-duration\",\n \"animation-timing-function\",\n \"animation-delay\",\n \"animation-iteration-count\",\n \"animation-direction\",\n \"animation-fill-mode\",\n \"animation-play-state\",\n ],\n expand: expandAnimation,\n },\n // Logical properties (CSS Logical Properties)\n \"margin-inline\": {\n properties: [\"margin-inline-start\", \"margin-inline-end\"],\n expand: (v) => expandGap(v),\n },\n \"margin-block\": {\n properties: [\"margin-block-start\", \"margin-block-end\"],\n expand: (v) => expandGap(v),\n },\n \"padding-inline\": {\n properties: [\"padding-inline-start\", \"padding-inline-end\"],\n expand: (v) => expandGap(v),\n },\n \"padding-block\": {\n properties: [\"padding-block-start\", \"padding-block-end\"],\n expand: (v) => expandGap(v),\n },\n \"inset-inline\": {\n properties: [\"inset-inline-start\", \"inset-inline-end\"],\n expand: (v) => expandGap(v),\n },\n \"inset-block\": {\n properties: [\"inset-block-start\", \"inset-block-end\"],\n expand: (v) => expandGap(v),\n },\n \"border-inline\": {\n properties: [\"border-inline-start\", \"border-inline-end\"],\n expand: (v) => expandGap(v),\n },\n \"border-block\": {\n properties: [\"border-block-start\", \"border-block-end\"],\n expand: (v) => expandGap(v),\n },\n \"border-inline-width\": {\n properties: [\"border-inline-start-width\", \"border-inline-end-width\"],\n expand: (v) => expandGap(v),\n },\n \"border-block-width\": {\n properties: [\"border-block-start-width\", \"border-block-end-width\"],\n expand: (v) => expandGap(v),\n },\n \"border-inline-style\": {\n properties: [\"border-inline-start-style\", \"border-inline-end-style\"],\n expand: (v) => expandGap(v),\n },\n \"border-block-style\": {\n properties: [\"border-block-start-style\", \"border-block-end-style\"],\n expand: (v) => expandGap(v),\n },\n \"border-inline-color\": {\n properties: [\"border-inline-start-color\", \"border-inline-end-color\"],\n expand: (v) => expandGap(v),\n },\n \"border-block-color\": {\n properties: [\"border-block-start-color\", \"border-block-end-color\"],\n expand: (v) => expandGap(v),\n },\n \"scroll-margin\": {\n properties: [\"scroll-margin-top\", \"scroll-margin-right\", \"scroll-margin-bottom\", \"scroll-margin-left\"],\n expand: expandBoxModel,\n },\n \"scroll-margin-inline\": {\n properties: [\"scroll-margin-inline-start\", \"scroll-margin-inline-end\"],\n expand: (v) => expandGap(v),\n },\n \"scroll-margin-block\": {\n properties: [\"scroll-margin-block-start\", \"scroll-margin-block-end\"],\n expand: (v) => expandGap(v),\n },\n \"scroll-padding\": {\n properties: [\"scroll-padding-top\", \"scroll-padding-right\", \"scroll-padding-bottom\", \"scroll-padding-left\"],\n expand: expandBoxModel,\n },\n \"scroll-padding-inline\": {\n properties: [\"scroll-padding-inline-start\", \"scroll-padding-inline-end\"],\n expand: (v) => expandGap(v),\n },\n \"scroll-padding-block\": {\n properties: [\"scroll-padding-block-start\", \"scroll-padding-block-end\"],\n expand: (v) => expandGap(v),\n },\n};\n","/**\n * @apply Directive\n *\n * Processes the @apply directive for utility class composition.\n *\n * @module\n */\n\nimport type { AstNode, AtRule } from \"../../ast\";\nimport { decl, styleRule } from \"../../ast\";\nimport type { Variants } from \"../../variants\";\nimport { compileCandidate, type DesignSystem } from \"../../compile\";\nimport { parseCandidate, type ParseOptions, type Variant } from \"../../candidate\";\n// Import directly from specific utils to avoid pulling in Node.js-only modules\nimport { topologicalSort, CircularDependencyError } from \"../../utils/topological-sort\";\nimport { expandDeclaration, isShorthand } from \"../../utils/expand-declaration\";\nimport { escapeClassName } from \"../../utils/escape\";\nimport {\n ApplyContextError,\n ApplyBlockedError,\n ApplyPrefixError,\n ApplyVariantError,\n ApplyInvalidCandidateError,\n ApplyUnknownUtilityError,\n} from \"./errors\";\n\n// ============================================\n// Constants\n// ============================================\n\n// Pre-computed Set for compound variant roots (hoisted to avoid recreation on every call)\nconst COMPOUND_VARIANT_ROOTS = new Set([\"group\", \"peer\", \"has\", \"in\", \"not\"]);\n\n// ============================================\n// Types\n// ============================================\n\n/**\n * Context for @apply processing.\n */\nexport interface ApplyContext {\n /** Whether we're currently inside a @keyframes rule */\n inKeyframes: boolean;\n /** Stack of parent rule names (for error messages) */\n parentRules: string[];\n}\n\n/**\n * Options for extracting declarations.\n */\nexport interface ExtractOptions {\n /** Expand shorthand properties to their longhand equivalents */\n expandShorthands?: boolean;\n}\n\n// ============================================\n// Processing\n// ============================================\n\n/**\n * Create a default apply context.\n */\nexport function createApplyContext(): ApplyContext {\n return {\n inKeyframes: false,\n parentRules: [],\n };\n}\n\n/**\n * Process @apply directive within a rule.\n *\n * .card {\n * @apply p-4 bg-paper rounded-lg shadow;\n * }\n *\n * Expands utility classes inline with proper dependency ordering.\n *\n * @throws ApplyContextError if @apply is used inside @keyframes\n * @throws ApplyBlockedError if a blocked candidate is referenced\n * @throws ApplyPrefixError if a candidate doesn't have the required prefix\n * @throws CircularDependencyError if circular @apply dependencies are detected\n */\nexport function processApplyDirective(node: AtRule, designSystem: DesignSystem, context?: ApplyContext): AstNode[] {\n // Guard: Block @apply inside @keyframes\n if (context?.inKeyframes) {\n throw new ApplyContextError(\n `@apply cannot be used inside @keyframes. ` + `Found @apply ${node.params} in @keyframes rule.`\n );\n }\n\n const classes = node.params.split(/\\s+/).filter(Boolean);\n\n // Validate all classes before processing\n for (const className of classes) {\n // Check if blocked\n if (designSystem.blockedCandidates.has(className)) {\n throw new ApplyBlockedError(className);\n }\n\n // Check if invalid (from @source not inline)\n if (designSystem.invalidCandidates.has(className)) {\n throw new ApplyInvalidCandidateError(className);\n }\n\n // Check prefix requirement\n if (designSystem.prefix && !designSystem.hasValidPrefix(className)) {\n throw new ApplyPrefixError(className, designSystem.prefix);\n }\n }\n\n // Build dependency information for each class\n const classInfo: Array<{\n className: string;\n deps: string[];\n nodes: AstNode[];\n }> = [];\n\n for (const className of classes) {\n const { nodes, dependencies } = compileApplyClassWithDeps(className, designSystem);\n classInfo.push({\n className,\n deps: dependencies,\n nodes,\n });\n }\n\n // Sort classes topologically (dependencies first)\n try {\n const sorted = topologicalSort(\n classInfo,\n (info) => info.className,\n (info) => info.deps.filter((dep) => classes.includes(dep))\n );\n\n // Collect results in sorted order\n const result: AstNode[] = [];\n for (const info of sorted) {\n result.push(...info.nodes);\n }\n return result;\n } catch (error) {\n if (error instanceof CircularDependencyError) {\n throw new CircularDependencyError(\n error.cycle,\n `Circular @apply dependency detected: ${error.cycle.join(\" → \")}. ` +\n `Classes in @apply cannot depend on each other.`\n );\n }\n throw error;\n }\n}\n\n/**\n * Compile a utility class and extract its dependencies.\n * Dependencies are other utility classes that this class might depend on.\n */\nfunction compileApplyClassWithDeps(\n className: string,\n designSystem: DesignSystem\n): { nodes: AstNode[]; dependencies: string[] } {\n const { utilities, variants, theme } = designSystem;\n\n // Strip prefix if present for utility lookup\n const unprefixedClassName = designSystem.stripPrefix(className);\n\n const parseOptions: ParseOptions = {\n findRoot: (input: string) => utilities.findRoot(input),\n };\n\n const candidates = parseCandidate(unprefixedClassName, parseOptions);\n const result: AstNode[] = [];\n const dependencies: string[] = [];\n\n for (const candidate of candidates) {\n if (candidate.variants.length > 0) {\n const unknownVariants = collectUnknownApplyVariants(candidate.variants, variants);\n if (unknownVariants.length > 0) {\n const list = unknownVariants.map((variant) => `\"${variant}\"`).join(\", \");\n const message =\n `Cannot apply utility class \"${className}\" because the ` +\n `${unknownVariants.length > 1 ? \"variants\" : \"variant\"} ${list} does not exist.`;\n throw new ApplyVariantError(className, unknownVariants, message);\n }\n }\n\n // Compile the utility\n const nodes = compileCandidate(candidate, utilities, variants, theme);\n\n if (nodes && nodes.length > 0) {\n const appliedNodes = convertApplyNodes(nodes, candidate.raw);\n result.push(...appliedNodes);\n // Extract dependencies from @apply declarations within the utility\n dependencies.push(...extractApplyDependencies(appliedNodes));\n } else if (candidate.variants.length > 0) {\n // Has variants but no output - check if base utility exists\n const baseCandidate = { ...candidate, variants: [] };\n const baseNodes = compileCandidate(baseCandidate, utilities, variants, theme);\n if (baseNodes && baseNodes.length > 0) {\n // Base exists, so it's a variant issue.\n // Known variants that produce no output are allowed (variant may not apply to this utility).\n // Unknown variants are already checked earlier, so we don't need to re-check here.\n } else {\n // Base utility doesn't exist\n throw new ApplyUnknownUtilityError(className);\n }\n } else {\n // No variants and no output - unknown utility\n throw new ApplyUnknownUtilityError(className);\n }\n }\n\n return { nodes: result, dependencies };\n}\n\nfunction convertApplyNodes(nodes: AstNode[], rawCandidate: string): AstNode[] {\n const classSelector = `.${escapeClassName(rawCandidate)}`;\n const converted: AstNode[] = [];\n\n for (const node of nodes) {\n if (node.kind === \"rule\") {\n const selector = replaceApplySelector(node.selector, classSelector);\n if (selector === \"&\") {\n converted.push(...node.nodes);\n } else {\n converted.push(styleRule(selector, node.nodes));\n }\n } else {\n converted.push(node);\n }\n }\n\n return converted;\n}\n\nfunction replaceApplySelector(selector: string, classSelector: string): string {\n if (selector.includes(\"&\")) {\n return selector;\n }\n if (selector.includes(classSelector)) {\n return selector.split(classSelector).join(\"&\");\n }\n return selector;\n}\n\nfunction collectUnknownApplyVariants(variantsList: Variant[], registry: Variants): string[] {\n const unknown: string[] = [];\n\n function checkVariant(variant: Variant): void {\n switch (variant.kind) {\n case \"static\": {\n if (!registry.has(variant.root)) {\n unknown.push(variant.root);\n }\n return;\n }\n case \"functional\": {\n if (!registry.has(variant.root)) {\n unknown.push(variant.root);\n }\n return;\n }\n case \"compound\": {\n if (!COMPOUND_VARIANT_ROOTS.has(variant.root)) {\n unknown.push(variant.root);\n }\n checkVariant(variant.variant);\n return;\n }\n case \"arbitrary\":\n return;\n default:\n return;\n }\n }\n\n for (const variant of variantsList) {\n checkVariant(variant);\n }\n\n return Array.from(new Set(unknown));\n}\n\n/**\n * Extract @apply dependencies from compiled nodes.\n * This looks for any @apply directives within the compiled output.\n */\nfunction extractApplyDependencies(nodes: AstNode[]): string[] {\n const deps: string[] = [];\n\n for (const node of nodes) {\n if (node.kind === \"at-rule\" && node.name === \"@apply\") {\n // Extract class names from the @apply params\n const classes = node.params.split(/\\s+/).filter(Boolean);\n deps.push(...classes);\n }\n if (\"nodes\" in node && Array.isArray(node.nodes)) {\n deps.push(...extractApplyDependencies(node.nodes));\n }\n }\n\n return deps;\n}\n\n/**\n * Extract declarations from compiled AST nodes.\n * Handles nested rules and at-rules.\n *\n * @param nodes - The AST nodes to extract from\n * @param options - Extraction options\n */\nexport function extractDeclarations(nodes: AstNode[], options: ExtractOptions = {}): AstNode[] {\n const { expandShorthands = false } = options;\n const result: AstNode[] = [];\n\n for (const node of nodes) {\n if (node.kind === \"declaration\") {\n // Optionally expand shorthand properties\n if (expandShorthands && node.value !== undefined && isShorthand(node.property)) {\n const expanded = expandDeclaration(node.property, node.value);\n for (const exp of expanded) {\n result.push(decl(exp.property, exp.value, node.important));\n }\n } else {\n result.push(node);\n }\n } else if (node.kind === \"rule\" && \"nodes\" in node) {\n // Extract declarations from the rule\n result.push(...extractDeclarations(node.nodes, options));\n } else if (node.kind === \"at-rule\" && \"nodes\" in node) {\n // Keep at-rules (like @media) but extract their contents\n // This allows @apply to work with responsive utilities\n result.push({\n ...node,\n nodes: extractDeclarations(node.nodes, options),\n });\n }\n }\n\n return result;\n}\n","/**\n * @utility Directive\n *\n * Processes the @utility directive for custom utility registration.\n *\n * @module\n */\n\nimport type { AstNode, AtRule } from \"../../ast\";\nimport { decl } from \"../../ast\";\nimport type { DesignSystem } from \"../../compile\";\nimport type { CandidateValue, CandidateModifier } from \"../../candidate\";\nimport { UtilityApplyError } from \"./errors\";\nimport { processApplyDirective } from \"./apply\";\n\n// ============================================\n// Character codes for validation\n// ============================================\n\nconst CHAR_LOWER_A = 97;\nconst CHAR_LOWER_Z = 122;\nconst CHAR_UPPER_A = 65;\nconst CHAR_UPPER_Z = 90;\nconst CHAR_ZERO = 48;\nconst CHAR_NINE = 57;\nconst CHAR_DASH = 45;\nconst CHAR_UNDERSCORE = 95;\nconst CHAR_DOT = 46;\nconst CHAR_SLASH = 47;\nconst CHAR_PERCENT = 37;\n\n/**\n * Pattern for valid utility root: starts with lowercase letter, allows a-z, 0-9, -\n */\nconst UTILITY_ROOT_PATTERN = /^[a-z][a-z0-9-]*/;\n\n// Pre-compiled regex patterns for data type validation (hoisted to avoid recreation on every call)\nconst INTEGER_PATTERN = /^-?\\d+$/;\nconst NUMBER_PATTERN = /^-?\\d*\\.?\\d+$/;\nconst PERCENTAGE_PATTERN = /^-?\\d*\\.?\\d+%$/;\nconst RATIO_PATTERN = /^\\d+\\/\\d+$/;\n\n// Pre-compiled patterns for --value() and --modifier() function processing\nconst VALUE_FN_MATCH_PATTERN = /--value\\(([^)]*)\\)/;\nconst VALUE_FN_REPLACE_PATTERN = /--value\\([^)]*\\)/;\nconst MODIFIER_FN_MATCH_PATTERN = /--modifier\\(([^)]*)\\)/;\nconst MODIFIER_FN_REPLACE_PATTERN = /--modifier\\([^)]*\\)/;\n\n// ============================================\n// Validation\n// ============================================\n\n/**\n * Validate a static utility name (no wildcard).\n *\n * Valid examples:\n * - \"flex\", \"hidden\", \"block\"\n * - \"content-auto\", \"my-utility\"\n * - \"p-1.5\" (dots between digits)\n * - \"w-50%\" (percent at end)\n * - \"text-xs/8\" (slash for modifiers)\n *\n * Invalid examples:\n * - \"123\" (starts with digit)\n * - \"-foo\" (starts with dash)\n * - \"foo-\" (trailing dash with no value)\n * - \"tab-*\" (wildcard - that's functional)\n */\nexport function isValidStaticUtilityName(name: string): boolean {\n if (!name) return false;\n\n // Functional utilities (with *) are not static\n if (name.includes(\"*\")) return false;\n\n const match = UTILITY_ROOT_PATTERN.exec(name);\n if (!match) return false;\n\n let root = match[0];\n let value = name.slice(root.length);\n\n // If parsing stopped before a value segment, shift the last dash segment into the value.\n if (value.length > 0 && value[0] !== \"-\") {\n const lastDash = root.lastIndexOf(\"-\");\n if (lastDash > 0) {\n value = `-${root.slice(lastDash + 1)}${value}`;\n root = root.slice(0, lastDash);\n }\n }\n\n // If there's a trailing dash with no value, it's invalid\n if (value.length === 0 && root.endsWith(\"-\")) {\n return false;\n }\n\n // No value part means it's a valid static utility like \"flex\"\n if (value.length === 0) {\n return true;\n }\n\n // Value part must start with dash\n if (value[0] !== \"-\") {\n return false;\n }\n\n // Validate value part (after the dash)\n const valuePart = value.slice(1);\n let seenSlash = false;\n\n for (let i = 0; i < valuePart.length; i++) {\n const charCode = valuePart.charCodeAt(i);\n\n // Percent only allowed at end, after a digit\n if (charCode === CHAR_PERCENT) {\n if (i !== valuePart.length - 1) return false;\n const prevCode = valuePart.charCodeAt(i - 1);\n if (prevCode < CHAR_ZERO || prevCode > CHAR_NINE) return false;\n continue;\n }\n\n // Slash for modifiers (only one allowed, not at end)\n if (charCode === CHAR_SLASH) {\n if (i === valuePart.length - 1) return false;\n if (seenSlash) return false;\n seenSlash = true;\n continue;\n }\n\n // Dot must be between digits\n if (charCode === CHAR_DOT) {\n if (i === 0 || i === valuePart.length - 1) return false;\n const prevCode = valuePart.charCodeAt(i - 1);\n const nextCode = valuePart.charCodeAt(i + 1);\n if (prevCode < CHAR_ZERO || prevCode > CHAR_NINE) return false;\n if (nextCode < CHAR_ZERO || nextCode > CHAR_NINE) return false;\n continue;\n }\n\n // Allow lowercase letters\n if (charCode >= CHAR_LOWER_A && charCode <= CHAR_LOWER_Z) continue;\n\n // Allow uppercase letters\n if (charCode >= CHAR_UPPER_A && charCode <= CHAR_UPPER_Z) continue;\n\n // Allow digits\n if (charCode >= CHAR_ZERO && charCode <= CHAR_NINE) continue;\n\n // Allow dash and underscore\n if (charCode === CHAR_DASH || charCode === CHAR_UNDERSCORE) continue;\n\n // Any other character is invalid\n return false;\n }\n\n return true;\n}\n\n/**\n * Validate a functional utility name (ends with `-*`).\n *\n * Valid examples:\n * - \"tab-*\", \"bg-*\", \"text-*\"\n * - \"my-custom-*\"\n *\n * Invalid examples:\n * - \"flex\" (no wildcard - that's static)\n * - \"tab*\" (missing dash before asterisk)\n * - \"tab-foo-*\" (value before asterisk)\n * - \"-*\" (no root)\n */\nexport function isValidFunctionalUtilityName(name: string): boolean {\n if (!name) return false;\n\n // Must end with -* exactly\n if (!name.endsWith(\"-*\")) return false;\n\n // Get the base name without the -* suffix\n const baseName = name.slice(0, -2);\n\n // Base name must be valid\n const match = UTILITY_ROOT_PATTERN.exec(baseName);\n if (!match) return false;\n\n // The root must consume the entire base name\n // (no extra value parts like \"tab-foo-*\")\n if (match[0] !== baseName) return false;\n\n // Root cannot end with dash (would result in double dash: \"foo--*\")\n if (baseName.endsWith(\"-\")) return false;\n\n return true;\n}\n\n// ============================================\n// Utility Creation\n// ============================================\n\n/**\n * Create a CSS utility from an @utility at-rule.\n *\n * Returns a registration function that takes the DesignSystem\n * and registers the utility. Returns null if the utility name is invalid.\n *\n * Supports @apply inside @utility blocks for composition:\n * @example\n * // Static utility with @apply\n * @utility card {\n * @apply p-4 rounded-lg;\n * box-shadow: 0 1px 3px rgba(0,0,0,0.1);\n * }\n *\n * // Functional utility\n * @utility tab-* {\n * tab-size: --value(integer);\n * }\n */\nexport function createCssUtility(node: AtRule): ((designSystem: DesignSystem) => void) | null {\n const name = node.params.trim();\n\n if (!name) {\n return null;\n }\n\n // Check for functional utility (ends with -*)\n if (isValidFunctionalUtilityName(name)) {\n return createFunctionalCssUtility(name, node);\n }\n\n // Check for static utility\n if (isValidStaticUtilityName(name)) {\n return createStaticCssUtility(name, node);\n }\n\n return null;\n}\n\n/**\n * Create a static CSS utility.\n *\n * Supports @apply inside the utility body for composition.\n */\nfunction createStaticCssUtility(name: string, node: AtRule): (designSystem: DesignSystem) => void {\n // Extract declarations and @apply nodes from the node\n const extractedDecls: Array<{\n property: string;\n value: string;\n important?: boolean;\n }> = [];\n const applyNodes: AtRule[] = [];\n\n for (const child of node.nodes) {\n if (child.kind === \"declaration\" && child.value !== undefined) {\n extractedDecls.push({\n property: child.property,\n value: child.value,\n important: child.important,\n });\n } else if (child.kind === \"at-rule\" && child.name === \"@apply\") {\n applyNodes.push(child);\n }\n }\n\n return (designSystem: DesignSystem) => {\n const { utilities } = designSystem;\n\n utilities.static(name, () => {\n const result: AstNode[] = [];\n\n // Process @apply nodes first to get their declarations\n for (const applyNode of applyNodes) {\n try {\n const expandedDecls = processApplyDirective(applyNode, designSystem);\n result.push(...expandedDecls);\n } catch (error) {\n // Rethrow as UtilityApplyError with context\n throw new UtilityApplyError(\n name,\n error instanceof Error ? error.message : String(error),\n error instanceof Error ? error : undefined\n );\n }\n }\n\n // Add extracted declarations\n result.push(...extractedDecls.map((d) => decl(d.property, d.value, d.important)));\n\n return result;\n });\n\n // Custom utilities must be discoverable by findRoot() immediately.\n utilities.invalidateTrie();\n };\n}\n\n/**\n * Create a functional CSS utility.\n *\n * Functional utilities support --value() and --modifier() CSS functions\n * for dynamic value resolution. Also supports @apply for composition.\n */\nfunction createFunctionalCssUtility(name: string, node: AtRule): (designSystem: DesignSystem) => void {\n // Strip the -* suffix for registration\n const utilityRoot = name.slice(0, -2);\n\n // Extract declarations and @apply nodes from the node\n const extractedDecls: Array<{\n property: string;\n value: string;\n important?: boolean;\n }> = [];\n const applyNodes: AtRule[] = [];\n\n for (const child of node.nodes) {\n if (child.kind === \"declaration\" && child.value !== undefined) {\n extractedDecls.push({\n property: child.property,\n value: child.value,\n important: child.important,\n });\n } else if (child.kind === \"at-rule\" && child.name === \"@apply\") {\n applyNodes.push(child);\n }\n }\n\n return (designSystem: DesignSystem) => {\n const { utilities } = designSystem;\n\n // Pre-process @apply nodes once (they don't depend on the candidate value)\n const applyDecls: AstNode[] = [];\n for (const applyNode of applyNodes) {\n try {\n const expandedDecls = processApplyDirective(applyNode, designSystem);\n applyDecls.push(...expandedDecls);\n } catch (error) {\n // Rethrow as UtilityApplyError with context\n throw new UtilityApplyError(\n name,\n error instanceof Error ? error.message : String(error),\n error instanceof Error ? error : undefined\n );\n }\n }\n\n utilities.functional(utilityRoot, (candidate) => {\n const candidateValue = candidate.value;\n\n // Functional utilities require a value\n if (!candidateValue) return null;\n\n // Start with @apply declarations\n const resolvedDecls: AstNode[] = [...applyDecls];\n\n // Resolve --value() and --modifier() in declarations\n for (const d of extractedDecls) {\n const resolvedValue = resolveUtilityFunctions(d.value, candidateValue, candidate.modifier);\n\n if (resolvedValue === null) {\n // Resolution failed - this utility doesn't match\n return null;\n }\n\n resolvedDecls.push(decl(d.property, resolvedValue, d.important));\n }\n\n return resolvedDecls;\n });\n\n // Custom utilities must be discoverable by findRoot() immediately.\n utilities.invalidateTrie();\n };\n}\n\n// ============================================\n// Value Resolution\n// ============================================\n\n/**\n * Resolve --value() and --modifier() CSS functions in a value string.\n *\n * @param value - The CSS value string containing --value() or --modifier()\n * @param candidateValue - The value from the candidate (e.g., \"4\" from \"tab-4\")\n * @param candidateModifier - The modifier from the candidate (e.g., \"50\" from \"bg-red-500/50\")\n * @returns The resolved value string, or null if resolution failed\n */\nfunction resolveUtilityFunctions(\n value: string,\n candidateValue: CandidateValue,\n candidateModifier?: CandidateModifier | null\n): string | null {\n let result = value;\n let usedValueFn = false;\n let resolvedValueFn = false;\n let usedModifierFn = false;\n let resolvedModifierFn = false;\n\n // Process --value() function\n const valueMatch = result.match(VALUE_FN_MATCH_PATTERN);\n if (valueMatch) {\n usedValueFn = true;\n const args = valueMatch[1]!.trim();\n const resolved = resolveValueFunction(args, candidateValue);\n\n if (resolved !== null) {\n resolvedValueFn = true;\n result = result.replace(VALUE_FN_REPLACE_PATTERN, resolved);\n }\n }\n\n // Process --modifier() function\n const modifierMatch = result.match(MODIFIER_FN_MATCH_PATTERN);\n if (modifierMatch) {\n usedModifierFn = true;\n\n if (candidateModifier) {\n const args = modifierMatch[1]!.trim();\n const resolved = resolveModifierFunction(args, candidateModifier);\n\n if (resolved !== null) {\n resolvedModifierFn = true;\n result = result.replace(MODIFIER_FN_REPLACE_PATTERN, resolved);\n }\n }\n }\n\n // Validation: --value() used but nothing resolved\n if (usedValueFn && !resolvedValueFn) return null;\n\n // Validation: --modifier() used but nothing resolved\n if (usedModifierFn && !resolvedModifierFn) return null;\n\n // Validation: modifier present but --modifier() not used\n // (This is valid - some utilities don't use modifiers)\n\n return result;\n}\n\n/**\n * Resolve a --value() function call.\n *\n * Supported argument types:\n * - 'literal' - Match exact named value\n * - integer, number, percentage, ratio - Bare value types\n * - [integer], [*] - Arbitrary value types\n * - --color-*, --spacing-* - Theme namespace (not yet fully implemented)\n */\nfunction resolveValueFunction(args: string, candidateValue: CandidateValue): string | null {\n // Parse comma-separated arguments\n const argList = args\n .split(\",\")\n .map((a) => a.trim())\n .filter(Boolean);\n\n // If no args, accept any value\n if (argList.length === 0) {\n return candidateValue.kind === \"arbitrary\" ? candidateValue.value : candidateValue.value;\n }\n\n for (const arg of argList) {\n // Literal: 'revert', \"initial\"\n if ((arg.startsWith(\"'\") && arg.endsWith(\"'\")) || (arg.startsWith('\"') && arg.endsWith('\"'))) {\n const literal = arg.slice(1, -1);\n if (candidateValue.kind === \"named\" && candidateValue.value === literal) {\n return literal;\n }\n continue;\n }\n\n // Arbitrary with type hint: [integer], [*]\n if (arg.startsWith(\"[\") && arg.endsWith(\"]\")) {\n const dataType = arg.slice(1, -1);\n if (candidateValue.kind === \"arbitrary\") {\n // [*] accepts anything\n if (dataType === \"*\") {\n return candidateValue.value;\n }\n // Check data type matches if candidate has one\n if (!candidateValue.dataType || candidateValue.dataType === dataType) {\n if (isValidDataType(candidateValue.value, dataType)) {\n return candidateValue.value;\n }\n }\n }\n continue;\n }\n\n // Theme namespace: --color-*, --spacing-*\n if (arg.startsWith(\"--\")) {\n // Theme resolution would go here\n // For now, just pass through named values\n if (candidateValue.kind === \"named\") {\n return candidateValue.value;\n }\n continue;\n }\n\n // Bare value types: integer, number, percentage, ratio\n if (candidateValue.kind === \"named\") {\n if (isValidDataType(candidateValue.value, arg)) {\n // Handle ratio specially (uses fraction)\n if (arg === \"ratio\" && candidateValue.fraction) {\n return candidateValue.fraction;\n }\n return candidateValue.value;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Resolve a --modifier() function call.\n */\nfunction resolveModifierFunction(args: string, candidateModifier: CandidateModifier): string | null {\n // Parse comma-separated arguments\n const argList = args\n .split(\",\")\n .map((a) => a.trim())\n .filter(Boolean);\n\n // If no args, accept any modifier\n if (argList.length === 0) {\n return candidateModifier.value;\n }\n\n for (const arg of argList) {\n // Literal: 'auto'\n if ((arg.startsWith(\"'\") && arg.endsWith(\"'\")) || (arg.startsWith('\"') && arg.endsWith('\"'))) {\n const literal = arg.slice(1, -1);\n if (candidateModifier.kind === \"named\" && candidateModifier.value === literal) {\n return literal;\n }\n continue;\n }\n\n // Arbitrary with type hint: [integer], [*]\n if (arg.startsWith(\"[\") && arg.endsWith(\"]\")) {\n const dataType = arg.slice(1, -1);\n if (candidateModifier.kind === \"arbitrary\") {\n if (dataType === \"*\") {\n return candidateModifier.value;\n }\n if (isValidDataType(candidateModifier.value, dataType)) {\n return candidateModifier.value;\n }\n }\n continue;\n }\n\n // Bare value types\n if (candidateModifier.kind === \"named\") {\n if (isValidDataType(candidateModifier.value, arg)) {\n return candidateModifier.value;\n }\n }\n }\n\n return null;\n}\n\n/**\n * Check if a value matches a data type.\n */\nfunction isValidDataType(value: string, dataType: string): boolean {\n switch (dataType) {\n case \"integer\":\n return INTEGER_PATTERN.test(value);\n case \"number\":\n return NUMBER_PATTERN.test(value);\n case \"percentage\":\n return PERCENTAGE_PATTERN.test(value);\n case \"ratio\":\n return RATIO_PATTERN.test(value);\n case \"*\":\n return true;\n default:\n return false;\n }\n}\n","/**\n * @variant Directive\n *\n * Processes the @variant and @custom-variant directives for custom variant registration.\n *\n * @module\n */\n\nimport type { AstNode, AtRule, StyleRule } from \"../../ast\";\nimport { atRule, styleRule } from \"../../ast\";\nimport type { Variants } from \"../../variants\";\nimport type { Theme } from \"../../theme\";\nimport type { StaticVariant } from \"../../candidate\";\nimport { segment } from \"../../utils/segment\";\nimport {\n DirectiveNestingError,\n VariantNameError,\n VariantSelectorError,\n VariantParseError,\n VariantSlotError,\n VariantApplicationError,\n} from \"./errors\";\n\n// ============================================\n// Validation\n// ============================================\n\n// Pre-compiled regex patterns for variant name validation (hoisted to avoid recreation on every call)\nconst VARIANT_NAME_PATTERN = /^[a-zA-Z_-][a-zA-Z0-9_-]*$/;\n\n// Pre-compiled pattern for nesting selector replacement (hoisted to avoid recreation on every call)\nconst NESTING_SELECTOR_PATTERN = /&/g;\n\n/**\n * Validate a variant name.\n *\n * - Must start with a letter, underscore, or hyphen\n * - Can contain letters, numbers, underscores, and hyphens\n * - Cannot be empty\n */\nfunction isValidVariantName(name: string): boolean {\n // CSS identifier: must start with letter, underscore, or hyphen (not digit)\n // Followed by letters, digits, underscores, hyphens\n return VARIANT_NAME_PATTERN.test(name);\n}\n\nconst CUSTOM_VARIANT_NAME_REGEX = /^@?[a-z0-9][a-zA-Z0-9_-]*(?<![_-])$/;\n\nfunction isValidCustomVariantName(name: string): boolean {\n return CUSTOM_VARIANT_NAME_REGEX.test(name);\n}\n\n// ============================================\n// Parsing Helpers\n// ============================================\n\nfunction parseCustomVariantParams(params: string): { name: string; selector: string | null } {\n const parts = segment(params.trim(), \" \").filter((part) => part.trim().length > 0);\n const name = parts[0]?.trim() ?? \"\";\n let selector = parts.slice(1).join(\" \").trim();\n\n if (selector.endsWith(\";\")) {\n selector = selector.slice(0, -1).trim();\n }\n\n return { name, selector: selector.length > 0 ? selector : null };\n}\n\nfunction parseAtRuleSelector(selector: string): { name: string; params: string } | null {\n const trimmed = selector.trim();\n if (!trimmed.startsWith(\"@\")) return null;\n\n const body = trimmed.slice(1).trim();\n if (!body) return null;\n\n const firstSpace = body.indexOf(\" \");\n if (firstSpace === -1) {\n return { name: body, params: \"\" };\n }\n\n return {\n name: body.slice(0, firstSpace),\n params: body.slice(firstSpace + 1).trim(),\n };\n}\n\n// ============================================\n// Template Handling\n// ============================================\n\nexport function extractSlotTemplate(nodes: AstNode[]): boolean {\n for (const node of nodes) {\n if (node.kind === \"at-rule\" && node.name === \"@slot\") {\n return true;\n }\n if (\"nodes\" in node && Array.isArray(node.nodes) && extractSlotTemplate(node.nodes)) {\n return true;\n }\n }\n return false;\n}\n\n/**\n * Check if @variant body contains CSS rules (not just @slot).\n * Returns true if there are style rules that are not just @slot placeholders.\n */\nexport function hasVariantCSSContent(nodes: AstNode[]): boolean {\n for (const node of nodes) {\n if (node.kind === \"rule\") {\n // Check if any child is a declaration (actual CSS content)\n for (const child of node.nodes) {\n if (child.kind === \"declaration\") {\n return true;\n }\n // Check for nested rules with declarations\n if (child.kind === \"rule\" && hasVariantCSSContent([child])) {\n return true;\n }\n }\n }\n if (node.kind === \"at-rule\" && node.name !== \"slot\" && node.nodes.length > 0) {\n if (hasVariantCSSContent(node.nodes)) {\n return true;\n }\n }\n }\n return false;\n}\n\nfunction applyCustomVariantTemplate(template: AstNode[], rule: StyleRule): AstNode[] {\n const result: AstNode[] = [];\n\n for (const node of template) {\n if (node.kind === \"at-rule\" && node.name === \"@slot\") {\n result.push(...rule.nodes);\n continue;\n }\n\n if (node.kind === \"rule\") {\n result.push(styleRule(node.selector, applyCustomVariantTemplate(node.nodes, rule)));\n continue;\n }\n\n if (node.kind === \"at-rule\") {\n const childNodes = node.nodes.length > 0 ? applyCustomVariantTemplate(node.nodes, rule) : [];\n result.push(atRule(node.name, node.params, childNodes));\n continue;\n }\n\n result.push({ ...node });\n }\n\n return result;\n}\n\n/**\n * Extract variant template from @slot syntax.\n *\n * @variant foo {\n * .parent:hover & { @slot; }\n * }\n *\n * Returns the selector pattern containing @slot.\n */\nfunction extractVariantTemplate(nodes: AstNode[]): { selector: string } | null {\n for (const node of nodes) {\n if (node.kind === \"rule\") {\n // Check if any child is @slot\n for (const child of node.nodes) {\n if (child.kind === \"at-rule\" && child.name === \"@slot\") {\n return { selector: node.selector };\n }\n }\n // Recursively check nested rules\n const nested = extractVariantTemplate(node.nodes);\n if (nested) {\n return nested;\n }\n }\n }\n return null;\n}\n\n// ============================================\n// @custom-variant Processing\n// ============================================\n\nexport interface CustomVariantOptions {\n isTopLevel: boolean;\n customVariants: Map<string, (variants: Variants, order: number) => void>;\n customVariantDependencies: Map<string, Set<string>>;\n customVariantOrders: Map<string, number>;\n getNextOrder: () => number;\n}\n\nexport function processCustomVariantDirective(node: AtRule, variants: Variants, options: CustomVariantOptions): void {\n if (!options.isTopLevel) {\n throw new DirectiveNestingError(\"custom-variant\");\n }\n\n const { name, selector } = parseCustomVariantParams(node.params);\n\n if (!name || !isValidCustomVariantName(name)) {\n throw new Error(\n `\\`@custom-variant ${name}\\` defines an invalid variant name. ` +\n `Variants should only contain alphanumeric, dashes, or underscore characters and start with a lowercase letter or number.`\n );\n }\n\n if (node.nodes.length > 0 && selector) {\n throw new Error(`\\`@custom-variant ${name}\\` cannot have both a selector and a body.`);\n }\n\n if (node.nodes.length === 0) {\n if (!selector) {\n throw new Error(`\\`@custom-variant ${name}\\` has no selector or body.`);\n }\n\n if (!selector.startsWith(\"(\") || !selector.endsWith(\")\")) {\n throw new Error(`\\`@custom-variant ${name} ${selector}\\` selector is invalid.`);\n }\n\n const selectors = segment(selector.slice(1, -1), \",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n if (selectors.length === 0 || selectors.some((s) => s.length === 0)) {\n throw new Error(`\\`@custom-variant ${name} (${selectors.join(\",\")})\\` selector is invalid.`);\n }\n\n const styleSelectors: string[] = [];\n const atRuleSelectors: Array<{ name: string; params: string }> = [];\n\n for (const entry of selectors) {\n const parsedAtRule = parseAtRuleSelector(entry);\n if (parsedAtRule) {\n atRuleSelectors.push(parsedAtRule);\n continue;\n }\n styleSelectors.push(entry);\n }\n\n if (styleSelectors.length > 0) {\n const invalid = styleSelectors.find((s) => !s.includes(\"&\"));\n if (invalid) {\n throw new VariantSelectorError(\n name,\n invalid,\n `Selectors must include the \"&\" placeholder to indicate where the original selector should be inserted.`\n );\n }\n }\n\n // Capture the order when first encountering this variant\n const order = options.getNextOrder();\n options.customVariantOrders.set(name, order);\n\n options.customVariants.set(name, (variantsInstance, registrationOrder) => {\n variantsInstance.static(\n name,\n (rule) => {\n if (styleSelectors.length > 0) {\n rule.selector = styleSelectors\n .map((sel) => sel.replace(NESTING_SELECTOR_PATTERN, rule.selector))\n .join(\", \");\n }\n\n if (atRuleSelectors.length > 0) {\n const baseNodes = rule.nodes;\n rule.nodes = atRuleSelectors.map((entry) => atRule(entry.name, entry.params, baseNodes));\n }\n },\n { order: registrationOrder }\n );\n });\n\n options.customVariantDependencies.set(name, new Set());\n return;\n }\n\n const dependencies = new Set<string>();\n for (const child of node.nodes) {\n if (child.kind === \"at-rule\" && child.name === \"@variant\") {\n const dep = child.params.trim();\n if (dep.length > 0) {\n dependencies.add(dep);\n }\n }\n }\n\n if (!extractSlotTemplate(node.nodes)) {\n throw new Error(`\\`@custom-variant ${name}\\` must include @slot to mark where styles should be placed.`);\n }\n\n // Capture the order when first encountering this variant\n const order = options.getNextOrder();\n options.customVariantOrders.set(name, order);\n\n options.customVariants.set(name, (variantsInstance, registrationOrder) => {\n variantsInstance.static(\n name,\n (rule) => {\n rule.nodes = applyCustomVariantTemplate(node.nodes, rule);\n },\n { order: registrationOrder }\n );\n });\n options.customVariantDependencies.set(name, dependencies);\n}\n\n// ============================================\n// @variant Processing\n// ============================================\n\n/**\n * Process @variant or @custom-variant directive.\n *\n * Supports three syntaxes:\n *\n * 1. Block syntax with selectors:\n * @variant hocus (&:hover, &:focus) {\n * // styles\n * }\n *\n * 2. Body-less syntax (shorthand):\n * @variant hocus (&:hover, &:focus);\n *\n * 3. Block syntax with @slot:\n * @variant grouped {\n * .group:hover & { @slot; }\n * }\n *\n * Registers a custom variant.\n *\n * @throws VariantNameError if the variant name is invalid\n * @throws VariantSelectorError if selectors don't contain & placeholder\n */\nexport function processVariantDirective(node: AtRule, variants: Variants): void {\n const params = node.params.trim();\n\n // Body-less syntax: @variant name (selectors);\n // e.g., @variant hocus (&:hover, &:focus);\n const bodylessMatch = params.match(/^(\\S+)\\s*\\(([^)]+)\\);?$/);\n\n if (bodylessMatch && node.nodes.length === 0) {\n const name = bodylessMatch[1]!;\n const selectorsStr = bodylessMatch[2]!;\n const selectors = selectorsStr\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n // Validate variant name\n if (!isValidVariantName(name)) {\n throw new VariantNameError(\n name,\n `Variant names must start with a letter, underscore, or hyphen, ` +\n `followed by letters, digits, underscores, or hyphens.`\n );\n }\n\n // Validate that at least one selector has & placeholder\n const validSelectors = selectors.filter((s) => s.includes(\"&\"));\n if (validSelectors.length === 0) {\n throw new VariantSelectorError(\n name,\n selectors[0] ?? \"\",\n `Selectors must include the \"&\" placeholder to indicate where the ` +\n `original selector should be inserted.`\n );\n }\n\n // Register variant with all valid selectors (not just first)\n variants.static(name, (rule) => {\n // Apply first selector - for multiple selectors, use comma-separated result\n if (validSelectors.length === 1) {\n rule.selector = validSelectors[0]!.replace(NESTING_SELECTOR_PATTERN, rule.selector);\n } else {\n // Join multiple selectors with commas\n rule.selector = validSelectors\n .map((sel) => sel.replace(NESTING_SELECTOR_PATTERN, rule.selector))\n .join(\", \");\n }\n });\n return;\n }\n\n // Block syntax with @slot\n if (node.nodes.length > 0) {\n const nameMatch = params.match(/^(\\S+)$/);\n if (nameMatch) {\n const name = nameMatch[1]!;\n\n // Validate variant name\n if (!isValidVariantName(name)) {\n throw new VariantNameError(\n name,\n `Variant names must start with a letter, underscore, or hyphen, ` +\n `followed by letters, digits, underscores, or hyphens.`\n );\n }\n\n // Check for @slot inside the body\n const template = extractVariantTemplate(node.nodes);\n\n if (template) {\n // Validate that the template selector has & placeholder\n if (!template.selector.includes(\"&\")) {\n throw new VariantSelectorError(\n name,\n template.selector,\n `The rule containing @slot must include the \"&\" placeholder.`\n );\n }\n\n variants.static(name, (rule) => {\n rule.selector = template.selector.replace(NESTING_SELECTOR_PATTERN, rule.selector);\n });\n return;\n }\n\n // No @slot found - throw explicit error\n throw new VariantSlotError(name);\n }\n }\n\n // Traditional block syntax: @variant name (selectors) { ... }\n const match = params.match(/^(\\S+)\\s*\\(([^)]+)\\)$/);\n\n if (!match) {\n throw new VariantParseError(params);\n }\n\n const name = match[1]!;\n const selectorsStr = match[2]!;\n\n // Validate variant name\n if (!isValidVariantName(name)) {\n throw new VariantNameError(\n name,\n `Variant names must start with a letter, underscore, or hyphen, ` +\n `followed by letters, digits, underscores, or hyphens.`\n );\n }\n\n const selectors = selectorsStr\n .split(\",\")\n .map((s) => s.trim())\n .filter(Boolean);\n\n // Validate selectors\n const validSelectors = selectors.filter((s) => s.includes(\"&\"));\n if (validSelectors.length === 0) {\n throw new VariantSelectorError(name, selectors[0] ?? \"\", `Selectors must include the \"&\" placeholder.`);\n }\n\n // Register the variant with all valid selectors\n variants.static(name, (rule) => {\n if (validSelectors.length === 1) {\n rule.selector = validSelectors[0]!.replace(NESTING_SELECTOR_PATTERN, rule.selector);\n } else {\n rule.selector = validSelectors\n .map((sel) => sel.replace(NESTING_SELECTOR_PATTERN, rule.selector))\n .join(\", \");\n }\n });\n}\n\n// ============================================\n// Variant Application\n// ============================================\n\n/**\n * Substitute @variant directive by applying a variant to CSS content.\n *\n * @variant dark {\n * .card {\n * background: black;\n * color: white;\n * }\n * }\n *\n * Transforms the CSS rules by applying the variant's selector transformation.\n *\n * @throws VariantApplicationError if the variant does not exist\n */\nexport function substituteAtVariant(\n variantName: string,\n nodes: AstNode[],\n variants: Variants,\n theme: Theme\n): AstNode[] {\n // Check if variant exists\n if (!variants.has(variantName)) {\n throw new VariantApplicationError(variantName);\n }\n\n // Create a static variant object for the apply method\n const variant: StaticVariant = {\n kind: \"static\",\n root: variantName,\n };\n\n const result: AstNode[] = [];\n\n for (const node of nodes) {\n if (node.kind === \"rule\") {\n // Create a style rule for the variant to transform\n const inputRule = styleRule(node.selector, [...node.nodes]);\n\n // Apply the variant transformation\n const transformed = variants.apply(inputRule, variant, theme);\n\n if (transformed) {\n result.push(...transformed);\n }\n } else if (node.kind === \"at-rule\") {\n // Recursively process nested at-rules\n if (node.nodes.length > 0) {\n const transformedNodes = substituteAtVariant(variantName, node.nodes, variants, theme);\n result.push(atRule(node.name, node.params, transformedNodes));\n } else {\n result.push(node);\n }\n } else {\n // Pass through other nodes (comments, declarations)\n result.push(node);\n }\n }\n\n return result;\n}\n","/**\n * @color Directive\n *\n * Processes the @color directive for automatic color palette generation.\n *\n * @module\n */\n\nimport type { AtRule } from \"../../ast\";\nimport type { Theme } from \"../../theme\";\nimport { loadPalette, type PaletteLDParams } from \"../../theme/defaults\";\nimport { ColorError } from \"./errors\";\n\n// ============================================\n// Types\n// ============================================\n\n/**\n * Parsed options from @color params.\n */\nexport interface ParsedColorOptions {\n /** Scale name (will generate --color-{name}-{step} variables) */\n name: string;\n}\n\n// ============================================\n// Parsing\n// ============================================\n\n/**\n * Parse @color options from params.\n *\n * @color primary { ... }\n */\nexport function parseColorOptions(params: string): ParsedColorOptions {\n const tokens = params.trim().split(/\\s+/).filter(Boolean);\n const name = tokens[0] ?? \"\";\n\n return { name };\n}\n\n// ============================================\n// Validation\n// ============================================\n\n// Pre-compiled pattern for color name validation (hoisted to avoid recreation on every call)\nconst COLOR_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]*$/;\n\n/**\n * Validate color name is a valid CSS identifier.\n * Must start with a letter, then letters/numbers/hyphens/underscores.\n */\nexport function isValidColorName(name: string): boolean {\n return name.length > 0 && COLOR_NAME_PATTERN.test(name);\n}\n\n// ============================================\n// Processing\n// ============================================\n\n/**\n * Process @color directive.\n *\n * @color primary {\n * hue: 220;\n * chroma: 0.8;\n * }\n *\n * @color brand {\n * hue: 280;\n * chroma: 0.7;\n * kDark: 0.8;\n * }\n *\n * Generates a 19-step color scale (50-950) using OKLch color space.\n * Outputs light-dark() values for automatic dark mode.\n */\nexport function processColorDirective(node: AtRule, theme: Theme): void {\n const opts = parseColorOptions(node.params);\n\n // Validate name\n if (!isValidColorName(opts.name)) {\n throw new ColorError(\n \"name\",\n opts.name || \"(empty)\",\n \"Name must be a valid CSS identifier (start with letter, contain letters/numbers/hyphens/underscores).\"\n );\n }\n\n // Parse declarations to get parameters\n let hue: number | undefined;\n let chroma: number | undefined;\n let kDark: number | undefined;\n let a: number | undefined;\n let chromaShape: \"bell\" | \"flat\" | undefined;\n\n for (const child of node.nodes) {\n if (child.kind === \"declaration\") {\n const prop = child.property.toLowerCase();\n const value = child.value;\n\n if (value === undefined) continue;\n\n switch (prop) {\n case \"hue\": {\n const num = parseFloat(value);\n if (!Number.isFinite(num) || num < 0 || num > 360) {\n throw new ColorError(\"hue\", value, \"Hue must be a finite number between 0 and 360.\");\n }\n hue = num;\n break;\n }\n case \"chroma\":\n case \"intensity\": {\n const num = parseFloat(value);\n if (!Number.isFinite(num) || num < 0 || num > 1) {\n throw new ColorError(prop, value, \"Chroma/intensity must be a finite number between 0 and 1.\");\n }\n chroma = num;\n break;\n }\n case \"kdark\":\n case \"k-dark\": {\n const num = parseFloat(value);\n if (!Number.isFinite(num) || num < 0 || num > 1) {\n throw new ColorError(\"kDark\", value, \"kDark must be a finite number between 0 and 1.\");\n }\n kDark = num;\n break;\n }\n case \"a\": {\n const num = parseFloat(value);\n if (!Number.isFinite(num) || num < 0 || num > 1) {\n throw new ColorError(\"a\", value, \"Parameter 'a' must be a finite number between 0 and 1.\");\n }\n a = num;\n break;\n }\n case \"chromashape\":\n case \"chroma-shape\": {\n const normalized = value.toLowerCase();\n if (normalized !== \"bell\" && normalized !== \"flat\") {\n throw new ColorError(\"chromaShape\", value, \"chromaShape must be 'bell' or 'flat'.\");\n }\n chromaShape = normalized as \"bell\" | \"flat\";\n break;\n }\n }\n }\n }\n\n // Validate required parameters\n if (hue === undefined) {\n throw new ColorError(\"hue\", \"(missing)\", \"hue is required.\");\n }\n if (chroma === undefined) {\n throw new ColorError(\"chroma\", \"(missing)\", \"chroma is required.\");\n }\n\n // Build params for the generator\n const params: PaletteLDParams = {\n name: opts.name,\n hue,\n intensity: chroma,\n };\n\n if (kDark !== undefined) params.kDark = kDark;\n if (a !== undefined) params.a = a;\n if (chromaShape !== undefined) params.chromaShape = chromaShape;\n\n // Generate the color scale\n loadPalette(theme, params);\n}\n","/**\n * @import Directive\n *\n * Processes @import and @reference directives with enhanced layer/supports/media support.\n *\n * @module\n */\n\nimport type { AtRule } from \"../../ast\";\nimport { atRule } from \"../../ast\";\nimport { ImportOrderError } from \"./errors\";\n\n// Pre-compiled pattern for supports() detection (hoisted to avoid recreation in loops)\nconst SUPPORTS_START_PATTERN = /^\\s*supports\\s*\\(/i;\n\n// ============================================\n// Types\n// ============================================\n\nexport interface ImportOptions {\n /** Import path */\n path: string;\n /** Whether this is a reference-only import (no output) */\n reference: boolean;\n /** Whether to apply global !important to all utilities */\n important?: boolean;\n /** Media query for the import */\n media?: string;\n /** Layer name for the import */\n layer?: string;\n /** Supports condition for the import */\n supports?: string;\n /** Whether url() syntax was used (should be preserved, not inlined) */\n urlSyntax?: boolean;\n}\n\n// ============================================\n// Parsing Helpers\n// ============================================\n\n/**\n * Extract content from balanced parentheses starting at a given position.\n * Returns the content inside the parentheses and the end position.\n * Properly handles quoted strings to avoid counting parentheses inside quotes.\n */\nfunction extractBalancedParensAt(str: string, start: number): { content: string; end: number } | null {\n let depth = 1;\n let pos = start + 1;\n let inQuote: string | null = null;\n\n while (pos < str.length && depth > 0) {\n const char = str[pos]!;\n\n // Handle escape sequences\n if (char === \"\\\\\") {\n pos += 2;\n continue;\n }\n\n // Handle quotes - toggle in/out of quoted string\n if (char === '\"' || char === \"'\") {\n if (inQuote === null) {\n inQuote = char;\n } else if (inQuote === char) {\n inQuote = null;\n }\n pos++;\n continue;\n }\n\n // Skip parentheses handling inside quoted strings\n if (inQuote !== null) {\n pos++;\n continue;\n }\n\n if (char === \"(\") depth++;\n else if (char === \")\") depth--;\n pos++;\n }\n\n if (depth !== 0) return null;\n\n return {\n content: str.slice(start + 1, pos - 1),\n end: pos,\n };\n}\n\n/**\n * Remove all occurrences of a function call (e.g., theme(...), layer(...))\n * using proper balanced parentheses matching.\n * This avoids regex backtracking issues and correctly handles nested parens and quotes.\n */\nfunction removeFunctionCalls(str: string, funcName: string): string {\n let result = str;\n // Match function name with optional whitespace before paren, case-insensitive\n const funcPattern = new RegExp(`${funcName}\\\\s*\\\\(`, \"gi\");\n\n let match;\n // Process from the end to avoid offset issues after replacements\n const matches: Array<{ start: number; funcEnd: number }> = [];\n while ((match = funcPattern.exec(str)) !== null) {\n matches.push({ start: match.index, funcEnd: match.index + match[0].length });\n }\n\n // Process in reverse order\n for (let i = matches.length - 1; i >= 0; i--) {\n const { start, funcEnd } = matches[i]!;\n // Find the position of the opening paren\n const parenStart = funcEnd - 1;\n const extracted = extractBalancedParensAt(result, parenStart);\n if (extracted) {\n // Remove the entire function call\n result = result.slice(0, start) + result.slice(extracted.end);\n }\n }\n\n return result;\n}\n\n/**\n * Check if a string matches a pattern of repeated supports() calls only.\n * Uses balanced parentheses matching for correctness.\n */\nfunction isOnlySupportsPattern(str: string): boolean {\n let remaining = str.trim();\n if (!remaining) return true;\n\n while (remaining.length > 0) {\n // Match \"supports\" followed by optional whitespace and opening paren\n const supportsMatch = remaining.match(SUPPORTS_START_PATTERN);\n if (!supportsMatch) {\n // If there's non-whitespace content that isn't supports(), return false\n return remaining.trim().length === 0;\n }\n\n // Find the opening paren position\n const parenStart = remaining.indexOf(\"(\", supportsMatch.index!);\n const extracted = extractBalancedParensAt(remaining, parenStart);\n if (!extracted) return false;\n\n // Move past this supports() call\n remaining = remaining.slice(extracted.end).trim();\n }\n\n return true;\n}\n\n// ============================================\n// Processing\n// ============================================\n\n/**\n * Parse @import params with layer(), supports(), and reference support.\n *\n * @import \"./tokens.css\" reference;\n * @import \"./styles.css\" screen;\n * @import \"./other.css\" reference screen;\n * @import \"./utils.css\" layer(utilities);\n * @import \"./modern.css\" layer(utilities) supports(display: grid);\n * @import \"./modern.css\" layer(utilities) supports(display: grid) screen;\n * @import \"tailwindcss\" theme(reference);\n */\nexport function parseImportParams(params: string): ImportOptions {\n // Extract the path (quoted string or url())\n let path = \"\";\n let rest = params;\n let urlSyntax = false;\n\n // Check for url() syntax\n if (params.startsWith(\"url(\")) {\n // Find the content inside url() - handle quoted or unquoted\n const urlStart = 4; // after \"url(\"\n const quoteChar = params[urlStart];\n\n if (quoteChar === '\"' || quoteChar === \"'\") {\n // Quoted URL - find matching closing quote\n let pos = urlStart + 1;\n while (pos < params.length) {\n if (params[pos] === \"\\\\\") {\n pos += 2;\n continue;\n }\n if (params[pos] === quoteChar) {\n path = params.slice(urlStart + 1, pos);\n // Skip past quote and closing paren\n if (params[pos + 1] === \")\") {\n rest = params.slice(pos + 2).trim();\n urlSyntax = true;\n }\n break;\n }\n pos++;\n }\n } else {\n // Unquoted URL - stop at closing paren\n const closeIdx = params.indexOf(\")\", urlStart);\n if (closeIdx !== -1) {\n path = params.slice(urlStart, closeIdx).trim();\n rest = params.slice(closeIdx + 1).trim();\n urlSyntax = true;\n }\n }\n } else {\n // Check for quoted string\n const quoteChar = params[0];\n if (quoteChar === '\"' || quoteChar === \"'\") {\n let pos = 1;\n while (pos < params.length) {\n if (params[pos] === \"\\\\\") {\n pos += 2;\n continue;\n }\n if (params[pos] === quoteChar) {\n path = params.slice(1, pos);\n rest = params.slice(pos + 1).trim();\n break;\n }\n pos++;\n }\n }\n }\n\n if (!path) {\n return { path: \"\", reference: false };\n }\n\n let reference = false;\n let important = false;\n let layer: string | undefined;\n let supports: string | undefined;\n\n // Parse the rest of the params\n let remaining = rest;\n\n // Check for standalone \"reference\" keyword (not inside theme(...) or other functions)\n // We match \"reference\" only when it's not preceded by an open paren or followed by a close paren\n // This ensures theme(reference) doesn't trigger reference mode\n const standaloneRefMatch = remaining.match(/(?<![a-zA-Z(])reference(?!\\s*\\))/i);\n if (standaloneRefMatch) {\n reference = true;\n remaining = remaining.replace(/(?<![a-zA-Z(])reference(?!\\s*\\))/i, \"\").trim();\n }\n\n // Check for standalone \"important\" keyword\n // This sets designSystem.important to apply !important to all utilities\n const standaloneImportantMatch = remaining.match(/(?<![a-zA-Z(])important(?!\\s*\\))/i);\n if (standaloneImportantMatch) {\n important = true;\n remaining = remaining.replace(/(?<![a-zA-Z(])important(?!\\s*\\))/i, \"\").trim();\n }\n\n // Find positions for ordering validation\n const layerIndex = remaining.search(/layer\\s*\\(/);\n const supportsIndex = remaining.search(/supports\\s*\\(/);\n\n // Extract layer() with balanced parentheses\n const layerStartMatch = remaining.match(/layer\\s*\\(/);\n if (layerStartMatch) {\n const parenStart = remaining.indexOf(\"(\", layerStartMatch.index!);\n const result = extractBalancedParensAt(remaining, parenStart);\n if (result) {\n layer = result.content.trim() || undefined;\n remaining = remaining.slice(0, layerStartMatch.index!) + remaining.slice(result.end);\n remaining = remaining.trim();\n }\n }\n\n // Extract supports() with balanced parentheses (handles nested parens)\n const supportsStartMatch = remaining.match(/supports\\s*\\(/);\n if (supportsStartMatch) {\n const parenStart = remaining.indexOf(\"(\", supportsStartMatch.index!);\n const result = extractBalancedParensAt(remaining, parenStart);\n if (result) {\n supports = result.content.trim();\n remaining = remaining.slice(0, supportsStartMatch.index!) + remaining.slice(result.end);\n remaining = remaining.trim();\n }\n }\n\n // Remaining is the media query (may include theme(...) etc)\n const media = remaining.trim() || undefined;\n\n // Validate ordering: if layer() appears after supports(), that's an error\n if (layerIndex !== -1 && supportsIndex !== -1 && layerIndex > supportsIndex) {\n throw new ImportOrderError(path, \"`layer()` must appear before `supports()`.\");\n }\n\n // Validate ordering: if layer() appears after any media content\n // We check this by seeing if there was non-whitespace before layer()\n if (layerIndex !== -1 && media) {\n // Remove theme(), reference, and supports() from consideration\n // Using balanced parentheses matching to avoid regex backtracking issues\n let beforeLayer = rest.slice(0, layerIndex).replace(/(?<![a-zA-Z(])reference(?!\\s*\\))/gi, \"\");\n beforeLayer = removeFunctionCalls(beforeLayer, \"theme\");\n beforeLayer = beforeLayer.trim();\n if (!isOnlySupportsPattern(beforeLayer)) {\n throw new ImportOrderError(path, \"`layer()` must appear before media query.\");\n }\n }\n\n // Validate ordering: if supports() appears after media content\n if (supportsIndex !== -1 && media) {\n // Using balanced parentheses matching to avoid regex backtracking issues\n let beforeSupports = rest.slice(0, supportsIndex).replace(/(?<![a-zA-Z(])reference(?!\\s*\\))/gi, \"\");\n beforeSupports = removeFunctionCalls(beforeSupports, \"layer\");\n beforeSupports = removeFunctionCalls(beforeSupports, \"theme\");\n beforeSupports = beforeSupports.trim();\n if (beforeSupports) {\n throw new ImportOrderError(path, \"`supports()` must appear before media query.\");\n }\n }\n\n return {\n path,\n reference,\n important,\n layer,\n supports,\n media,\n urlSyntax,\n };\n}\n\n/**\n * Parse @reference params (path only).\n *\n * @reference \"./tokens.css\";\n * @reference url(\"./tokens.css\");\n */\nexport function parseReferenceParams(params: string): ImportOptions {\n const parsed = parseImportParams(`${params} reference`);\n return {\n path: parsed.path,\n reference: true,\n important: parsed.important,\n layer: parsed.layer,\n supports: parsed.supports,\n media: parsed.media,\n };\n}\n\n/**\n * Generate an @import rule with layer/supports/media.\n */\nexport function generateImportRule(options: ImportOptions): AtRule {\n let params = `\"${options.path}\"`;\n\n if (options.layer !== undefined) {\n params += ` layer(${options.layer})`;\n }\n\n if (options.supports) {\n params += ` supports(${options.supports})`;\n }\n\n if (options.media) {\n params += ` ${options.media}`;\n }\n\n return atRule(\"import\", params, []);\n}\n","/**\n * @font Directive\n *\n * Processes the @font directive for web font loading configuration.\n *\n * @module\n */\n\nimport type { AtRule } from \"../../ast\";\nimport { FontDirectiveError } from \"./errors\";\n\n// ============================================\n// Types\n// ============================================\n\n/**\n * Options for @font directive.\n */\nexport interface FontDirectiveOptions {\n /** Specific weights to include */\n weights?: number[];\n /** Include italic variants */\n italic?: boolean;\n /** Force variable or static font mode */\n variable?: boolean;\n /** Font display strategy */\n display?: \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n /** Hosting mode: cdn (default) or self */\n host?: \"cdn\" | \"self\";\n /** URL path for self-hosted fonts */\n path?: string;\n /** Set theme font family (sans, serif, mono) */\n set?: \"sans\" | \"serif\" | \"mono\";\n}\n\n/**\n * Parsed @font directive.\n */\nexport interface FontDirective {\n /** Font family name */\n family: string;\n /** Provider (currently only \"google\") */\n provider: \"google\";\n /** Font options */\n options: FontDirectiveOptions;\n}\n\n// ============================================\n// Processing\n// ============================================\n\n/**\n * Parse @font directive.\n *\n * @font \"Inter\" from google;\n * @font \"Roboto\" from google {\n * weights: 400, 500, 700;\n * italic: true;\n * display: swap;\n * }\n * @font \"Fira Code\" from google {\n * host: self;\n * path: \"/fonts\";\n * }\n */\nexport function processFontDirective(node: AtRule): FontDirective {\n const params = node.params.trim();\n\n // Parse: \"Family Name\" from provider\n const match = params.match(/^[\"']([^\"']+)[\"']\\s+from\\s+(\\S+)/);\n if (!match) {\n throw new FontDirectiveError(\"syntax\", params, 'Expected format: @font \"Font Name\" from google');\n }\n\n const family = match[1]!;\n const provider = match[2]!.toLowerCase();\n\n // Validate provider\n if (provider !== \"google\") {\n throw new FontDirectiveError(\"provider\", provider, 'Only \"google\" provider is currently supported');\n }\n\n // Parse body for options\n const options: FontDirectiveOptions = {};\n\n if (node.nodes && node.nodes.length > 0) {\n for (const child of node.nodes) {\n if (child.kind === \"declaration\") {\n const prop = child.property.toLowerCase();\n const value = child.value;\n\n if (value === undefined) continue;\n\n switch (prop) {\n case \"weights\": {\n const weights = value.split(\",\").map((w) => parseInt(w.trim(), 10));\n for (const w of weights) {\n if (isNaN(w) || w < 100 || w > 900 || w % 100 !== 0) {\n throw new FontDirectiveError(\n \"weights\",\n value,\n \"Weights must be multiples of 100 from 100-900\"\n );\n }\n }\n options.weights = weights;\n break;\n }\n case \"italic\": {\n options.italic = value.toLowerCase() === \"true\";\n break;\n }\n case \"variable\": {\n options.variable = value.toLowerCase() === \"true\";\n break;\n }\n case \"display\": {\n const valid = [\"auto\", \"block\", \"swap\", \"fallback\", \"optional\"];\n if (!valid.includes(value)) {\n throw new FontDirectiveError(\"display\", value, `Valid values: ${valid.join(\", \")}`);\n }\n options.display = value as FontDirectiveOptions[\"display\"];\n break;\n }\n case \"host\": {\n const validHosts = [\"cdn\", \"self\"];\n if (!validHosts.includes(value)) {\n throw new FontDirectiveError(\"host\", value, `Valid values: ${validHosts.join(\", \")}`);\n }\n options.host = value as \"cdn\" | \"self\";\n break;\n }\n case \"path\": {\n // Remove quotes if present\n options.path = value.replace(/^[\"']|[\"']$/g, \"\");\n break;\n }\n case \"set\": {\n const normalized = value.replace(/^[\"']|[\"']$/g, \"\").toLowerCase();\n const valid = [\"sans\", \"serif\", \"mono\"];\n if (!valid.includes(normalized)) {\n throw new FontDirectiveError(\"set\", value, `Valid values: ${valid.join(\", \")}`);\n }\n options.set = normalized as FontDirectiveOptions[\"set\"];\n break;\n }\n }\n }\n }\n }\n\n return {\n family,\n provider: \"google\",\n options,\n };\n}\n","/**\n * Utility Injection\n *\n * Functions for injecting compiled utilities into the AST and cleaning up\n * internal nodes after processing.\n *\n * @module\n */\n\nimport type { AstNode } from \"../../ast\";\n\n// ============================================\n// Utility Node Cleanup\n// ============================================\n\n/**\n * Remove @utility nodes from AST.\n *\n * Call this AFTER @apply processing to clean up @utility nodes that were\n * kept for dependency resolution.\n */\nexport function removeUtilityNodes(ast: AstNode[]): AstNode[] {\n const result: AstNode[] = [];\n\n for (const node of ast) {\n // Skip @utility nodes\n if (node.kind === \"at-rule\" && node.name === \"@utility\") {\n continue;\n }\n\n // Recursively process nodes with children\n if (\"nodes\" in node && Array.isArray(node.nodes) && node.nodes.length > 0) {\n result.push({\n ...node,\n nodes: removeUtilityNodes(node.nodes),\n } as AstNode);\n } else {\n result.push(node);\n }\n }\n\n return result;\n}\n\n// ============================================\n// Utility Injection\n// ============================================\n\n/**\n * Inject compiled utilities into the AST at @rainbowindex utilities placeholders.\n *\n * This function is called after utilities are compiled to replace the\n * @rainbowindex utilities directive with actual generated CSS.\n */\nexport function injectUtilities(\n ast: AstNode[],\n compiledUtilities: AstNode[],\n baseStyles: AstNode[],\n componentStyles: AstNode[]\n): AstNode[] {\n const result: AstNode[] = [];\n\n for (const node of ast) {\n if (node.kind === \"at-rule\" && node.name === \"@rainbowindex\") {\n const params = node.params.trim();\n const type = params.split(/\\s+/)[0];\n\n switch (type) {\n case \"base\":\n // Inject base styles (CSS reset, variables, etc.)\n result.push(...baseStyles);\n break;\n\n case \"utilities\":\n // Inject compiled utility classes\n result.push(...compiledUtilities);\n break;\n\n case \"components\":\n // Inject component styles from plugins\n result.push(...componentStyles);\n break;\n\n default:\n // Unknown directive type - keep as is\n result.push(node);\n }\n } else if (\"nodes\" in node && Array.isArray(node.nodes) && node.nodes.length > 0) {\n // Recursively process nested nodes\n result.push({\n ...node,\n nodes: injectUtilities(node.nodes, compiledUtilities, baseStyles, componentStyles),\n } as AstNode);\n } else {\n result.push(node);\n }\n }\n\n return result;\n}\n","/**\n * Directive Handlers\n *\n * Processes special CSS directives: @rainbowindex, @theme, @color, @apply, @utility, @variant, @source, @layer\n */\n\nimport type { AstNode, AtRule, Declaration } from \"../ast\";\nimport { atRule, comment, decl, styleRule } from \"../ast\";\nimport { ThemeOptions, type Theme } from \"../theme\";\nimport type { Variants } from \"../variants\";\nimport { type DesignSystem } from \"../compile\";\n// Import directly from specific utils to avoid pulling in Node.js-only modules\nimport { segment } from \"../utils/segment\";\nimport { topologicalSort, CircularDependencyError } from \"../utils/topological-sort\";\n\n// Re-export from extracted modules\nexport * from \"./directives/errors\";\nexport * from \"./directives/rainbowindex\";\nexport * from \"./directives/layer\";\nexport * from \"./directives/preflight\";\nexport * from \"./directives/source\";\nexport * from \"./directives/theme\";\nexport * from \"./directives/apply\";\nexport * from \"./directives/utility\";\nexport * from \"./directives/variant\";\nexport * from \"./directives/color\";\nexport * from \"./directives/import\";\nexport * from \"./directives/font\";\nexport * from \"./directives/injection\";\n\n// Import what we need from extracted modules\nimport {\n ThemePrefixError,\n ApplyVariantError,\n ApplyUnknownUtilityError,\n DirectiveNestingError,\n DirectiveEmptyError,\n UtilityNameError,\n} from \"./directives/errors\";\nimport { type RainbowIndexDirective, processRainbowIndexDirective } from \"./directives/rainbowindex\";\nimport { processLayerDirective } from \"./directives/layer\";\nimport { type PreflightConfig, processPreflightDirective } from \"./directives/preflight\";\nimport { type SourceDirective, processSourceDirective } from \"./directives/source\";\nimport { processThemeDirective, parseThemeOptions, isValidThemePrefix } from \"./directives/theme\";\nimport { type ApplyContext, processApplyDirective, createApplyContext } from \"./directives/apply\";\nimport { createCssUtility } from \"./directives/utility\";\nimport {\n processVariantDirective,\n processCustomVariantDirective,\n substituteAtVariant,\n extractSlotTemplate,\n hasVariantCSSContent,\n} from \"./directives/variant\";\nimport { processColorDirective } from \"./directives/color\";\nimport { parseImportParams, parseReferenceParams, generateImportRule } from \"./directives/import\";\nimport type { FontDirective } from \"./directives/font\";\nimport { processFontDirective } from \"./directives/font\";\n\n// ============================================\n// CSS Transformer\n// ============================================\n\n/**\n * Compile features bitmask.\n * Tracks which Rainbow Index features are used in a CSS file.\n * Used to skip processing files that don't use any features.\n */\nexport const CompileFeatures = {\n /** No features detected */\n None: 0,\n /** Uses @apply directive */\n AtApply: 1 << 0,\n /** Uses @import or @reference directive */\n AtImport: 1 << 1,\n /** Uses @theme directive */\n AtTheme: 1 << 2,\n /** Uses @rainbowindex directive (will generate utilities) */\n Utilities: 1 << 3,\n /** Uses @utility directive (custom utilities) */\n CustomUtility: 1 << 4,\n /** Uses @variant or @custom-variant directive */\n CustomVariant: 1 << 5,\n /** Uses @source directive */\n AtSource: 1 << 6,\n /** Uses @layer directive */\n AtLayer: 1 << 7,\n /** Uses @preflight directive */\n AtPreflight: 1 << 8,\n /** Uses @font directive */\n AtFont: 1 << 9,\n} as const;\n\nexport type CompileFeaturesFlags = number;\n\nexport interface TransformOptions {\n designSystem: DesignSystem;\n /** Base directory for @source patterns */\n base?: string;\n}\n\nexport interface TransformResult {\n /** Transformed AST nodes */\n ast: AstNode[];\n /** Collected @source directives */\n sources: SourceDirective[];\n /** Inline candidates from @source inline() */\n inlineCandidates: string[];\n /** Ignored candidates from @source not inline() */\n ignoredCandidates: string[];\n /** Reference imports (path -> true) */\n referenceImports: Set<string>;\n /** @rainbowindex directives found (for utility injection) */\n rainbowIndexDirectives: RainbowIndexDirective[];\n /** Layers declared via @layer */\n layers: string[];\n /** Custom utility registration functions (call with DesignSystem to register and process @apply) */\n customUtilities: Array<(designSystem: DesignSystem) => void>;\n /**\n * Process deferred @apply directives after custom utilities are registered.\n * Call this after registering customUtilities to expand @apply references\n * to utilities defined later in the CSS.\n * Returns a new AST with deferred @apply directives expanded.\n */\n processDeferredApply: (ast: AstNode[]) => AstNode[];\n /** Preflight configuration from @preflight directive */\n preflightConfig: PreflightConfig;\n /** Bitmask of detected Rainbow Index features */\n features: CompileFeaturesFlags;\n /** @font directives found (for font import generation) */\n fontDirectives: FontDirective[];\n}\n\n/**\n * Context for CSS transformation, extends ApplyContext with nesting tracking.\n */\ninterface TransformContext extends ApplyContext {\n /** Whether we're at the top level (depth 0) */\n isTopLevel: boolean;\n}\n\n/**\n * Consolidate @theme output into a single :root block with hoisted keyframes.\n */\nfunction consolidateThemeOutput(ast: AstNode[], theme: Theme, hasRainbow: boolean, placeholder: string): AstNode[] {\n const result: AstNode[] = [];\n\n for (const node of ast) {\n // Find the placeholder comment\n if (node.kind === \"comment\" && node.value === placeholder) {\n // Build consolidated :root declarations from theme entries\n const declarations: Declaration[] = [];\n\n for (const [key, entry] of theme.entries()) {\n // Skip reference-only entries\n if (entry.options & ThemeOptions.REFERENCE) {\n continue;\n }\n\n // Apply prefix if set\n const outputKey = theme.prefix ? key.replace(/^--/, `--${theme.prefix}-`) : key;\n\n declarations.push(decl(outputKey, entry.value));\n }\n\n // Get all keyframes\n const keyframes = theme.getAllKeyframes();\n\n // Hoist keyframes - emit them before :root\n for (const [, keyframeRule] of keyframes) {\n result.push(keyframeRule);\n }\n\n // Emit consolidated :root, :host block if we have declarations\n // Using :root, :host enables theme variables in shadow DOM\n if (declarations.length > 0) {\n // Add color-scheme for rainbow mode\n if (hasRainbow) {\n declarations.unshift(decl(\"color-scheme\", \"light dark\"));\n }\n\n result.push(styleRule(\":root, :host\", declarations));\n }\n } else {\n result.push(node);\n }\n }\n\n return result;\n}\n\n/**\n * Deferred variant application info.\n */\ninterface DeferredVariantApplication {\n variantName: string;\n nodes: AstNode[];\n placeholderId: string;\n}\n\n/**\n * Deferred @apply info.\n */\ninterface DeferredApply {\n /** The original @apply at-rule node */\n node: AtRule;\n /** Unique placeholder ID */\n placeholderId: string;\n /** The context when the @apply was encountered */\n context: ApplyContext;\n}\n\n/**\n * Process deferred @variant applications by replacing placeholders with transformed CSS.\n *\n * This function walks the AST looking for placeholder comments and replaces them\n * with the result of applying the variant to the stored CSS content.\n *\n * @throws VariantApplicationError if a referenced variant still doesn't exist\n */\nfunction processDeferredVariantApplications(\n ast: AstNode[],\n deferredApplications: DeferredVariantApplication[],\n variants: Variants,\n theme: Theme,\n placeholderPrefix: string\n): AstNode[] {\n // Build a map of placeholder IDs to their application info\n const placeholderMap = new Map<string, DeferredVariantApplication>();\n for (const app of deferredApplications) {\n placeholderMap.set(app.placeholderId, app);\n }\n\n function processNode(node: AstNode): AstNode[] {\n // Check if this is a placeholder comment\n if (node.kind === \"comment\" && node.value.startsWith(placeholderPrefix)) {\n const application = placeholderMap.get(node.value);\n if (application) {\n // Now apply the variant - it should exist after all custom variants are registered\n return substituteAtVariant(application.variantName, application.nodes, variants, theme);\n }\n }\n\n // Recursively process nodes with children\n if (\"nodes\" in node && Array.isArray(node.nodes) && node.nodes.length > 0) {\n const processedChildren: AstNode[] = [];\n for (const child of node.nodes) {\n processedChildren.push(...processNode(child));\n }\n return [\n {\n ...node,\n nodes: processedChildren,\n } as AstNode,\n ];\n }\n\n return [node];\n }\n\n const result: AstNode[] = [];\n for (const node of ast) {\n result.push(...processNode(node));\n }\n return result;\n}\n\n/**\n * Transform CSS by processing all directives.\n */\nexport function transformCSS(ast: AstNode[], options: TransformOptions): TransformResult {\n const { designSystem, base = process.cwd() } = options;\n const { theme, utilities: _utilities, variants } = designSystem;\n\n const sources: SourceDirective[] = [];\n const inlineCandidates: string[] = [];\n const ignoredCandidates: string[] = [];\n const referenceImports = new Set<string>();\n const rainbowIndexDirectives: RainbowIndexDirective[] = [];\n const fontDirectives: FontDirective[] = [];\n const layers: string[] = [];\n let preflightConfig: PreflightConfig = { mode: \"full\", modules: [] };\n const customUtilities: Array<(designSystem: DesignSystem) => void> = [];\n let features: CompileFeaturesFlags = CompileFeatures.None;\n const customVariants = new Map<string, (variants: Variants, order: number) => void>();\n const customVariantDependencies = new Map<string, Set<string>>();\n const customVariantOrders = new Map<string, number>();\n let customVariantOrderCounter = 10000; // Start at a high number to come after built-in variants\n\n // Deferred @variant application tracking\n // We collect variant applications and process them after all custom variants are registered\n // This allows @variant to reference variants defined later in the CSS\n const deferredVariantApplications: DeferredVariantApplication[] = [];\n let variantPlaceholderCounter = 0;\n const VARIANT_PLACEHOLDER_PREFIX = \"__DEFERRED_VARIANT_APPLICATION_\";\n\n // Deferred @apply tracking\n // We collect @apply directives that reference unknown utilities (might be defined later via @utility)\n // and process them after custom utilities are registered\n const deferredApplyDirectives: DeferredApply[] = [];\n let applyPlaceholderCounter = 0;\n const APPLY_PLACEHOLDER_PREFIX = \"__DEFERRED_APPLY_\";\n\n // Theme consolidation tracking\n // We collect all theme data first, then emit a single consolidated :root block\n // at the position of the first @theme directive\n const THEME_PLACEHOLDER = \"__THEME_CONSOLIDATION_PLACEHOLDER__\";\n let hasThemePlaceholder = false;\n let themeHasRainbow = false; // Track if any @theme uses rainbow mode\n\n function createTransformContext(isTopLevel: boolean): TransformContext {\n return {\n ...createApplyContext(),\n isTopLevel,\n };\n }\n\n function processNodes(nodes: AstNode[], context: TransformContext = createTransformContext(true)): AstNode[] {\n const result: AstNode[] = [];\n\n for (const node of nodes) {\n if (node.kind === \"at-rule\") {\n switch (node.name) {\n case \"@rainbowindex\": {\n // Process @rainbowindex directive\n features |= CompileFeatures.Utilities;\n const riDirective = processRainbowIndexDirective(node, base);\n rainbowIndexDirectives.push(riDirective);\n\n // For source() on utilities, add to sources\n if (riDirective.source && riDirective.source !== \"none\" && riDirective.type === \"utilities\") {\n sources.push({\n kind: \"glob\",\n pattern: riDirective.source.pattern,\n base: riDirective.source.base,\n negated: false,\n });\n }\n // The node is kept as a placeholder for later injection\n result.push(node);\n break;\n }\n\n case \"@layer\": {\n // Process @layer directive\n features |= CompileFeatures.AtLayer;\n const layerDirective = processLayerDirective(node);\n\n if (layerDirective.isDefinition) {\n // Layer with content - wrap content in @layer\n // Content inside @layer is NOT top-level\n result.push(\n atRule(\n \"layer\",\n layerDirective.names[0] ?? \"\",\n processNodes(layerDirective.nodes, { ...context, isTopLevel: false })\n )\n );\n } else {\n // Layer declaration - just declare the order\n layers.push(...layerDirective.names);\n result.push(atRule(\"layer\", layerDirective.names.join(\", \"), []));\n }\n break;\n }\n\n case \"@theme\": {\n // Parse theme options to check for rainbow mode\n features |= CompileFeatures.AtTheme;\n const themeOpts = parseThemeOptions(node.params);\n\n // Track rainbow mode for consolidated output\n if (themeOpts.rainbow) {\n themeHasRainbow = true;\n }\n\n // Process theme directive to register values (side effects)\n // but we defer output to emit a single consolidated :root block\n processThemeDirective(node, theme);\n\n // On first non-reference @theme, add a placeholder for consolidated output\n if (!themeOpts.reference && !hasThemePlaceholder) {\n hasThemePlaceholder = true;\n // Use a comment as placeholder - will be replaced after processing\n result.push(comment(THEME_PLACEHOLDER));\n }\n // Subsequent @theme blocks don't emit anything - values are already registered\n break;\n }\n\n case \"@color\": {\n // @color must be at top-level\n if (!context.isTopLevel) {\n throw new DirectiveNestingError(\"color\");\n }\n\n // @color always emits light-dark() values\n themeHasRainbow = true;\n\n // Process color directive to register color values\n processColorDirective(node, theme);\n\n // Add placeholder for consolidated output if not already present\n if (!hasThemePlaceholder) {\n hasThemePlaceholder = true;\n result.push(comment(THEME_PLACEHOLDER));\n }\n break;\n }\n\n case \"@utility\": {\n // @utility must be at top-level\n features |= CompileFeatures.CustomUtility;\n if (!context.isTopLevel) {\n throw new DirectiveNestingError(\"utility\");\n }\n\n // Validate utility is not empty\n if (node.nodes.length === 0) {\n throw new DirectiveEmptyError(\"utility\", node.params);\n }\n\n // Create the utility using the new function with validation\n const utilityRegistration = createCssUtility(node);\n if (utilityRegistration === null) {\n // Invalid utility name - throw appropriate error\n const name = node.params.trim();\n if (name.includes(\"*\") && !name.endsWith(\"-*\")) {\n if (name.endsWith(\"*\")) {\n throw new UtilityNameError(name, \"A functional utility must end in `-*`.\");\n }\n throw new UtilityNameError(\n name,\n \"The dynamic portion marked by `-*` must appear once at the end.\"\n );\n }\n throw new UtilityNameError(\n name,\n \"Utilities should be alphanumeric and start with a lowercase letter.\"\n );\n }\n\n // Collect for later registration (after @apply processing)\n customUtilities.push(utilityRegistration);\n\n // Keep the @utility node in AST for @apply processing\n // It will be removed later via removeUtilityNodes()\n result.push(node);\n break;\n }\n\n case \"@variant\": {\n features |= CompileFeatures.CustomVariant;\n const variantParams = node.params.trim();\n const hasBody = node.nodes.length > 0;\n const hasSelectors = variantParams.includes(\"(\");\n const hasSlot = hasBody && extractSlotTemplate(node.nodes);\n const hasCSSContent = hasBody && hasVariantCSSContent(node.nodes);\n\n // Determine if this is a definition or application:\n // - Definition: has selectors in params, OR has @slot in body\n // - Application: just a name with CSS content (no selectors, no @slot)\n const isDefinition = hasSelectors || hasSlot || !hasCSSContent;\n\n if (isDefinition) {\n // Register the variant definition\n processVariantDirective(node, variants);\n // Don't output anything - just registers the variant\n } else {\n // Apply the variant to CSS content\n // Extract the variant name (should be just the name, no selectors)\n const variantName = variantParams.match(/^(\\S+)$/)?.[1];\n if (variantName) {\n // Check if variant already exists (built-in or already registered)\n if (variants.has(variantName)) {\n // Apply immediately if variant is already registered\n const transformed = substituteAtVariant(variantName, node.nodes, variants, theme);\n result.push(...transformed);\n } else {\n // Defer application - variant may be defined later\n const placeholderId = `${VARIANT_PLACEHOLDER_PREFIX}${variantPlaceholderCounter++}__`;\n deferredVariantApplications.push({\n variantName,\n nodes: node.nodes,\n placeholderId,\n });\n result.push(comment(placeholderId));\n }\n } else {\n // Fallback: treat as definition\n processVariantDirective(node, variants);\n }\n }\n break;\n }\n\n case \"@custom-variant\":\n features |= CompileFeatures.CustomVariant;\n processCustomVariantDirective(node, variants, {\n isTopLevel: context.isTopLevel,\n customVariants,\n customVariantDependencies,\n customVariantOrders,\n getNextOrder: () => customVariantOrderCounter++,\n });\n // Don't output anything - just registers the variant\n break;\n\n case \"@source\": {\n // @source must be at top-level\n features |= CompileFeatures.AtSource;\n if (!context.isTopLevel) {\n throw new DirectiveNestingError(\"source\");\n }\n\n // Process @source directive (throws on error)\n const sourceDirective = processSourceDirective(node, base);\n if (sourceDirective.kind === \"glob\") {\n sources.push(sourceDirective);\n } else if (sourceDirective.kind === \"inline\") {\n inlineCandidates.push(...sourceDirective.candidates!);\n } else {\n ignoredCandidates.push(...sourceDirective.candidates!);\n }\n // Don't output anything - just collects sources\n break;\n }\n\n case \"@preflight\":\n // @preflight must be at top-level\n features |= CompileFeatures.AtPreflight;\n if (!context.isTopLevel) {\n throw new DirectiveNestingError(\"preflight\");\n }\n\n // Process @preflight directive\n preflightConfig = processPreflightDirective(node);\n // Don't output anything - configures preflight filtering\n break;\n\n case \"@font\":\n // @font must be at top-level\n features |= CompileFeatures.AtFont;\n if (!context.isTopLevel) {\n throw new DirectiveNestingError(\"font\");\n }\n\n // Process @font directive and collect for later processing\n fontDirectives.push(processFontDirective(node));\n // Don't output anything here - font imports will be prepended\n // to the output after all processing is complete\n break;\n\n case \"@import\": {\n // Check for reference import\n features |= CompileFeatures.AtImport;\n const importOpts = parseImportParams(node.params);\n if (importOpts.reference) {\n referenceImports.add(importOpts.path);\n // Don't output reference imports\n } else if (importOpts.layer || importOpts.supports) {\n // Generate enhanced @import with layer/supports\n result.push(generateImportRule(importOpts));\n } else {\n // Pass through regular @import\n result.push(node);\n }\n break;\n }\n case \"@reference\": {\n features |= CompileFeatures.AtImport;\n if (!context.isTopLevel) {\n throw new DirectiveNestingError(\"reference\");\n }\n const referenceOpts = parseReferenceParams(node.params);\n if (referenceOpts.path) {\n referenceImports.add(referenceOpts.path);\n }\n // Do not output @reference\n break;\n }\n\n case \"@media\": {\n // Handle @media important - sets global !important for all utilities\n // This is triggered by @import \"tailwindcss\" important\n if (node.params.trim() === \"important\") {\n // Set the important flag on the design system\n designSystem.important = true;\n // Process children normally (unwrap the @media important)\n const processed = processNodes(node.nodes, { ...context, isTopLevel: false });\n result.push(...processed);\n break;\n }\n\n // Handle @media theme(reference ...) semantics\n const themeMediaMatch = node.params.match(/^theme\\s*\\(\\s*(.*?)\\s*\\)$/);\n if (themeMediaMatch) {\n const themeParams = themeMediaMatch[1]!;\n const themeOpts = parseThemeOptions(themeParams);\n\n // Track rainbow mode for consolidated output\n if (themeOpts.rainbow) {\n themeHasRainbow = true;\n }\n\n // Validate: @media theme(...) can only contain @theme rules\n for (const child of node.nodes) {\n if (child.kind === \"at-rule\" && child.name === \"@theme\") {\n // Process @theme with the parsed options (registers values with theme)\n processThemeDirective(child, theme, {\n reference: themeOpts.reference,\n rainbow: themeOpts.rainbow,\n inline: themeOpts.inline,\n default: themeOpts.default,\n static: themeOpts.static,\n prefix: themeOpts.prefix ?? undefined,\n });\n\n // Add placeholder if first non-reference @theme\n if (!themeOpts.reference && !hasThemePlaceholder) {\n hasThemePlaceholder = true;\n result.push(comment(THEME_PLACEHOLDER));\n }\n } else if (child.kind === \"comment\") {\n // Comments are allowed\n } else {\n // Other content is not allowed in @media theme(reference)\n if (themeOpts.reference) {\n let contentDesc: string;\n if (child.kind === \"at-rule\") {\n contentDesc = `@${child.name}`;\n } else if (child.kind === \"rule\") {\n contentDesc = `style rule \"${child.selector}\"`;\n } else {\n contentDesc = child.kind;\n }\n throw new Error(\n `\\`@media theme(reference)\\` can only contain \\`@theme\\` rules, but found ${contentDesc}.`\n );\n }\n // For non-reference @media theme(), process normally\n result.push(child);\n }\n }\n // Don't output the @media theme() wrapper itself\n break;\n }\n\n // Handle @media source(...) - propagates source to nested @rainbowindex utilities\n const sourceMediaMatch = node.params.match(/^source\\s*\\(\\s*[\"']?([^\"')]+)[\"']?\\s*\\)$/);\n if (sourceMediaMatch) {\n const sourcePattern = sourceMediaMatch[1]!;\n\n // Process children, rewriting @rainbowindex utilities to include source\n for (const child of node.nodes) {\n if (child.kind === \"at-rule\" && child.name === \"@rainbowindex\") {\n const riParams = child.params.trim();\n const riParts = segment(riParams, \" \");\n const riType = riParts[0];\n\n if (riType === \"utilities\") {\n // Rewrite to include source pattern if not already present\n const hasSource = riParts.some((p) => p.startsWith(\"source(\"));\n if (!hasSource) {\n // Create new @rainbowindex utilities with source\n const newParams = `utilities source(\"${sourcePattern}\")`;\n const newNode = atRule(\"rainbowindex\", newParams, child.nodes);\n const riDirective = processRainbowIndexDirective(newNode, base);\n rainbowIndexDirectives.push(riDirective);\n const injectedSource = riDirective.source as {\n base: string;\n pattern: string;\n };\n sources.push({\n kind: \"glob\",\n pattern: injectedSource.pattern,\n base: injectedSource.base,\n negated: false,\n });\n result.push(newNode);\n } else {\n // Already has source, process normally\n const riDirective = processRainbowIndexDirective(child, base);\n rainbowIndexDirectives.push(riDirective);\n if (\n riDirective.source &&\n riDirective.source !== \"none\" &&\n riDirective.type === \"utilities\"\n ) {\n sources.push({\n kind: \"glob\",\n pattern: riDirective.source.pattern,\n base: riDirective.source.base,\n negated: false,\n });\n }\n result.push(child);\n }\n } else {\n // Non-utilities @rainbowindex - process normally\n const riDirective = processRainbowIndexDirective(child, base);\n rainbowIndexDirectives.push(riDirective);\n result.push(child);\n }\n } else if (child.kind === \"comment\") {\n // Comments are allowed\n } else {\n // Process other content normally\n const processed = processNodes([child], { ...context, isTopLevel: false });\n result.push(...processed);\n }\n }\n // Don't output the @media source() wrapper itself\n break;\n }\n\n // Handle @media prefix(...) - propagates prefix to nested @theme\n const prefixMediaMatch = node.params.match(/^prefix\\s*\\(\\s*([^)\\s]+)\\s*\\)$/);\n if (prefixMediaMatch) {\n const mediaPrefix = prefixMediaMatch[1]!;\n\n // Validate prefix\n if (!isValidThemePrefix(mediaPrefix)) {\n throw new ThemePrefixError(mediaPrefix);\n }\n\n // Process children, applying prefix to @theme blocks\n for (const child of node.nodes) {\n if (child.kind === \"at-rule\" && child.name === \"@theme\") {\n // Check if this @theme is reference-only\n const childOpts = parseThemeOptions(child.params);\n\n // Track rainbow mode\n if (childOpts.rainbow) {\n themeHasRainbow = true;\n }\n\n // Process @theme with the prefix applied (registers values with theme)\n processThemeDirective(child, theme, {\n prefix: mediaPrefix,\n });\n\n // Add placeholder if first non-reference @theme\n if (!childOpts.reference && !hasThemePlaceholder) {\n hasThemePlaceholder = true;\n result.push(comment(THEME_PLACEHOLDER));\n }\n } else if (child.kind === \"comment\") {\n // Comments are allowed\n } else {\n // Process other content normally (could include nested @media prefix)\n const processed = processNodes([child], { ...context, isTopLevel: false });\n result.push(...processed);\n }\n }\n // Don't output the @media prefix() wrapper itself\n break;\n }\n\n // Regular @media rule - fall through to default handling\n if (node.nodes.length > 0) {\n const newContext: TransformContext = {\n ...context,\n parentRules: [...context.parentRules, `@media`],\n isTopLevel: false,\n };\n\n result.push({\n ...node,\n nodes: processNodes(node.nodes, newContext),\n });\n } else {\n result.push(node);\n }\n break;\n }\n\n default:\n // Process nested nodes in other at-rules\n if (node.nodes.length > 0) {\n // Track @keyframes context and mark as not top-level\n const newContext: TransformContext =\n node.name === \"@keyframes\"\n ? {\n inKeyframes: true,\n parentRules: [...context.parentRules, `@${node.name} ${node.params}`],\n isTopLevel: false,\n }\n : {\n ...context,\n parentRules: [...context.parentRules, `@${node.name}`],\n isTopLevel: false,\n };\n\n result.push({\n ...node,\n nodes: processNodes(node.nodes, newContext),\n });\n } else {\n result.push(node);\n }\n }\n } else if (node.kind === \"rule\") {\n // Process @apply within rules\n const processedDecls: AstNode[] = [];\n\n for (const child of node.nodes) {\n if (child.kind === \"at-rule\" && child.name === \"@apply\") {\n features |= CompileFeatures.AtApply;\n try {\n processedDecls.push(...processApplyDirective(child, designSystem, context));\n } catch (error) {\n // If @apply references an unknown utility or variant, defer it\n // The utility/variant might be defined later via @utility or @variant\n if (error instanceof ApplyUnknownUtilityError || error instanceof ApplyVariantError) {\n const placeholderId = `${APPLY_PLACEHOLDER_PREFIX}${applyPlaceholderCounter++}__`;\n deferredApplyDirectives.push({\n node: child as AtRule,\n placeholderId,\n context: { ...context },\n });\n processedDecls.push(comment(placeholderId));\n } else {\n // Re-throw other errors\n throw error;\n }\n }\n } else {\n processedDecls.push(child);\n }\n }\n\n result.push({\n ...node,\n nodes: processedDecls,\n });\n } else {\n result.push(node);\n }\n }\n\n return result;\n }\n\n function trackCssVariableUsage(nodes: AstNode[]): void {\n for (const node of nodes) {\n switch (node.kind) {\n case \"declaration\": {\n const value = node.value;\n if (value && value.includes(\"var(\")) {\n designSystem.trackUsedVariables(value);\n }\n break;\n }\n case \"at-rule\": {\n if (node.params && node.params.includes(\"var(\")) {\n designSystem.trackUsedVariables(node.params);\n }\n if (node.nodes.length > 0) {\n trackCssVariableUsage(node.nodes);\n }\n break;\n }\n case \"rule\":\n case \"context\":\n case \"at-root\": {\n if (node.nodes.length > 0) {\n trackCssVariableUsage(node.nodes);\n }\n break;\n }\n default:\n break;\n }\n }\n }\n\n let transformedAst = processNodes(ast);\n\n // Consolidate @theme output: replace placeholder with single :root block + hoisted keyframes\n // Note: hasThemePlaceholder may be false if no @theme/@color directives exist,\n // but the consolidation function handles this gracefully by doing nothing if no placeholder is found\n transformedAst = consolidateThemeOutput(transformedAst, theme, themeHasRainbow, THEME_PLACEHOLDER);\n\n // Propagate theme prefix to designSystem.prefix\n // This ensures utility class names require the prefix when configured\n //\n // IMPORTANT: This mutates the designSystem object. Callers should pass\n // a dedicated design system instance (via createDesignSystem() or createCompiler()),\n // NOT the cached getDefaultDesignSystem(). The cached default should never have\n // a prefix set, as it's shared across compilations.\n if (theme.prefix) {\n designSystem.prefix = theme.prefix;\n }\n\n if (customVariants.size > 0) {\n try {\n const ordered = topologicalSort(\n [...customVariants.keys()],\n (name) => name,\n (name) => [...customVariantDependencies.get(name)!]\n );\n\n for (const name of ordered) {\n // Use the captured order from when the variant was first encountered\n // This preserves the appearance order in the CSS\n const order = customVariantOrders.get(name)!;\n customVariants.get(name)?.(variants, order);\n }\n } catch (error) {\n if (error instanceof CircularDependencyError) {\n throw new Error(`Circular dependency detected in custom variants: ${error.cycle.join(\" → \")}`);\n }\n throw error;\n }\n }\n\n // Process deferred @variant applications now that all custom variants are registered\n if (deferredVariantApplications.length > 0) {\n transformedAst = processDeferredVariantApplications(\n transformedAst,\n deferredVariantApplications,\n variants,\n theme,\n VARIANT_PLACEHOLDER_PREFIX\n );\n }\n\n // Track CSS variable usage from CSS-first patterns (e.g., var(--token))\n trackCssVariableUsage(transformedAst);\n\n // Create the processDeferredApply function that can be called after custom utilities are registered\n const processDeferredApply = (ast: AstNode[]): AstNode[] => {\n if (deferredApplyDirectives.length === 0) {\n return ast;\n }\n\n // Build a map of placeholder IDs to their deferred apply info\n const placeholderMap = new Map<string, DeferredApply>();\n for (const app of deferredApplyDirectives) {\n placeholderMap.set(app.placeholderId, app);\n }\n\n function processNode(node: AstNode): AstNode[] {\n // Check if this is a placeholder comment\n if (node.kind === \"comment\" && node.value.startsWith(APPLY_PLACEHOLDER_PREFIX)) {\n const deferredApply = placeholderMap.get(node.value);\n if (deferredApply) {\n // Now process the @apply - utilities should be registered\n return processApplyDirective(deferredApply.node, designSystem, deferredApply.context);\n }\n }\n\n // Recursively process nodes with children\n if (\"nodes\" in node && Array.isArray(node.nodes) && node.nodes.length > 0) {\n const processedChildren: AstNode[] = [];\n for (const child of node.nodes) {\n processedChildren.push(...processNode(child));\n }\n return [\n {\n ...node,\n nodes: processedChildren,\n } as AstNode,\n ];\n }\n\n return [node];\n }\n\n const result: AstNode[] = [];\n for (const node of ast) {\n result.push(...processNode(node));\n }\n return result;\n };\n\n return {\n ast: transformedAst,\n sources,\n inlineCandidates,\n ignoredCandidates,\n referenceImports,\n rainbowIndexDirectives,\n layers,\n customUtilities,\n processDeferredApply,\n preflightConfig,\n features,\n fontDirectives,\n };\n}\n","/**\n * Parser Utilities\n *\n * Shared utility functions used across parser modules.\n * Consolidated from attribute-selector.ts, css-parser.ts, at-import.ts.\n */\n\nimport { SPACE, TAB, LINE_BREAK, CARRIAGE_RETURN, UPPER_A, UPPER_Z, BACKSLASH } from \"./char-codes\";\n\n/**\n * Check if a character code is whitespace.\n *\n * Per CSS spec (https://www.w3.org/TR/css-syntax-3/#whitespace), CSS whitespace is:\n * - U+0020 SPACE\n * - U+0009 TAB\n * - U+000A LINE FEED\n * - U+000D CARRIAGE RETURN\n * - U+000C FORM FEED (not handled here for simplicity, rare in practice)\n */\nexport function isWhitespace(char: number): boolean {\n return char === SPACE || char === TAB || char === LINE_BREAK || char === CARRIAGE_RETURN;\n}\n\n/**\n * ASCII-only lowercase conversion.\n *\n * Per CSS spec, case-insensitive matching should use ASCII case folding,\n * not Unicode case folding. This avoids locale-sensitive issues\n * (e.g., Turkish \"İ\" -> \"i\" vs \"I\" -> \"ı\").\n *\n * Only converts A-Z (65-90) to a-z (97-122), leaving all other characters unchanged.\n */\nexport function asciiLowerCase(str: string): string {\n let result = \"\";\n for (let i = 0; i < str.length; i++) {\n const code = str.charCodeAt(i);\n if (code >= UPPER_A && code <= UPPER_Z) {\n result += String.fromCharCode(code + 32);\n } else {\n result += str[i];\n }\n }\n return result;\n}\n\n/**\n * Unescape backslash-escaped characters in a CSS identifier or value.\n *\n * Handles simple backslash escapes where the backslash is followed by\n * a literal character that should be kept as-is.\n *\n * @example\n * unescape(\"data-\\\\[foo\\\\]\") // \"data-[foo]\"\n * unescape(\"hello\\\\_world\") // \"hello_world\"\n */\nexport function unescape(input: string): string {\n let result = \"\";\n let idx = 0;\n const len = input.length;\n\n while (idx < len) {\n const char = input.charCodeAt(idx);\n\n if (char === BACKSLASH && idx + 1 < len) {\n // Skip backslash, take next character literally\n idx++;\n result += input[idx];\n idx++;\n continue;\n }\n\n result += input[idx];\n idx++;\n }\n\n return result;\n}\n","/**\n * Attribute Selector Parser\n *\n * Parses CSS attribute selectors: [attr], [attr=value], [attr~=value], etc.\n * Uses character-code state machine for proper escape handling and performance.\n *\n * Performance optimizations:\n * - Direct operator comparison (no Map lookup)\n * - Track escapes during parsing (no includes() scan)\n * - Fast path for simple [attr] selectors\n * - Inline whitespace skipping\n * - Minimal bounds checking\n */\n\nimport {\n TAB,\n LINE_BREAK,\n CARRIAGE_RETURN,\n SPACE,\n DOUBLE_QUOTE,\n SINGLE_QUOTE,\n ASTERISK,\n CARET,\n DOLLAR,\n PIPE,\n TILDE,\n EQUALS,\n OPEN_BRACKET,\n CLOSE_BRACKET,\n BACKSLASH,\n UPPER_I,\n LOWER_I,\n UPPER_S,\n LOWER_S,\n} from \"../char-codes\";\nimport { isWhitespace, asciiLowerCase, unescape } from \"../parser-utils\";\n\n/** Attribute selector operators */\nexport type AttributeOperator = \"=\" | \"~=\" | \"|=\" | \"^=\" | \"$=\" | \"*=\";\n\n/** Quote type used in attribute value */\nexport type QuoteType = '\"' | \"'\" | null;\n\n/** Parsed attribute selector */\nexport interface AttributeSelector {\n /** The attribute name */\n attribute: string;\n /** The comparison operator (if any) */\n operator?: AttributeOperator;\n /** The value to compare (if any) */\n value?: string;\n /** The original quote used (for serialization) */\n quote?: QuoteType;\n /** Case sensitivity flag: \"i\" (insensitive) or \"s\" (sensitive) */\n flags?: \"i\" | \"s\";\n}\n\n/**\n * Parse a CSS attribute selector string using character-by-character state machine.\n *\n * Properly handles:\n * - Escaped identifiers (e.g., data-\\[foo\\])\n * - Escaped values within quotes\n * - Unquoted values\n * - Case sensitivity flags\n *\n * Performance optimizations:\n * - Direct operator comparison (no Map lookup)\n * - Track escapes during parsing (no includes() scan)\n * - Fast path for simple [attr] selectors\n * - Minimal whitespace handling for common cases\n *\n * @example\n * parseAttributeSelector(\"[data-state]\")\n * // { attribute: \"data-state\" }\n *\n * parseAttributeSelector('[data-state=\"open\"]')\n * // { attribute: \"data-state\", operator: \"=\", value: \"open\", quote: '\"' }\n */\nexport function parseAttributeSelector(input: string): AttributeSelector | null {\n const len = input.length;\n if (len < 3) return null; // Minimum: [x]\n\n let idx = 0;\n let c = input.charCodeAt(0);\n\n // Fast path: skip leading whitespace only if present\n if (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN) {\n do {\n idx++;\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n } while (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN);\n }\n\n // Must start with [\n if (c !== OPEN_BRACKET) return null;\n idx++;\n c = input.charCodeAt(idx);\n\n // Skip whitespace after [ only if present\n if (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN) {\n do {\n idx++;\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n } while (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN);\n }\n\n // Parse attribute name - track if we see escapes\n const attrStart = idx;\n let hasAttrEscape = false;\n\n while (idx < len) {\n c = input.charCodeAt(idx);\n\n // Backslash escapes next character\n if (c === BACKSLASH) {\n hasAttrEscape = true;\n idx += 2;\n continue;\n }\n\n // Stop at operator characters, whitespace, or closing bracket\n // Ordered by likelihood for branch prediction\n if (\n c === CLOSE_BRACKET ||\n c === EQUALS ||\n c === SPACE ||\n c === TAB ||\n c === TILDE ||\n c === PIPE ||\n c === CARET ||\n c === DOLLAR ||\n c === ASTERISK ||\n c === LINE_BREAK ||\n c === CARRIAGE_RETURN\n ) {\n break;\n }\n\n idx++;\n }\n\n if (idx === attrStart) return null;\n\n // Get attribute - unescape only if needed\n const attribute = hasAttrEscape ? unescape(input.slice(attrStart, idx)) : input.slice(attrStart, idx);\n\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n\n // Skip whitespace only if present\n if (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN) {\n do {\n idx++;\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n } while (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN);\n }\n\n // Simple attribute selector [attr]\n if (c === CLOSE_BRACKET) {\n idx++;\n // Check for trailing content\n while (idx < len) {\n c = input.charCodeAt(idx);\n if (c !== SPACE && c !== TAB && c !== LINE_BREAK && c !== CARRIAGE_RETURN) return null;\n idx++;\n }\n return { attribute };\n }\n\n // Parse operator using direct comparison (faster than Map lookup)\n let operator: AttributeOperator;\n if (c === EQUALS) {\n operator = \"=\";\n idx++;\n } else if (c === TILDE) {\n if (idx + 1 >= len || input.charCodeAt(idx + 1) !== EQUALS) return null;\n operator = \"~=\";\n idx += 2;\n } else if (c === PIPE) {\n if (idx + 1 >= len || input.charCodeAt(idx + 1) !== EQUALS) return null;\n operator = \"|=\";\n idx += 2;\n } else if (c === CARET) {\n if (idx + 1 >= len || input.charCodeAt(idx + 1) !== EQUALS) return null;\n operator = \"^=\";\n idx += 2;\n } else if (c === DOLLAR) {\n if (idx + 1 >= len || input.charCodeAt(idx + 1) !== EQUALS) return null;\n operator = \"$=\";\n idx += 2;\n } else if (c === ASTERISK) {\n if (idx + 1 >= len || input.charCodeAt(idx + 1) !== EQUALS) return null;\n operator = \"*=\";\n idx += 2;\n } else {\n return null;\n }\n\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n\n // Skip whitespace after operator only if present\n if (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN) {\n do {\n idx++;\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n } while (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN);\n }\n\n // Parse value\n let value: string;\n let quote: QuoteType = null;\n let hasValueEscape = false;\n\n if (c === DOUBLE_QUOTE || c === SINGLE_QUOTE) {\n // Quoted value\n const quoteChar = c;\n quote = c === DOUBLE_QUOTE ? '\"' : \"'\";\n idx++;\n const valueStart = idx;\n\n // Find closing quote, tracking escapes\n while (idx < len) {\n c = input.charCodeAt(idx);\n if (c === BACKSLASH) {\n hasValueEscape = true;\n idx += 2;\n continue;\n }\n if (c === quoteChar) break;\n idx++;\n }\n\n if (idx >= len) return null; // Unclosed quote\n\n value = hasValueEscape ? unescape(input.slice(valueStart, idx)) : input.slice(valueStart, idx);\n idx++; // Skip closing quote\n } else {\n // Unquoted value\n const valueStart = idx;\n\n while (idx < len) {\n c = input.charCodeAt(idx);\n if (c === BACKSLASH) {\n hasValueEscape = true;\n idx += 2;\n continue;\n }\n if (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN || c === CLOSE_BRACKET) {\n break;\n }\n idx++;\n }\n\n if (idx === valueStart) return null; // Empty value\n\n value = hasValueEscape ? unescape(input.slice(valueStart, idx)) : input.slice(valueStart, idx);\n }\n\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n\n // Skip whitespace after value only if present\n if (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN) {\n do {\n idx++;\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n } while (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN);\n }\n\n // Check for flags (i or s)\n let flags: \"i\" | \"s\" | undefined;\n if (c === UPPER_I || c === LOWER_I) {\n flags = \"i\";\n idx++;\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n } else if (c === UPPER_S || c === LOWER_S) {\n flags = \"s\";\n idx++;\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n }\n\n // Skip whitespace after flags only if present\n if (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN) {\n do {\n idx++;\n if (idx >= len) return null;\n c = input.charCodeAt(idx);\n } while (c === SPACE || c === TAB || c === LINE_BREAK || c === CARRIAGE_RETURN);\n }\n\n // Must end with ]\n if (c !== CLOSE_BRACKET) return null;\n idx++;\n\n // Check for trailing content\n while (idx < len) {\n c = input.charCodeAt(idx);\n if (c !== SPACE && c !== TAB && c !== LINE_BREAK && c !== CARRIAGE_RETURN) return null;\n idx++;\n }\n\n return { attribute, operator, value, quote, flags };\n}\n\n/**\n * Escape a CSS identifier for use in attribute selectors.\n */\nfunction escapeIdentifier(input: string): string {\n let result = \"\";\n\n for (let i = 0; i < input.length; i++) {\n const char = input[i]!;\n // Escape special characters\n if (\"[]\\\\\\\"'=~|^$*\".includes(char)) {\n result += \"\\\\\" + char;\n } else {\n result += char;\n }\n }\n\n return result;\n}\n\n/**\n * Serialize an attribute selector back to string.\n *\n * @example\n * serializeAttributeSelector({ attribute: \"data-state\", operator: \"=\", value: \"open\" })\n * // '[data-state=\"open\"]'\n */\nexport function serializeAttributeSelector(selector: AttributeSelector): string {\n let result = `[${escapeIdentifier(selector.attribute)}`;\n\n if (selector.operator && selector.value !== undefined) {\n result += selector.operator;\n\n // Determine quote style\n let quote: QuoteType = selector.quote ?? null;\n if (quote === null) {\n if (selector.value.includes('\"')) {\n quote = \"'\";\n } else if (needsQuoting(selector.value)) {\n quote = '\"';\n }\n }\n\n if (quote) {\n // Escape the value for the chosen quote\n const escaped = selector.value.replace(new RegExp(`[\\\\\\\\${quote}]`, \"g\"), \"\\\\$&\");\n result += `${quote}${escaped}${quote}`;\n } else {\n result += selector.value;\n }\n }\n\n if (selector.flags) {\n result += ` ${selector.flags}`;\n }\n\n result += \"]\";\n return result;\n}\n\n/**\n * Check if a value needs quoting.\n */\nfunction needsQuoting(value: string): boolean {\n if (value === \"\") return true;\n\n for (let i = 0; i < value.length; i++) {\n const char = value.charCodeAt(i);\n if (isWhitespace(char) || char === CLOSE_BRACKET || char === EQUALS) {\n return true;\n }\n }\n\n return false;\n}\n\n/**\n * Check if a string is a valid attribute selector.\n */\nexport function isAttributeSelector(input: string): boolean {\n return parseAttributeSelector(input) !== null;\n}\n\n/**\n * Extract all attribute selectors from a full selector string.\n * Uses state machine to properly handle nested brackets and escapes.\n *\n * @example\n * extractAttributeSelectors(\"button[type='submit'][disabled]\")\n * // [\n * // { attribute: \"type\", operator: \"=\", value: \"submit\", quote: \"'\" },\n * // { attribute: \"disabled\" }\n * // ]\n */\nexport function extractAttributeSelectors(selector: string): AttributeSelector[] {\n const results: AttributeSelector[] = [];\n let idx = 0;\n\n while (idx < selector.length) {\n const char = selector.charCodeAt(idx);\n\n // Skip escaped characters\n if (char === BACKSLASH && idx + 1 < selector.length) {\n idx += 2;\n continue;\n }\n\n // Skip quoted strings\n if (char === DOUBLE_QUOTE || char === SINGLE_QUOTE) {\n idx++;\n while (idx < selector.length) {\n const c = selector.charCodeAt(idx);\n if (c === BACKSLASH && idx + 1 < selector.length) {\n idx += 2;\n continue;\n }\n if (c === char) {\n idx++;\n break;\n }\n idx++;\n }\n continue;\n }\n\n // Found start of attribute selector\n if (char === OPEN_BRACKET) {\n const start = idx;\n\n // Find matching close bracket\n idx++;\n let depth = 1;\n\n while (idx < selector.length && depth > 0) {\n const c = selector.charCodeAt(idx);\n\n if (c === BACKSLASH && idx + 1 < selector.length) {\n idx += 2;\n continue;\n }\n\n if (c === DOUBLE_QUOTE || c === SINGLE_QUOTE) {\n // Skip quoted content\n const quote = c;\n idx++;\n while (idx < selector.length) {\n const qc = selector.charCodeAt(idx);\n if (qc === BACKSLASH && idx + 1 < selector.length) {\n idx += 2;\n continue;\n }\n if (qc === quote) {\n idx++;\n break;\n }\n idx++;\n }\n continue;\n }\n\n if (c === OPEN_BRACKET) depth++;\n if (c === CLOSE_BRACKET) depth--;\n idx++;\n }\n\n const selectorStr = selector.slice(start, idx);\n const parsed = parseAttributeSelector(selectorStr);\n if (parsed) {\n results.push(parsed);\n }\n continue;\n }\n\n idx++;\n }\n\n return results;\n}\n\n/**\n * Match an attribute selector against an element's attributes.\n *\n * @example\n * matchAttributeSelector(\n * { attribute: \"data-state\", operator: \"=\", value: \"open\" },\n * { \"data-state\": \"open\", \"class\": \"modal\" }\n * )\n * // true\n */\nexport function matchAttributeSelector(selector: AttributeSelector, attributes: Record<string, string>): boolean {\n const value = attributes[selector.attribute];\n\n // Attribute doesn't exist\n if (value === undefined) {\n return false;\n }\n\n // Simple attribute selector - just check existence\n if (!selector.operator || selector.value === undefined) {\n return true;\n }\n\n const selectorValue = selector.value;\n // Per CSS spec, case-insensitive matching uses ASCII case folding\n const attrValue = selector.flags === \"i\" ? asciiLowerCase(value) : value;\n const compareValue = selector.flags === \"i\" ? asciiLowerCase(selectorValue) : selectorValue;\n\n switch (selector.operator) {\n case \"=\":\n return attrValue === compareValue;\n\n case \"~=\":\n return attrValue.split(/\\s+/).includes(compareValue);\n\n case \"|=\":\n return attrValue === compareValue || attrValue.startsWith(compareValue + \"-\");\n\n case \"^=\":\n return attrValue.startsWith(compareValue);\n\n case \"$=\":\n return attrValue.endsWith(compareValue);\n\n case \"*=\":\n return attrValue.includes(compareValue);\n\n default:\n return false;\n }\n}\n","/**\n * Selector Parser\n *\n * Minimal CSS selector parser for programmatic manipulation.\n * Supports parsing, serialization, and common transformations.\n */\n\n// ============================================\n// Types\n// ============================================\n\nexport type SelectorNode =\n | TypeSelector\n | ClassSelector\n | IdSelector\n | AttributeSelector\n | PseudoClassSelector\n | PseudoElementSelector\n | NestingSelector\n | UniversalSelector\n | Combinator\n | RawArgSelector;\n\nexport interface TypeSelector {\n kind: \"type\";\n name: string;\n}\n\nexport interface ClassSelector {\n kind: \"class\";\n name: string;\n}\n\nexport interface IdSelector {\n kind: \"id\";\n name: string;\n}\n\nexport interface AttributeSelector {\n kind: \"attribute\";\n name: string;\n operator?: \"=\" | \"~=\" | \"|=\" | \"^=\" | \"$=\" | \"*=\";\n value?: string;\n flags?: string;\n}\n\nexport interface PseudoClassSelector {\n kind: \"pseudo-class\";\n name: string;\n args?: SelectorNode[][];\n}\n\nexport interface PseudoElementSelector {\n kind: \"pseudo-element\";\n name: string;\n}\n\nexport interface NestingSelector {\n kind: \"nesting\";\n}\n\nexport interface UniversalSelector {\n kind: \"universal\";\n}\n\nexport interface Combinator {\n kind: \"combinator\";\n value: \" \" | \">\" | \"+\" | \"~\";\n}\n\n/**\n * Raw argument for pseudo-class functions like :nth-child(2n+1).\n * Stored as raw string to avoid conflating with type selectors\n * (which would affect specificity calculations).\n */\nexport interface RawArgSelector {\n kind: \"raw-arg\";\n value: string;\n}\n\nexport interface SelectorList {\n kind: \"selector-list\";\n selectors: SelectorNode[][];\n}\n\n// ============================================\n// Parser\n// ============================================\n\nconst WHITESPACE = /\\s/;\n\n// Pseudo-classes that take selector arguments (O(1) Set lookup instead of O(n) array.includes())\nconst SELECTOR_ARG_PSEUDO_CLASSES = new Set([\"not\", \"is\", \"has\", \"where\", \"matches\"]);\n\n// CSS identifier patterns - support full Unicode including astral plane (emojis, etc.)\n// Uses Unicode property escapes for proper character class support\n// - \\p{L}: Any letter (including non-Latin scripts)\n// - \\p{N}: Any numeric character\n// - \\p{M}: Combining marks (diacritics, etc.)\n// - Zero-width joiner (\\u200D) for emoji sequences\n// - Private use area and supplementary characters\nconst IDENT_START_UNICODE = /[a-zA-Z_\\u0080-\\uFFFF\\u{10000}-\\u{10FFFF}-]|\\p{L}/u;\n// eslint-disable-next-line no-misleading-character-class -- ZWJ (\\u200D) is intentional for emoji sequences in CSS identifiers\nconst IDENT_CHAR_UNICODE = /[a-zA-Z0-9_\\u0080-\\uFFFF\\u{10000}-\\u{10FFFF}\\u200D-]|\\p{L}|\\p{N}|\\p{M}/u;\n\n/**\n * Fast-path check for identifier start character.\n * Uses character code checks for common ASCII cases (which are the vast majority)\n * and falls back to regex only for non-ASCII characters.\n */\nfunction isIdentStart(char: string): boolean {\n const code = char.charCodeAt(0);\n\n // Fast path: ASCII letters, underscore, hyphen\n // a-z: 97-122, A-Z: 65-90, _: 95, -: 45\n if (\n (code >= 97 && code <= 122) || // a-z\n (code >= 65 && code <= 90) || // A-Z\n code === 95 || // _\n code === 45 // -\n ) {\n return true;\n }\n\n // Non-ASCII: fall back to regex\n if (code >= 0x80) {\n return IDENT_START_UNICODE.test(char);\n }\n\n return false;\n}\n\n/**\n * Fast-path check for identifier continuation character.\n * Uses character code checks for common ASCII cases and falls back to regex for Unicode.\n */\nfunction isIdentChar(char: string): boolean {\n const code = char.charCodeAt(0);\n\n // Fast path: ASCII letters, digits, underscore, hyphen\n // a-z: 97-122, A-Z: 65-90, 0-9: 48-57, _: 95, -: 45\n if (\n (code >= 97 && code <= 122) || // a-z\n (code >= 65 && code <= 90) || // A-Z\n (code >= 48 && code <= 57) || // 0-9\n code === 95 || // _\n code === 45 // -\n ) {\n return true;\n }\n\n // Non-ASCII: fall back to regex (includes combining marks, ZWJ, etc.)\n if (code >= 0x80) {\n return IDENT_CHAR_UNICODE.test(char);\n }\n\n return false;\n}\n\n/**\n * Parse a CSS selector string into a SelectorList AST.\n */\nexport function parseSelector(input: string): SelectorList {\n let pos = 0;\n\n function peek(): string {\n return input[pos] ?? \"\";\n }\n\n function advance(): string {\n return input[pos++] ?? \"\";\n }\n\n function skipWhitespace(): boolean {\n let skipped = false;\n while (WHITESPACE.test(peek())) {\n advance();\n skipped = true;\n }\n return skipped;\n }\n\n function parseIdent(): string {\n let name = \"\";\n // Handle escape sequences and identifiers\n while (pos < input.length) {\n const char = peek();\n if (char === \"\\\\\") {\n advance(); // consume backslash\n // Check for CSS Unicode escape (hex digits followed by optional whitespace)\n const nextChar = peek();\n if (/[0-9a-fA-F]/.test(nextChar)) {\n // Parse up to 6 hex digits\n let hexCode = \"\";\n while (hexCode.length < 6 && /[0-9a-fA-F]/.test(peek())) {\n hexCode += advance();\n }\n // Optional single whitespace after hex escape\n if (WHITESPACE.test(peek())) {\n advance();\n }\n // Convert hex to character\n const codePoint = parseInt(hexCode, 16);\n if (codePoint > 0 && codePoint <= 0x10ffff) {\n name += String.fromCodePoint(codePoint);\n }\n } else {\n // Regular escaped character\n name += advance();\n }\n } else if (isIdentChar(char)) {\n name += advance();\n } else {\n break;\n }\n }\n return name;\n }\n\n function parseString(quote: string): string {\n let value = \"\";\n advance(); // skip opening quote\n while (pos < input.length && peek() !== quote) {\n if (peek() === \"\\\\\") {\n advance();\n value += advance();\n } else {\n value += advance();\n }\n }\n advance(); // skip closing quote\n return value;\n }\n\n function parseAttributeSelector(): AttributeSelector {\n advance(); // skip [\n skipWhitespace();\n\n const name = parseIdent();\n skipWhitespace();\n\n let operator: AttributeSelector[\"operator\"];\n let value: string | undefined;\n let flags: string | undefined;\n\n const op = peek();\n if (op === \"=\") {\n operator = \"=\";\n advance();\n } else if (op === \"~\" || op === \"|\" || op === \"^\" || op === \"$\" || op === \"*\") {\n advance();\n if (peek() === \"=\") {\n operator = `${op}=` as AttributeSelector[\"operator\"];\n advance();\n }\n }\n\n if (operator) {\n skipWhitespace();\n const quote = peek();\n if (quote === '\"' || quote === \"'\") {\n value = parseString(quote);\n } else {\n value = parseIdent();\n }\n skipWhitespace();\n\n // Check for case sensitivity flag\n if (peek() === \"i\" || peek() === \"I\" || peek() === \"s\" || peek() === \"S\") {\n flags = advance().toLowerCase();\n }\n }\n\n skipWhitespace();\n if (peek() === \"]\") advance();\n\n return { kind: \"attribute\", name, operator, value, flags };\n }\n\n function parsePseudoClass(): PseudoClassSelector | PseudoElementSelector {\n advance(); // skip first :\n const isElement = peek() === \":\";\n if (isElement) advance();\n\n const name = parseIdent();\n\n if (isElement) {\n return { kind: \"pseudo-element\", name };\n }\n\n let args: SelectorNode[][] | undefined;\n\n // Check for functional pseudo-class\n if (peek() === \"(\") {\n advance();\n // Parse arguments as selector list for :not(), :is(), :has(), :where()\n if (SELECTOR_ARG_PSEUDO_CLASSES.has(name)) {\n args = parseSelectors();\n } else {\n // For other pseudo-classes, parse as raw content\n let depth = 1;\n let content = \"\";\n while (pos < input.length && depth > 0) {\n const char = peek();\n if (char === \"(\") depth++;\n if (char === \")\") depth--;\n if (depth > 0) content += advance();\n else advance();\n }\n // Store raw content as raw-arg node (not type selector to avoid specificity issues)\n if (content) {\n args = [[{ kind: \"raw-arg\", value: content.trim() }]];\n }\n }\n }\n\n return { kind: \"pseudo-class\", name, args };\n }\n\n function parseSimpleSelector(): SelectorNode | null {\n const char = peek();\n\n // Nesting selector\n if (char === \"&\") {\n advance();\n return { kind: \"nesting\" };\n }\n\n // Universal selector\n if (char === \"*\") {\n advance();\n return { kind: \"universal\" };\n }\n\n // Class selector\n if (char === \".\") {\n advance();\n return { kind: \"class\", name: parseIdent() };\n }\n\n // ID selector\n if (char === \"#\") {\n advance();\n return { kind: \"id\", name: parseIdent() };\n }\n\n // Attribute selector\n if (char === \"[\") {\n return parseAttributeSelector();\n }\n\n // Pseudo selector\n if (char === \":\") {\n return parsePseudoClass();\n }\n\n // Type selector (or end of input)\n if (isIdentStart(char)) {\n return { kind: \"type\", name: parseIdent() };\n }\n\n return null;\n }\n\n function parseCompoundSelector(): SelectorNode[] {\n const nodes: SelectorNode[] = [];\n\n while (pos < input.length) {\n const char = peek();\n\n // Stop at combinators or comma\n if (char === \">\" || char === \"+\" || char === \"~\" || char === \",\") {\n break;\n }\n\n // Check for descendant combinator (whitespace followed by non-combinator)\n if (WHITESPACE.test(char)) {\n skipWhitespace();\n const next = peek();\n if (next && next !== \">\" && next !== \"+\" && next !== \"~\" && next !== \",\" && next !== \")\") {\n nodes.push({ kind: \"combinator\", value: \" \" });\n }\n continue;\n }\n\n const node = parseSimpleSelector();\n if (!node) break;\n nodes.push(node);\n }\n\n return nodes;\n }\n\n function parseSelector(): SelectorNode[] {\n const nodes: SelectorNode[] = [];\n\n while (pos < input.length) {\n skipWhitespace();\n const char = peek();\n\n if (char === \"\" || char === \",\") break;\n\n // Combinators\n if (char === \">\") {\n advance();\n nodes.push({ kind: \"combinator\", value: \">\" });\n continue;\n }\n if (char === \"+\") {\n advance();\n nodes.push({ kind: \"combinator\", value: \"+\" });\n continue;\n }\n if (char === \"~\") {\n advance();\n nodes.push({ kind: \"combinator\", value: \"~\" });\n continue;\n }\n\n // Compound selector\n const compound = parseCompoundSelector();\n nodes.push(...compound);\n\n if (compound.length === 0) break;\n }\n\n return nodes;\n }\n\n function parseSelectors(): SelectorNode[][] {\n const selectors: SelectorNode[][] = [];\n\n while (pos < input.length) {\n skipWhitespace();\n if (peek() === \")\") break;\n\n const selector = parseSelector();\n if (selector.length > 0) {\n selectors.push(selector);\n }\n\n skipWhitespace();\n if (peek() === \",\") {\n advance();\n } else {\n break;\n }\n }\n\n return selectors;\n }\n\n return {\n kind: \"selector-list\",\n selectors: parseSelectors(),\n };\n}\n\n// ============================================\n// Serialization\n// ============================================\n\n/**\n * Serialize a selector node to a CSS string.\n */\nexport function serializeNode(node: SelectorNode): string {\n switch (node.kind) {\n case \"type\":\n return node.name;\n case \"class\":\n return `.${node.name}`;\n case \"id\":\n return `#${node.name}`;\n case \"universal\":\n return \"*\";\n case \"nesting\":\n return \"&\";\n case \"attribute\": {\n let result = `[${node.name}`;\n if (node.operator && node.value !== undefined) {\n const needsQuotes = /[\\s[\\]()'\"=~|^$*]/.test(node.value);\n const quote = needsQuotes ? '\"' : \"\";\n result += `${node.operator}${quote}${node.value}${quote}`;\n }\n if (node.flags) {\n result += ` ${node.flags}`;\n }\n return result + \"]\";\n }\n case \"pseudo-class\": {\n let result = `:${node.name}`;\n if (node.args) {\n result += `(${node.args.map(serializeSelector).join(\", \")})`;\n }\n return result;\n }\n case \"pseudo-element\":\n return `::${node.name}`;\n case \"combinator\":\n return node.value === \" \" ? \" \" : ` ${node.value} `;\n case \"raw-arg\":\n return node.value;\n }\n}\n\n/**\n * Serialize a selector (array of nodes) to a CSS string.\n */\nexport function serializeSelector(nodes: SelectorNode[]): string {\n return nodes.map(serializeNode).join(\"\");\n}\n\n/**\n * Serialize a selector list to a CSS string.\n */\nexport function serializeSelectorList(list: SelectorList): string {\n return list.selectors.map(serializeSelector).join(\", \");\n}\n\n// ============================================\n// Transformations\n// ============================================\n\n/**\n * Replace all nesting selectors (&) with a replacement selector string.\n */\nexport function replaceNesting(list: SelectorList, replacement: string): SelectorList {\n const replacementParsed = parseSelector(replacement);\n\n function replaceInNode(node: SelectorNode): SelectorNode[] {\n if (node.kind === \"nesting\") {\n return replacementParsed.selectors[0] ?? [];\n }\n if (node.kind === \"pseudo-class\" && node.args) {\n return [\n {\n ...node,\n args: node.args.map((selector) => selector.flatMap(replaceInNode)),\n },\n ];\n }\n return [node];\n }\n\n return {\n kind: \"selector-list\",\n selectors: list.selectors.map((selector) => selector.flatMap(replaceInNode)),\n };\n}\n\n/**\n * Check if a selector list contains a specific pseudo-class.\n */\nexport function hasPseudoClass(list: SelectorList, name: string): boolean {\n function checkNode(node: SelectorNode): boolean {\n if (node.kind === \"pseudo-class\" && node.name === name) {\n return true;\n }\n if (node.kind === \"pseudo-class\" && node.args) {\n return node.args.some((selector) => selector.some(checkNode));\n }\n return false;\n }\n\n return list.selectors.some((selector) => selector.some(checkNode));\n}\n\n/**\n * Check if a selector list contains a nesting selector (&).\n */\nexport function hasNesting(list: SelectorList): boolean {\n function checkNode(node: SelectorNode): boolean {\n if (node.kind === \"nesting\") return true;\n if (node.kind === \"pseudo-class\" && node.args) {\n return node.args.some((selector) => selector.some(checkNode));\n }\n return false;\n }\n\n return list.selectors.some((selector) => selector.some(checkNode));\n}\n\n/**\n * Extract all pseudo-class names from a selector list.\n */\nexport function extractPseudoClasses(list: SelectorList): string[] {\n const pseudos: string[] = [];\n\n function checkNode(node: SelectorNode): void {\n if (node.kind === \"pseudo-class\") {\n pseudos.push(node.name);\n if (node.args) {\n node.args.forEach((selector) => selector.forEach(checkNode));\n }\n }\n }\n\n list.selectors.forEach((selector) => selector.forEach(checkNode));\n return [...new Set(pseudos)];\n}\n\n/**\n * Prepend a selector to each selector in the list.\n */\nexport function prependSelector(list: SelectorList, prefix: string): SelectorList {\n const prefixParsed = parseSelector(prefix);\n const prefixNodes = prefixParsed.selectors[0] ?? [];\n\n return {\n kind: \"selector-list\",\n selectors: list.selectors.map((selector) => [\n ...prefixNodes,\n { kind: \"combinator\", value: \" \" } as Combinator,\n ...selector,\n ]),\n };\n}\n\n/**\n * Append a selector to each selector in the list.\n */\nexport function appendSelector(list: SelectorList, suffix: string): SelectorList {\n const suffixParsed = parseSelector(suffix);\n const suffixNodes = suffixParsed.selectors[0] ?? [];\n\n return {\n kind: \"selector-list\",\n selectors: list.selectors.map((selector) => [...selector, ...suffixNodes]),\n };\n}\n","/**\n * Generate the cartesian product of multiple arrays.\n *\n * @example\n * ```ts\n * cartesian([\"a\", \"b\"], [\"1\", \"2\"])\n * // [[\"a\", \"1\"], [\"a\", \"2\"], [\"b\", \"1\"], [\"b\", \"2\"]]\n *\n * cartesian([\"x\"], [\"y\", \"z\"], [\"1\", \"2\"])\n * // [[\"x\", \"y\", \"1\"], [\"x\", \"y\", \"2\"], [\"x\", \"z\", \"1\"], [\"x\", \"z\", \"2\"]]\n * ```\n */\nexport function cartesian<T>(...arrays: T[][]): T[][] {\n if (arrays.length === 0) return [[]];\n if (arrays.length === 1) return arrays[0]!.map((x) => [x]);\n\n const result: T[][] = [];\n\n function generate(current: T[], depth: number): void {\n if (depth === arrays.length) {\n result.push(current.slice());\n return;\n }\n\n const arr = arrays[depth]!;\n for (const item of arr) {\n current.push(item);\n generate(current, depth + 1);\n current.pop();\n }\n }\n\n generate([], 0);\n return result;\n}\n\n/**\n * Generate the cartesian product as an iterator (memory-efficient for large products).\n *\n * @example\n * ```ts\n * for (const combo of cartesianIterator([\"a\", \"b\"], [\"1\", \"2\"])) {\n * console.log(combo); // [\"a\", \"1\"], [\"a\", \"2\"], [\"b\", \"1\"], [\"b\", \"2\"]\n * }\n * ```\n */\nexport function* cartesianIterator<T>(...arrays: T[][]): Generator<T[]> {\n if (arrays.length === 0) {\n yield [];\n return;\n }\n\n if (arrays.some((arr) => arr.length === 0)) {\n return; // Empty product if any array is empty\n }\n\n const indices = arrays.map(() => 0);\n const lengths = arrays.map((arr) => arr.length);\n\n while (true) {\n // Yield current combination\n yield arrays.map((arr, i) => arr[indices[i]!]!);\n\n // Increment indices\n let i = arrays.length - 1;\n while (i >= 0) {\n indices[i]!++;\n if (indices[i]! < lengths[i]!) {\n break;\n }\n indices[i] = 0;\n i--;\n }\n\n // All combinations exhausted\n if (i < 0) break;\n }\n}\n\n/**\n * Calculate the size of a cartesian product without generating it.\n *\n * @example\n * ```ts\n * cartesianSize([[\"a\", \"b\"], [\"1\", \"2\", \"3\"]]) // 6\n * ```\n */\nexport function cartesianSize(arrays: unknown[][]): number {\n if (arrays.length === 0) return 1;\n return arrays.reduce((acc, arr) => acc * arr.length, 1);\n}\n\n/**\n * Generate cartesian product with a transform function.\n *\n * @example\n * ```ts\n * cartesianMap([\"a\", \"b\"], [\"1\", \"2\"], (a, b) => `${a}-${b}`)\n * // [\"a-1\", \"a-2\", \"b-1\", \"b-2\"]\n * ```\n */\nexport function cartesianMap<T, U>(array1: T[], array2: T[], fn: (a: T, b: T) => U): U[];\nexport function cartesianMap<T, U>(array1: T[], array2: T[], array3: T[], fn: (a: T, b: T, c: T) => U): U[];\nexport function cartesianMap<T, U>(...args: [...T[][], (...items: T[]) => U]): U[] {\n const fn = args.pop() as (...items: T[]) => U;\n const arrays = args as T[][];\n\n const result: U[] = [];\n\n for (const combo of cartesianIterator(...arrays)) {\n result.push(fn(...combo));\n }\n\n return result;\n}\n\n/**\n * Generate pairs from two arrays (2-way cartesian product).\n *\n * @example\n * ```ts\n * pairs([\"a\", \"b\"], [1, 2])\n * // [[\"a\", 1], [\"a\", 2], [\"b\", 1], [\"b\", 2]]\n * ```\n */\nexport function pairs<A, B>(array1: A[], array2: B[]): [A, B][] {\n const result: [A, B][] = [];\n\n for (const a of array1) {\n for (const b of array2) {\n result.push([a, b]);\n }\n }\n\n return result;\n}\n\n/**\n * Generate all combinations of a single array with itself.\n *\n * @example\n * ```ts\n * selfCartesian([\"a\", \"b\"], 2)\n * // [[\"a\", \"a\"], [\"a\", \"b\"], [\"b\", \"a\"], [\"b\", \"b\"]]\n * ```\n */\nexport function selfCartesian<T>(array: T[], repeat: number): T[][] {\n const arrays = Array(repeat).fill(array) as T[][];\n return cartesian(...arrays);\n}\n\n/**\n * Generate cartesian product but filter during generation.\n *\n * @example\n * ```ts\n * cartesianFilter(\n * [1, 2, 3],\n * [1, 2, 3],\n * (a, b) => a < b\n * )\n * // [[1, 2], [1, 3], [2, 3]]\n * ```\n */\nexport function cartesianFilter<T>(array1: T[], array2: T[], predicate: (a: T, b: T) => boolean): [T, T][];\nexport function cartesianFilter<T>(...args: [...T[][], (...items: T[]) => boolean]): T[][] {\n const predicate = args.pop() as (...items: T[]) => boolean;\n const arrays = args as T[][];\n\n const result: T[][] = [];\n\n for (const combo of cartesianIterator(...arrays)) {\n if (predicate(...combo)) {\n result.push(combo);\n }\n }\n\n return result;\n}\n","/**\n * @import Processing - Recursive inlining of CSS @import statements.\n */\n\nimport type { AstNode } from \"../ast\";\nimport { atRule } from \"../ast\";\nimport { asciiLowerCase } from \"../parser/parser-utils\";\n\ninterface ImportCacheEntry {\n contentHash: string;\n ast: AstNode[];\n lastAccess: number;\n}\n\n/** LRU cache for imported stylesheets with content hash validation. */\nexport class ImportCache {\n private cache = new Map<string, ImportCacheEntry>();\n private maxSize: number;\n\n constructor(options: { maxSize?: number } = {}) {\n this.maxSize = options.maxSize ?? 100;\n }\n\n get(path: string, contentHash: string): AstNode[] | null {\n const entry = this.cache.get(path);\n if (!entry) return null;\n if (entry.contentHash !== contentHash) {\n this.cache.delete(path);\n return null;\n }\n entry.lastAccess = Date.now();\n return entry.ast;\n }\n\n set(path: string, contentHash: string, ast: AstNode[]): void {\n if (this.cache.size >= this.maxSize && !this.cache.has(path)) {\n this.evictLRU();\n }\n this.cache.set(path, { contentHash, ast, lastAccess: Date.now() });\n }\n\n has(path: string): boolean {\n return this.cache.has(path);\n }\n\n invalidate(path: string): void {\n this.cache.delete(path);\n }\n\n clear(): void {\n this.cache.clear();\n }\n\n stats(): { size: number; maxSize: number } {\n return { size: this.cache.size, maxSize: this.maxSize };\n }\n\n private evictLRU(): void {\n let oldestPath: string | null = null;\n let oldestTime = Infinity;\n for (const [path, entry] of this.cache) {\n if (entry.lastAccess < oldestTime) {\n oldestTime = entry.lastAccess;\n oldestPath = path;\n }\n }\n if (oldestPath) this.cache.delete(oldestPath);\n }\n}\n\n/** FNV-1a hash for cache validation. */\nexport function hashContent(content: string): string {\n let hash = 2166136261;\n for (let i = 0; i < content.length; i++) {\n hash ^= content.charCodeAt(i);\n hash = Math.imul(hash, 16777619);\n }\n return (hash >>> 0).toString(16);\n}\n\nlet defaultImportCache: ImportCache | null = null;\n\nexport function getDefaultImportCache(): ImportCache {\n if (!defaultImportCache) {\n defaultImportCache = new ImportCache({ maxSize: 100 });\n }\n return defaultImportCache;\n}\n\nexport function clearDefaultImportCache(): void {\n defaultImportCache?.clear();\n}\n\nexport class CircularImportError extends Error {\n path: string;\n chain: string[];\n constructor(path: string, chain: string[]) {\n super(`Circular @import detected: ${[...chain, path].join(\" → \")}`);\n this.name = \"CircularImportError\";\n this.path = path;\n this.chain = chain;\n }\n}\n\nexport class ImportDepthError extends Error {\n depth: number;\n maxDepth: number;\n constructor(depth: number, maxDepth: number) {\n super(`@import recursion limit exceeded: depth ${depth} > max ${maxDepth}`);\n this.name = \"ImportDepthError\";\n this.depth = depth;\n this.maxDepth = maxDepth;\n }\n}\n\nexport interface SubstituteImportsOptions {\n loadStylesheet: (path: string, from: string) => Promise<AstNode[] | null> | AstNode[] | null;\n base: string;\n maxDepth?: number;\n onImport?: (path: string, from: string) => void;\n onError?: (path: string, from: string, error: Error) => void;\n}\n\nexport interface SubstituteImportsResult {\n ast: AstNode[];\n imports: string[];\n errors: Array<{ path: string; from: string; error: Error }>;\n}\n\n/** Check if import should be skipped (URLs, data URIs). */\nexport function shouldSkipImport(path: string): boolean {\n const trimmed = asciiLowerCase(path.trim());\n return (\n trimmed.startsWith(\"http://\") ||\n trimmed.startsWith(\"https://\") ||\n trimmed.startsWith(\"//\") ||\n trimmed.startsWith(\"data:\")\n );\n}\n\n/** Parse @import params to extract the path. */\nexport function parseImportPath(params: string): string | null {\n const trimmed = params.trim();\n const urlMatch = trimmed.match(/^url\\(\\s*[\"']?([^\"')]+)[\"']?\\s*\\)/);\n if (urlMatch) return urlMatch[1] ?? null;\n const quotedMatch = trimmed.match(/^[\"']([^\"']+)[\"']/);\n if (quotedMatch) return quotedMatch[1] ?? null;\n return null;\n}\n\n/** Extract content from balanced parentheses. */\nfunction extractBalancedParens(str: string, start: number): { content: string; end: number } | null {\n if (str[start] !== \"(\") return null;\n let depth = 1;\n let pos = start + 1;\n while (pos < str.length && depth > 0) {\n if (str[pos] === \"(\") depth++;\n else if (str[pos] === \")\") depth--;\n pos++;\n }\n if (depth !== 0) return null;\n return { content: str.slice(start + 1, pos - 1), end: pos };\n}\n\n/** Parse @import conditions (layer, supports, media). */\nexport function parseImportConditions(params: string): {\n path: string | null;\n layer?: string;\n supports?: string;\n media?: string;\n} {\n let remaining = params.trim();\n let path: string | null = null;\n\n const urlMatch = remaining.match(/^url\\(\\s*[\"']?([^\"')]+)[\"']?\\s*\\)/i);\n if (urlMatch) {\n path = urlMatch[1] ?? null;\n remaining = remaining.slice(urlMatch[0].length).trim();\n } else {\n const quotedMatch = remaining.match(/^[\"']([^\"']+)[\"']/);\n if (quotedMatch) {\n path = quotedMatch[1] ?? null;\n remaining = remaining.slice(quotedMatch[0].length).trim();\n }\n }\n\n let layer: string | undefined;\n let supports: string | undefined;\n\n const layerFnMatch = remaining.match(/layer\\s*\\(/i);\n if (layerFnMatch) {\n const layerIndex = layerFnMatch.index!;\n const parenStart = remaining.indexOf(\"(\", layerIndex);\n const result = extractBalancedParens(remaining, parenStart);\n if (result) {\n layer = result.content.trim();\n remaining = remaining.slice(0, layerIndex) + remaining.slice(result.end);\n remaining = remaining.trim();\n }\n } else {\n const bareLayerMatch = remaining.match(/\\blayer\\b(?!\\s*\\()/i);\n if (bareLayerMatch) {\n layer = \"\";\n remaining =\n remaining.slice(0, bareLayerMatch.index!) +\n remaining.slice(bareLayerMatch.index! + bareLayerMatch[0].length);\n remaining = remaining.trim();\n }\n }\n\n const supportsMatch = remaining.match(/supports\\s*\\(/i);\n if (supportsMatch) {\n const supportsIndex = supportsMatch.index!;\n const parenStart = remaining.indexOf(\"(\", supportsIndex);\n const result = extractBalancedParens(remaining, parenStart);\n if (result) {\n supports = result.content.trim();\n remaining = remaining.slice(0, supportsIndex) + remaining.slice(result.end);\n remaining = remaining.trim();\n }\n }\n\n const media = remaining.trim() || undefined;\n return { path, layer, supports, media };\n}\n\n/** Wrap AST nodes with layer/supports/media conditions. */\nexport function wrapWithConditions(\n nodes: AstNode[],\n conditions: { layer?: string; supports?: string; media?: string }\n): AstNode[] {\n let result = nodes;\n if (conditions.media) result = [atRule(\"media\", conditions.media, result)];\n if (conditions.supports) result = [atRule(\"supports\", conditions.supports, result)];\n if (conditions.layer) result = [atRule(\"layer\", conditions.layer, result)];\n return result;\n}\n\n/** Recursively substitute @import rules with their content. */\nexport async function substituteAtImports(\n ast: AstNode[],\n options: SubstituteImportsOptions\n): Promise<SubstituteImportsResult> {\n const { loadStylesheet, base, maxDepth = 10, onImport, onError } = options;\n const imports: string[] = [];\n const errors: Array<{ path: string; from: string; error: Error }> = [];\n\n async function processNodes(\n nodes: AstNode[],\n currentBase: string,\n depth: number,\n ancestors: Set<string>\n ): Promise<AstNode[]> {\n if (depth > maxDepth) throw new ImportDepthError(depth, maxDepth);\n const result: AstNode[] = [];\n\n for (const node of nodes) {\n const atRuleName = node.kind === \"at-rule\" ? asciiLowerCase(node.name) : \"\";\n const isImport = atRuleName === \"import\";\n const isReference = atRuleName === \"reference\";\n\n if (node.kind === \"at-rule\" && (isImport || isReference)) {\n const conditions = parseImportConditions(node.params);\n const path = conditions.path;\n\n if (!path) {\n result.push(node);\n continue;\n }\n if (isImport && asciiLowerCase(node.params.trim()).startsWith(\"url(\")) {\n result.push(node);\n continue;\n }\n if (shouldSkipImport(path)) {\n result.push(node);\n continue;\n }\n\n const resolvedPath = resolvePath(path, currentBase);\n if (ancestors.has(resolvedPath)) throw new CircularImportError(resolvedPath, Array.from(ancestors));\n\n imports.push(resolvedPath);\n onImport?.(resolvedPath, currentBase);\n\n try {\n const imported = await loadStylesheet(path, currentBase);\n if (imported === null) {\n const error = new Error(`Failed to load @import \"${path}\" from \"${currentBase}\"`);\n errors.push({ path: resolvedPath, from: currentBase, error });\n onError?.(resolvedPath, currentBase, error);\n result.push(node);\n continue;\n }\n\n const newBase = getDirectory(resolvedPath);\n const newAncestors = new Set(ancestors);\n newAncestors.add(resolvedPath);\n const processed = await processNodes(imported, newBase, depth + 1, newAncestors);\n result.push(...wrapWithConditions(processed, conditions));\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n errors.push({ path: resolvedPath, from: currentBase, error });\n onError?.(resolvedPath, currentBase, error);\n result.push(node);\n }\n } else if (\"nodes\" in node && Array.isArray(node.nodes) && node.nodes.length > 0) {\n const processedChildren = await processNodes(node.nodes, currentBase, depth, ancestors);\n result.push({ ...node, nodes: processedChildren } as AstNode);\n } else {\n result.push(node);\n }\n }\n return result;\n }\n\n return { ast: await processNodes(ast, base, 0, new Set()), imports, errors };\n}\n\n/** Synchronous version of substituteAtImports. */\nexport function substituteAtImportsSync(\n ast: AstNode[],\n options: Omit<SubstituteImportsOptions, \"loadStylesheet\"> & {\n loadStylesheet: (path: string, from: string) => AstNode[] | null;\n }\n): SubstituteImportsResult {\n const { loadStylesheet, base, maxDepth = 10, onImport, onError } = options;\n const imports: string[] = [];\n const errors: Array<{ path: string; from: string; error: Error }> = [];\n\n function processNodes(nodes: AstNode[], currentBase: string, depth: number, ancestors: Set<string>): AstNode[] {\n if (depth > maxDepth) throw new ImportDepthError(depth, maxDepth);\n const result: AstNode[] = [];\n\n for (const node of nodes) {\n const atRuleName = node.kind === \"at-rule\" ? asciiLowerCase(node.name) : \"\";\n const isImport = atRuleName === \"import\";\n const isReference = atRuleName === \"reference\";\n\n if (node.kind === \"at-rule\" && (isImport || isReference)) {\n const conditions = parseImportConditions(node.params);\n const path = conditions.path;\n\n if (!path) {\n result.push(node);\n continue;\n }\n if (isImport && asciiLowerCase(node.params.trim()).startsWith(\"url(\")) {\n result.push(node);\n continue;\n }\n if (shouldSkipImport(path)) {\n result.push(node);\n continue;\n }\n\n const resolvedPath = resolvePath(path, currentBase);\n if (ancestors.has(resolvedPath)) throw new CircularImportError(resolvedPath, Array.from(ancestors));\n\n imports.push(resolvedPath);\n onImport?.(resolvedPath, currentBase);\n\n try {\n const imported = loadStylesheet(path, currentBase);\n if (imported === null) {\n const error = new Error(`Failed to load @import \"${path}\" from \"${currentBase}\"`);\n errors.push({ path: resolvedPath, from: currentBase, error });\n onError?.(resolvedPath, currentBase, error);\n result.push(node);\n continue;\n }\n\n const newBase = getDirectory(resolvedPath);\n const newAncestors = new Set(ancestors);\n newAncestors.add(resolvedPath);\n const processed = processNodes(imported, newBase, depth + 1, newAncestors);\n result.push(...wrapWithConditions(processed, conditions));\n } catch (err) {\n const error = err instanceof Error ? err : new Error(String(err));\n errors.push({ path: resolvedPath, from: currentBase, error });\n onError?.(resolvedPath, currentBase, error);\n result.push(node);\n }\n } else if (\"nodes\" in node && Array.isArray(node.nodes) && node.nodes.length > 0) {\n const processedChildren = processNodes(node.nodes, currentBase, depth, ancestors);\n result.push({ ...node, nodes: processedChildren } as AstNode);\n } else {\n result.push(node);\n }\n }\n return result;\n }\n\n return { ast: processNodes(ast, base, 0, new Set()), imports, errors };\n}\n\n/** Resolve a path against a base, preventing traversal above root. */\nexport function resolvePath(path: string, base: string): string {\n if (path.startsWith(\"/\")) return normalizePath(path);\n const baseDir = getDirectory(base);\n const parts = [...baseDir.split(\"/\").filter(Boolean), ...path.split(\"/\")];\n const normalized: string[] = [];\n for (const part of parts) {\n if (part === \"..\") {\n if (normalized.length > 0) normalized.pop();\n } else if (part !== \".\") {\n normalized.push(part);\n }\n }\n return \"/\" + normalized.join(\"/\");\n}\n\n/** Normalize an absolute path. */\nexport function normalizePath(path: string): string {\n const parts = path.split(\"/\").filter(Boolean);\n const normalized: string[] = [];\n for (const part of parts) {\n if (part === \"..\") {\n if (normalized.length > 0) normalized.pop();\n } else if (part !== \".\") {\n normalized.push(part);\n }\n }\n return \"/\" + normalized.join(\"/\");\n}\n\nfunction getDirectory(path: string): string {\n const lastSlash = path.lastIndexOf(\"/\");\n if (lastSlash === -1) return \".\";\n return path.slice(0, lastSlash) || \"/\";\n}\n","// Pre-computed Sets for O(1) lookup (hoisted to avoid recreation on every call)\nconst COLOR_FUNCTION_NAMES = new Set([\"rgb\", \"rgba\", \"hsl\", \"hsla\", \"hwb\", \"lab\", \"lch\", \"oklch\", \"oklab\", \"color\"]);\nconst VALID_HEX_LENGTHS = new Set([3, 4, 6, 8]);\nconst _SHADOW_NAMED_COLORS = new Set([\n \"transparent\",\n \"currentcolor\",\n \"inherit\",\n \"black\",\n \"white\",\n \"red\",\n \"green\",\n \"blue\",\n \"yellow\",\n \"cyan\",\n \"magenta\",\n \"gray\",\n \"grey\",\n \"orange\",\n \"pink\",\n \"purple\",\n \"brown\",\n]);\n\n// Pre-compiled character class patterns for shadow parsing (hoisted to avoid recreation on every call)\nconst HEX_DIGIT_PATTERN = /[0-9a-fA-F]/;\nconst WHITESPACE_PATTERN = /\\s/;\nconst SHADOW_WORD_BOUNDARY_PATTERN = /[\\s,)]/;\n\n// Sorted by length descending for proper matching (longest match first)\nconst SHADOW_NAMED_COLORS_SORTED = [\n \"transparent\",\n \"currentcolor\",\n \"magenta\",\n \"inherit\",\n \"yellow\",\n \"orange\",\n \"purple\",\n \"brown\",\n \"green\",\n \"white\",\n \"black\",\n \"blue\",\n \"cyan\",\n \"gray\",\n \"grey\",\n \"pink\",\n \"red\",\n];\n\n/**\n * Shadow segment parsed from a shadow value.\n */\nexport interface ShadowSegment {\n /** The original text of this segment */\n raw: string;\n /** Whether this segment is a color */\n isColor: boolean;\n /** Start position in the original string */\n start: number;\n /** End position in the original string */\n end: number;\n}\n\n/**\n * Parse a CSS shadow value into segments, identifying color values.\n *\n * @example\n * ```ts\n * parseShadowSegments(\"0 1px 3px rgba(0, 0, 0, 0.1)\")\n * // [\n * // { raw: \"0 1px 3px \", isColor: false, start: 0, end: 11 },\n * // { raw: \"rgba(0, 0, 0, 0.1)\", isColor: true, start: 11, end: 29 }\n * // ]\n * ```\n */\nexport function parseShadowSegments(shadow: string): ShadowSegment[] {\n const segments: ShadowSegment[] = [];\n let i = 0;\n let currentStart = 0;\n let current = \"\";\n\n while (i < shadow.length) {\n const char = shadow[i]!;\n\n // Check for color functions\n const remaining = shadow.slice(i).toLowerCase();\n const parenIdx = remaining.indexOf(\"(\");\n\n if (parenIdx > 0) {\n const fnName = remaining.slice(0, parenIdx);\n if (COLOR_FUNCTION_NAMES.has(fnName)) {\n // Save any non-color content before this\n if (current) {\n segments.push({\n raw: current,\n isColor: false,\n start: currentStart,\n end: i,\n });\n }\n\n // Find the closing paren\n let depth = 0;\n let end = i;\n while (end < shadow.length) {\n if (shadow[end] === \"(\") depth++;\n if (shadow[end] === \")\") {\n depth--;\n if (depth === 0) {\n end++;\n break;\n }\n }\n end++;\n }\n\n const colorValue = shadow.slice(i, end);\n segments.push({\n raw: colorValue,\n isColor: true,\n start: i,\n end,\n });\n\n i = end;\n currentStart = end;\n current = \"\";\n continue;\n }\n }\n\n // Check for hex colors\n if (char === \"#\") {\n // Save any non-color content before this\n if (current) {\n segments.push({\n raw: current,\n isColor: false,\n start: currentStart,\n end: i,\n });\n }\n\n // Parse hex color\n let end = i + 1;\n while (end < shadow.length && HEX_DIGIT_PATTERN.test(shadow[end]!)) {\n end++;\n }\n\n const hexValue = shadow.slice(i, end);\n // Validate hex length (3, 4, 6, or 8 digits)\n const hexDigits = hexValue.length - 1;\n if (VALID_HEX_LENGTHS.has(hexDigits)) {\n segments.push({\n raw: hexValue,\n isColor: true,\n start: i,\n end,\n });\n i = end;\n currentStart = end;\n current = \"\";\n continue;\n }\n }\n\n // Check for named colors (simple word boundary check)\n let foundNamed = false;\n for (const color of SHADOW_NAMED_COLORS_SORTED) {\n if (\n shadow.slice(i).toLowerCase().startsWith(color) &&\n (i === 0 || WHITESPACE_PATTERN.test(shadow[i - 1]!)) &&\n (i + color.length >= shadow.length || SHADOW_WORD_BOUNDARY_PATTERN.test(shadow[i + color.length]!))\n ) {\n // Save any non-color content before this\n if (current) {\n segments.push({\n raw: current,\n isColor: false,\n start: currentStart,\n end: i,\n });\n }\n\n const colorValue = shadow.slice(i, i + color.length);\n segments.push({\n raw: colorValue,\n isColor: true,\n start: i,\n end: i + color.length,\n });\n\n i += color.length;\n currentStart = i;\n current = \"\";\n foundNamed = true;\n break;\n }\n }\n\n if (foundNamed) continue;\n\n current += char;\n i++;\n }\n\n // Add any remaining content\n if (current) {\n segments.push({\n raw: current,\n isColor: false,\n start: currentStart,\n end: shadow.length,\n });\n }\n\n return segments;\n}\n\n/**\n * Replace colors in a shadow value using a replacer function.\n *\n * @param shadow - The shadow value to process\n * @param replacer - Function to replace each color, receives the color string and returns the replacement\n * @returns The shadow with colors replaced\n *\n * @example\n * ```ts\n * replaceShadowColors(\"0 1px 3px rgba(0, 0, 0, 0.1)\", () => \"var(--shadow-color)\")\n * // \"0 1px 3px var(--shadow-color)\"\n *\n * replaceShadowColors(\"0 1px 3px black, 0 2px 6px #00000020\", (c) => `color-mix(in srgb, ${c}, transparent 50%)`)\n * // \"0 1px 3px color-mix(in srgb, black, transparent 50%), 0 2px 6px color-mix(in srgb, #00000020, transparent 50%)\"\n * ```\n */\nexport function replaceShadowColors(shadow: string, replacer: (color: string, index: number) => string): string {\n const segments = parseShadowSegments(shadow);\n\n let result = \"\";\n let colorIndex = 0;\n\n for (const segment of segments) {\n if (segment.isColor) {\n result += replacer(segment.raw, colorIndex++);\n } else {\n result += segment.raw;\n }\n }\n\n return result;\n}\n\n/**\n * Extract all colors from a shadow value.\n *\n * @example\n * ```ts\n * extractShadowColors(\"0 1px 3px rgba(0, 0, 0, 0.1), 0 2px 6px #00000020\")\n * // [\"rgba(0, 0, 0, 0.1)\", \"#00000020\"]\n * ```\n */\nexport function extractShadowColors(shadow: string): string[] {\n const colors: string[] = [];\n for (const segment of parseShadowSegments(shadow)) {\n if (segment.isColor) {\n colors.push(segment.raw);\n }\n }\n return colors;\n}\n\n/**\n * Check if a shadow value contains any colors.\n *\n * @example\n * ```ts\n * shadowHasColors(\"0 1px 3px rgba(0, 0, 0, 0.1)\") // true\n * shadowHasColors(\"0 1px 3px\") // false\n * ```\n */\nexport function shadowHasColors(shadow: string): boolean {\n const segments = parseShadowSegments(shadow);\n return segments.some((s) => s.isColor);\n}\n\n/**\n * Remove all colors from a shadow value.\n *\n * @example\n * ```ts\n * stripShadowColors(\"0 1px 3px rgba(0, 0, 0, 0.1)\")\n * // \"0 1px 3px\"\n * ```\n */\nexport function stripShadowColors(shadow: string): string {\n return replaceShadowColors(shadow, () => \"\")\n .replace(/\\s+/g, \" \")\n .trim();\n}\n\n/**\n * Replace shadow colors with a CSS variable reference.\n *\n * @param shadow - The shadow value\n * @param varName - The CSS variable name (with or without --)\n * @returns Shadow with colors replaced by var() reference\n *\n * @example\n * ```ts\n * shadowWithVariable(\"0 1px 3px rgba(0, 0, 0, 0.1)\", \"--shadow-color\")\n * // \"0 1px 3px var(--shadow-color, rgba(0, 0, 0, 0.1))\"\n * ```\n */\nexport function shadowWithVariable(shadow: string, varName: string): string {\n const normalizedVar = varName.startsWith(\"--\") ? varName : `--${varName}`;\n return replaceShadowColors(shadow, (color) => `var(${normalizedVar}, ${color})`);\n}\n","/**\n * Google Fonts Metadata System\n *\n * Hybrid approach for font metadata:\n * 1. Bundled snapshot of top 200 fonts (works offline)\n * 2. On-demand fetch from Google Fonts API\n * 3. Local cache with 7-day TTL\n */\n\nimport { existsSync, readFileSync, writeFileSync, mkdirSync } from \"node:fs\";\nimport { join, dirname, isAbsolute } from \"node:path\";\nimport { tmpdir } from \"node:os\";\n\n// ============================================\n// Types\n// ============================================\n\n/**\n * Metadata for a Google Font.\n */\nexport interface FontMetadata {\n /** Font family name (e.g., \"Inter\", \"Roboto\") */\n family: string;\n /** Available weights (e.g., [100, 200, 300, 400, 500, 600, 700, 800, 900]) */\n weights: number[];\n /** Available styles (e.g., [\"normal\", \"italic\"]) */\n styles: (\"normal\" | \"italic\")[];\n /** Whether the font supports variable axes */\n isVariable: boolean;\n /** Variable font axes (only if isVariable is true) */\n variableAxes?: {\n wght?: { min: number; max: number };\n ital?: { min: number; max: number };\n opsz?: { min: number; max: number };\n wdth?: { min: number; max: number };\n };\n /** Font subsets (e.g., [\"latin\", \"latin-ext\", \"cyrillic\"]) */\n subsets: string[];\n /** Last modified date from Google Fonts */\n lastModified?: string;\n}\n\n/**\n * Cache entry structure.\n */\ninterface CacheEntry {\n metadata: FontMetadata;\n fetchedAt: number;\n}\n\n/**\n * Cached metadata file structure.\n */\ninterface MetadataCache {\n version: 1;\n entries: Record<string, CacheEntry>;\n}\n\n// ============================================\n// Constants\n// ============================================\n\n/** Cache time-to-live: 7 days in milliseconds */\nconst CACHE_TTL = 7 * 24 * 60 * 60 * 1000;\n\n/** Cache file name */\nconst CACHE_FILE = \"google-fonts-cache.json\";\n\n/** Google Fonts metadata API endpoint (no API key required) */\nconst GOOGLE_FONTS_API = \"https://fonts.google.com/metadata/fonts\";\n\n// ============================================\n// Bundled Snapshot\n// ============================================\n\nlet bundledSnapshot: Record<string, FontMetadata> | null = null;\n/** Case-insensitive index: lowercase family name -> original family name */\nlet bundledSnapshotIndex: Map<string, string> | null = null;\n\n/**\n * Load the bundled snapshot of popular fonts.\n * Returns empty object if snapshot doesn't exist.\n */\nfunction loadBundledSnapshot(): Record<string, FontMetadata> {\n if (bundledSnapshot !== null) {\n return bundledSnapshot;\n }\n\n const snapshotPath = join(__dirname, \"../data/google-snapshot.json\");\n\n if (!existsSync(snapshotPath)) {\n bundledSnapshot = {};\n bundledSnapshotIndex = new Map();\n return bundledSnapshot;\n }\n\n try {\n const data = JSON.parse(readFileSync(snapshotPath, \"utf-8\"));\n bundledSnapshot = data as Record<string, FontMetadata>;\n bundledSnapshotIndex = new Map();\n for (const key of Object.keys(bundledSnapshot)) {\n bundledSnapshotIndex.set(key.toLowerCase(), key);\n }\n } catch {\n bundledSnapshot = {};\n bundledSnapshotIndex = new Map();\n }\n\n return bundledSnapshot;\n}\n\n/**\n * Get metadata from bundled snapshot.\n * Normalizes family name for case-insensitive lookup.\n */\nexport function getBundledMetadata(family: string): FontMetadata | null {\n const snapshot = loadBundledSnapshot();\n\n if (snapshot[family]) {\n return snapshot[family]!;\n }\n\n const originalKey = bundledSnapshotIndex?.get(family.toLowerCase());\n if (originalKey) {\n return snapshot[originalKey]!;\n }\n\n return null;\n}\n\n// ============================================\n// Local Cache\n// ============================================\n\nlet memoryCache: MetadataCache | null = null;\n\n/**\n * Get the cache file path.\n * Uses OS temp directory to avoid issues with cross-platform paths\n * (e.g., process.cwd() returning Windows paths in CI environments).\n */\nfunction getCachePath(): string {\n // Use temp directory instead of process.cwd() to avoid issues where\n // process.cwd() returns a Windows-style path (e.g., \"C:\\project\") in\n // CI environments, which creates malformed directories on Unix systems.\n const cwd = process.cwd();\n const baseDir = isAbsolute(cwd) && !cwd.includes(\"\\\\\") ? cwd : tmpdir();\n return join(baseDir, \"node_modules\", \".cache\", \"rainbowindex\", CACHE_FILE);\n}\n\n/**\n * Load the local cache from disk.\n */\nfunction loadCache(): MetadataCache {\n if (memoryCache !== null) {\n return memoryCache;\n }\n\n const cachePath = getCachePath();\n if (existsSync(cachePath)) {\n try {\n const data = JSON.parse(readFileSync(cachePath, \"utf-8\"));\n if (data.version === 1) {\n memoryCache = data as MetadataCache;\n return memoryCache;\n }\n } catch {\n // Invalid cache, will recreate\n }\n }\n\n const newCache: MetadataCache = { version: 1, entries: {} };\n memoryCache = newCache;\n return newCache;\n}\n\n/**\n * Save the local cache to disk.\n */\nfunction saveCache(): void {\n if (!memoryCache) return;\n\n const cachePath = getCachePath();\n try {\n mkdirSync(dirname(cachePath), { recursive: true });\n writeFileSync(cachePath, JSON.stringify(memoryCache, null, 2));\n } catch {\n // Silently fail if we can't write cache\n }\n}\n\n/**\n * Get metadata from local cache.\n * Returns null if not cached or expired.\n */\nexport function getCachedMetadata(family: string): FontMetadata | null {\n const cache = loadCache();\n const entry = cache.entries[normalizeFamily(family)];\n\n if (!entry || Date.now() - entry.fetchedAt > CACHE_TTL) {\n return null;\n }\n\n return entry.metadata;\n}\n\n/**\n * Store metadata in local cache.\n */\nfunction setCachedMetadata(family: string, metadata: FontMetadata): void {\n const cache = loadCache();\n const normalized = normalizeFamily(family);\n\n cache.entries[normalized] = {\n metadata,\n fetchedAt: Date.now(),\n };\n\n saveCache();\n}\n\n// ============================================\n// API Fetching\n// ============================================\n\n/**\n * Normalize font family name for lookup.\n * Converts to lowercase and trims whitespace.\n */\nfunction normalizeFamily(family: string): string {\n return family.trim().toLowerCase();\n}\n\n/**\n * Parse Google Fonts API response into FontMetadata.\n */\nfunction parseGoogleFontData(fontData: GoogleFontApiItem): FontMetadata {\n const weights: number[] = [];\n const styles: (\"normal\" | \"italic\")[] = [];\n let hasNormal = false;\n let hasItalic = false;\n\n const variableAxes: FontMetadata[\"variableAxes\"] = {};\n const isVariable = fontData.axes !== undefined && fontData.axes.length > 0;\n\n if (isVariable) {\n for (const axis of fontData.axes!) {\n const tag = axis.tag.toLowerCase() as \"wght\" | \"ital\" | \"opsz\" | \"wdth\";\n\n switch (tag) {\n case \"wght\":\n variableAxes.wght = { min: axis.min, max: axis.max };\n for (let w = Math.ceil(axis.min / 100) * 100; w <= axis.max; w += 100) {\n if (w >= 100 && w <= 900) {\n weights.push(w);\n }\n }\n break;\n case \"ital\":\n case \"opsz\":\n case \"wdth\":\n variableAxes[tag] = { min: axis.min, max: axis.max };\n break;\n }\n }\n }\n\n // Parse font files/variants\n if (fontData.fonts) {\n for (const [key] of Object.entries(fontData.fonts)) {\n // Keys are like \"400\", \"400i\", \"700\", \"700i\"\n const match = key.match(/^(\\d+)(i)?$/);\n if (match) {\n const weight = parseInt(match[1]!, 10);\n if (!weights.includes(weight)) {\n weights.push(weight);\n }\n if (match[2] === \"i\") {\n hasItalic = true;\n } else {\n hasNormal = true;\n }\n }\n }\n }\n\n // Fallback to default weight if none found\n if (weights.length === 0) {\n weights.push(400);\n }\n\n // Determine styles\n if (hasNormal || !hasItalic) {\n styles.push(\"normal\");\n }\n if (hasItalic || (isVariable && variableAxes.ital)) {\n styles.push(\"italic\");\n }\n if (styles.length === 0) {\n styles.push(\"normal\");\n }\n\n // Sort weights\n weights.sort((a, b) => a - b);\n\n return {\n family: fontData.family,\n weights,\n styles,\n isVariable,\n variableAxes: isVariable ? variableAxes : undefined,\n subsets: fontData.subsets ?? [],\n lastModified: fontData.lastModified,\n };\n}\n\n/**\n * Google Fonts API response item structure.\n */\ninterface GoogleFontApiItem {\n family: string;\n axes?: Array<{ tag: string; min: number; max: number }>;\n fonts?: Record<\n string,\n { thickness: number | null; slant: number | null; width: number | null; lineHeight: number }\n >;\n subsets?: string[];\n lastModified?: string;\n}\n\n/**\n * Fetch font metadata from Google Fonts API.\n * Returns null if the font is not found or on network error.\n */\nexport async function fetchFontMetadata(family: string): Promise<FontMetadata | null> {\n try {\n const response = await fetch(GOOGLE_FONTS_API);\n if (!response.ok) {\n return null;\n }\n\n const data = (await response.json()) as { familyMetadataList?: GoogleFontApiItem[] };\n const fonts = data.familyMetadataList;\n\n if (!Array.isArray(fonts)) {\n return null;\n }\n\n // Find the font (case-insensitive)\n const normalized = normalizeFamily(family);\n const fontData = fonts.find((f) => normalizeFamily(f.family) === normalized);\n\n if (!fontData) {\n return null;\n }\n\n return parseGoogleFontData(fontData);\n } catch {\n return null;\n }\n}\n\n/**\n * Fetch metadata and cache it.\n */\nexport async function fetchAndCacheMetadata(family: string): Promise<FontMetadata | null> {\n const metadata = await fetchFontMetadata(family);\n if (metadata) {\n setCachedMetadata(family, metadata);\n }\n return metadata;\n}\n\n// ============================================\n// Main API\n// ============================================\n\n/**\n * Get font metadata using the hybrid resolution order:\n * 1. Bundled snapshot (instant, offline)\n * 2. Local cache (fast, may be expired)\n * 3. Network fetch (slow, fresh data)\n *\n * @param family Font family name (e.g., \"Inter\", \"Roboto\")\n * @returns Font metadata or null if not found\n */\nexport async function getFontMetadata(family: string): Promise<FontMetadata | null> {\n // 1. Check bundled snapshot\n const bundled = getBundledMetadata(family);\n if (bundled) {\n return bundled;\n }\n\n // 2. Check local cache\n const cached = getCachedMetadata(family);\n if (cached) {\n return cached;\n }\n\n // 3. Fetch from API\n return fetchAndCacheMetadata(family);\n}\n\n/**\n * Synchronous version that only checks bundled snapshot and cache.\n * Does not make network requests.\n *\n * @param family Font family name\n * @returns Font metadata or null if not available offline\n */\nexport function getFontMetadataSync(family: string): FontMetadata | null {\n // 1. Check bundled snapshot\n const bundled = getBundledMetadata(family);\n if (bundled) {\n return bundled;\n }\n\n // 2. Check local cache\n const cached = getCachedMetadata(family);\n if (cached) {\n return cached;\n }\n\n return null;\n}\n\n/**\n * Clear the in-memory cache.\n * Useful for testing.\n */\nexport function clearMemoryCache(): void {\n memoryCache = null;\n bundledSnapshot = null;\n bundledSnapshotIndex = null;\n}\n","/**\n * Google Fonts URL Generator\n *\n * Generates Google Fonts API v2 URLs and preload hints.\n * Supports both CDN and self-hosted font loading.\n */\n\nimport type { FontMetadata } from \"./google-metadata\";\n\n// ============================================\n// Types\n// ============================================\n\n/**\n * Options for generating a Google Fonts URL.\n */\nexport interface GoogleFontOptions {\n /** Font family name (e.g., \"Inter\", \"Roboto\") */\n family: string;\n /** Specific weights to include. If not specified, uses metadata weights. */\n weights?: number[];\n /** Include italic variants */\n italic?: boolean;\n /** Force variable or static font mode. If not specified, auto-detects. */\n variable?: boolean;\n /** Font display strategy */\n display?: \"auto\" | \"block\" | \"swap\" | \"fallback\" | \"optional\";\n /** Hosting mode: CDN (default) or self-hosted */\n host?: \"cdn\" | \"self\";\n /** URL path for self-hosted fonts (e.g., \"/fonts\") */\n path?: string;\n}\n\n/**\n * Preload link for HTML <head>.\n */\nexport interface FontPreloadLink {\n /** Link relation type */\n rel: \"preconnect\" | \"preload\" | \"stylesheet\";\n /** URL */\n href: string;\n /** Resource type for preload */\n as?: \"style\" | \"font\";\n /** Whether to include crossorigin attribute */\n crossorigin?: boolean;\n /** MIME type for font preloading */\n type?: string;\n}\n\n/**\n * Result of font URL generation.\n */\nexport interface FontUrlResult {\n /** The @import URL for CSS */\n importUrl: string;\n /** Preload hints for HTML <head> */\n preloadLinks: FontPreloadLink[];\n /** CSS comment with HTML hints */\n htmlComment: string;\n}\n\n/**\n * Result of @font-face generation for self-hosted fonts.\n */\nexport interface FontFaceResult {\n /** Generated @font-face CSS declarations */\n css: string;\n /** Font file URLs that need to be downloaded */\n fontUrls: Array<{\n url: string;\n filename: string;\n weight: number;\n style: \"normal\" | \"italic\";\n }>;\n}\n\n// ============================================\n// Constants\n// ============================================\n\nconst GOOGLE_FONTS_CSS_API = \"https://fonts.googleapis.com/css2\";\nconst GOOGLE_FONTS_PRECONNECT = \"https://fonts.googleapis.com\";\nconst GOOGLE_FONTS_STATIC = \"https://fonts.gstatic.com\";\n\n// ============================================\n// URL Generation (CDN Mode)\n// ============================================\n\n/**\n * Generate a Google Fonts API v2 URL.\n *\n * @param options Font options\n * @param metadata Font metadata from Google Fonts\n * @returns Google Fonts CSS URL\n */\nexport function generateGoogleFontsUrl(options: GoogleFontOptions, metadata: FontMetadata): string {\n const { family, display = \"swap\" } = options;\n\n // URL-encode family name (spaces -> +)\n const encodedFamily = encodeURIComponent(family).replace(/%20/g, \"+\");\n\n // Determine weights to include\n const weights = options.weights ?? metadata.weights;\n\n // Determine if using variable font\n const isVariable = options.variable ?? metadata.isVariable;\n\n // Determine if including italics\n const includeItalic = options.italic ?? (metadata.styles.includes(\"italic\") && isVariable);\n\n // Build axis specification\n let axisSpec: string;\n\n if (isVariable && metadata.variableAxes?.wght) {\n // Variable font: use weight ranges\n const { min, max } = metadata.variableAxes.wght;\n const minWeight = options.weights ? Math.max(Math.min(...options.weights), min) : min;\n const maxWeight = options.weights ? Math.min(Math.max(...options.weights), max) : max;\n\n if (includeItalic) {\n // Include optical size if available\n if (metadata.variableAxes.opsz) {\n const opsz = metadata.variableAxes.opsz;\n axisSpec = `ital,opsz,wght@0,${opsz.min}..${opsz.max},${minWeight}..${maxWeight};1,${opsz.min}..${opsz.max},${minWeight}..${maxWeight}`;\n } else {\n axisSpec = `ital,wght@0,${minWeight}..${maxWeight};1,${minWeight}..${maxWeight}`;\n }\n } else {\n if (metadata.variableAxes.opsz) {\n const opsz = metadata.variableAxes.opsz;\n axisSpec = `opsz,wght@${opsz.min}..${opsz.max},${minWeight}..${maxWeight}`;\n } else {\n axisSpec = `wght@${minWeight}..${maxWeight}`;\n }\n }\n } else {\n // Static font: list individual weights\n const sortedWeights = [...weights].sort((a, b) => a - b);\n\n if (includeItalic) {\n const specs: string[] = [];\n for (const weight of sortedWeights) {\n specs.push(`0,${weight}`);\n }\n for (const weight of sortedWeights) {\n specs.push(`1,${weight}`);\n }\n axisSpec = `ital,wght@${specs.join(\";\")}`;\n } else {\n axisSpec = `wght@${sortedWeights.join(\";\")}`;\n }\n }\n\n return `${GOOGLE_FONTS_CSS_API}?family=${encodedFamily}:${axisSpec}&display=${display}`;\n}\n\n/**\n * Generate preload links for HTML <head>.\n *\n * @param fontUrl Google Fonts CSS URL\n * @returns Array of preload links\n */\nexport function generatePreloadLinks(fontUrl: string): FontPreloadLink[] {\n return [\n {\n rel: \"preconnect\",\n href: GOOGLE_FONTS_PRECONNECT,\n },\n {\n rel: \"preconnect\",\n href: GOOGLE_FONTS_STATIC,\n crossorigin: true,\n },\n {\n rel: \"preload\",\n href: fontUrl,\n as: \"style\",\n },\n ];\n}\n\n/**\n * Generate HTML comment with preload hints.\n *\n * @param links Preload links\n * @returns CSS comment containing HTML to copy\n */\nexport function generateHtmlComment(links: FontPreloadLink[]): string {\n const htmlLines = links.map(linkToHtml);\n\n return `/*!\n * @rainbowindex/fonts - Copy to HTML <head> for optimal loading:\n * ${htmlLines.join(\"\\n * \")}\n */`;\n}\n\n/**\n * Convert a single preload link to an HTML string.\n */\nfunction linkToHtml(link: FontPreloadLink): string {\n let attrs = `rel=\"${link.rel}\" href=\"${link.href}\"`;\n if (link.as) attrs += ` as=\"${link.as}\"`;\n if (link.crossorigin) attrs += \" crossorigin\";\n if (link.type) attrs += ` type=\"${link.type}\"`;\n return `<link ${attrs}>`;\n}\n\n/**\n * Generate full font URL result with preload hints.\n *\n * @param options Font options\n * @param metadata Font metadata\n * @returns Import URL, preload links, and HTML comment\n */\nexport function generateFontUrl(options: GoogleFontOptions, metadata: FontMetadata): FontUrlResult {\n const importUrl = generateGoogleFontsUrl(options, metadata);\n const preloadLinks = generatePreloadLinks(importUrl);\n const htmlComment = generateHtmlComment(preloadLinks);\n\n return {\n importUrl,\n preloadLinks,\n htmlComment,\n };\n}\n\n// ============================================\n// @font-face Generation (Self-Hosted Mode)\n// ============================================\n\n/**\n * Generate @font-face declarations for self-hosted fonts.\n *\n * @param options Font options\n * @param metadata Font metadata\n * @returns CSS and font file URLs\n */\nexport function generateFontFace(options: GoogleFontOptions, metadata: FontMetadata): FontFaceResult {\n const { family, display = \"swap\", path = \"/fonts\" } = options;\n\n // Determine weights to include\n const weights = options.weights ?? metadata.weights;\n\n // Determine if including italics\n const includeItalic = options.italic ?? metadata.styles.includes(\"italic\");\n\n // Normalize path (remove trailing slash)\n const normalizedPath = path.replace(/\\/$/, \"\");\n\n // Generate filename-safe version of family name\n const fileFamily = family.toLowerCase().replace(/\\s+/g, \"-\");\n\n const fontUrls: FontFaceResult[\"fontUrls\"] = [];\n const fontFaceDecls: string[] = [];\n\n const styles: Array<\"normal\" | \"italic\"> = [\"normal\"];\n if (includeItalic) {\n styles.push(\"italic\");\n }\n\n for (const weight of weights) {\n for (const style of styles) {\n // Skip italic if not available\n if (style === \"italic\" && !metadata.styles.includes(\"italic\")) {\n continue;\n }\n\n const suffix = style === \"italic\" ? \"i\" : \"\";\n const filename = `${fileFamily}-${weight}${suffix}.woff2`;\n const url = `${normalizedPath}/${filename}`;\n\n // Google Fonts woff2 URL pattern\n // This is a simplified version - actual self-hosting would need to download from\n // the CSS response which contains the actual font URLs\n fontUrls.push({\n url,\n filename,\n weight,\n style,\n });\n\n fontFaceDecls.push(`@font-face {\n font-family: '${family}';\n font-style: ${style};\n font-weight: ${weight};\n font-display: ${display};\n src: url('${url}') format('woff2');\n}`);\n }\n }\n\n return {\n css: fontFaceDecls.join(\"\\n\\n\"),\n fontUrls,\n };\n}\n\n// ============================================\n// Combined Generation\n// ============================================\n\n/**\n * Generate font CSS based on options.\n * Returns @import URL for CDN mode, or @font-face declarations for self-hosted.\n *\n * @param options Font options\n * @param metadata Font metadata\n * @returns CSS string and metadata\n */\nexport function generateFontCss(\n options: GoogleFontOptions,\n metadata: FontMetadata\n): {\n css: string;\n preloadLinks: FontPreloadLink[];\n mode: \"cdn\" | \"self\";\n fontUrls?: FontFaceResult[\"fontUrls\"];\n} {\n if (options.host === \"self\") {\n const result = generateFontFace(options, metadata);\n return {\n css: result.css,\n preloadLinks: [],\n mode: \"self\",\n fontUrls: result.fontUrls,\n };\n }\n\n // CDN mode (default)\n const result = generateFontUrl(options, metadata);\n return {\n css: `${result.htmlComment}\\n@import url('${result.importUrl}');`,\n preloadLinks: result.preloadLinks,\n mode: \"cdn\",\n };\n}\n\n// ============================================\n// Utility: Extract preload links from compiled CSS\n// ============================================\n\n/**\n * Extract font preload links from compiled CSS.\n * Parses CSS to find Google Fonts @import statements and generates preload hints.\n *\n * @param css Compiled CSS string\n * @returns Array of preload links for HTML <head>\n */\nexport function getFontPreloadLinks(css: string): FontPreloadLink[] {\n const links: FontPreloadLink[] = [];\n const seenUrls = new Set<string>();\n const seenPreconnect = new Set<string>();\n\n const importRegex = /@import\\s+url\\(['\"]?(https:\\/\\/fonts\\.googleapis\\.com\\/css2\\?[^'\")\\s]+)['\"]?\\)/gi;\n let match;\n\n while ((match = importRegex.exec(css)) !== null) {\n const fontUrl = match[1]!;\n if (seenUrls.has(fontUrl)) continue;\n\n seenUrls.add(fontUrl);\n\n for (const link of generatePreloadLinks(fontUrl)) {\n if (link.rel === \"preconnect\") {\n const key = `${link.href}-${link.crossorigin ?? false}`;\n if (seenPreconnect.has(key)) continue;\n seenPreconnect.add(key);\n }\n links.push(link);\n }\n }\n\n return links;\n}\n\n/**\n * Generate HTML string for preload links.\n * Useful for build tool plugins.\n *\n * @param links Preload links\n * @returns HTML string for <head>\n */\nexport function preloadLinksToHtml(links: FontPreloadLink[]): string {\n return links.map(linkToHtml).join(\"\\n\");\n}\n"],"mappings":"kfAAA,IAAAA,GAAAC,GAAA,CAAA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,GAAoB,CAEtB,UACA,WACA,OACA,OACA,QACA,QACA,aACA,WACA,aACA,aAEA,iBACA,YACA,YACA,YACA,cACA,aACA,kBACA,cACA,gBACA,aACA,QACA,MACA,UACA,aAEA,wBACA,qBACA,cACA,WACA,YACA,iBACA,oBACA,iBAEA,SACA,aACA,eACA,gBACA,cACA,UACA,cACA,gBACA,iBACA,eACA,QACA,YACA,YACA,SACA,aACA,aAEA,MACA,QACA,SACA,OACA,QACA,UAEA,SACA,eACA,eACA,eACA,gBACA,aACA,eACA,gBACA,cACA,yBACA,0BACA,4BACA,6BAEA,aACA,mBACA,mBACA,sBACA,kBACA,oBACA,wBAEA,QACA,OACA,cACA,YACA,cACA,aACA,cACA,iBACA,aACA,kBACA,iBACA,cACA,cACA,aACA,eAEA,UACA,aACA,cACA,SACA,kBACA,YACA,mBACA,aACA,YAEA,SACA,iBACA,cAEA,UACA,aACA,iBACJ,EAGMC,GAAgB,CAElB,OACA,QACA,SACA,eACA,OACA,cACA,OACA,cACA,WACA,YACA,YACA,QAEA,SACA,WACA,WACA,QACA,SAEA,MACA,cACA,SACA,iBACA,SACA,OACA,eACA,aACA,WACA,SACA,gBACA,eACA,eACA,UACA,WAEA,OACA,UACA,UACA,QACA,SACA,IACA,MACA,MACA,OACA,MACA,cACA,eACA,SACA,OACA,SACA,SACA,UACA,SACA,QACA,SACA,SACA,OACA,QACA,SACA,UACA,MACA,SACA,SACA,YACA,YACA,aACA,UACA,UACA,aACJ,EAGA,QAAWC,KAAQF,GACfD,GAAY,IAAIG,EAAMA,CAAI,EAE9B,QAAWC,KAAOF,GACdF,GAAY,IAAII,EAAKA,CAAG,EAYrB,SAASC,GAAOC,EAAqB,CACxC,IAAMC,EAAWP,GAAY,IAAIM,CAAG,EACpC,OAAIC,IAAa,OAAkBA,GAG/BD,EAAI,QAAU,IACdN,GAAY,IAAIM,EAAKA,CAAG,EAErBA,EACX,CAKO,SAASE,GAAWF,EAAsB,CAC7C,OAAON,GAAY,IAAIM,CA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,EAEpC,GAAIoB,IAAY,QAAaC,IAAW,OAAW,SAKnD,IAAMC,GAAU,IAAMtB,GAAS,IACzBuB,GAASvB,EAAQ,IAAM,IAEvBwB,EAAQjB,GAAc,CACxB,EAAGa,EACH,IAAAxB,EACA,UAAAa,EACA,EAAAJ,EACA,EAAGiB,EACH,YAAAZ,EACA,iBAAkB,CACtB,CAAC,EAEKe,EAAOlB,GAAc,CACvB,EAAGc,EACH,IAAAzB,EACA,UAAAa,EACA,EAAAJ,EACA,EAAGkB,EACH,YAAAb,EACA,iBAAkBO,CACtB,CAAC,EAEKS,EAAQ,cAAcF,EAAM,GAAG,KAAKC,EAAK,GAAG,IAClDrC,EAAM,IAAI,WAAW4B,CAAI,IAAIhB,CAAK,GAAI0B,GAA2B,CACrE,CACJ,CC1WA,IAAMC,GAAe,IAAI,IAAI,CAEzB,QACA,SACA,OACA,QACA,SACA,MACA,SACA,UACA,QACA,OACA,QACA,SACA,OACA,OACA,OACA,OAGA,YACA,eACA,aACA,QACA,QACA,SACA,iBACA,aACA,QACA,YACA,YACA,aACA,YACA,QACA,iBACA,WACA,UACA,OACA,WACA,WACA,gBACA,WACA,YACA,WACA,YACA,cACA,iBACA,aACA,aACA,UACA,aACA,eACA,gBACA,gBACA,gBACA,gBACA,aACA,WACA,cACA,UACA,UACA,aACA,YACA,cACA,cACA,YACA,aACA,OACA,YACA,cACA,OACA,WACA,UACA,YACA,SACA,QACA,QACA,WACA,gBACA,YACA,eACA,YACA,aACA,YACA,uBACA,YACA,aACA,YACA,YACA,cACA,gBACA,eACA,iBACA,iBACA,iBACA,cACA,YACA,QACA,UACA,mBACA,aACA,eACA,eACA,iBACA,kBACA,oBACA,kBACA,kBACA,eACA,YACA,YACA,WACA,cACA,UACA,YACA,SACA,YACA,SACA,gBACA,YACA,gBACA,gBACA,aACA,YACA,OACA,OACA,OACA,aACA,YACA,YACA,cACA,SACA,aACA,WACA,WACA,SACA,UACA,YACA,YACA,YACA,OACA,cACA,YACA,MACA,U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ChE,IAAMrB,EAA2B,CAAC,EAC5BsB,EAAW,IAAI,IACfC,EAAiB,IAAI,IAErBC,EAAc,mFAChBC,EAEJ,MAAQA,EAAQD,EAAY,KAAKH,CAAG,KAAO,MAAM,CAC7C,IAAMvB,EAAU2B,EAAM,CAAC,EACvB,GAAI,CAAAH,EAAS,IAAIxB,CAAO,EAExB,CAAAwB,EAAS,IAAIxB,CAAO,EAEpB,QAAWI,KAAQL,GAAqBC,CAAO,EAAG,CAC9C,GAAII,EAAK,MAAQ,aAAc,CAC3B,IAAMwB,EAAM,GAAGxB,EAAK,IAAI,IAAIA,EAAK,aAAe,EAAK,GACrD,GAAIqB,EAAe,IAAIG,CAAG,EAAG,SAC7BH,EAAe,IAAIG,CAAG,CAC1B,CACA1B,EAAM,KAAKE,CAAI,CACnB,EACJ,CAEA,OAAOF,CACX,CASO,SAAS2B,GAAmB3B,EAAkC,CACjE,OAAOA,EAAM,IAAIC,EAAU,EAAE,KAAK;AAAA,CAAI,CAC1C,CvF5WO,IAAM2B,GAAW,CAEpB,QAAS,EAET,aAAc,EAEd,kBAAmB,EAEnB,YAAa,EAEb,UAAW,GAEX,YAAa,GAEb,UAAW,GAEX,SAAU,IAEV,cAAe,IAEf,KAAM,EAEN,IAAM,GACV,EAKMC,GAAoBD,GAAS,IAM5B,SAASE,GAAoBC,EAAuC,CACvE,OAAO,OAAOA,GAAU,UAAY,OAAO,UAAUA,CAAK,GAAKA,GAAS,GAAKA,GAASF,EAC1F,CASO,SAASG,GAAqBD,EAA8B,CAC/D,OAAID,GAAoBC,CAAK,EAClBA,EAEJH,GAAS,IACpB,CASO,SAASK,GAAWC,EAAqBC,EAAgC,CAC5E,OAAQD,EAAQC,KAAaA,CACjC","names":["require_ignore","__commonJSMin","exports","module","makeArray","subject","UNDEFINED","EMPTY","SPACE","ESCAPE","REGEX_TEST_BLANK_LINE","REGEX_INVALID_TRAILING_BACKSLASH","REGEX_REPLACE_LEADING_EXCAPED_EXCLAMATION","REGEX_REPLACE_LEADING_EXCAPED_HASH","REGEX_SPLITALL_CRLF","REGEX_TEST_INVALID_PATH","REGEX_TEST_TRAILING_SLASH","SLASH","TMP_KEY_IGNORE","KEY_IGNORE","define","object","key","value","REGEX_REGEXP_RANGE","RETURN_FALSE","sanitizeRange","range","match","from","to","cleanRangeBackSlash","slashes","length","REPLACERS","_","m1","m2","index","str","p1","p2","unescaped","leadEscape","endEscape","close","REGEX_REPLACE_TRAILING_WILDCARD","MODE_IGNORE","MODE_CHECK_IGNORE","UNDERSCORE","TRAILING_WILD_CARD_REPLACERS","makeRegexPrefix","pattern","prev","matcher","replacer","isString","checkPattern","splitPattern","IgnoreRule","mark","body","ignoreCase","negative","prefix","mode","regex","createRule","regexPrefix","RuleManager","rule","path","checkUnignored","ignored","unignored","matchedRule","ret","throwError","message","Ctor","checkPath","originalPath","doThrow","isNotRelative","p","Ignore","ignorecase","allowRelativePaths","cache","slices","parent","paths","factory","options","isPathValid","setupWindows","makePosix","REGEX_TEST_WINDOWS_PATH_ABSOLUTE","index_exports","__export","Scanner","clearExtractCache","clearScanCache","clearUtilitySet","compileCandidate","compileCandidateString","compileCandidatesBatch","compileToCss","extractCandidates","extractCandidatesBatch","extractCandidatesBatchCombined","extractCandidatesNative","extractCandidatesUncached","findRootNative","hasUtility","hasVariant","isCandidateParserAvailable","isCompilerAvailable","isCssParserAvailable","isNativeAvailable","isParserAvailable","isPrinterAvailable","isUtilitySetLoaded","loadUtilitySet","parseCandidate","parseCandidateWithUtilitySet","parseCandidatesBatch","parseCandidatesBatchWithUtilitySet","parseCss","setCssParserTimings","toCss","toCssMinified","toCssPretty","module","__toCommonJS","fs","__toESM","path","import_node_url","import_node_module","import_node_util","import_ignore","HELPER_PATTERNS","WHITESPACE","isValidStartChar","charCode","isValidUtilityChar","hasBalancedDelimiters","str","stack","quote","i","ch","extractCandidatesFast","content","len","candidates","seen","nextClass","hasClass","earliest","matchType","helperLen","helper","idx","afterClass","attrEnd","quoteChar","closeQuote","classValue","extractClassesFromString","closeBacktick","staticParts","openParen","depth","j","char","stringValue","value","start","isEnd","isWhitespace","token","firstChar","isLikelyUtility","bangIndex","import_meta","PLATFORM_SUFFIXES","getModuleDir","platformKey","platformSuffix","optionalPackage","dir","platformFile","genericFile","getRequireFunc","id","__dirnameCompat","requireCompat","nativeModule","nativeLoadAttempted","VERIFY_SCAN_CACHE","ENABLE_SCAN_MTIME","LOG_NATIVE_ERRORS","LOG_SCAN_ERRORS","EXTRACT_CACHE_LIMIT","EXTRACT_CACHE_MAX_LEN","extractCache","ENABLE_EXTRACT_CACHE","SCAN_CACHE_LIMIT","scanCache","ENABLE_GLOBAL_SCAN_CACHE","PARSE_CACHE_LIMIT","parseCandidateCache","parseCandidateWithUtilitySetCache","loggedMessages","logOnce","key","message","error","warnOnce","FNV_OFFSET_BASIS_64","FNV_PRIME_64","FNV_MASK_64","HASH_SAMPLE_THRESHOLD","HASH_SAMPLE_SIZE","HASH_SAMPLE_POINTS","getExtractCacheKey","hash","prefixEnd","suffixStart","middleStart","middleEnd","middleLen","step","p","hex","UTF8_DECODER","readFileContent","filePath","buffer","evictOldestEntry","cache","oldestKey","getCachedExtractByKey","cached","setCachedExtractByKey","getScanCacheKey","sources","s","getGlobalScanCache","file","mtime","setGlobalScanCache","mtimes","getCachedParse","input","setCachedParse","toPosixPath","readGitIgnoreLines","line","prefixGitIgnorePattern","pattern","prefix","negated","body","normalized","joined","buildGitIgnoreState","base","parentPatterns","patterns","ignoreFile","relDir","lines","ignore","matchGlob","relativePath","anyDirExtMatch","prefixExtMatch","ext","prefixBraceMatch","extList","exts","braceMatch","extMatch","matchesSourcePattern","relative","relPosix","patternPosix","tryLoadNative","platform","arch","packageRoot","resolvedPackageRoot","searchRoots","pathsToTry","addPath","candidate","envPath","resolved","root","lastError","modulePath","attempts","looksLikeMarkup","EXTRACT_NATIVE_MIN_SIZE","extractCandidatesImpl","native","preferFast","result","contents","TsScanner","options","results","source","files","extracted","resolvedFiles","unique","newCandidates","normalizedBase","extensions","normalizedPattern","walkDir","ignoreState","currentIgnoreState","matcher","entries","entry","fullPath","hasSpecialExt","rootIgnoreState","cacheKey","nativeImpl","nativeFiles","getNativeFilesSafe","scanErrors","getNativeScanErrorsSafe","tsImpl","fallback","filesValue","errorsValue","inputs","allCached","cachedResults","utilities","theme","name","nodes","indent","enabled","index_exports","__export","ALL_LENGTH_UNITS","ApplyBlockedError","ApplyContextError","ApplyInvalidCandidateError","ApplyPrefixError","ApplyUnknownUtilityError","ApplyVariantError","AstCycleError","AstMaxDepthError","CSSFunctionError","CSS_FUNCTION_PATTERN","CircularDependencyError","ColorError","CompileFeatures","Compounds","CssSyntaxError","DefaultMap","DirectiveBodyError","DirectiveEmptyError","DirectiveNestingError","DirectiveTypeError","Features","FontDirectiveError","ImportCache","ImportOrderError","LENGTH_UNITS","PREFLIGHT_MODULES","PreflightModuleError","SourceMapError","SourcePathError","Theme","ThemeContentError","ThemeOptions","ThemePrefixError","UnitBucket","Utilities","UtilityApplyError","UtilityNameError","VariantApplicationError","VariantNameError","VariantParseError","VariantSelectorError","VariantSlotError","Variants","WalkAction","__buildDecodedSourceMap","__convertNativeAst","__getModuleDirForTest","__nodeToNative","__resetNativeCssParser","__resetNodeModuleStateForTest","__resetTestOverrides","__setNativeCandidateParser","__setNativeCssParser","__setNodeModuleStateForTest","__setNodeRequireForTest","__setTestRequireOverrides","__toCssWithPositions","addWhitespaceAroundMathOperators","appendSelector","applyImportant","arrayMap","aspectRatioPlugin","atRoot","atRule","breakpointsEqual","buildDependencyGraph","buildLineTable","buildVariableDependencyGraph","calcSpacing","canonicalizeCandidates","canonicalizeClasses","cartesian","cartesianFilter","cartesianIterator","cartesianMap","cartesianSize","chainCompare","chainSourceMaps","classListsEquivalent","clearDefaultImportCache","clearDesignSystemCache","clearMemoryCache","clearInternPool","cloneAstNode","comment","compare","compareBreakpoints","compareBy","compareClassNames","compareDimensions","compareNumbers","compileCandidate","compileClasses","containerQueriesPlugin","context","counterMap","createApplyContext","createCompiler","createCssUtility","createDefaultUtilities","createDefaultVariants","createDesignSystem","createLineTable","createPluginAPI","createSource","createSourceLocation","createSourceMap","createSourceMapGenerator","createTranslationMap","createVarExpression","decl","decodeArbitraryValue","decodeMappings","descending","encodeArbitraryValue","encodeSourceMap","escapeClassName","escapeSequenceToChar","escapeString","expand","expandCanonical","expandDeclaration","extractAttributeSelectors","extractBracketContent","extractCustomProperties","extractDeclarations","extractMathFunctions","extractPseudoClasses","extractShadowColors","extractSlotTemplate","extractUsedVariables","extractValueSegments","extractVarReferences","fetchAndCacheMetadata","fetchFontMetadata","filterPreflightInLayer","filterPreflightModules","find","findAll","findCircularVariables","findFunctions","foldAST","foldCalc","foldDeclaration","formatDimension","formsPlugin","generateFontCss","generateFontFace","generateFontUrl","generateGoogleFontsUrl","generateHtmlComment","generateImportRule","generatePreloadLinks","generateSourceMap","getBundledMetadata","getCachedMetadata","getCandidateOrder","getCircularReferenceTelemetry","getClassList","getClassOrder","getColorFormat","getDefaultDesignSystem","getDefaultImportCache","getFontMetadata","getFontMetadataSync","getFontPreloadLinks","getInternPoolSize","getLonghandProperties","getPossibleDataTypes","getPropertyOrder","getSuggestions","getUnitBucket","getUnitCategory","getVariableNames","getVariants","handleNegative","hasAlpha","hasCSSFunctions","hasFeature","hasFunction","hasMathFunction","hasNativeUtility","hasNativeVariant","hasNesting","hasPseudoClass","hasVariantCSSContent","hashContent","hybridCompileCandidates","inferDataType","injectUtilities","intern","isArbitraryCandidate","isArbitraryVariant","isAtRoot","isAtRule","isAttributeSelector","isColor","isComment","isCompoundVariant","isContext","isDeclaration","isFunctionalCandidate","isFunctionalVariant","isInterned","isLength","isNativeAvailable","isNativeCandidateParserAvailable","isNativeCompilerAvailable","isNativeCssParserAvailable","isNativeParserAvailable","isNativePrinterAvailable","isPluginWithOptions","isPositiveInteger","isRule","isShorthand","isSimpleNumber","isStaticCandidate","isStaticVariant","isStrictPositiveInteger","isStyleRule","isValidArbitrary","isValidClass","isValidColorName","isValidFeatureFlags","isValidFunctionalUtilityName","isValidOpacityValue","isValidSpacingMultiplier","isValidStaticUtilityName","isValidThemePrefix","isValidVariableName","loadDefaultTheme","loadPalette","loadPlugins","looksLikeColor","mapMap","matchAttributeSelector","matchesDataType","maxBreakpoint","mediaVariant","mergeSourceMaps","minBreakpoint","minify","nativeCompileCandidateString","nativeCompileCandidatesBatch","nativeCompileToCss","nativeParseCandidate","nativeParseCandidatesBatch","nativePrintCss","needsDecoding","needsEscaping","normalizeClassString","normalizeMathExpression","normalizeVariableName","offsetToPosition","pairs","parse","parseAttributeSelector","parseCandidate","parseColorOptions","parseComplexValue","parseDimension","parseHexColor","parseImportConditions","parseImportParams","parseImportPath","parseReferenceParams","parseSelector","parseShadowSegments","parseThemeOptions","parseValue","plugin","pluginWithOptions","preloadLinksToHtml","prependSelector","print","printNative","printWithRawSourceMap","printWithSourceMap","processApplyDirective","processColorDirective","processCustomVariantDirective","processFontDirective","processLayerDirective","processPreflightDirective","processRainbowIndexDirective","processSourceDirective","processThemeDirective","processVariantDirective","registerAccessibilityUtilities","registerAnimationUtilities","registerBackgroundUtilities","registerBorderUtilities","registerColorUtilities","registerDataVariants","registerEffectsUtilities","registerFilterUtilities","registerGridUtilities","registerInteractivityUtilities","registerLayoutUtilities","registerMaskingUtilities","registerMediaVariants","registerPseudoVariants","registerSizingUtilities","registerSpacingUtilities","registerSvgUtilities","registerTableUtilities","registerTransformUtilities","registerTransitionUtilities","registerTypographyUtilities","remove","removeUtilityNodes","removeWhitespaceAroundMathOperators","replace","replaceNesting","replaceShadowColors","replaceVariables","resetCircularReferenceTelemetry","resolveSpacing","resolveThemeColor","resolveVariables","rgbToHex","segment","selectorVariant","selfCartesian","serializeAttributeSelector","serializeNode","serializeSelector","serializeSelectorList","serializeValue","setMap","shadowHasColors","shadowWithVariable","shouldIncludePreflightModule","shouldSkipImport","simplifyMath","simplifyValue","sortAST","sortBreakpoints","sortClassList","sortClasses","sortDeclarations","sortDimensions","sortRuleDeclarations","splitBalanced","stableSort","staticUtility","stringify","stripShadowColors","styleRule","substituteAtImports","substituteAtImportsSync","substituteAtVariant","substituteFunctions","substituteFunctionsInValue","suggestCanonical","toPx","topologicalSort","transformCSS","transformLightDarkValue","transformValue","typographyPlugin","unescape","unescapeString","unwrapCalc","usesVariables","validateArbitrary","validateFeatureFlags","walk","withAlpha","withOpacity","wouldCreateCycle","wrapInLayer","wrapWithConditions","__toCommonJS","INTERN_POOL","COMMON_PROPERTIES","COMMON_VALUES","prop","val","intern","str","existing","isInterned","getInternPoolSize","clearInternPool","styleRule","selector","nodes","atRule","name","params","decl","property","value","important","intern","comment","context","ctx","atRoot","isStyleRule","node","isAtRule","isDeclaration","isComment","isContext","isAtRoot","isRule","cloneAstNode","WalkAction","DEFAULT_MAX_DEPTH","AstCycleError","message","AstMaxDepthError","depth","maxDepth","walk","ast","callback","options","pathStack","visiting","walkNodes","nodes","parent","result","i","node","action","replacement","parentRule","replace","predicate","replacer","remove","findAll","found","find","DefaultMap","factory","entries","key","value","arrayMap","setMap","mapMap","counterMap","BASE64_CHARS","encodeVLQ","value","result","vlq","digit","createSourceMapGenerator","file","sources","sourcesContent","names","mappings","prevGeneratedColumn","prevOriginalLine","prevOriginalColumn","prevSourceIndex","currentLine","ensureLine","line","sourceFile","content","index","generated","original","source","segment","encodedMappings","v","createSource","code","createSourceLocation","start","end","offsetToPosition","offset","column","i","hasSourceLocation","node","buildLineTable","lineStarts","codeLength","tableLength","count","mid","offsetA","offsetB","createLineTable","decodeMappings","lines","generatedColumn","sourceIndex","originalLine","originalColumn","nameIndex","char","values","shift","continuation","charCode","negate","chainSourceMaps","transformed","originalDecoded","transformedDecoded","originalLookup","key","generator","originalSegment","mergeSourceMaps","maps","options","sourceOffsets","map","lineOffset","mapIndex","decoded","sourceOffset","generateSourceMap","nodes","outputCode","sourceIndices","getSourceIndex","idx","processNode","srcSource","srcStart","dstSource","dstStart","sourceIdx","originalPos","generatedPos","child","createSourceMap","ast","lineTables","DefaultMap","src","sourceTable","walk","WalkAction","originalSource","originalTable","generatedTable","originalSlice","originalStart","generatedStart","originalEnd","generatedEnd","seenSources","decodedSource","a","b","createTranslationMap","translations","encodeSourceMap","mapping","SourceMapError","message","INDENTS_2","_","i","INDENTS_4","INDENTS_TAB","getIndentArray","indent","print","ast","options","minify","printWithSourceMap","toCss","printWithRawSourceMap","toCssWithRawMappings","sourceMap","decodedSourceMap","file","code","decodedMap","toCssWithDecodedMap","map","encodeSourceMap","toCssMinified","toCssPretty","indents","stringify","node","depth","ind","css","child","params","_toCssWithPositions","parts","pos","source","annotate","start","end","segment","openSegment","closeSegment","_buildDecodedSourceMap","generatedSource","lineTables","DefaultMap","src","buildLineTable","sourceTable","generatedTable","processNode","srcSource","srcStart","dstStart","originalSource","originalPos","generatedPos","seenSources","decodedSource","generatedLineStarts","sources","srcOffsets","dstOffsets","buildLineStarts","lineStarts","LF","CR","char","binarySearchLine","offset","line","count","mid","rawSources","rawSrcOffsets","rawDstOffsets","sourceLineStarts","decodedSources","getLineStarts","starts","getDecodedSource","decoded","mappingCount","mappings","srcOffset","dstOffset","originalLineStarts","sourceLength","srcLine","validSrcLine","srcColumn","dstLine","validDstLine","dstColumn","printNative","oxide","nativeAst","nodeToNative","__nodeToNative","__toCssWithPositions","__buildDecodedSourceMap","isStaticCandidate","c","isFunctionalCandidate","isArbitraryCandidate","isStaticVariant","v","isFunctionalVariant","isArbitraryVariant","isCompoundVariant","BRACKETS","CLOSING_BRACKETS","CURLY_OPEN","CURLY_CLOSE","QUOTES","isValidEscapeTarget","char","code","CHAR_BACKSLASH","CHAR_SINGLE_QUOTE","CHAR_DOUBLE_QUOTE","CHAR_BACKTICK","CHAR_SEMICOLON","CHAR_OPEN_BRACE","CHAR_CLOSE_BRACE","CHAR_OPEN_PAREN","CHAR_CLOSE_PAREN","CHAR_OPEN_BRACKET","CHAR_CLOSE_BRACKET","isValidArbitrary","value","len","hasSpecial","j","c","needsValidation","stack","inQuote","curlyDepth","i","next","validateArbitrary","curlyStack","opening","unclosed","extractBracketContent","start","openChar","closeChar","depth","splitBalanced","delimiter","result","current","SIMPLE_NUMBER_PATTERN","MATH_FUNCTIONS","hasMathFunction","value","lower","fn","addWhitespaceAroundMathOperators","result","i","depth","inMathFn","mathFnDepth","char","prevChar","nextChar","beforeParen","removeWhitespaceAroundMathOperators","normalizeMathExpression","normalized","extractMathFunctions","pattern","match","start","end","isSimpleNumber","SIMPLIFY_PATTERNS","simplifyMath","word","value","fun","nodes","separator","COMMA_NO_SPACE","MATH_FN_QUICK","parseValue","input","ast","stack","parent","bufferStart","bufferEnd","flushBuffer","node","i","currentChar","start","end","peekChar","j","funcName","tail","toCss","parts","toCssParts","convertUnderscoresToWhitespace","input","skipUnderscoreToSpace","underscoreIdx","backslashIdx","len","parts","start","i","char","startsWithSpaceOrUnderscore","node","first","recursivelyDecodeArbitraryValues","ast","funcName","isUrl","isVarOrTheme","nodes","child","nextChild","COMMA_NO_SPACE","decodeArbitraryValue","needsMathProcessing","MATH_FN_QUICK","parseValue","result","toCss","addWhitespaceAroundMathOperators","encodeArbitraryValue","value","needsDecoding","hasMathFunction","MATH_FUNCTION","extractValueSegments","parseComplexValue","decoded","functions","current","depth","funcStart","args","convertNativeCandidate","native","variants","convertNativeVariant","convertNativeModifier","convertNativeValue","innerVariant","parsed","LruCache","maxSize","key","node","value","existing","total","tail","nativeParseCandidate","nativeParseCandidateWithUtilitySet","nativeIsUtilitySetLoaded","nativeParserLoadAttempted","tryLoadNativeParser","oxide","__setNativeCandidateParser","parser","isNativeCandidateParserAvailable","COLON","SLASH","OPEN_BRACKET","CLOSE_BRACKET","OPEN_PAREN","CLOSE_PAREN","DASH","BANG","AT","COMPOUND_ROOTS","EMPTY_CANDIDATES","isNumericOnly","input","len","i","c","ARBITRARY_CACHE_LIMIT","arbitraryDecodeCache","LruCache","arbitraryValidCache","staticVariantCache","VARIANT_CACHE_LIMIT","variantCache","primedFindRoots","PARSE_CACHE_LIMIT","parseCacheNoRoot","VARIANT_CHAIN_CACHE_LIMIT","variantChainCache","decodeArbitraryCached","cached","decoded","decodeArbitraryValue","isValidArbitraryCached","valid","isValidArbitrary","getStaticVariant","root","variant","parseVariantFast","parseVariant","firstChar","primeUtilitySet","findRoot","getParseCache","rememberParseResult","cache","key","value","frozen","getCachedVariantChain","chain","rememberVariantChain","variants","parseCandidate","options","code","result","convertNativeCandidate","nativeParse","candidate","parseCandidateTypeScript","isSimpleStatic","originalInput","important","base","firstColon","hasBrackets","lastColon","chainKey","cachedChain","parts","built","part","parsed","parseVariantsAndBase","inner","colonIdx","property","modifier","modifierResult","extractModifier","baseWithoutModifier","bracketIdx","arbitraryPart","dataType","parenIdx","varPart","negative","utilityBase","rootValue","rootPart","valuePart","fractionIdx","fraction","valueStr","beforeSlash","afterSlash","selector","relative","normalizedSelector","variantModifier","baseInput","rootDash","dashIdx","rest","innerVariant","slashIdx","actualRoot","modifierPart","start","idx","segment","depth","char","validateArbitrary","lastSlashIdx","ThemeOptions","Theme","_Theme","next","key","value","options","src","existing","entry","unprefixed","prefixed","candidateValue","themeKeys","namespace","fullKey","emittedKey","result","prefix","prefixedNamespace","prefixedPrefix","suffix","name","keyframes","child","other","loadDefaultTheme","theme","loadPalette","TOKENS_19","DEFAULT_L_SCHEDULE","clamp01","x","hueWeight","h","hue","bell01","t","mirrorToken","token","applyLightnessCorrection","L","C","H","a","formatOklch","computeSwatch","opts","intensity","chromaShape","chromaMultiplier","C0","shape","L1","params","name","kDark","lightnessByToken","Ls","L_light","L_dark","tLight","tDark","light","dark","value","NAMED_COLORS","COLOR_FUNCTIONS","HEX_COLOR_3","HEX_COLOR_4","HEX_COLOR_6","HEX_COLOR_8","HEX_LIKE_PATTERN","COLOR_KEYWORDS","isColor","value","trimmed","lowercased","parenIdx","fnName","looksLikeColor","keyword","parseHexColor","hex","normalized","r","g","b","a","rgbToHex","toHex","n","getColorFormat","hasAlpha","LENGTH_UNITS","ANGLE_UNITS","TIME_UNITS","FREQUENCY_UNITS","RESOLUTION_UNITS","POSITION_KEYWORDS","GRADIENT_FUNCTIONS","IMAGE_FUNCTIONS","NUMBER_WITH_UNIT","RATIO_PATTERN","INTEGER_PATTERN","inferDataType","value","trimmed","fn","isColor","match","unit","inferMathFunctionType","looksLikeColor","isPositionValue","looksLikeShadow","openParen","closeParen","content","parts","part","normalized","p","hasLength","hasColor","matchesDataType","type","inferred","getPossibleDataTypes","types","g","LENGTH_UNITS","ALL_LENGTH_UNITS","FONT_RELATIVE_UNITS","VIEWPORT_UNITS","CONTAINER_UNITS","FLEX_UNITS","INTEGER_PATTERN","DECIMAL_PATTERN","OPTIONAL_DECIMAL_PATTERN","DIMENSION_PATTERN","parseDimension","input","match","value","unit","isLength","dim","isPositiveInteger","trimmed","num","isStrictPositiveInteger","isValidSpacingMultiplier","isValidOpacityValue","raw","toPx","context","absoluteRatio","compareDimensions","a","b","aPx","bPx","sortDimensions","dimensions","d","result","p","formatDimension","getUnitCategory","UtilityTrie","utility","segments","node","segment","child","segmentStart","pos","findChild","input","lastMatchPos","matches","start","end","segmentLength","isMatch","i","NEGATABLE_TYPES","TRANSFORM_FUNCTIONS_PATTERN","NEGATABLE_FUNCTIONS_PATTERN","nativeFindRoot","nativeLoadAttempted","tryLoadNativeFindRoot","oxide","loadUtilitySetToNative","utilities","Utilities","_Utilities","UtilityTrie","name","input","cached","native","result","next","defs","getter","compileFn","def","options","kind","d","candidate","theme","isNegative","positiveRoot","rootsToTry","isFunctionalWithNoValue","root","candidateToCompile","staticCandidate","nodes","node","decl","value","dataType","inferDataType","groups","staticUtility","declarations","property","resolveThemeColor","themeKeys","withOpacity","color","modifier","opacity","num","SPACING_KEYWORDS","resolveSpacing","isValidSpacingMultiplier","spacing","numerator","denominator","named","handleNegative","positiveCandidate","UnitBucket","getUnitBucket","value","trimmed","hasMathFunction","dim","parseDimension","unit","DEFAULT_CONTEXT","compareBreakpoints","a","b","context","ctx","bucketA","bucketB","pxA","toAbsolutePx","pxB","dimA","dimB","toPx","sortBreakpoints","breakpoints","groups","bucket","group","items","cmp","sortedBuckets","result","item","breakpointsEqual","minBreakpoint","min","i","current","maxBreakpoint","max","FLEX_BASIS_VALUES","ORDER_VALUES","COLUMN_WIDTH_VALUES","POSITION_TRY_VALUES","registerLayoutUtilities","utilities","_theme","staticUtility","candidate","decl","lhs","rhs","num","theme","val","value","spacing","containValue","boxDecorationSlice","boxDecorationClone","_candidate","breakpoints","a","b","cmp","compareBreakpoints","nodes","atRule","name","insetAreaPositions","createSpacingUtility","property","candidate","theme","value","resolveSpacing","decl","registerSpacingUtilities","utilities","_theme","ASPECT_RATIO_VALUES","registerSizingUtilities","utilities","_theme","resolveSizeValue","raw","theme","namedValues","options","named","containerValue","num","spacing","parts","numPart","denomPart","spacingValue","createSizeUtility","property","candidate","decl","value","baseNamed","widthNamed","heightNamed","maxWidthNamed","maxHeightNamed","staticUtility","resolveSpacing","w","h","BORDER_WIDTH_VALUES","OUTLINE_STYLE_VALUES","RING_WIDTH_VALUES","registerColorUtilities","utilities","_theme","candidate","theme","color","resolveThemeColor","withOpacity","decl","sizeValue","lineHeight","namedLineHeight","num","spacing","result","dataType","inferDataType","width","style","val","registerTypographyUtilities","utilities","_theme","candidate","theme","weight","decl","family","staticUtility","value","num","themeValue","color","looksLikeColor","spacing","CORNER_SHAPES","resolveRadius","candidate","theme","spacing","val","num","resolveSquircleRadius","scale","registerBorderUtilities","utilities","_theme","value","decl","shape","color","staticUtility","ringWidth","ringColor","ringOffsetWidth","opacity","BOX_SHADOW_VALUE","INSET_SHADOW_VALUE","TEXT_SHADOW_VALUES","registerEffectsUtilities","utilities","_theme","candidate","theme","value","decl","color","staticUtility","looksLikeColor","isValidOpacityValue","num","namedValue","opacity","TRANSFORM_2D","FRACTION_PATTERN","registerTransformUtilities","utilities","_theme","candidate","num","value","decl","theme","fractionMatch","denom","percentage","staticUtility","FILTER_VALUE","BACKDROP_FILTER_VALUE","registerFilterUtilities","utilities","_theme","candidate","theme","value","decl","num","staticUtility","registerInteractivityUtilities","utilities","_theme","staticUtility","candidate","theme","decl","color","resolveScrollSpacing","value","num","registerTransitionUtilities","utilities","_theme","staticUtility","candidate","decl","num","theme","value","SPACING_VAR","SLIDE_IN_PATTERN","SLIDE_OUT_PATTERN","durationScale","registerAnimationUtilities","utilities","_theme","candidate","theme","val","decl","durVal","ms","delVal","themeValue","num","slideInMatch","direction","numStr","isNegative","prop","value","slideOutMatch","UNDERSCORE_PATTERN","SVG_OPACITY_VALUES","registerSvgUtilities","utilities","_theme","staticUtility","candidate","theme","decl","color","num","value","opacity","registerAccessibilityUtilities","utilities","_theme","staticUtility","resolveBorderSpacingValue","candidate","theme","themeValue","num","BORDER_SPACING_DECL","registerTableUtilities","utilities","_theme","staticUtility","value","decl","LINEAR_GRADIENT_DIRECTIONS","RADIAL_GRADIENT_POSITIONS","buildGradientStops","resolveInterpolationMethod","modifier","registerBackgroundUtilities","utilities","_theme","staticUtility","candidate","decl","gradientStops","stops","interpolation","dir","deg","pos","theme","resolvePosition","num","color","position","result","value","MASK_EDGES","registerMaskingUtilities","utilities","_theme","staticUtility","candidate","decl","num","maskComposite","maskLayers","createEdgeMaskUtility","edges","stop","theme","color","position","result","activeEdges","e","edgeGradients","edge","resolveMaskStopValue","value","linearGradient","radialGradient","conicGradient","createMaskGradientUtility","variablePrefix","gradientVariable","gradientValue","GRID_AUTO_VALUES","registerGridUtilities","utilities","_theme","candidate","val","decl","num","value","staticUtility","_cachedDefaultUtilities","createDefaultUtilities","theme","utilities","Utilities","registerLayoutUtilities","registerSpacingUtilities","registerSizingUtilities","registerColorUtilities","registerTypographyUtilities","registerBorderUtilities","registerEffectsUtilities","registerTransformUtilities","registerFilterUtilities","registerInteractivityUtilities","registerTransitionUtilities","registerAnimationUtilities","registerSvgUtilities","registerAccessibilityUtilities","registerTableUtilities","registerBackgroundUtilities","registerMaskingUtilities","registerGridUtilities","closingBracketStack","segment","input","separator","stackPos","parts","lastPos","len","separatorCode","idx","char","nextChar","NESTING_SELECTOR_PATTERN","negateConditions","ruleName","conditions","condition","trimmed","parts","segment","negateAtRule","node","negated","atRule","negateSelector","selector","s","NUMERIC_VARIANT_PATTERN","NESTING_SELECTOR_PATTERN","Compounds","COMPOUND_PSEUDO_MAP","Variants","_Variants","name","applyFn","options","order","config","pattern","rule","variant","theme","_name","selector","styleRule","modifiedRule","a","b","orderA","orderB","valueA","valueB","comparison","compareBreakpoints","breakpointA","breakpointB","next","entries","i","fn","_startIndex","_theme","root","modifier","innerVariant","markerClass","escapedMarker","escapeSelector","stateSelector","newSelector","innerResult","firstNode","negated","negateAtRule","ruleNode","negatedSelector","negateSelector","str","selectorVariant","mediaVariant","query","mediaRule","atRule","registerPseudoVariants","variants","rule","mediaRule","atRule","selectorVariant","startingRule","variant","BREAKPOINT_DEFAULTS","registerMediaVariants","variants","name","defaultValue","rule","_variant","theme","breakpoint","atRule","variant","remValue","mediaRule","mediaPreferences","query","size","containerRule","containerName","condition","supportsRule","pointerVariants","value","resolveContainerValue","registerDataVariants","variants","_theme","rule","variant","attrValue","ariaShortcuts","attr","dataShortcuts","inner","_cachedDefaultVariants","createDefaultVariants","theme","variants","Variants","registerPseudoVariants","registerMediaVariants","registerDataVariants","createPluginAPI","theme","utilities","variants","baseStyles","componentStyles","name","declarations","nodes","prop","value","decl","handler","candidate","themeRef","result","val","selector","rule","variant","values","key","styles","styleRule","plugin","fn","pluginWithOptions","wrapper","options","isPluginWithOptions","value","loadPlugins","plugins","theme","utilities","variants","baseStyles","componentStyles","api","createPluginAPI","pluginItem","containerQueriesPlugin","aspectRatioPlugin","formsPlugin","typographyPlugin","ESCAPE_CHARS","NON_PRINTABLE_ASCII","escapeClassName","className","result","i","codePoint","char","nextIndex","nextCode","unescape","escaped","nextChar","isHexDigit","hex","j","code","escapeString","str","quote","unescapeString","needsEscaping","firstCode","secondCode","escapeSequenceToChar","escape","compare","a","b","aLen","bLen","ai","bi","aChar","bChar","aIsDigit","isDigit","bIsDigit","aNum","extractNumber","bNum","charCode","str","start","end","compareBy","fn","compareNumbers","descending","compareFn","chainCompare","compareFns","result","stableSort","array","indexed","item","index","NUMERIC_ONLY_PATTERN","NUMERIC_WITH_UNIT_PATTERN","PROPERTY_ORDER","DEFAULT_ORDER","CSS_VAR_ORDER","getPropertyOrder","property","sortDeclarations","declarations","a","b","orderA","orderB","compare","sortRuleDeclarations","rule","other","node","sortAST","ast","compareClassNames","partsA","partsB","i","variantA","variantB","breakpointCompare","compareBreakpointVariants","getVariantOrder","baseA","baseB","variant","responsiveOrder","normalizeBreakpointVariant","stateIndex","aValue","bValue","cmp","compareBreakpoints","hasMathFunction","WHITESPACE","NUMBER","WORD","FUNCTION_START","STRING_DOUBLE","STRING_SINGLE","COMMENT","OPERATOR","tokenize","input","tokens","pos","remaining","wsMatch","commentMatch","dqMatch","sqMatch","numMatch","raw","unit","numPart","name","wordMatch","opMatch","parseTokens","result","i","token","next","depth","j","t","argTokens","args","parseValue","serializeValue","nodes","node","serializeNode","findFunctions","results","visit","arg","hasFunction","extractVarReferences","v","firstArg","transformValue","transform","transformNode","transformed","CSSFunctionError","functionName","message","cause","alphaFunction","_ctx","value","slashIndex","color","alpha","withAlpha","spacingFunction","ctx","base","num","calcSpacing","themeFunction","path","fallback","shouldInline","normalizedPath","resolvedValue","CSS_FUNCTIONS","CSS_FUNCTION_PATTERN","hasCSSFunctions","substituteFunctionsInValue","ast","parseValue","transformed","transformNodes","serializeValue","nodes","node","transformNode","transformedArgs","fn","argStrings","splitArgs","result","parsed","error","args","current","substituteFunctions","theme","walk","atRuleCtx","alphaPercent","multiplier","UNIT_CONVERSIONS","FOLDABLE_UNITS","isFoldableUnit","unit","LENGTH_UNITS","ANGLE_UNITS","TIME_UNITS","CSS_VALUE_PATTERN","areUnitsCompatible","unit1","unit2","parseValue","value","match","number","formatValue","rounded","toPixels","remSize","conversion","fromPixels","pixels","tokenize","expr","tokens","current","depth","prevNonSpaceChar","index","i","char","prevChar","evaluateSimpleCalc","options","inner","leftStr","operator","rightStr","left","right","resultUnit","result","leftPx","rightPx","resultPx","preferredUnit","foldCalc","start","end","rawInner","processedMatch","folded","foldDeclaration","declaration","foldedValue","decl","foldAST","ast","node","unwrapCalc","simplifyValue","optimizeAst","ast","options","theme","important","foldConstants","sortDeclarations","substituteFunctions","optimizeNodes","nodes","ctx","opts","i","optimizeNode","node","optimizeDeclaration","optimizeRule","optimizeAtRule","decl","value","hasCSSFunctions","substituteFunctionsInValue","foldCalc","isImportant","rule","sortDeclarationsInPlace","atRule","params","atRuleCtx","declarations","b","orderA","getPropertyOrder","orderB","changed","result","sortedDecls","d","indices","PROPERTY_ORDER","property","order","unprefixed","prefixOrder","CSS_VARIABLE_NAME_PATTERN","INVALID_VARIABLE_CHARS_PATTERN","parseVarCall","value","start","depth","end","i","char","content","commaIndex","name","fallbackRaw","leadingWhitespace","extractUsedVariables","results","index","parsed","nestedVars","nested","getVariableNames","refs","r","usesVariables","replaceVariables","replacer","result","resolveVariables","lookup","options","preserveUnresolved","fallback","resolved","extractCustomProperties","css","seen","declPattern","match","buildVariableDependencyGraph","declarations","graph","property","deps","warnedLargeGraph","findCircularVariables","indices","lowlink","onStack","stack","sccs","strongconnect","v","neighbors","w","scc","node","circular","isValidVariableName","normalizeVariableName","normalized","createVarExpression","nativeModule","nativeModuleChecked","NATIVE_MOCK_KEY","getInjectedNativeModule","isNativeRuntimeAvailable","native","isNativeParserAvailableFor","isNativeCompilerAvailableFor","isNativePrinterAvailableFor","tryLoadNative","injected","isNativeAvailable","isNativeParserAvailable","isNativeCompilerAvailable","isNativePrinterAvailable","hasNativeUtility","name","hasNativeVariant","nativeAstToTs","nodes","node","tsAstToNative","nativeParseCandidate","input","result","convertNativeCandidate","nativeCompileCandidateString","_theme","nativePrintCss","options","nativeNodes","nativeCompileToCss","inputs","nativeParseCandidatesBatch","r","nativeCompileCandidatesBatch","hybridCompileCandidates","candidates","theme","preferNative","fallback","results","candidate","nativeResult","_cachedDefaultDesignSystem","_cachedDefaultTheme","getDefaultDesignSystem","createDesignSystem","clearDesignSystemCache","getDefaultThemeClone","base","Theme","loadDefaultTheme","options","theme","utilities","createDefaultUtilities","variants","createDefaultVariants","baseStyles","componentStyles","pluginResult","loadPlugins","prefix","invalidCandidates","blockedCandidates","parseOptions","input","parsedCandidates","LruCache","getParsedCandidates","candidate","cached","parsed","parseCandidate","frozen","CompileFlags","compiledAstCache","DefaultMap","compileCandidateCached","flags","key","flagCache","result","compileCandidate","compileCandidateDefault","usedVariables","trackedVariables","raw","variables","getVariableNames","variable","classes","className","candidates","nodes","print","compiledAstCount","stats","compileClasses","designSystem","generatedClasses","ast","descriptors","lookupClassName","orderCache","desc","getCandidateOrder","a","b","orderA","orderB","compareClassNames","descriptor","compiled","outputCandidate","finalAst","optimizeAst","printWithSourceMap","createCompiler","useBuildCache","allValidCandidates","cachedResult","cachedBuildResult","cachedBuildCandidates","cachedBuildCandidatesLength","cachedBuildCandidatesFirst","cachedBuildCandidatesMid","cachedBuildCandidatesLast","previousClassCount","_didChange","compileOptions","hasPlugins","useNative","isNativeCompilerAvailable","sameCandidateList","midIndex","i","css","nativeCompileToCss","newCandidates","didChange","prevSize","allCandidates","nativeResult","decl","applyImportant","selector","escapeClassName","rule","styleRule","variantList","variant","node","BIGINT_SHIFTS","UNKNOWN_VARIANT_BIT","ARBITRARY_VARIANT_BIT","IMPORTANT_BIT","orderMap","variantMask","idx","sortClasses","aOrder","bOrder","p","getClassOrder","order","sortClassList","classList","CANONICALIZATION_RULES","PX_VALUE_PATTERN","STANDARD_SPACING_VALUES","DEFAULT_VALUES","parseUtility","className","isNegative","baseClass","colonIndex","utility","variants","dashIndex","prefix","value","canonicalizeClasses","classes","options","collapse","removeDefaults","result","cls","valueGroups","parsed","cleanPrefix","toRemove","toAdd","prefixes","rule","part","classListsEquivalent","a","b","canonicalA","canonicalB","expandCanonical","suggestCanonical","canonical","normalizeClassString","classString","canonicalizeCandidates","designSystem","candidates","rem","logicalToPhysical","processed","candidate","convertPxToRem","pxMatch","pxValue","spacingUnit","standardValue","PSEUDO_VARIANTS","MEDIA_VARIANTS","COMPOUND_ROOTS","COMPOUND_ROOTS_SET","SELECTOR_MAP","PSEUDO_VARIANTS_ARRAY","SPACING_UTILITIES","SIZING_UTILITIES","ORDER_UTILITIES","SPACING_UTILITY_NAMES","variantsCache","getCachedVariants","designSystem","cacheKey","setCachedVariants","result","dsCache","getClassList","options","utilities","theme","seen","includeNegative","name","defs","def","completions","group","value","className","isNegatable","negativeClassName","themeValues","getThemeValuesForUtility","a","b","getVariants","includeCompound","cached","variants","resultMap","isPseudo","isMedia","canCompound","root","pseudo","compoundName","getSuggestions","partial","limit","classes","lowerPartial","c","isValidClass","colonIndex","baseClass","positiveClass","dashIndex","utilityName","categoryName","namespace","values","key","import_meta","_path","_createRequire","_fileURLToPath","_nodeModulesLoaded","testGlobalRequireOverride","testLocalRequireOverride","testImportMetaUrlOverride","getGlobalRequire","globalCandidate","localCandidate","loadNodeModules","req","CSS_NODE_RULE","CSS_NODE_AT_RULE","CSS_NODE_DECLARATION","CSS_NODE_COMMENT","nativeParseCss","nativeParserChecked","nodeRequire","getNodeRequire","globalRequire","getModuleDir","moduleUrl","DEBUG_NATIVE_PARSER","KEEP_NATIVE_COMMENTS","DISABLE_NATIVE_PARSER","tryLoadNativeParser","platformSuffix","nativeFileName","envPath","resolved","result","tryLoadFromPath","oxide","directPaths","moduleDir","modulePath","__setNativeCssParser","parser","__setTestRequireOverrides","options","__resetTestOverrides","__setNodeModuleStateForTest","state","__resetNodeModuleStateForTest","__setNodeRequireForTest","value","__getModuleDirForTest","__resetNativeCssParser","nativeModule","isNodeKind","kind","numKind","strKind","convertNativeAst","nodes","out","outPos","i","node","childNodes","converted","name","property","intern","__convertNativeAst","isNativeCssParserAvailable","CssSyntaxError","message","line","column","file","location","getLineNumber","input","offset","getColumnNumber","col","parse","source","parseTypeScript","nativeParser","c","comment","error","ast","licenseComments","stack","parent","buffer","bufferStart","closingBracketStack","len","createSourceLocation","start","end","char","closed","j","commentText","unclosed","parseString","lastChar","localBracketStack","colonIdx","k","declaration","parseDeclarationSimple","parseAtRuleSimple","trimmed","styleRule","grandParent","params","atRule","exclamIdx","importantIdx","rest","decl","quote","stringify","indent","pad","important","CircularDependencyError","cycle","message","topologicalSort","items","getId","getDeps","itemMap","inDegree","dependents","item","id","deps","dep","depList","queue","degree","result","dependent","newDegree","findCycle","visited","inStack","parent","dfs","current","buildDependencyGraph","graph","node","wouldCreateCycle","from","to","canReach","target","PREFLIGHT_MODULES","PreflightModuleError","module","validModules","ThemeContentError","contentType","ThemePrefixError","prefix","ColorError","param","value","reason","ApplyContextError","message","ApplyBlockedError","candidate","ApplyPrefixError","ApplyVariantError","variants","variantList","ApplyInvalidCandidateError","ApplyUnknownUtilityError","DirectiveNestingError","directive","DirectiveEmptyError","params","DirectiveBodyError","DirectiveTypeError","invalidType","validTypes","typeStr","t","UtilityNameError","utilityName","UtilityApplyError","cause","SourcePathError","path","ImportOrderError","VariantNameError","variantName","VariantSelectorError","selector","VariantParseError","VariantSlotError","VariantApplicationError","FontDirectiveError","processRainbowIndexDirective","node","base","params","parts","segment","type","DirectiveTypeError","source","part","path","SourcePathError","processLayerDirective","node","params","isDefinition","n","wrapInLayer","layerName","nodes","atRule","processPreflightDirective","node","params","moduleList","parsePreflightModules","modules","part","moduleName","PREFLIGHT_MODULES","PreflightModuleError","shouldIncludePreflightModule","module","config","filterPreflightModules","nodes","result","currentModule","includeCurrentModule","startIdx","endIdx","afterMarker","spaceIdx","filterPreflightInLayer","ast","hasPreflightMarkers","filteredNodes","NUMERICAL_RANGE","INTEGER_PATTERN","OPEN_BRACE","CLOSE_BRACE","expand","pattern","options","maxResults","result","expandInternal","expandInternal","pattern","result","maxResults","braceIdx","pre","braceContent","findBraceContent","inside","post","parts","isSequence","expandSequenceArray","segment","expandedParts","part","partResults","expandedTails","tail","partArray","startIdx","depth","len","i","char","OPEN_BRACE","CLOSE_BRACE","str","NUMERICAL_RANGE","seq","seqMatch","startStr","endStr","stepStr","INTEGER_PATTERN","startNum","endNum","step","increasing","count","idx","processSourceDirective","node","base","DirectiveBodyError","params","negated","inline","closeIndex","SourcePathError","source","candidates","parts","segment","part","expanded","expand","telemetryEnabled","telemetryData","isTelemetryEnabled","getCircularReferenceTelemetry","resetCircularReferenceTelemetry","processThemeDirective","node","theme","options","parsed","parseThemeOptions","reference","rainbow","inline","defaultOpt","staticOpt","prefix","isValidThemePrefix","ThemePrefixError","output","declarations","keyframeRules","child","ThemeContentError","value","property","transformLightDarkValue","themeOpts","outputProperty","decl","declsForGraph","d","graph","buildVariableDependencyGraph","circular","findCircularVariables","styleRule","THEME_PREFIX_PATTERN","params","prefixMatch","tokens","token","lightDarkParts","splitLightDark","lightValue","darkValue","depth","lastSplit","parts","char","before","after","remaining","BORDER_STYLES","BORDER_WIDTH_KEYWORDS","OUTLINE_STYLES","TEXT_DECORATION_LINES","TEXT_DECORATION_STYLES","expandDeclaration","property","value","rule","EXPANSION_RULES","expandedValues","prop","isShorthand","getLonghandProperties","splitBySpace","splitBalanced","expandBoxModel","parts","expandBorderRadius","expandBorder","width","style","color","part","isBorderStyle","isBorderWidth","expandBackground","expandFlex","grow","shrink","basis","expandFont","_value","expandGap","expandOverflow","expandInset","expandPlace","expandOutline","isOutlineStyle","expandTextDecoration","line","thickness","isTextDecorationLine","isTextDecorationStyle","expandTransition","expandAnimation","v","COMPOUND_VARIANT_ROOTS","createApplyContext","processApplyDirective","node","designSystem","context","ApplyContextError","classes","className","ApplyBlockedError","ApplyInvalidCandidateError","ApplyPrefixError","classInfo","nodes","dependencies","compileApplyClassWithDeps","sorted","topologicalSort","info","dep","result","error","CircularDependencyError","utilities","variants","theme","unprefixedClassName","candidates","parseCandidate","input","candidate","unknownVariants","collectUnknownApplyVariants","list","variant","message","ApplyVariantError","compileCandidate","appliedNodes","convertApplyNodes","extractApplyDependencies","baseCandidate","baseNodes","ApplyUnknownUtilityError","rawCandidate","classSelector","escapeClassName","converted","selector","replaceApplySelector","styleRule","variantsList","registry","unknown","checkVariant","deps","extractDeclarations","options","expandShorthands","isShorthand","expanded","expandDeclaration","exp","decl","CHAR_LOWER_A","CHAR_LOWER_Z","CHAR_UPPER_A","CHAR_UPPER_Z","CHAR_ZERO","CHAR_NINE","CHAR_DASH","CHAR_UNDERSCORE","CHAR_DOT","CHAR_SLASH","CHAR_PERCENT","UTILITY_ROOT_PATTERN","INTEGER_PATTERN","NUMBER_PATTERN","PERCENTAGE_PATTERN","RATIO_PATTERN","VALUE_FN_MATCH_PATTERN","VALUE_FN_REPLACE_PATTERN","MODIFIER_FN_MATCH_PATTERN","MODIFIER_FN_REPLACE_PATTERN","isValidStaticUtilityName","name","match","root","value","lastDash","valuePart","seenSlash","i","charCode","prevCode","nextCode","isValidFunctionalUtilityName","baseName","createCssUtility","node","createFunctionalCssUtility","createStaticCssUtility","extractedDecls","applyNodes","child","designSystem","utilities","result","applyNode","expandedDecls","processApplyDirective","error","UtilityApplyError","d","decl","utilityRoot","applyDecls","candidate","candidateValue","resolvedDecls","resolvedValue","resolveUtilityFunctions","candidateModifier","usedValueFn","resolvedValueFn","usedModifierFn","resolvedModifierFn","valueMatch","args","resolved","resolveValueFunction","modifierMatch","resolveModifierFunction","argList","a","arg","literal","dataType","isValidDataType","VARIANT_NAME_PATTERN","NESTING_SELECTOR_PATTERN","isValidVariantName","name","CUSTOM_VARIANT_NAME_REGEX","isValidCustomVariantName","parseCustomVariantParams","params","parts","segment","part","selector","parseAtRuleSelector","trimmed","body","firstSpace","extractSlotTemplate","nodes","node","hasVariantCSSContent","child","applyCustomVariantTemplate","template","rule","result","styleRule","childNodes","atRule","extractVariantTemplate","nested","processCustomVariantDirective","variants","options","DirectiveNestingError","selectors","s","styleSelectors","atRuleSelectors","entry","parsedAtRule","invalid","VariantSelectorError","order","variantsInstance","registrationOrder","sel","baseNodes","dependencies","dep","processVariantDirective","bodylessMatch","VariantNameError","validSelectors","nameMatch","VariantSlotError","match","VariantParseError","selectorsStr","substituteAtVariant","variantName","theme","VariantApplicationError","variant","inputRule","transformed","transformedNodes","parseColorOptions","params","COLOR_NAME_PATTERN","isValidColorName","name","processColorDirective","node","theme","opts","ColorError","hue","chroma","kDark","chromaShape","child","prop","value","num","normalized","loadPalette","SUPPORTS_START_PATTERN","extractBalancedParensAt","str","start","depth","pos","inQuote","char","removeFunctionCalls","funcName","result","funcPattern","match","matches","i","funcEnd","parenStart","extracted","isOnlySupportsPattern","remaining","supportsMatch","parseImportParams","params","path","rest","urlSyntax","quoteChar","closeIdx","reference","important","layer","supports","layerIndex","supportsIndex","layerStartMatch","supportsStartMatch","media","ImportOrderError","beforeLayer","beforeSupports","parseReferenceParams","parsed","generateImportRule","options","atRule","processFontDirective","node","params","match","FontDirectiveError","family","provider","options","child","prop","value","weights","w","valid","validHosts","normalized","removeUtilityNodes","ast","result","node","injectUtilities","compiledUtilities","baseStyles","componentStyles","CompileFeatures","consolidateThemeOutput","ast","theme","hasRainbow","placeholder","result","node","declarations","key","entry","outputKey","decl","keyframes","keyframeRule","styleRule","processDeferredVariantApplications","deferredApplications","variants","placeholderPrefix","placeholderMap","app","processNode","application","substituteAtVariant","processedChildren","child","transformCSS","options","designSystem","base","_utilities","sources","inlineCandidates","ignoredCandidates","referenceImports","rainbowIndexDirectives","fontDirectives","layers","preflightConfig","customUtilities","features","customVariants","customVariantDependencies","customVariantOrders","customVariantOrderCounter","deferredVariantApplications","variantPlaceholderCounter","VARIANT_PLACEHOLDER_PREFIX","deferredApplyDirectives","applyPlaceholderCounter","APPLY_PLACEHOLDER_PREFIX","THEME_PLACEHOLDER","hasThemePlaceholder","themeHasRainbow","createTransformContext","isTopLevel","createApplyContext","processNodes","nodes","context","riDirective","processRainbowIndexDirective","layerDirective","processLayerDirective","atRule","themeOpts","parseThemeOptions","processThemeDirective","comment","DirectiveNestingError","processColorDirective","DirectiveEmptyError","utilityRegistration","createCssUtility","name","UtilityNameError","variantParams","hasBody","hasSelectors","hasSlot","extractSlotTemplate","hasCSSContent","hasVariantCSSContent","processVariantDirective","variantName","transformed","placeholderId","processCustomVariantDirective","sourceDirective","processSourceDirective","processPreflightDirective","processFontDirective","importOpts","parseImportParams","generateImportRule","referenceOpts","parseReferenceParams","processed","themeMediaMatch","themeParams","contentDesc","sourceMediaMatch","sourcePattern","riParams","riParts","segment","p","newParams","newNode","injectedSource","prefixMediaMatch","mediaPrefix","isValidThemePrefix","ThemePrefixError","childOpts","newContext","processedDecls","processApplyDirective","error","ApplyUnknownUtilityError","ApplyVariantError","trackCssVariableUsage","value","transformedAst","ordered","topologicalSort","order","CircularDependencyError","deferredApply","isWhitespace","char","asciiLowerCase","str","result","i","code","unescape","input","idx","len","parseAttributeSelector","input","len","idx","c","attrStart","hasAttrEscape","attribute","unescape","operator","value","quote","hasValueEscape","quoteChar","valueStart","flags","escapeIdentifier","result","i","char","serializeAttributeSelector","selector","needsQuoting","escaped","isWhitespace","isAttributeSelector","extractAttributeSelectors","results","start","depth","qc","selectorStr","parsed","matchAttributeSelector","attributes","selectorValue","attrValue","asciiLowerCase","compareValue","WHITESPACE","SELECTOR_ARG_PSEUDO_CLASSES","IDENT_START_UNICODE","IDENT_CHAR_UNICODE","isIdentStart","char","code","isIdentChar","parseSelector","input","pos","peek","advance","skipWhitespace","skipped","parseIdent","name","nextChar","hexCode","codePoint","parseString","quote","value","parseAttributeSelector","operator","flags","op","parsePseudoClass","isElement","args","parseSelectors","depth","content","parseSimpleSelector","parseCompoundSelector","nodes","next","node","compound","selectors","selector","serializeNode","result","serializeSelector","serializeSelectorList","list","replaceNesting","replacement","replacementParsed","replaceInNode","hasPseudoClass","checkNode","hasNesting","extractPseudoClasses","pseudos","prependSelector","prefix","prefixNodes","appendSelector","suffix","suffixNodes","cartesian","arrays","x","result","generate","current","depth","arr","item","cartesianIterator","indices","lengths","i","cartesianSize","acc","cartesianMap","args","fn","combo","pairs","array1","array2","a","b","selfCartesian","array","repeat","cartesianFilter","predicate","ImportCache","options","path","contentHash","entry","ast","oldestPath","oldestTime","hashContent","content","hash","i","defaultImportCache","getDefaultImportCache","clearDefaultImportCache","CircularImportError","chain","ImportDepthError","depth","maxDepth","shouldSkipImport","trimmed","asciiLowerCase","parseImportPath","params","urlMatch","quotedMatch","extractBalancedParens","str","start","pos","parseImportConditions","remaining","layer","supports","layerFnMatch","layerIndex","parenStart","result","bareLayerMatch","supportsMatch","supportsIndex","media","wrapWithConditions","nodes","conditions","atRule","substituteAtImports","loadStylesheet","base","onImport","onError","imports","errors","processNodes","currentBase","ancestors","node","atRuleName","isImport","isReference","resolvedPath","resolvePath","imported","error","newBase","getDirectory","newAncestors","processed","err","processedChildren","substituteAtImportsSync","normalizePath","parts","normalized","part","lastSlash","COLOR_FUNCTION_NAMES","VALID_HEX_LENGTHS","HEX_DIGIT_PATTERN","WHITESPACE_PATTERN","SHADOW_WORD_BOUNDARY_PATTERN","SHADOW_NAMED_COLORS_SORTED","parseShadowSegments","shadow","segments","i","currentStart","current","char","remaining","parenIdx","fnName","COLOR_FUNCTION_NAMES","depth","end","colorValue","hexValue","hexDigits","VALID_HEX_LENGTHS","foundNamed","color","replaceShadowColors","replacer","result","colorIndex","segment","extractShadowColors","colors","shadowHasColors","s","stripShadowColors","shadowWithVariable","varName","normalizedVar","import_node_fs","import_node_path","import_node_os","CACHE_TTL","CACHE_FILE","GOOGLE_FONTS_API","bundledSnapshot","bundledSnapshotIndex","loadBundledSnapshot","snapshotPath","key","getBundledMetadata","family","snapshot","originalKey","memoryCache","getCachePath","cwd","baseDir","loadCache","cachePath","data","newCache","saveCache","getCachedMetadata","entry","normalizeFamily","setCachedMetadata","metadata","cache","normalized","parseGoogleFontData","fontData","weights","styles","hasNormal","hasItalic","variableAxes","isVariable","axis","tag","w","match","weight","a","b","fetchFontMetadata","response","fonts","f","fetchAndCacheMetadata","getFontMetadata","bundled","cached","getFontMetadataSync","clearMemoryCache","GOOGLE_FONTS_CSS_API","GOOGLE_FONTS_PRECONNECT","GOOGLE_FONTS_STATIC","generateGoogleFontsUrl","options","metadata","family","display","encodedFamily","weights","isVariable","includeItalic","axisSpec","min","max","minWeight","maxWeight","opsz","sortedWeights","a","b","specs","weight","generatePreloadLinks","fontUrl","generateHtmlComment","links","linkToHtml","link","attrs","generateFontUrl","importUrl","preloadLinks","htmlComment","generateFontFace","path","normalizedPath","fileFamily","fontUrls","fontFaceDecls","styles","style","filename","url","generateFontCss","result","getFontPreloadLinks","css","seenUrls","seenPreconnect","importRegex","match","key","preloadLinksToHtml","Features","MAX_FEATURE_FLAGS","isValidFeatureFlags","value","validateFeatureFlags","hasFeature","flags","feature"]}