@tenphi/tasty 3.7.0 → 3.9.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (103) hide show
  1. package/dist/{babel-DWCsafYw.d.ts → babel-Zs1Q03qt.d.ts} +2 -2
  2. package/dist/chunks/async-storage-CG5HnUT5.js +20 -0
  3. package/dist/chunks/async-storage-CG5HnUT5.js.map +1 -0
  4. package/dist/chunks/build-config-CUQVwdWF.js +42 -0
  5. package/dist/chunks/build-config-CUQVwdWF.js.map +1 -0
  6. package/dist/{collector-B3OsM252.js → chunks/collector-B0LTHw6Z.js} +6 -125
  7. package/dist/chunks/collector-B0LTHw6Z.js.map +1 -0
  8. package/dist/chunks/config-engine-C3pF9EK9.js +267 -0
  9. package/dist/chunks/config-engine-C3pF9EK9.js.map +1 -0
  10. package/dist/chunks/css-definitions-D_it4XZH.js +875 -0
  11. package/dist/chunks/css-definitions-D_it4XZH.js.map +1 -0
  12. package/dist/{css-resources-Cyl_axbI.js → chunks/css-resources-BN8apgxt.js} +1 -8
  13. package/dist/chunks/css-resources-BN8apgxt.js.map +1 -0
  14. package/dist/chunks/debug-C9LeNVoJ.js +501 -0
  15. package/dist/chunks/debug-C9LeNVoJ.js.map +1 -0
  16. package/dist/chunks/dsl-C5yuAn41.js +1373 -0
  17. package/dist/chunks/dsl-C5yuAn41.js.map +1 -0
  18. package/dist/chunks/hydration-TRcz5vnk.js +41 -0
  19. package/dist/chunks/hydration-TRcz5vnk.js.map +1 -0
  20. package/dist/chunks/react-runtime-O-OUrKLH.js +557 -0
  21. package/dist/chunks/react-runtime-O-OUrKLH.js.map +1 -0
  22. package/dist/chunks/runtime-engine-DvnE2g-E.js +2437 -0
  23. package/dist/chunks/runtime-engine-DvnE2g-E.js.map +1 -0
  24. package/dist/chunks/runtime-state-BTDqSYBk.js +127 -0
  25. package/dist/chunks/runtime-state-BTDqSYBk.js.map +1 -0
  26. package/dist/{merge-styles-DuoZEsm9.js → chunks/shared-utils-DWA4LjIa.js} +55 -54
  27. package/dist/chunks/shared-utils-DWA4LjIa.js.map +1 -0
  28. package/dist/chunks/style-engine-C1ECBZxR.js +5131 -0
  29. package/dist/chunks/style-engine-C1ECBZxR.js.map +1 -0
  30. package/dist/{css-writer-Bgowobbx.js → chunks/zero-engine-B6EnYcXY.js} +3 -120
  31. package/dist/chunks/zero-engine-B6EnYcXY.js.map +1 -0
  32. package/dist/{collector-BTVXj2hS.d.ts → collector-hl5KNH7k.d.ts} +6 -4
  33. package/dist/{config-LfIDmVHx.d.ts → config-DWL1ZYue.d.ts} +20 -25
  34. package/dist/core/index.d.ts +5 -5
  35. package/dist/core/index.js +9 -6
  36. package/dist/{index-Bm9ltvdH.d.ts → index-D9N9GV24.d.ts} +96 -82
  37. package/dist/index.d.ts +5 -5
  38. package/dist/index.js +11 -922
  39. package/dist/{merge-styles-BcLl1u_d.d.ts → merge-styles-C_oMoJVd.d.ts} +2 -2
  40. package/dist/ssr/astro-client.js +1 -14
  41. package/dist/ssr/astro-client.js.map +1 -1
  42. package/dist/ssr/astro-middleware-extract-static.js +1 -1
  43. package/dist/ssr/astro-middleware-extract.js +1 -1
  44. package/dist/ssr/astro-middleware-static.js +1 -12
  45. package/dist/ssr/astro-middleware-static.js.map +1 -1
  46. package/dist/ssr/astro-middleware.js +1 -13
  47. package/dist/ssr/astro-middleware.js.map +1 -1
  48. package/dist/ssr/astro.js +219 -1
  49. package/dist/ssr/astro.js.map +1 -0
  50. package/dist/ssr/index.d.ts +6 -6
  51. package/dist/ssr/index.js +4 -4
  52. package/dist/ssr/next-config.d.ts +1 -1
  53. package/dist/ssr/next-config.js +29 -20
  54. package/dist/ssr/next-config.js.map +1 -1
  55. package/dist/ssr/next.d.ts +1 -1
  56. package/dist/ssr/next.js +5 -37
  57. package/dist/ssr/next.js.map +1 -1
  58. package/dist/static/index.d.ts +2 -2
  59. package/dist/static/index.js +1 -19
  60. package/dist/static/index.js.map +1 -1
  61. package/dist/{index-BmogEzTo.d.ts → types-jKZNpias.d.ts} +845 -804
  62. package/dist/zero/babel.d.ts +1 -1
  63. package/dist/zero/babel.js +25 -96
  64. package/dist/zero/babel.js.map +1 -1
  65. package/dist/zero/index.d.ts +1 -1
  66. package/dist/zero/index.js +1 -1
  67. package/dist/zero/next.d.ts +1 -1
  68. package/dist/zero/next.js +0 -31
  69. package/dist/zero/next.js.map +1 -1
  70. package/docs/ai-agents.md +8 -3
  71. package/docs/debug.md +2 -5
  72. package/docs/methodology.md +3 -3
  73. package/docs/pipeline.md +3 -0
  74. package/docs/runtime-benchmarks.md +105 -68
  75. package/docs/styles.md +43 -11
  76. package/package.json +48 -5
  77. package/dist/astro-CeYENy2x.js +0 -301
  78. package/dist/astro-CeYENy2x.js.map +0 -1
  79. package/dist/async-storage-DKK-wTD4.js +0 -44
  80. package/dist/async-storage-DKK-wTD4.js.map +0 -1
  81. package/dist/collector-B3OsM252.js.map +0 -1
  82. package/dist/config-B3gPdCqd.js +0 -12421
  83. package/dist/config-B3gPdCqd.js.map +0 -1
  84. package/dist/context-CA8YKeMn.js +0 -24
  85. package/dist/context-CA8YKeMn.js.map +0 -1
  86. package/dist/core-DGm0CFHP.js +0 -1732
  87. package/dist/core-DGm0CFHP.js.map +0 -1
  88. package/dist/css-resources-Cyl_axbI.js.map +0 -1
  89. package/dist/css-writer-Bgowobbx.js.map +0 -1
  90. package/dist/format-global-rules-DklyaXv-.js +0 -22
  91. package/dist/format-global-rules-DklyaXv-.js.map +0 -1
  92. package/dist/format-rules-XRw9u7d4.js +0 -104
  93. package/dist/format-rules-XRw9u7d4.js.map +0 -1
  94. package/dist/hydrate-CNOmZprz.js +0 -37
  95. package/dist/hydrate-CNOmZprz.js.map +0 -1
  96. package/dist/index.js.map +0 -1
  97. package/dist/keyframes-DE-OE76F.js +0 -535
  98. package/dist/keyframes-DE-OE76F.js.map +0 -1
  99. package/dist/merge-styles-DuoZEsm9.js.map +0 -1
  100. package/dist/resolve-recipes-H9NqOQuP.js +0 -144
  101. package/dist/resolve-recipes-H9NqOQuP.js.map +0 -1
  102. package/dist/ssr-collector-ref-COs_ioWl.js +0 -29
  103. package/dist/ssr-collector-ref-COs_ioWl.js.map +0 -1
@@ -0,0 +1 @@
1
+ {"version":3,"file":"dsl-C5yuAn41.js","names":["clamp"],"sources":["../../src/parser/const.ts","../../src/utils/string.ts","../../src/utils/color-math.ts","../../src/utils/color-space.ts","../../src/parser/types.ts","../../src/parser/classify.ts","../../src/parser/lru.ts","../../src/parser/tokenizer.ts","../../src/parser/parser.ts","../../src/plugins/color-func.ts","../../src/plugins/okhsl-plugin.ts","../../src/plugins/okhst-plugin.ts","../../src/plugins/defaults.ts","../../src/utils/styles.ts","../../src/utils/function-color.ts","../../src/utils/colors.ts"],"sourcesContent":["export const VALUE_KEYWORDS = new Set([\n 'auto',\n 'max-content',\n 'min-content',\n 'fit-content',\n 'stretch',\n 'initial',\n 'inherit',\n 'revert',\n 'unset',\n 'revert-layer',\n]);\n\nexport const CSS_WIDE_KEYWORDS = new Set([\n 'initial',\n 'inherit',\n 'revert',\n 'unset',\n 'revert-layer',\n]);\n\n/**\n * Color functions that *derive* a color from other colors. They take no alpha\n * channel, so opacity has to wrap the whole call in `color-mix()` instead of\n * being appended after a slash.\n */\nconst DERIVED_COLOR_FUNCS_LIST = [\n 'color-mix',\n 'color-contrast',\n 'contrast-color',\n 'light-dark',\n];\n\nexport const DERIVED_COLOR_FUNCS = new Set(DERIVED_COLOR_FUNCS_LIST);\n\n/**\n * Every color function the parser recognizes. The ones outside\n * `DERIVED_COLOR_FUNCS` take channels as arguments, optionally followed by\n * `/ <alpha>` — which is where an opacity suffix writes.\n */\nexport const COLOR_FUNCS = new Set([\n 'rgb',\n 'rgba',\n 'hsl',\n 'hsla',\n 'hwb',\n 'lab',\n 'lch',\n 'oklab',\n 'oklch',\n 'color',\n 'device-cmyk',\n 'gray',\n ...DERIVED_COLOR_FUNCS_LIST,\n]);\n\n/**\n * The one color function CSS also allows to carry non-color values, so its\n * bucket depends on the arguments: `light-dark(#dark, #light)` is a color, while\n * `light-dark(1x, 2x)` is a plain value and has to stay out of the color slot.\n */\nexport const POLYMORPHIC_COLOR_FUNC = 'light-dark';\n\n/** A value that is a single `name(args)` call: captures the name and the args. */\nexport const RE_FUNC_CALL = /^([a-z][a-z0-9-]*)\\((.+)\\)$/i;\n\nexport const RE_UNIT_NUM = /^[+-]?(?:\\d*\\.\\d+|\\d+)([a-z][a-z0-9]*)$/;\nexport const RE_NUMBER = /^[+-]?(?:\\d*\\.\\d+|\\d+)$/;\nexport const RE_HEX = /^(?:[0-9a-f]{3,4}|[0-9a-f]{6}(?:[0-9a-f]{2})?)$/;\n// Matches raw CSS unit values like \"8px\", \"1rem\", \"0.5em\" - captures number and unit separately\nexport const RE_RAW_UNIT = /^([+-]?(?:\\d*\\.\\d+|\\d+))([a-z%]+)$/;\n\nconst CANONICAL_FUNC_CASE = new Map([\n ['translatex', 'translateX'],\n ['translatey', 'translateY'],\n ['translatez', 'translateZ'],\n ['scalex', 'scaleX'],\n ['scaley', 'scaleY'],\n ['scalez', 'scaleZ'],\n ['rotatex', 'rotateX'],\n ['rotatey', 'rotateY'],\n ['rotatez', 'rotateZ'],\n ['skewx', 'skewX'],\n ['skewy', 'skewY'],\n]);\n\nexport function canonicalFuncName(lowered: string): string {\n return CANONICAL_FUNC_CASE.get(lowered) ?? lowered;\n}\n","import { RE_HEX } from '../parser/const';\n\nexport function toSnakeCase(str: string): string {\n return str.replace(/[A-Z]/g, (s) => `-${s.toLowerCase()}`);\n}\n\n/**\n * Normalize a DSL identifier to the CSS custom-property name it emits.\n *\n * CSS custom-property names are case-sensitive, so `$myVar` has to keep its\n * inner case to reference `--myVar`. A leading capital is the one exception:\n * `$Foo` is not a supported way to name a property, so the first character is\n * folded rather than kebab-cased (`--foo`, not `---foo`) and every later\n * character is left alone.\n *\n * Every place that turns a `$name` / `#name` identifier into a CSS name goes\n * through this, so authoring a token and referencing it always agree.\n */\nexport function normalizeDslName(name: string): string {\n if (!name) return name;\n\n const first = name[0];\n const lower = first.toLowerCase();\n\n return lower === first ? name : lower + name.slice(1);\n}\n\n/** A DSL identifier: `$name`, `$$name`, `#name` or `##name`. */\nconst RE_DSL_IDENTIFIER = /(\\$\\$?|##?)([a-zA-Z_][a-zA-Z0-9_-]*)/g;\n\n/**\n * Case-fold a DSL string for parsing, preserving the case of custom-property\n * names.\n *\n * Everything the parser matches on — keywords, units, modifiers, function names,\n * color-token names — is compared lowercase, so the whole string used to be\n * lowercased up front. That also folded custom-property names, which are\n * case-sensitive in CSS: `$myVar` referenced `var(--myvar)` while the token\n * definition emitted `--myVar`, so the two could never meet.\n *\n * Identifier bodies now keep their case (their first character still folds, see\n * {@link normalizeDslName}); everything else is lowercased exactly as before.\n * Hex literals are excluded — `#FF0000` is a color, not a name, and must fold to\n * match {@link RE_HEX}.\n */\nexport function foldDslCase(src: string): string {\n const folded = src.toLowerCase();\n\n // Fast paths, in the order they pay off: an input that was already lowercase\n // has no case to protect, and one without a sigil has no identifier to protect.\n // Both reduce to the single fold this replaced, so only mixed-case values that\n // actually name a custom property reach the scan below.\n if (folded === src || (!src.includes('$') && !src.includes('#'))) {\n return folded;\n }\n\n RE_DSL_IDENTIFIER.lastIndex = 0;\n\n let out = '';\n let last = 0;\n let match: RegExpExecArray | null;\n\n while ((match = RE_DSL_IDENTIFIER.exec(src))) {\n const [whole, prefix, body] = match;\n\n out += src.slice(last, match.index).toLowerCase();\n out +=\n prefix +\n (prefix[0] === '#' && RE_HEX.test(body.toLowerCase())\n ? body.toLowerCase()\n : normalizeDslName(body));\n last = match.index + whole.length;\n }\n\n return out + src.slice(last).toLowerCase();\n}\n","/**\n * Consolidated color conversion math.\n *\n * Single source of truth for all color space conversions used across the\n * library: sRGB gamma, HSL, OKLab, OKLCH, OKHSL, hex parsing, named\n * colors, and CSS string converters.\n *\n * This module has zero internal imports — it is a leaf dependency.\n *\n * Reference: https://bottosson.github.io/posts/oklab/\n */\n\n// ============================================================================\n// Types\n// ============================================================================\n\ntype Vec3 = [number, number, number];\ntype Vec2 = [number, number];\n\n// ============================================================================\n// Conversion Matrices\n// ============================================================================\n\nconst OKLab_to_LMS_ab: Vec2[] = [\n [0.3963377773761749, 0.2158037573099136],\n [-0.1055613458156586, -0.0638541728258133],\n [-0.0894841775298119, -1.2914855480194092],\n];\n\nconst LMS_to_linear_sRGB_M: Vec3[] = [\n [4.076741636075959, -3.307711539258062, 0.2309699031821041],\n [-1.2684379732850313, 2.6097573492876878, -0.3413193760026569],\n [-0.004196076138675526, -0.703418617935936, 1.7076146940746113],\n];\n\nconst OKLab_to_linear_sRGB_coefficients: [\n [[number, number], number[]],\n [[number, number], number[]],\n [[number, number], number[]],\n] = [\n [\n [-1.8817030993265873, -0.8093650129914302],\n [1.19086277, 1.76576728, 0.59662641, 0.75515197, 0.56771245],\n ],\n [\n [1.8144407988010998, -1.194452667805235],\n [0.73956515, -0.45954404, 0.08285427, 0.1254107, 0.14503204],\n ],\n [\n [0.13110757611180954, 1.813339709266608],\n [1.35733652, -0.00915799, -1.1513021, -0.50559606, 0.00692167],\n ],\n];\n\n// ============================================================================\n// Linear Algebra Helpers\n// ============================================================================\n\nconst dotXY = (vector: Vec2, x: number, y: number): number =>\n vector[0] * x + vector[1] * y;\n\nconst dotXYZ = (matrix: Vec3, x: number, y: number, z: number): number =>\n matrix[0] * x + matrix[1] * y + matrix[2] * z;\n\n// ============================================================================\n// sRGB Gamma <-> Linear\n// ============================================================================\n\n/**\n * sRGB gamma to linear. Only the sRGB-to-OKLab direction needs it, so this is\n * test-only for the same reason as {@link srgbToOkhsl} — the forward path goes\n * through {@link srgbLinearToGamma} instead.\n */\nexport function srgbToLinear(c: number): number {\n return c <= 0.04045 ? c / 12.92 : ((c + 0.055) / 1.055) ** 2.4;\n}\n\nconst INV_GAMMA = 1 / 2.4;\n\nexport function srgbLinearToGamma(val: number): number {\n const sign = val < 0 ? -1 : 1;\n const abs = Math.abs(val);\n return abs > 0.0031308\n ? sign * (1.055 * abs ** INV_GAMMA - 0.055)\n : 12.92 * val;\n}\n\n// ============================================================================\n// OKHSL Constants & Helpers\n// ============================================================================\n\nconst TAU = 2 * Math.PI;\nconst K1 = 0.206;\nconst K2 = 0.03;\nconst K3 = (1.0 + K1) / (1.0 + K2);\nconst EPSILON = 1e-10;\n\nconst clamp = (value: number, min: number, max: number): number =>\n Math.max(Math.min(value, max), min);\n\nconst constrainAngle = (angle: number): number => ((angle % 360) + 360) % 360;\n\nconst toe = (x: number): number =>\n 0.5 *\n (K3 * x - K1 + Math.sqrt((K3 * x - K1) * (K3 * x - K1) + 4 * K2 * K3 * x));\n\nconst toeInv = (x: number): number => (x ** 2 + K1 * x) / (K3 * (x + K2));\n\n// ============================================================================\n// OKHST Tone Transfers\n// ============================================================================\n\nconst OKHST_REF_EPS = 0.05;\n\nfunction lToY(l: number): number {\n const L = toeInv(l);\n return L * L * L;\n}\n\nfunction yToL(y: number): number {\n return toe(Math.cbrt(Math.max(0, y)));\n}\n\nfunction toneFromY(y: number, eps: number = OKHST_REF_EPS): number {\n const num = Math.log(y + eps) - Math.log(eps);\n const den = Math.log(1 + eps) - Math.log(eps);\n return (num / den) * 100;\n}\n\nfunction yFromTone(t: number, eps: number = OKHST_REF_EPS): number {\n const den = Math.log(1 + eps) - Math.log(eps);\n return Math.exp((t / 100) * den + Math.log(eps)) - eps;\n}\n\n/**\n * Lightness to OKHST tone — the reverse of {@link fromTone}, which is the\n * direction `okhst()` uses. Kept for the same reason as {@link srgbToOkhsl},\n * and kept out of the build the same way: it lets the forward transfer be\n * round-tripped in tests, and `scripts/check-test-only-code.mjs` verifies it\n * never reaches an emitted file.\n */\nexport function toTone(l: number, eps: number = OKHST_REF_EPS): number {\n return toneFromY(lToY(l), eps);\n}\n\nexport function fromTone(t: number, eps: number = OKHST_REF_EPS): number {\n return yToL(yFromTone(t, eps));\n}\n\n// ============================================================================\n// OKLab <-> Linear sRGB\n// ============================================================================\n\nconst oklabToLinearSrgb = (lab: Vec3): Vec3 => {\n const L = lab[0];\n const a = lab[1];\n const b = lab[2];\n\n // OKLab -> LMS (inlined OKLab_to_LMS_M multiply)\n const l_ = L + 0.3963377773761749 * a + 0.2158037573099136 * b;\n const m_ = L - 0.1055613458156586 * a - 0.0638541728258133 * b;\n const s_ = L - 0.0894841775298119 * a - 1.2914855480194092 * b;\n\n // Cube\n const l = l_ * l_ * l_;\n const m = m_ * m_ * m_;\n const s = s_ * s_ * s_;\n\n // LMS -> linear sRGB (inlined LMS_to_linear_sRGB_M multiply)\n return [\n 4.076741636075959 * l - 3.307711539258062 * m + 0.2309699031821041 * s,\n -1.2684379732850313 * l + 2.6097573492876878 * m - 0.3413193760026569 * s,\n -0.004196076138675526 * l - 0.703418617935936 * m + 1.7076146940746113 * s,\n ];\n};\n\nconst linearSrgbToOklab = (rgb: Vec3): Vec3 => {\n const r = rgb[0];\n const g = rgb[1];\n const b = rgb[2];\n\n // linear sRGB -> LMS (inlined linear_sRGB_to_LMS_M multiply)\n const l = 0.4122214708 * r + 0.5363325363 * g + 0.0514459929 * b;\n const m = 0.2119034982 * r + 0.6806995451 * g + 0.1073969566 * b;\n const s = 0.0883024619 * r + 0.2817188376 * g + 0.6299787005 * b;\n\n // Cube root\n const l_ = Math.cbrt(l);\n const m_ = Math.cbrt(m);\n const s_ = Math.cbrt(s);\n\n // LMS -> OKLab (inlined LMS_to_OKLab_M multiply)\n return [\n 0.2104542553 * l_ + 0.793617785 * m_ - 0.0040720468 * s_,\n 1.9779984951 * l_ - 2.428592205 * m_ + 0.4505937099 * s_,\n 0.0259040371 * l_ + 0.7827717662 * m_ - 0.808675766 * s_,\n ];\n};\n\n// ============================================================================\n// OKHSL Gamut-Mapping Internals\n// ============================================================================\n\nconst computeMaxSaturationOKLC = (a: number, b: number): number => {\n const okCoeff = OKLab_to_linear_sRGB_coefficients;\n const lmsToRgb = LMS_to_linear_sRGB_M;\n\n let chnlCoeff: number[];\n let chnlLMS: Vec3;\n\n if (dotXY(okCoeff[0][0], a, b) > 1) {\n chnlCoeff = okCoeff[0][1];\n chnlLMS = lmsToRgb[0];\n } else if (dotXY(okCoeff[1][0], a, b) > 1) {\n chnlCoeff = okCoeff[1][1];\n chnlLMS = lmsToRgb[1];\n } else {\n chnlCoeff = okCoeff[2][1];\n chnlLMS = lmsToRgb[2];\n }\n\n const [k0, k1, k2, k3, k4] = chnlCoeff;\n const [wl, wm, ws] = chnlLMS;\n\n let sat = k0 + k1 * a + k2 * b + k3 * (a * a) + k4 * a * b;\n\n const kl = dotXY(OKLab_to_LMS_ab[0], a, b);\n const km = dotXY(OKLab_to_LMS_ab[1], a, b);\n const ks = dotXY(OKLab_to_LMS_ab[2], a, b);\n\n const l_ = 1.0 + sat * kl;\n const m_ = 1.0 + sat * km;\n const s_ = 1.0 + sat * ks;\n\n const l = l_ ** 3;\n const m = m_ ** 3;\n const s = s_ ** 3;\n\n const lds = 3.0 * kl * (l_ * l_);\n const mds = 3.0 * km * (m_ * m_);\n const sds = 3.0 * ks * (s_ * s_);\n\n const lds2 = 6.0 * (kl * kl) * l_;\n const mds2 = 6.0 * (km * km) * m_;\n const sds2 = 6.0 * (ks * ks) * s_;\n\n const f = wl * l + wm * m + ws * s;\n const f1 = wl * lds + wm * mds + ws * sds;\n const f2 = wl * lds2 + wm * mds2 + ws * sds2;\n\n sat = sat - (f * f1) / (f1 * f1 - 0.5 * f * f2);\n\n return sat;\n};\n\nconst findCuspOKLCH = (a: number, b: number): [number, number] => {\n const S_cusp = computeMaxSaturationOKLC(a, b);\n const lab: Vec3 = [1, S_cusp * a, S_cusp * b];\n const rgb_at_max = oklabToLinearSrgb(lab);\n const L_cusp = Math.cbrt(\n 1 /\n Math.max(\n Math.max(rgb_at_max[0], rgb_at_max[1]),\n Math.max(rgb_at_max[2], 0.0),\n ),\n );\n return [L_cusp, L_cusp * S_cusp];\n};\n\nconst findGamutIntersectionOKLCH = (\n a: number,\n b: number,\n l1: number,\n c1: number,\n l0: number,\n cusp: [number, number],\n): number => {\n const lmsToRgb = LMS_to_linear_sRGB_M;\n\n let t: number;\n\n if ((l1 - l0) * cusp[1] - (cusp[0] - l0) * c1 <= 0.0) {\n const denom = c1 * cusp[0] + cusp[1] * (l0 - l1);\n t = denom === 0 ? 0 : (cusp[1] * l0) / denom;\n } else {\n const denom = c1 * (cusp[0] - 1.0) + cusp[1] * (l0 - l1);\n t = denom === 0 ? 0 : (cusp[1] * (l0 - 1.0)) / denom;\n\n const dl = l1 - l0;\n const dc = c1;\n\n const kl = dotXY(OKLab_to_LMS_ab[0], a, b);\n const km = dotXY(OKLab_to_LMS_ab[1], a, b);\n const ks = dotXY(OKLab_to_LMS_ab[2], a, b);\n\n const ldt_ = dl + dc * kl;\n const mdt_ = dl + dc * km;\n const sdt_ = dl + dc * ks;\n\n const L = l0 * (1.0 - t) + t * l1;\n const C = t * c1;\n\n const l_ = L + C * kl;\n const m_ = L + C * km;\n const s_ = L + C * ks;\n\n const l = l_ ** 3;\n const m = m_ ** 3;\n const s = s_ ** 3;\n\n const ldt = 3 * ldt_ * l_ * l_;\n const mdt = 3 * mdt_ * m_ * m_;\n const sdt = 3 * sdt_ * s_ * s_;\n\n const ldt2 = 6 * ldt_ * ldt_ * l_;\n const mdt2 = 6 * mdt_ * mdt_ * m_;\n const sdt2 = 6 * sdt_ * sdt_ * s_;\n\n let correction = Number.MAX_VALUE;\n for (const matrix of lmsToRgb) {\n const value = dotXYZ(matrix, l, m, s) - 1;\n const slope = dotXYZ(matrix, ldt, mdt, sdt);\n const slope2 = dotXYZ(matrix, ldt2, mdt2, sdt2);\n const u = slope / (slope * slope - 0.5 * value * slope2);\n if (u >= 0) correction = Math.min(correction, -value * u);\n }\n t += correction;\n }\n\n return t;\n};\n\nconst computeSt = (cusp: [number, number]): [number, number] => [\n cusp[1] / cusp[0],\n cusp[1] / (1 - cusp[0]),\n];\n\nconst computeStMid = (a: number, b: number): [number, number] => [\n 0.11516993 +\n 1.0 /\n (7.4477897 +\n 4.1590124 * b +\n a *\n (-2.19557347 +\n 1.75198401 * b +\n a *\n (-2.13704948 -\n 10.02301043 * b +\n a * (-4.24894561 + 5.38770819 * b + 4.69891013 * a)))),\n 0.11239642 +\n 1.0 /\n (1.6132032 -\n 0.68124379 * b +\n a *\n (0.40370612 +\n 0.90148123 * b +\n a *\n (-0.27087943 +\n 0.6122399 * b +\n a * (0.00299215 - 0.45399568 * b - 0.14661872 * a)))),\n];\n\nconst getCs = (\n L: number,\n a: number,\n b: number,\n cusp: [number, number],\n): [number, number, number] => {\n const cMax = findGamutIntersectionOKLCH(a, b, L, 1, L, cusp);\n const stMax = computeSt(cusp);\n const k = cMax / Math.min(L * stMax[0], (1 - L) * stMax[1]);\n const stMid = computeStMid(a, b);\n let ca = L * stMid[0];\n let cb = (1.0 - L) * stMid[1];\n const cMid =\n 0.9 * k * Math.sqrt(Math.sqrt(1.0 / (1.0 / ca ** 4 + 1.0 / cb ** 4)));\n ca = L * 0.4;\n cb = (1.0 - L) * 0.8;\n const c0 = Math.sqrt(1.0 / (1.0 / ca ** 2 + 1.0 / cb ** 2));\n return [c0, cMid, cMax];\n};\n\nconst okhslToOklab = (hsl: Vec3): Vec3 => {\n let h = hsl[0];\n const s = hsl[1];\n const l = hsl[2];\n\n const L = toeInv(l);\n let a = 0;\n let b = 0;\n\n h = constrainAngle(h) / 360.0;\n\n if (L !== 0.0 && L !== 1.0 && s !== 0) {\n const a_ = Math.cos(TAU * h);\n const b_ = Math.sin(TAU * h);\n\n const cusp = findCuspOKLCH(a_, b_);\n const Cs = getCs(L, a_, b_, cusp);\n const [c0, cMid, cMax] = Cs;\n\n const mid = 0.8;\n const midInv = 1.25;\n let t: number, k0: number, k1: number, k2: number;\n\n if (s < mid) {\n t = midInv * s;\n k0 = 0.0;\n k1 = mid * c0;\n k2 = 1.0 - k1 / cMid;\n } else {\n t = 5 * (s - 0.8);\n k0 = cMid;\n k1 = (0.2 * cMid ** 2 * 1.25 ** 2) / c0;\n k2 = 1.0 - k1 / (cMax - cMid);\n }\n\n const c = k0 + (t * k1) / (1.0 - k2 * t);\n a = c * a_;\n b = c * b_;\n }\n\n return [L, a, b];\n};\n\nconst oklabToOkhsl = (lab: Vec3): Vec3 => {\n const L = lab[0];\n const a = lab[1];\n const b = lab[2];\n\n const C = Math.sqrt(a * a + b * b);\n\n if (C < EPSILON) {\n return [0, 0, toe(L)];\n }\n\n const a_ = a / C;\n const b_ = b / C;\n\n let h = Math.atan2(b, a) * (180 / Math.PI);\n h = constrainAngle(h);\n\n const cusp = findCuspOKLCH(a_, b_);\n const Cs = getCs(L, a_, b_, cusp);\n const [c0, cMid, cMax] = Cs;\n\n const mid = 0.8;\n const midInv = 1.25;\n\n let s: number;\n\n if (C < cMid) {\n const k1 = mid * c0;\n const k2 = 1.0 - k1 / cMid;\n const t = C / (k1 + C * k2);\n s = t / midInv;\n } else {\n const k0 = cMid;\n const k1 = (0.2 * cMid ** 2 * 1.25 ** 2) / c0;\n const k2 = 1.0 - k1 / (cMax - cMid);\n const cDiff = C - k0;\n const t = cDiff / (k1 + cDiff * k2);\n s = mid + t / 5;\n }\n\n const l = toe(L);\n\n return [h, clamp(s, 0, 1), clamp(l, 0, 1)];\n};\n\n// ============================================================================\n// Public Conversions — Pure Math (Vec3 in / Vec3 out)\n// ============================================================================\n\n/**\n * HSL to RGB.\n * Algorithm from CSS Color 4 spec.\n *\n * @param h - Hue in degrees (0-360)\n * @param s - Saturation (0-1)\n * @param l - Lightness (0-1)\n * @returns RGB values in 0-255 range (may have fractional values)\n */\nexport function hslToRgbValues(h: number, s: number, l: number): Vec3 {\n const a = s * Math.min(l, 1 - l);\n\n const f = (n: number): number => {\n const k = (n + h / 30) % 12;\n return l - a * Math.max(-1, Math.min(k - 3, 9 - k, 1));\n };\n\n return [f(0) * 255, f(8) * 255, f(4) * 255];\n}\n\n/**\n * OKHSL to sRGB (0-1 range).\n * @param h - Hue in degrees (0-360)\n * @param s - Saturation (0-1)\n * @param l - Lightness (0-1)\n * @returns sRGB values in 0-1 range, clamped to gamut\n */\nexport function okhslToSrgb(h: number, s: number, l: number): Vec3 {\n const oklab = okhslToOklab([h, s, l]);\n const linearRGB = oklabToLinearSrgb(oklab);\n\n return [\n clamp(srgbLinearToGamma(linearRGB[0]), 0, 1),\n clamp(srgbLinearToGamma(linearRGB[1]), 0, 1),\n clamp(srgbLinearToGamma(linearRGB[2]), 0, 1),\n ];\n}\n\n/**\n * OKHST to sRGB (0-1 range).\n * @param h - Hue in degrees (0-360)\n * @param s - Saturation (0-1)\n * @param t - Tone (0-1)\n * @returns sRGB values in 0-1 range, clamped to gamut\n */\nexport function okhstToSrgb(h: number, s: number, t: number): Vec3 {\n return okhslToSrgb(h, clamp(s, 0, 1), clamp(fromTone(t * 100), 0, 1));\n}\n\n/**\n * OKLCH to sRGB (0-255 range).\n * @param L - Lightness (0-1)\n * @param C - Chroma (typically 0-0.4)\n * @param H - Hue in degrees (0-360)\n * @returns RGB values in 0-255 range, clamped to gamut\n */\nexport function oklchToRgbValues(L: number, C: number, H: number): Vec3 {\n const hRad = (H * Math.PI) / 180;\n const a = C * Math.cos(hRad);\n const b = C * Math.sin(hRad);\n const linear = oklabToLinearSrgb([L, a, b]);\n\n return [\n clamp(srgbLinearToGamma(linear[0]), 0, 1) * 255,\n clamp(srgbLinearToGamma(linear[1]), 0, 1) * 255,\n clamp(srgbLinearToGamma(linear[2]), 0, 1) * 255,\n ];\n}\n\n/**\n * sRGB (0-1 range) to OKHSL.\n *\n * The reverse of {@link okhslToSrgb}, which is the direction the `okhsl()`\n * plugin uses. Nothing in the engine calls this — it exists so the forward\n * conversion can be round-tripped in tests, which checks its accuracy without\n * depending on hand-written fixtures.\n *\n * Test-only, and kept out of the build by not being reachable from any package\n * entry point. `scripts/check-test-only-code.mjs` fails the build if that ever\n * stops being true.\n *\n * @returns [H (0-360), S (0-1), L (0-1)]\n */\nexport function srgbToOkhsl(rgb: Vec3): Vec3 {\n const linear: Vec3 = [\n srgbToLinear(rgb[0]),\n srgbToLinear(rgb[1]),\n srgbToLinear(rgb[2]),\n ];\n const oklab = linearSrgbToOklab(linear);\n return oklabToOkhsl(oklab);\n}\n\n// ============================================================================\n// Named CSS Colors\n// ============================================================================\n\nlet _namedColorHex: Map<string, string> | null = null;\n\nexport function getNamedColorHex(): Map<string, string> {\n if (_namedColorHex) return _namedColorHex;\n\n // The second string stores one six-digit value for every space-separated\n // name in the first. The table checksum test keeps the packed columns in\n // lockstep while avoiding an object literal in every runtime bundle.\n const names =\n 'aliceblue antiquewhite aqua aquamarine azure beige bisque black blanchedalmond blue blueviolet brown burlywood cadetblue chartreuse chocolate coral cornflowerblue cornsilk crimson cyan darkblue darkcyan darkgoldenrod darkgray darkgreen darkgrey darkkhaki darkmagenta darkolivegreen darkorange darkorchid darkred darksalmon darkseagreen darkslateblue darkslategray darkslategrey darkturquoise darkviolet deeppink deepskyblue dimgray dimgrey dodgerblue firebrick floralwhite forestgreen fuchsia gainsboro ghostwhite gold goldenrod gray green greenyellow grey honeydew hotpink indianred indigo ivory khaki lavender lavenderblush lawngreen lemonchiffon lightblue lightcoral lightcyan lightgoldenrodyellow lightgray lightgreen lightgrey lightpink lightsalmon lightseagreen lightskyblue lightslategray lightslategrey lightsteelblue lightyellow lime limegreen linen magenta maroon mediumaquamarine mediumblue mediumorchid mediumpurple mediumseagreen mediumslateblue mediumspringgreen mediumturquoise mediumvioletred midnightblue mintcream mistyrose moccasin navajowhite navy oldlace olive olivedrab orange orangered orchid palegoldenrod palegreen paleturquoise palevioletred papayawhip peachpuff peru pink plum powderblue purple rebeccapurple red rosybrown royalblue saddlebrown salmon sandybrown seagreen seashell sienna silver skyblue slateblue slategray slategrey snow springgreen steelblue tan teal thistle tomato turquoise violet wheat white whitesmoke yellow yellowgreen'.split(\n ' ',\n );\n const hex =\n 'f0f8fffaebd700ffff7fffd4f0fffff5f5dcffe4c4000000ffebcd0000ff8a2be2a52a2adeb8875f9ea07fff00d2691eff7f506495edfff8dcdc143c00ffff00008b008b8bb8860ba9a9a9006400a9a9a9bdb76b8b008b556b2fff8c009932cc8b0000e9967a8fbc8f483d8b2f4f4f2f4f4f00ced19400d3ff149300bfff6969696969691e90ffb22222fffaf0228b22ff00ffdcdcdcf8f8ffffd700daa520808080008000adff2f808080f0fff0ff69b4cd5c5c4b0082fffff0f0e68ce6e6fafff0f57cfc00fffacdadd8e6f08080e0fffffafad2d3d3d390ee90d3d3d3ffb6c1ffa07a20b2aa87cefa778899778899b0c4deffffe000ff0032cd32faf0e6ff00ff80000066cdaa0000cdba55d39370db3cb3717b68ee00fa9a48d1ccc71585191970f5fffaffe4e1ffe4b5ffdead000080fdf5e68080006b8e23ffa500ff4500da70d6eee8aa98fb98afeeeedb7093ffefd5ffdab9cd853fffc0cbdda0ddb0e0e6800080663399ff0000bc8f8f4169e18b4513fa8072f4a4602e8b57fff5eea0522dc0c0c087ceeb6a5acd708090708090fffafa00ff7f4682b4d2b48c008080d8bfd8ff634740e0d0ee82eef5deb3fffffff5f5f5ffff009acd32';\n const colors = new Map<string, string>();\n\n for (let i = 0; i < names.length; i++) {\n colors.set(names[i], `#${hex.slice(i * 6, i * 6 + 6)}`);\n }\n\n return (_namedColorHex = colors);\n}\n\n// ============================================================================\n// String Converters\n// ============================================================================\n\n/**\n * Convert hex color string to `rgb()` CSS string.\n * Supports 3, 4, 6, and 8 character hex values (with or without `#`).\n */\nexport function hexToRgb(hex: string): string | null {\n const matched = hex\n .replace(\n /^#?([a-f\\d])([a-f\\d])([a-f\\d])$/i,\n (_m: string, r: string, g: string, b: string) =>\n '#' + r + r + g + g + b + b,\n )\n .substring(1)\n .match(/.{2}/g);\n\n if (!matched) return null;\n\n const rgba = matched.map(\n (x: string, i: number) => parseInt(x, 16) * (i === 3 ? 1 / 255 : 1),\n );\n\n if (rgba.some((v) => Number.isNaN(v))) {\n return null;\n }\n\n if (rgba.length >= 3) {\n return `rgb(${rgba.slice(0, 3).join(' ')}${rgba.length > 3 ? ` / ${rgba[3]}` : ''})`;\n }\n\n return null;\n}\n\n/**\n * Extract RGB values from an `rgb()`/`rgba()` string.\n * Supports comma-separated, space-separated, fractional, percentage,\n * and slash alpha notation.\n *\n * @returns Array of RGB values (0-255 range), converting percentages as needed.\n */\nexport function getRgbValuesFromRgbaString(str: string): number[] {\n const match = str.match(/rgba?\\(([^)]+)\\)/i);\n if (!match) return [];\n\n const inner = match[1].trim();\n const [colorPart] = inner.split('/');\n const parts = colorPart\n .trim()\n .split(/[,\\s]+/)\n .filter(Boolean);\n\n return parts.slice(0, 3).map((part) => {\n part = part.trim();\n if (part.endsWith('%')) {\n return (parseFloat(part) / 100) * 255;\n }\n return parseFloat(part);\n });\n}\n\n/**\n * Convert any recognized color string to an `rgb()` CSS string.\n * Handles hex, `okhsl()`, `okhst()`, `hsl()`/`hsla()`, named CSS colors,\n * and `rgb()`/`rgba()` pass-through.\n */\nexport function strToRgb(\n color: string,\n _ignoreAlpha = false,\n): string | null | undefined {\n if (!color) return undefined;\n\n if (color.startsWith('rgb')) return color;\n if (color.startsWith('#')) return hexToRgb(color);\n if (color.startsWith('oklch(')) return oklchStringToRgb(color);\n if (color.startsWith('hsl')) return hslStringToRgb(color);\n\n const namedHex = getNamedColorHex().get(color.toLowerCase());\n if (namedHex) return hexToRgb(namedHex);\n\n return null;\n}\n\n/**\n * Convert an HSL/HSLA color string to an `rgb()`/`rgba()` CSS string.\n * Supports modern space-separated and legacy comma-separated syntax,\n * deg/turn/rad hue units, and slash alpha notation.\n */\nexport function hslStringToRgb(hslStr: string): string | null {\n const match = hslStr.match(/hsla?\\(([^)]+)\\)/i);\n if (!match) return null;\n\n const inner = match[1].trim();\n const [colorPart, slashAlpha] = inner.split('/');\n const parts = colorPart\n .trim()\n .split(/[,\\s]+/)\n .filter(Boolean);\n\n if (parts.length < 3) return null;\n\n const alphaPart = slashAlpha?.trim() || (parts.length >= 4 ? parts[3] : null);\n\n let h = parseFloat(parts[0]);\n const hueStr = parts[0].toLowerCase();\n if (hueStr.endsWith('turn')) h = parseFloat(hueStr) * 360;\n else if (hueStr.endsWith('rad')) h = (parseFloat(hueStr) * 180) / Math.PI;\n h = ((h % 360) + 360) % 360;\n\n const parsePercent = (val: string): number => {\n const num = parseFloat(val);\n return val.includes('%') ? num / 100 : num;\n };\n const s = Math.max(0, Math.min(1, parsePercent(parts[1])));\n const l = Math.max(0, Math.min(1, parsePercent(parts[2])));\n\n const [r, g, b] = hslToRgbValues(h, s, l);\n\n if (alphaPart) {\n const alpha = parseFloat(alphaPart.trim());\n return `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${alpha})`;\n }\n\n return `rgb(${Math.round(r)} ${Math.round(g)} ${Math.round(b)})`;\n}\n\n/**\n * Convert an `oklch()` color string to an `rgb()`/`rgba()` CSS string.\n * Supports deg/turn/rad hue units and percentage lightness.\n */\nexport function oklchStringToRgb(oklchStr: string): string | null {\n const match = oklchStr.match(/oklch\\(([^)]+)\\)/i);\n if (!match) return null;\n\n const inner = match[1].trim();\n const [colorPart, alphaPart] = inner.split('/');\n const parts = colorPart\n .trim()\n .split(/[,\\s]+/)\n .filter(Boolean);\n\n if (parts.length < 3) return null;\n\n const parsePercent = (val: string): number => {\n const num = parseFloat(val);\n return val.includes('%') ? num / 100 : num;\n };\n const L = Math.max(0, Math.min(1, parsePercent(parts[0])));\n const C = Math.max(0, parseFloat(parts[1]));\n\n let H = parseFloat(parts[2]);\n const hueStr = parts[2].toLowerCase();\n if (hueStr.endsWith('turn')) H = parseFloat(hueStr) * 360;\n else if (hueStr.endsWith('rad')) H = (parseFloat(hueStr) * 180) / Math.PI;\n else if (hueStr.endsWith('deg')) H = parseFloat(hueStr);\n\n const [r, g, b] = oklchToRgbValues(L, C, H);\n\n if (alphaPart) {\n const alpha = parseFloat(alphaPart.trim());\n return `rgba(${Math.round(r)}, ${Math.round(g)}, ${Math.round(b)}, ${alpha})`;\n }\n\n return `rgb(${Math.round(r)} ${Math.round(g)} ${Math.round(b)})`;\n}\n","/**\n * Color handling that survives into the emitted CSS.\n *\n * Tasty does not rewrite a color into a particular color space: opacity is\n * applied with CSS relative color syntax, which reads the channels off whatever\n * the browser resolves a value to, so a color is emitted exactly as authored.\n * What is left here is how an alpha gets applied, and the one distinction that\n * matters — replacing a token's alpha versus composing onto an inherited one.\n */\n\n/**\n * The color space a `#name` token's value used to be rewritten into.\n *\n * @deprecated Kept for the `colorSpace` config option, which no longer has any\n * effect. Colors are emitted as authored and opacity is always applied in\n * `oklch` through relative color syntax.\n */\nexport type ColorSpace = 'rgb' | 'hsl' | 'oklch';\n\n/**\n * Set the alpha of a whole color, replacing any it already carries.\n *\n * CSS relative color syntax is how opacity is applied to every color Tasty\n * emits. `oklch(from <color> l c h / <alpha>)` copies the channels over and\n * writes the alpha slot, which needs nothing from the color except that it *is*\n * a color: a `color-mix()`, a `light-dark()`, a `currentcolor`, a\n * `--name-color` written by hand-authored CSS that Tasty never defined — all of\n * them work, where writing into a channel slot directly would require channels\n * the engine has no way to compute.\n *\n * Alpha is *replaced*, not composed. A token holding `rgb(255 0 0 / .8)` faded\n * to `.5` is alpha `.5`. `color-mix()` against `transparent` cannot do this —\n * it would multiply the two to `.4`.\n *\n * The alpha slot takes a `<number>` or a `<percentage>`, so an opacity custom\n * property passes straight through in whichever form the author declared it.\n *\n * The space is always `oklch`, regardless of the configured {@link ColorSpace}:\n * it is unbounded, so a wide-gamut color survives the round trip that a\n * gamut-limited space would clamp, and it is the space the computed value used\n * to be reported in. Channels are copied rather than interpolated, so the polar\n * form costs nothing even for an achromatic color, whose hue is carried through\n * untouched.\n */\nexport function overrideColorAlpha(color: string, alpha: string): string {\n return `oklch(from ${color} l c h / ${alpha})`;\n}\n\n/**\n * Compose an alpha onto a color, multiplying with any it already carries.\n *\n * This is the counterpart to {@link overrideColorAlpha}, and the difference is\n * the point. A design token names a color, so fading it *sets* its alpha. But\n * `currentcolor` is the color an element **inherits**, which an ancestor may\n * already have faded — `#current.4` there means \"40% of what reaches me\", and a\n * nested `#current.18` under it composes to `.072`. Design systems build ramps\n * out of exactly that, so `#current` composes and a token replaces.\n *\n * `color-mix()` against `transparent` is what composes: mixing premultiplied\n * leaves the channels alone and multiplies the alphas. Its percentage slot takes\n * no `<number>`, so a `$prop` alpha has to be scaled — which is why an opacity\n * property used as `#current.$prop` has to hold a unitless number, where a token\n * accepts either form.\n */\nexport function mixColorAlpha(color: string, percentage: string): string {\n return `color-mix(in oklab, ${color} ${percentage}, transparent)`;\n}\n\n/**\n * Matches what {@link overrideColorAlpha} builds. The first group is greedy so a\n * nested override splits on its outermost layer.\n */\nconst RE_ALPHA_OVERRIDE = /^oklch\\(from (.+) l c h \\/ (.+)\\)$/;\n\n/**\n * Split what {@link overrideColorAlpha} builds back into the color it faded and\n * the alpha, or `null` when the value is not one of those.\n */\nexport function parseAlphaOverride(\n value: string,\n): { color: string; alpha: string } | null {\n const match = value.match(RE_ALPHA_OVERRIDE);\n\n return match ? { color: match[1], alpha: match[2] } : null;\n}\n","export enum Bucket {\n Color,\n Value,\n Mod,\n /**\n * A custom-property reference whose name ends with `-color`, e.g.\n * `$brand-color`. The suffix is the only hint the parser has, so the reference\n * is filed as a color *and* as a value: a color slot finds it, and so does a\n * handler reading `values` — otherwise `padding: '$brand-color'` would find no\n * value and silently emit its default instead.\n */\n ColorValue,\n}\n\n/**\n * A part within a group, representing a slash-separated segment.\n * For example, in `'2px solid #red / 4px'`, there are two parts:\n * - Part 0: `2px solid #red`\n * - Part 1: `4px`\n */\nexport interface StyleDetailsPart {\n mods: string[];\n values: string[];\n colors: string[];\n all: string[];\n output: string;\n}\n\n/**\n * A group of style details, representing a comma-separated segment.\n * Contains aggregated values from all parts for backward compatibility,\n * plus the structured `parts` array for handlers that need slash separation.\n */\nexport interface StyleDetails {\n input: string;\n output: string;\n /** Aggregated mods from all parts (backward compatible) */\n mods: string[];\n /** Aggregated values from all parts (backward compatible) */\n values: string[];\n /** Aggregated colors from all parts (backward compatible) */\n colors: string[];\n /** Aggregated all tokens from all parts (backward compatible) */\n all: string[];\n /** Slash-separated parts within this group */\n parts: StyleDetailsPart[];\n}\n\nexport interface ProcessedStyle {\n output: string;\n groups: StyleDetails[];\n}\n\nexport type UnitHandler = (scalar: number) => string;\n\nexport interface ParserOptions {\n functions?: Record<string, (parsed: StyleDetails[]) => string>;\n units?: Record<string, string | UnitHandler>;\n cacheSize?: number;\n}\n\nexport const makeEmptyPart = (): StyleDetailsPart => ({\n mods: [],\n values: [],\n colors: [],\n all: [],\n output: '',\n});\n\nexport const makeEmptyDetails = (): StyleDetails => ({\n input: '',\n output: '',\n mods: [],\n values: [],\n colors: [],\n all: [],\n parts: [],\n});\n","import { getNamedColorHex } from '../utils/color-math';\nimport { mixColorAlpha, overrideColorAlpha } from '../utils/color-space';\nimport { getGlobalPredefinedTokens } from '../utils/styles';\nimport { foldDslCase } from '../utils/string';\n\nimport {\n COLOR_FUNCS,\n DERIVED_COLOR_FUNCS,\n POLYMORPHIC_COLOR_FUNC,\n RE_FUNC_CALL,\n RE_HEX,\n RE_NUMBER,\n RE_RAW_UNIT,\n RE_UNIT_NUM,\n VALUE_KEYWORDS,\n canonicalFuncName,\n} from './const';\nimport { StyleParser } from './parser';\nimport type { ParserOptions, ProcessedStyle } from './types';\nimport { Bucket } from './types';\n\n/**\n * Convert an opacity suffix to the alpha value it denotes.\n *\n * The authored digits are kept verbatim — `.07` stays `.07` rather than being\n * multiplied into `7.000000000000001%` — and a `$prop` suffix passes the\n * reference straight through, so it works whether the property holds a\n * `<number>` or a `<percentage>`. Both are what the alpha slot accepts.\n */\nfunction alphaSuffixToAlpha(rawAlpha: string): string {\n // Custom property: $disabled -> var(--disabled)\n if (rawAlpha.startsWith('$')) return `var(--${rawAlpha.slice(1)})`;\n if (rawAlpha === '0') return '0';\n\n return `.${rawAlpha}`;\n}\n\n/** Apply an opacity suffix to a color, replacing any alpha it already carries. */\nfunction fadeColor(color: string, rawAlpha: string): string {\n return overrideColorAlpha(color, alphaSuffixToAlpha(rawAlpha));\n}\n\n/**\n * Convert an opacity suffix to the percentage `color-mix()` needs, by shifting\n * the decimal point rather than multiplying: `.07` is `7%`, not the\n * `7.000000000000001%` that `parseFloat('.07') * 100` produces.\n */\nfunction alphaSuffixToPercentage(rawAlpha: string): string {\n if (rawAlpha.startsWith('$')) {\n // A mix percentage cannot be a `<number>`, so the reference has to be scaled.\n return `calc(var(--${rawAlpha.slice(1)}) * 100%)`;\n }\n if (rawAlpha === '0') return '0%';\n\n const digits = rawAlpha.length === 1 ? `${rawAlpha}0` : rawAlpha;\n const whole = String(Number(digits.slice(0, 2)));\n const fraction = digits.slice(2);\n\n return `${fraction ? `${whole}.${fraction}` : whole}%`;\n}\n\n/**\n * Apply an opacity suffix to `currentcolor`, composing with any alpha an\n * ancestor already applied. See {@link mixColorAlpha} for why this differs from\n * how a token is faded.\n */\nfunction fadeCurrentColor(rawAlpha: string): string {\n return mixColorAlpha('currentcolor', alphaSuffixToPercentage(rawAlpha));\n}\n\n/**\n * Whether parsed function arguments hold a color. Colors reach either the color\n * bucket (`#token`, a nested color function, `transparent`) or — for the CSS\n * named colors, which the parser has no token syntax for — the modifier bucket.\n */\nfunction hasColorArgs(parsed: ProcessedStyle): boolean {\n const namedColors = getNamedColorHex();\n\n return parsed.groups.some(\n (group) =>\n group.colors.length > 0 || group.mods.some((mod) => namedColors.has(mod)),\n );\n}\n\n/**\n * Re-parses a value through the parser until it stabilizes (no changes)\n * or max iterations reached. This allows units to reference other units.\n * Example: { x: '8px', y: '2x' } -> '1y' resolves to '16px'\n */\nfunction resolveUntilStable(\n value: string,\n opts: ParserOptions,\n recurse: (str: string) => ProcessedStyle,\n maxIterations = 10,\n): string {\n let current = value;\n for (let i = 0; i < maxIterations; i++) {\n // Check if the current value contains a custom unit that needs resolution\n const unitMatch = current.match(RE_UNIT_NUM);\n if (!unitMatch) break; // Not a unit number, no resolution needed\n\n const unitName = unitMatch[1];\n // Only recurse if the unit is a custom unit we know about\n // Any unit not in opts.units is assumed to be a native CSS unit\n if (!opts.units || !(unitName in opts.units)) break;\n\n const result = recurse(current);\n if (result.output === current) break; // Stable\n current = result.output;\n }\n return current;\n}\n\nexport function classify(\n raw: string,\n opts: ParserOptions,\n recurse: (str: string) => ProcessedStyle,\n): { bucket: Bucket; processed: string } {\n const token = raw.trim();\n if (!token) return { bucket: Bucket.Mod, processed: '' };\n\n // Early-out: if the token contains unmatched parentheses treat it as invalid\n // and skip it. This avoids cases like `drop-shadow(` that are missing a\n // closing parenthesis (e.g., a user-typo in CSS). We count paren depth while\n // ignoring everything inside string literals to avoid false positives.\n if (token.includes('(')) {\n let depth = 0;\n let inQuote: string | 0 = 0;\n for (let i = 0; i < token.length; i++) {\n const ch = token[i];\n\n // track quote context so parentheses inside quotes are ignored\n if (inQuote) {\n if (ch === inQuote && token[i - 1] !== '\\\\') inQuote = 0;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inQuote = ch;\n continue;\n }\n\n if (ch === '(') depth++;\n else if (ch === ')' && depth) depth--;\n }\n\n if (depth !== 0) {\n // Unbalanced parens → treat as invalid token (skipped).\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n '[Tasty] skipped invalid function token with unmatched parentheses:',\n token,\n );\n }\n return { bucket: Bucket.Mod, processed: '' };\n }\n }\n\n // Quoted string literals should be treated as value tokens (e.g., \"\" for content)\n if (\n (token.startsWith('\"') && token.endsWith('\"')) ||\n (token.startsWith(\"'\") && token.endsWith(\"'\"))\n ) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 0. Double prefix for literal CSS property names ($$name -> --name, ##name -> --name-color)\n // Used in transitions and animations to reference the property name itself, not its value.\n // Also supports custom @function invocation: $$name(args) -> --name(processed args).\n if (token.startsWith('$$')) {\n const rest = token.slice(2);\n const openIdx = rest.indexOf('(');\n if (openIdx > 0 && rest.endsWith(')')) {\n const fname = rest.slice(0, openIdx);\n if (/^[a-z_][a-z0-9-_]*$/i.test(fname)) {\n const inner = rest.slice(openIdx + 1, -1).trim();\n const cssName = `--${fname}`;\n // @function polyfill: when a compiled closure is registered for this\n // function, inline the call into plain CSS instead of emitting the\n // (limited-support) native `--name(...)` call.\n if (opts.functions && cssName in opts.functions) {\n const groups = inner\n ? new StyleParser(opts).process(inner).groups\n : [];\n const funcResult = opts.functions[cssName](groups);\n // Empty result signals a recursion-cycle bail: leave the call as-is.\n if (funcResult !== '') {\n return classify(\n funcResult,\n { ...opts, functions: undefined },\n recurse,\n );\n }\n }\n const args = inner ? recurse(inner).output : '';\n return { bucket: Bucket.Value, processed: `--${fname}(${args})` };\n }\n }\n if (/^[a-z_][a-z0-9-_]*$/i.test(rest)) {\n return { bucket: Bucket.Value, processed: `--${rest}` };\n }\n }\n if (token.startsWith('##')) {\n const rest = token.slice(2);\n const openIdx = rest.indexOf('(');\n if (openIdx > 0 && rest.endsWith(')')) {\n const fname = rest.slice(0, openIdx);\n if (/^[a-z_][a-z0-9-_]*$/i.test(fname)) {\n const inner = rest.slice(openIdx + 1, -1).trim();\n const args = inner ? recurse(inner).output : '';\n return { bucket: Bucket.Value, processed: `--${fname}-color(${args})` };\n }\n }\n if (/^[a-z_][a-z0-9-_]*$/i.test(rest)) {\n return { bucket: Bucket.Value, processed: `--${rest}-color` };\n }\n }\n\n // 0b. Special handling for #current (reserved keyword, cannot be overridden by\n // predefined tokens).\n //\n // `#current` is the `currentcolor` keyword, and emitting the keyword itself is\n // what makes it compose: it resolves against each element's own color, so a\n // `#current` under an ancestor that faded its color reads the *faded* color.\n // `var(--current-color)` cannot do that — the variable carries whatever the\n // nearest publishing ancestor put in it, and a faded color is deliberately not\n // published (see `colorStyle`), so a ramp built on `#current` would read\n // through to the unfaded color above it.\n if (token === '#current') {\n return { bucket: Bucket.Color, processed: 'currentcolor' };\n }\n\n // #current with opacity: #current.5 or #current.$opacity\n //\n // `color-mix()` rather than the relative color syntax a token fade uses.\n // Fading a token *names* a color, so it replaces the alpha; `currentcolor` is\n // the color an element inherits, which an ancestor may already have faded, so\n // `#current.4` means \"40% of what reaches me\" and composes — `#current.4` with\n // `#current.18` under it lands at `.072`. `color-mix()` with `currentcolor`\n // has worked since Safari 16.2.\n const currentAlphaMatch = token.match(\n /^#current\\.(\\$[a-z_][a-z0-9-_]*|[0-9]+)$/i,\n );\n if (currentAlphaMatch) {\n return {\n bucket: Bucket.Color,\n processed: fadeCurrentColor(currentAlphaMatch[1]),\n };\n }\n\n // 0c. Check for predefined tokens (configured via configure({ replaceTokens: {...} }))\n // Must happen before default $ and # handling to allow overriding\n if (token[0] === '$' || token[0] === '#') {\n const predefinedTokens = getGlobalPredefinedTokens();\n if (predefinedTokens) {\n // Exact match. Keys are stored lowercase, and token names are matched\n // case-insensitively even though the name they *emit* keeps its case.\n const lookupKey = token.toLowerCase();\n if (lookupKey in predefinedTokens) {\n const tokenValue = predefinedTokens[lookupKey];\n // Fold the token value the same way the parser folds its input.\n return classify(foldDslCase(tokenValue), opts, recurse);\n }\n // Check for color token with alpha suffix: #token.alpha or #token.$prop\n if (token[0] === '#') {\n const alphaMatch = token.match(\n /^(#[a-z0-9-]+)\\.(\\$[a-z_][a-z0-9-_]*|[0-9]+)$/i,\n );\n if (alphaMatch) {\n const [, baseToken, rawAlpha] = alphaMatch;\n const baseKey = baseToken.toLowerCase();\n if (baseKey in predefinedTokens) {\n const resolvedValue = predefinedTokens[baseKey];\n\n // If resolved value starts with # (color token), use standard alpha syntax\n if (resolvedValue.startsWith('#')) {\n // Fold to match parser behavior\n return classify(\n `${foldDslCase(resolvedValue)}.${rawAlpha}`,\n opts,\n recurse,\n );\n }\n\n // For color functions like rgb(), rgba(), hsl(), hwb(), etc., inject alpha.\n // This covers all standard CSS color functions plus any custom color\n // function registered as a parse function (e.g. okhsl/okhst via plugins),\n // so no function name is hardcoded here.\n const funcMatch = resolvedValue.match(RE_FUNC_CALL);\n if (funcMatch) {\n const [, funcName, args] = funcMatch;\n const lowerFunc = funcName.toLowerCase();\n\n // A derived color function (color-mix, light-dark, …) has no alpha\n // channel to write into, so opacity is applied to the whole call\n // the same way `#current.5` is.\n if (DERIVED_COLOR_FUNCS.has(lowerFunc)) {\n const resolved = classify(\n foldDslCase(resolvedValue),\n opts,\n recurse,\n );\n\n return {\n bucket: Bucket.Color,\n processed: fadeColor(resolved.processed, rawAlpha),\n };\n }\n const isCustomFunc = !!(\n opts.functions &&\n lowerFunc in opts.functions &&\n !COLOR_FUNCS.has(lowerFunc) &&\n !COLOR_FUNCS.has(funcName.replace(/a$/i, '').toLowerCase())\n );\n // Native color function name with the legacy 'a' suffix dropped\n // (rgba->rgb, hsla->hsl). Custom functions keep their original name.\n const normalizedFunc = isCustomFunc\n ? lowerFunc\n : funcName.replace(/a$/i, '').toLowerCase();\n // Only treat as a color function if it is a native CSS color\n // function or a registered custom parse function. Otherwise the\n // resolved value is some other function call and alpha injection\n // does not apply.\n const isColorFunc =\n COLOR_FUNCS.has(normalizedFunc) ||\n COLOR_FUNCS.has(lowerFunc) ||\n isCustomFunc;\n if (!isColorFunc) {\n return classify(`${resolvedValue}.${rawAlpha}`, opts, recurse);\n }\n // Handle $prop syntax for custom property alpha\n let alpha: string;\n if (rawAlpha.startsWith('$')) {\n const propName = rawAlpha.slice(1);\n alpha = `var(--${propName})`;\n } else {\n alpha = rawAlpha === '0' ? '0' : `.${rawAlpha}`;\n }\n // Normalize to modern syntax: replace top-level commas with spaces\n // Preserves commas inside nested functions like min(), max(), clamp()\n const normalizeArgs = (a: string) => {\n let result = '';\n let depth = 0;\n for (let i = 0; i < a.length; i++) {\n const c = a[i];\n if (c === '(') {\n depth++;\n result += c;\n } else if (c === ')') {\n depth = Math.max(0, depth - 1);\n result += c;\n } else if (c === ',' && depth === 0) {\n // Skip comma and any following whitespace at top level\n while (i + 1 < a.length && /\\s/.test(a[i + 1])) i++;\n result += ' ';\n } else {\n result += c;\n }\n }\n return result;\n };\n // Helper: find last top-level occurrence of a character (ignores parentheses)\n const findLastTopLevel = (str: string, ch: string) => {\n let depth = 0;\n for (let i = str.length - 1; i >= 0; i--) {\n const c = str[i];\n if (c === ')') depth++;\n else if (c === '(') depth = Math.max(0, depth - 1);\n else if (c === ch && depth === 0) return i;\n }\n return -1;\n };\n\n // Check if already has alpha:\n // - Modern syntax: has `/` separator at top level (works with dynamic alpha like var()/calc())\n // - Legacy syntax: function ends with 'a' (rgba, hsla) and has exactly 4 top-level comma-separated values\n const slashIdx = findLastTopLevel(args, '/');\n const hasModernAlpha = slashIdx !== -1;\n\n // Count top-level commas to avoid commas inside nested functions\n let topLevelCommaCount = 0;\n let lastTopLevelComma = -1;\n {\n let depth = 0;\n for (let i = 0; i < args.length; i++) {\n const c = args[i];\n if (c === '(') depth++;\n else if (c === ')') depth = Math.max(0, depth - 1);\n else if (c === ',' && depth === 0) {\n topLevelCommaCount++;\n lastTopLevelComma = i;\n }\n }\n }\n\n const hasLegacyAlpha =\n !hasModernAlpha &&\n /a$/i.test(funcName) &&\n topLevelCommaCount === 3;\n\n const colorArgs =\n hasModernAlpha || hasLegacyAlpha\n ? normalizeArgs(\n hasModernAlpha\n ? args.slice(0, slashIdx).trim()\n : args.slice(0, lastTopLevelComma).trim(),\n )\n : normalizeArgs(args);\n\n const constructed = `${normalizedFunc}(${colorArgs} / ${alpha})`;\n\n // Custom functions (not native CSS) must be re-classified\n // so the function handler can convert them to valid CSS\n if (\n !COLOR_FUNCS.has(normalizedFunc) &&\n opts.functions &&\n normalizedFunc in opts.functions\n ) {\n return classify(constructed, opts, recurse);\n }\n\n return { bucket: Bucket.Color, processed: constructed };\n }\n\n // Fallback: try appending .alpha (may not work for all cases)\n return classify(`${resolvedValue}.${rawAlpha}`, opts, recurse);\n }\n }\n }\n }\n }\n\n // 0. Direct var(--*-color) token\n const varColorMatch = token.match(/^var\\(--([a-zA-Z0-9-]+)-color\\)$/);\n if (varColorMatch) {\n return { bucket: Bucket.Color, processed: token };\n }\n\n // 1. URL\n if (token.startsWith('url(')) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 2. Custom property\n if (token[0] === '$') {\n const identMatch = token.match(/^\\$([a-z_][a-zA-Z0-9-_]*)$/);\n if (identMatch) {\n const name = identMatch[1];\n const processed = `var(--${name})`;\n const bucketType = name.endsWith('-color')\n ? Bucket.ColorValue\n : Bucket.Value;\n return {\n bucket: bucketType,\n processed,\n };\n }\n // invalid custom property → modifier\n }\n\n // 3. Hash colors (with optional alpha suffix e.g., #purple.5 or #purple.$disabled)\n if (token[0] === '#' && token.length > 1) {\n // alpha form: #name.alpha or #name.$prop\n const alphaMatch = token.match(\n /^#([a-z0-9-]+)\\.(\\$[a-z_][a-z0-9-_]*|[0-9]+)$/i,\n );\n if (alphaMatch) {\n const [, base, rawAlpha] = alphaMatch;\n\n // Opacity applies to the color variable as a whole. The token may hold\n // anything a `<color>` can be — including a `color-mix()` or a\n // `light-dark()` with no channels to decompose, or a value written\n // straight into `--name-color` by hand-authored CSS that Tasty never\n // defined — and relative color syntax fades all of them.\n return {\n bucket: Bucket.Color,\n processed: fadeColor(`var(--${base}-color)`, rawAlpha),\n };\n }\n\n // hyphenated names like #dark-05 should keep full name\n\n const name = token.slice(1);\n // valid hex → treat as hex literal with fallback\n if (RE_HEX.test(name)) {\n return {\n bucket: Bucket.Color,\n processed: `var(--${name}-color, #${name})`,\n };\n }\n // simple color name token → css variable lookup with rgb fallback\n return { bucket: Bucket.Color, processed: `var(--${name}-color)` };\n }\n\n // 4 & 5. Functions\n const openIdx = token.indexOf('(');\n if (openIdx > 0 && token.endsWith(')')) {\n const fname = token.slice(0, openIdx);\n const inner = token.slice(openIdx + 1, -1); // without ()\n\n if (COLOR_FUNCS.has(fname)) {\n // Process inner to expand nested colors or units.\n const parsedInner = recurse(inner);\n const argProcessed = parsedInner.output.replace(/,\\s+/g, ','); // color funcs expect no spaces after commas\n const processed = `${canonicalFuncName(fname)}(${argProcessed})`;\n // `light-dark()` is not color-only — CSS lets it pick between values of\n // any type — so bucket it by what it actually holds. Otherwise\n // `padding: 'light-dark(1x, 2x)'` would land in the color slot and the\n // padding handler would emit its default instead.\n const bucket =\n fname === POLYMORPHIC_COLOR_FUNC && !hasColorArgs(parsedInner)\n ? Bucket.Value\n : Bucket.Color;\n\n return { bucket, processed };\n }\n\n // user function (provided via opts)\n if (opts.functions && fname in opts.functions) {\n // split by top-level commas within inner\n const tmp = new StyleParser(opts).process(inner); // fresh parser w/ same opts but no cache share issues\n const funcResult = opts.functions[fname](tmp.groups);\n // Re-classify the result to determine proper bucket (e.g., if it returns a color)\n // Pass functions: undefined to prevent infinite recursion if result matches a function pattern\n return classify(funcResult, { ...opts, functions: undefined }, recurse);\n }\n\n // generic: process inner and rebuild\n const argProcessed = recurse(inner).output;\n return {\n bucket: Bucket.Value,\n processed: `${canonicalFuncName(fname)}(${argProcessed})`,\n };\n }\n\n // 6. Color fallback syntax: (#name, fallback)\n if (token.startsWith('(') && token.endsWith(')')) {\n const inner = token.slice(1, -1);\n const colorMatch = inner.match(/^#([a-z0-9-]+)\\s*,\\s*(.*)$/i);\n if (colorMatch) {\n const [, name, fallback] = colorMatch;\n const processedFallback = recurse(fallback).output;\n return {\n bucket: Bucket.Color,\n processed: `var(--${name}-color, ${processedFallback})`,\n };\n }\n }\n\n // 7. Custom property with fallback syntax: ($prop, fallback)\n if (token.startsWith('(') && token.endsWith(')')) {\n const inner = token.slice(1, -1);\n const match = inner.match(/^\\$([a-z_][a-zA-Z0-9-_]*)\\s*,\\s*(.*)$/);\n if (match) {\n const [, name, fallback] = match;\n const processedFallback = recurse(fallback).output;\n const bucketType = name.endsWith('-color')\n ? Bucket.ColorValue\n : Bucket.Value;\n return {\n bucket: bucketType,\n processed: `var(--${name}, ${processedFallback})`,\n };\n }\n }\n\n // 8. Auto-calc group\n if (token[0] === '(' && token[token.length - 1] === ')') {\n const inner = token.slice(1, -1);\n const innerProcessed = recurse(inner).output;\n return { bucket: Bucket.Value, processed: `calc(${innerProcessed})` };\n }\n\n // 9. Unit number\n const um = token.match(RE_UNIT_NUM);\n if (um) {\n const unit = um[1];\n const numericPart = parseFloat(token.slice(0, -unit.length));\n const handler = opts.units && opts.units[unit];\n if (handler) {\n if (typeof handler === 'string') {\n // Check if this is a raw CSS unit (e.g., \"8px\", \"1rem\")\n const rawMatch = handler.match(RE_RAW_UNIT);\n if (rawMatch) {\n // Raw unit: calculate directly instead of using calc()\n const [, baseNum, cssUnit] = rawMatch;\n const result = numericPart * parseFloat(baseNum);\n const processed = `${result}${cssUnit}`;\n // Re-parse to resolve any nested units (e.g., units referencing other units)\n const resolved = resolveUntilStable(processed, opts, recurse);\n return { bucket: Bucket.Value, processed: resolved };\n }\n\n // Non-raw handler (e.g., \"var(--gap)\", \"calc(...)\"): use calc() wrapping\n const base = handler;\n if (numericPart === 1) {\n return { bucket: Bucket.Value, processed: base };\n }\n return {\n bucket: Bucket.Value,\n processed: `calc(${numericPart} * ${base})`,\n };\n } else {\n // Function units return complete CSS expressions, no wrapping needed\n const inner = handler(numericPart);\n return {\n bucket: Bucket.Value,\n processed: inner,\n };\n }\n }\n }\n\n // 9b. Unknown numeric+unit → treat as literal value (e.g., 1fr)\n if (/^[+-]?(?:\\d*\\.\\d+|\\d+)[a-z%]+$/.test(token)) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 9c. Plain unit-less numbers should be treated as value tokens (e.g.,\n // numeric arguments in custom style handlers).\n if (RE_NUMBER.test(token)) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 10. Literal value keywords\n if (VALUE_KEYWORDS.has(token)) {\n return { bucket: Bucket.Value, processed: token };\n }\n\n // 10b. Special keyword colors\n if (token === 'transparent' || token === 'currentcolor') {\n return { bucket: Bucket.Color, processed: token };\n }\n\n // 11. Fallback modifier\n return { bucket: Bucket.Mod, processed: token };\n}\n","interface LruNode<K, V> {\n key: K;\n prev: LruNode<K, V> | null;\n next: LruNode<K, V> | null;\n value: V;\n}\n\n/**\n * Doubly-linked-list LRU.\n *\n * The list holds direct node references rather than keys, so rewiring on a\n * `get()` of a non-MRU entry is pure pointer work. Storing keys instead cost\n * three extra `Map.get()` lookups per read (prev, next and the current head),\n * which is measurable on these read-mostly caches: they are hit on every\n * render once the style pipeline is warm.\n */\nexport class Lru<K, V> {\n private map = new Map<K, LruNode<K, V>>();\n private head: LruNode<K, V> | null = null;\n private tail: LruNode<K, V> | null = null;\n private onEvict?: (key: K, value: V) => void;\n\n constructor(\n private limit = 1000,\n onEvict?: (key: K, value: V) => void,\n ) {\n // Normalize limit; fall back to sensible default (1000) to keep caching enabled\n let normalized = Number.isFinite(this.limit)\n ? Math.floor(this.limit)\n : 1000;\n if (normalized <= 0) normalized = 1000;\n this.limit = normalized;\n this.onEvict = onEvict;\n }\n\n setOnEvict(fn?: (key: K, value: V) => void) {\n this.onEvict = fn;\n }\n\n get(key: K): V | undefined {\n const node = this.map.get(key);\n if (node === undefined) return undefined;\n // Fast path: already MRU, nothing to rewire.\n if (this.head !== node) this.moveToHead(node);\n return node.value;\n }\n\n set(key: K, value: V) {\n const existing = this.map.get(key);\n if (existing !== undefined) {\n existing.value = value;\n if (this.head !== existing) this.moveToHead(existing);\n return;\n }\n\n const node: LruNode<K, V> = { key, prev: null, next: this.head, value };\n if (this.head) this.head.prev = node;\n this.head = node;\n if (!this.tail) this.tail = node;\n this.map.set(key, node);\n if (this.map.size > this.limit) this.evict();\n }\n\n delete(key: K) {\n const node = this.map.get(key);\n if (node === undefined) return;\n this.detach(node);\n this.map.delete(key);\n }\n\n keys(): IterableIterator<K> {\n return this.map.keys();\n }\n\n private detach(node: LruNode<K, V>) {\n if (node.prev) node.prev.next = node.next;\n if (node.next) node.next.prev = node.prev;\n if (this.head === node) this.head = node.next;\n if (this.tail === node) this.tail = node.prev;\n node.prev = null;\n node.next = null;\n }\n\n private moveToHead(node: LruNode<K, V>) {\n this.detach(node);\n node.next = this.head;\n if (this.head) this.head.prev = node;\n this.head = node;\n if (!this.tail) this.tail = node;\n }\n\n private evict() {\n const node = this.tail;\n if (!node) return;\n this.detach(node);\n this.map.delete(node.key);\n\n if (this.onEvict) {\n try {\n this.onEvict(node.key, node.value);\n } catch {\n // ignore user callback errors\n }\n }\n }\n\n clear() {\n this.map.clear();\n this.head = this.tail = null;\n }\n}\n","type TokenCallback = (\n token: string,\n isComma: boolean,\n isSlash: boolean,\n) => void;\n\nconst isWhitespace = (ch: string | undefined): boolean =>\n ch === ' ' || ch === '\\n' || ch === '\\t' || ch === '\\r' || ch === '\\f';\n\nexport function scan(src: string, cb: TokenCallback) {\n let depth = 0;\n let inQuote: string | 0 = 0;\n let start = 0;\n let i = 0;\n // Track if we just saw a standalone slash separator (whitespace before, whitespace after)\n let pendingSlash = false;\n\n const flush = (isComma: boolean, isSlash: boolean) => {\n // If we have a pending slash, emit the part break\n const actualSlash = isSlash || pendingSlash;\n pendingSlash = false;\n\n if (start < i) {\n cb(src.slice(start, i), isComma, actualSlash);\n } else if (isComma) {\n cb('', true, false); // empty token followed by comma => group break.\n } else if (actualSlash) {\n cb('', false, true); // empty token followed by slash => part break.\n }\n start = i + 1;\n };\n\n for (; i < src.length; i++) {\n const ch = src[i];\n\n // quote mode\n if (inQuote) {\n if (ch === inQuote && src[i - 1] !== '\\\\') inQuote = 0;\n continue;\n }\n if (ch === '\"' || ch === \"'\") {\n inQuote = ch;\n continue;\n }\n\n // Parenthesis tracking keeps separators inside any function together.\n if (ch === '(') {\n depth++;\n continue;\n }\n if (ch === ')') {\n if (depth) depth--;\n continue;\n }\n\n if (!depth) {\n if (ch === ',') {\n flush(true, false);\n continue;\n }\n // Slash is only a separator when surrounded by whitespace (e.g., \"a / b\")\n // This preserves CSS patterns like \"center/cover\" as single tokens\n if (ch === '/') {\n const prevIsWhitespace = isWhitespace(src[i - 1]);\n const nextIsWhitespace = isWhitespace(src[i + 1]);\n if (prevIsWhitespace && nextIsWhitespace) {\n // Already flushed by whitespace before, mark pending slash\n pendingSlash = true;\n start = i + 1; // skip the slash character\n continue;\n }\n // Not surrounded by whitespace - treat as part of token\n continue;\n }\n if (isWhitespace(ch)) {\n flush(false, false);\n continue;\n }\n }\n }\n flush(false, false); // tail\n}\n","import { foldDslCase } from '../utils/string';\n\nimport { classify } from './classify';\nimport { Lru } from './lru';\nimport { scan } from './tokenizer';\nimport type {\n ParserOptions,\n ProcessedStyle,\n StyleDetails,\n StyleDetailsPart,\n} from './types';\nimport { Bucket, makeEmptyDetails, makeEmptyPart } from './types';\n\nexport class StyleParser {\n private cache: Lru<string, ProcessedStyle>;\n constructor(private opts: ParserOptions = {}) {\n this.cache = new Lru<string, ProcessedStyle>(this.opts.cacheSize ?? 1000);\n }\n\n /* ---------------- Public API ---------------- */\n process(src: string): ProcessedStyle {\n const key = String(src);\n const hit = this.cache.get(key);\n if (hit) return hit;\n\n // strip comments, then case-fold everything except custom-property names\n const stripped = foldDslCase(\n src.replace(/\\/\\*[^*]*\\*+(?:[^/*][^*]*\\*+)*\\//g, ''),\n );\n\n const groups: StyleDetails[] = [];\n let currentGroup = makeEmptyDetails();\n let currentPart = makeEmptyPart();\n let parts: StyleDetailsPart[] = [];\n\n const pushToken = (bucket: Bucket, processed: string) => {\n if (!processed) return;\n\n // If the previous token was a url(...) value, merge this token into it so that\n // background layer segments like \"url(img) no-repeat center/cover\" are kept\n // as a single value entry.\n const prevIsUrlValue =\n currentPart.values.length > 0 &&\n currentPart.values[currentPart.values.length - 1].startsWith('url(');\n\n if (prevIsUrlValue) {\n // Extend the existing url(...) value regardless of current bucket.\n currentPart.values[currentPart.values.length - 1] += ` ${processed}`;\n currentPart.all[currentPart.all.length - 1] += ` ${processed}`;\n return;\n }\n\n switch (bucket) {\n case Bucket.Color:\n currentPart.colors.push(processed);\n break;\n case Bucket.Value:\n currentPart.values.push(processed);\n break;\n case Bucket.Mod:\n currentPart.mods.push(processed);\n break;\n case Bucket.ColorValue:\n // Untyped reference: readable from either bucket, listed once in `all`.\n currentPart.colors.push(processed);\n currentPart.values.push(processed);\n break;\n }\n currentPart.all.push(processed);\n };\n\n const endPart = (reset = true) => {\n // Only add non-empty parts\n if (currentPart.all.length > 0) {\n currentPart.output = currentPart.all.join(' ');\n parts.push(currentPart);\n }\n if (reset) currentPart = makeEmptyPart();\n };\n\n const endGroup = (reset = true) => {\n endPart(reset); // finalize last part\n\n // Ensure at least one part exists (even if empty) for backward compat\n if (parts.length === 0) {\n parts.push(makeEmptyPart());\n }\n\n currentGroup.parts = parts;\n for (const part of parts) {\n currentGroup.mods.push(...part.mods);\n currentGroup.values.push(...part.values);\n currentGroup.colors.push(...part.colors);\n currentGroup.all.push(...part.all);\n }\n currentGroup.output =\n parts.length === 1\n ? parts[0].output\n : parts.map((part) => part.output).join(' / ');\n groups.push(currentGroup);\n\n if (reset) {\n currentGroup = makeEmptyDetails();\n parts = [];\n }\n };\n\n scan(stripped, (tok, isComma, isSlash) => {\n if (tok) {\n // Accumulate raw token into currentGroup.input\n if (currentGroup.input) {\n currentGroup.input += ` ${tok}`;\n } else {\n currentGroup.input = tok;\n }\n\n const { bucket, processed } = classify(tok, this.opts, (sub) =>\n this.process(sub),\n );\n pushToken(bucket, processed);\n }\n if (isSlash) endPart();\n if (isComma) endGroup();\n });\n\n // push final group if not already\n if (currentPart.all.length || parts.length || !groups.length)\n endGroup(false);\n\n const output =\n groups.length === 1\n ? groups[0].output\n : groups.map((group) => group.output).join(', ');\n const result: ProcessedStyle = { output, groups };\n Object.freeze(result);\n this.cache.set(key, result);\n return result;\n }\n\n setFunctions(functions: Required<ParserOptions>['functions']): void {\n this.opts.functions = functions;\n this.cache.clear();\n }\n\n setUnits(units: Required<ParserOptions>['units']): void {\n this.opts.units = units;\n this.cache.clear();\n }\n\n updateOptions(patch: Partial<ParserOptions>): void {\n Object.assign(this.opts, patch);\n if (patch.cacheSize)\n this.cache = new Lru<string, ProcessedStyle>(patch.cacheSize);\n else this.cache.clear();\n }\n\n /**\n * Clear the parser cache.\n * Call this when external state that affects parsing results has changed\n * (e.g., predefined tokens).\n */\n clearCache(): void {\n this.cache.clear();\n }\n\n /**\n * Get the current units configuration.\n */\n getUnits(): ParserOptions['units'] {\n return this.opts.units;\n }\n}\n","import { Lru } from '../parser/lru';\nimport { isDevEnv } from '../utils/is-dev-env';\nimport { warnOnceDev } from '../utils/warnings';\nimport type { StyleDetails } from '../parser/types';\n\nconst clamp = (value: number, min: number, max: number): number =>\n Math.max(Math.min(value, max), min);\n\n/**\n * Parse an angle value with optional unit.\n * Supports: deg, turn, rad, or unitless (treated as degrees).\n */\nconst parseAngle = (value: string): number => {\n const match = value.match(/^([+-]?\\d*\\.?\\d+)(deg|turn|rad)?$/);\n if (!match) return 0;\n\n const num = parseFloat(match[1]);\n const unit = match[2];\n\n switch (unit) {\n case 'turn':\n return num * 360;\n case 'rad':\n return (num * 180) / Math.PI;\n case 'deg':\n default:\n return num;\n }\n};\n\n/**\n * Parse a percentage value (e.g., \"50%\") to a 0-1 range. A unitless number is\n * read as the factor it already looks like, so `okhsl(280 .8 .52)` and\n * `okhsl(280 80% 52%)` are the same color.\n */\nconst parsePercentage = (value: string): number => {\n const match = value.match(/^([+-]?\\d*\\.?\\d+)%?$/);\n if (!match) return 0;\n\n const num = parseFloat(match[1]);\n return value.includes('%') ? num / 100 : num;\n};\n\n/**\n * Creates a color function handler for the tasty parser.\n *\n * A color function is a custom `functions` entry that converts its arguments\n * to an `rgb(...)` string (an already-supported color), so it needs no special\n * core integration — registering it as a parse function is enough.\n *\n * @param name The name of the color function (e.g., 'okhsl', 'okhst')\n * @param convert Converts the parsed first three channel values (after angle/\n * percent normalization) to sRGB `[r, g, b]` in the 0-1 range\n * @param label Optional diagnostic label shown in dev warnings when the wrong\n * number of arguments is supplied (e.g., 'H S L'). Has no effect on parsing\n * or output.\n */\nexport function createColorFunc(\n name: string,\n convert: (h: number, c2: number, c3: number) => [number, number, number],\n label?: string,\n): (groups: StyleDetails[]) => string {\n const conversionCache = new Lru<string, string>(500);\n const expected = label ? ` (${label})` : '';\n\n return (groups: StyleDetails[]): string => {\n if (groups.length === 0 || groups[0].all.length < 3) {\n if (isDevEnv()) {\n console.warn(\n `[Tasty] ${name}(): expected 3 values${expected}, got:`,\n groups,\n );\n }\n\n return 'rgb(0% 0% 0%)';\n }\n\n const group = groups[0];\n const tokens = group.all;\n\n const alpha =\n group.parts.length > 1 && group.parts[1].all.length > 0\n ? group.parts[1].output\n : undefined;\n\n const cacheKey =\n tokens.slice(0, 3).join(' ') + (alpha ? ` / ${alpha}` : '');\n const cached = conversionCache.get(cacheKey);\n if (cached) return cached;\n\n const h = parseAngle(tokens[0]);\n const c2 = parsePercentage(tokens[1]);\n const c3 = parsePercentage(tokens[2]);\n\n // A *unitless* channel above 1 cannot be a factor, so it is a missing `%`.\n // Clamping it quietly is the worst outcome: `okhsl(280 80 52)` renders as\n // white, which looks like a color rather than like a mistake.\n //\n // The raw token decides, not the parsed number: `150%` parses to `1.5`,\n // which is over-saturation that legitimately clamps, and warning about it\n // would also burn the dedup slot and silence a real `80` later. `1` itself\n // is a legitimate factor, so the comparison is strict.\n const misscaled = [tokens[1], tokens[2]].filter(\n (raw, i) => !raw.includes('%') && (i === 0 ? c2 : c3) > 1,\n );\n\n if (misscaled.length) {\n warnOnceDev(\n `${name}:percent-scale`,\n `${name}(): channels are factors (0-1) or percentages, so ` +\n `${misscaled.map((v) => `\"${v}\"`).join(' and ')} ` +\n `${misscaled.length > 1 ? 'clamp' : 'clamps'} to 1 — add the ` +\n `missing '%', or write the value as a 0-1 number.`,\n );\n }\n\n const [r, g, b] = convert(h, clamp(c2, 0, 1), clamp(c3, 0, 1));\n\n const format = (n: number): string => {\n const pct = n * 100;\n return parseFloat(pct.toFixed(1)).toString() + '%';\n };\n\n const result = alpha\n ? `rgb(${format(r)} ${format(g)} ${format(b)} / ${alpha})`\n : `rgb(${format(r)} ${format(g)} ${format(b)})`;\n\n conversionCache.set(cacheKey, result);\n return result;\n };\n}\n","/**\n * OKHSL Plugin for Tasty\n *\n * Converts OKHSL color syntax to RGB notation.\n * Supports angle units: deg, turn, rad, or unitless (degrees).\n *\n * Examples:\n * okhsl(240.5 50% 50%)\n * okhsl(240.5deg 50% 50%)\n * okhsl(0.25turn 50% 50%)\n * okhsl(1.57rad 50% 50%)\n */\n\nimport { okhslToSrgb } from '../utils/color-math';\n\nimport { createColorFunc } from './color-func';\n\nimport type { TastyPlugin, TastyPluginFactory } from './types';\n\n/**\n * The okhsl function handler for tasty parser.\n * Receives parsed style groups and returns an RGB color string.\n */\nconst okhslFunction = createColorFunc('okhsl', okhslToSrgb, 'H S L');\n\n/**\n * OKHSL Plugin for Tasty.\n *\n * Adds support for the `okhsl()` color function in tasty styles.\n *\n * @example\n * ```ts\n * import { configure } from '@tenphi/tasty';\n * import { okhslPlugin } from '@tenphi/tasty';\n *\n * configure({\n * plugins: [okhslPlugin()],\n * });\n *\n * // Now you can use okhsl in styles:\n * const Box = tasty({\n * styles: {\n * fill: 'okhsl(240 50% 50%)',\n * },\n * });\n * ```\n */\nexport const okhslPlugin: TastyPluginFactory = (): TastyPlugin => ({\n name: 'okhsl',\n functions: {\n okhsl: okhslFunction,\n },\n});\n\nexport { okhslFunction };\n","/**\n * OKHST Plugin for Tasty\n *\n * Converts OKHST color syntax to RGB notation.\n * OKHST is OKHSL with the lightness axis replaced by a contrast-uniform tone axis.\n * Supports angle units: deg, turn, rad, or unitless (degrees).\n *\n * Examples:\n * okhst(240.5 50% 50%)\n * okhst(240.5deg 50% 50%)\n * okhst(0.25turn 50% 50%)\n * okhst(1.57rad 50% 50%)\n */\n\nimport { okhstToSrgb } from '../utils/color-math';\n\nimport { createColorFunc } from './color-func';\n\nimport type { TastyPlugin, TastyPluginFactory } from './types';\n\n/**\n * The okhst function handler for tasty parser.\n * Receives parsed style groups and returns an RGB color string.\n */\nconst okhstFunction = createColorFunc('okhst', okhstToSrgb, 'H S T');\n\n/**\n * OKHST Plugin for Tasty.\n *\n * Adds support for the `okhst()` color function in tasty styles.\n *\n * @example\n * ```ts\n * import { configure } from '@tenphi/tasty';\n * import { okhstPlugin } from '@tenphi/tasty';\n *\n * configure({\n * plugins: [okhstPlugin()],\n * });\n *\n * // Now you can use okhst in styles:\n * const Box = tasty({\n * styles: {\n * fill: 'okhst(240 50% 50%)',\n * },\n * });\n * ```\n */\nexport const okhstPlugin: TastyPluginFactory = (): TastyPlugin => ({\n name: 'okhst',\n functions: {\n okhst: okhstFunction,\n },\n});\n\nexport { okhstFunction };\n","import { customFunction } from '../utils/styles';\n\nimport { okhslFunction } from './okhsl-plugin';\nimport { okhstFunction } from './okhst-plugin';\n\n/**\n * Register the default color functions (okhsl, okhst) with the global parser.\n *\n * They are ordinary `functions` entries — the same mechanism any third-party\n * color plugin uses — so they need no special-casing in core.\n *\n * Idempotent and safe to call from the lazy parser initializer so that\n * zero-config usage keeps working. `resetGlobalParseFunctions()` re-invokes it\n * after clearing user-registered functions so the defaults survive a config reset.\n *\n * @internal\n */\nexport function registerDefaultFunctions(): void {\n customFunction('okhsl', okhslFunction);\n customFunction('okhst', okhstFunction);\n}\n","import { StyleParser } from '../parser/parser';\nimport { registerDefaultFunctions } from '../plugins/defaults';\n\nimport type { ProcessedStyle, StyleDetails } from '../parser/types';\n\nimport { getNamedColorHex } from './color-math';\nimport { parseAlphaOverride } from './color-space';\n\nexport {\n getNamedColorHex,\n getRgbValuesFromRgbaString,\n hexToRgb,\n strToRgb,\n} from './color-math';\n\nexport type StyleValue<T = string> = T | boolean | number | null | undefined;\n\n/**\n * Normalize a color token value.\n * - Boolean `true` is converted to `'transparent'`\n * - Boolean `false` returns `null` (signals the token should be skipped)\n * - Other values are returned as-is\n *\n * @param value - The raw token value\n * @returns Normalized value or null if the token should be skipped\n */\nexport function normalizeColorTokenValue<T>(\n value: T | boolean,\n): T | 'transparent' | null {\n if (value === true) {\n return 'transparent';\n }\n if (value === false) {\n return null;\n }\n return value as T;\n}\n\nexport type StyleValueStateMap<T = string> = Record<\n string,\n StyleValue<T> | '@inherit'\n>;\n\n/**\n * Combined type for style values that can be either a direct value or a state map.\n * Use this for component props that accept style values.\n */\nexport type StylePropValue<T = string> = StyleValue<T> | StyleValueStateMap<T>;\n\n/**\n * One dependency value as a style handler receives it: already resolved for a\n * single state, but still the **raw authored DSL string** (`'2x'`, `'#purple.5'`).\n * Handlers parse it themselves via {@link parseStyle} / {@link parseColor}.\n */\nexport type ResolvedStyleValue = StyleValue<string>;\n\n/**\n * The dependency map a handler receives — one resolved value per style name in\n * its `__lookupStyles`.\n */\nexport type StyleHandlerProps<TDeps extends string = string> = Partial<\n Record<TDeps, ResolvedStyleValue>\n>;\n\n/**\n * One set of CSS declarations returned by a style handler.\n *\n * Keys are **kebab-case** CSS property names (`'background-color'`, not\n * `backgroundColor`) or `--custom-property` names. Values are stringified, so\n * numbers are accepted. `$` is reserved as a selector suffix.\n */\nexport type CSSMap = {\n /** Selector suffix (or suffixes) these declarations apply to, e.g. `'& > *'`. */\n $?: string | string[];\n} & Record<string, string | number | (string | number)[] | undefined>;\n\nexport type StyleHandlerResult = CSSMap | CSSMap[] | null | void;\n\nexport type RawStyleHandler<TProps extends object = StyleHandlerProps> = (\n props: TProps,\n) => StyleHandlerResult;\n\nexport type StyleHandler<TProps extends object = StyleHandlerProps> =\n RawStyleHandler<TProps> & {\n __lookupStyles: string[];\n };\n\n/**\n * The handler type used by the registry (`STYLE_HANDLER_MAP`), with parameter\n * variance erased.\n *\n * Handlers declare narrow, hand-written dependency types — `({ fill }: { fill?:\n * string }) => …` — which under `strictFunctionTypes` are not assignable to a\n * wider parameter type. The registry stores handlers of many different dependency\n * shapes together, so it needs the erased form. Prefer {@link StyleHandler} (or\n * {@link defineHandler}) when writing a handler; this type is for code that\n * inspects the registry.\n */\nexport type AnyStyleHandler = ((\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n props: any,\n) => StyleHandlerResult) & {\n __lookupStyles: string[];\n};\n\n/**\n * Handler definition forms for configure() and plugins.\n * - Function only: lookup styles inferred from key name\n * - Single property tuple: ['styleName', handler]\n * - Multi-property tuple: [['style1', 'style2'], handler]\n *\n * Use {@link defineHandler} to have the dependency names inferred into the\n * handler's parameter type instead of annotating it by hand.\n */\nexport type StyleHandlerDefinition<TDeps extends string = string> =\n | RawStyleHandler<StyleHandlerProps<TDeps>>\n | [TDeps, RawStyleHandler<StyleHandlerProps<TDeps>>]\n | [readonly TDeps[], RawStyleHandler<StyleHandlerProps<TDeps>>];\n\nexport interface ParsedColor {\n color?: string;\n name?: string;\n opacity?: number;\n}\n\nexport type StyleMap = Record<string, StyleValue | StyleValueStateMap>;\n\nconst devMode = process.env.NODE_ENV !== 'production';\n\n// Precompiled regex patterns for parseColor optimization\n// Match var(--name-color...) and extract the name, regardless of fallbacks.\n// Anchored: a reference inside a color function is an *argument* of that color,\n// not the color's own name — `color-mix(in oklab, var(--purple-color) 50%, …)`\n// is not named `purple`.\nconst COLOR_VAR_PATTERN = /^var\\(--([a-z0-9-]+)-color[,)]/;\nconst RGB_ALPHA_PATTERN = /\\/\\s*([0-9.]+)\\)/;\nconst RE_HEX_COLOR = /^#[0-9a-fA-F]{3,8}$/;\nconst RE_VAR_COLOR = /^var\\(--[a-z0-9-]+-color/;\n\nfunction isSimpleColorFast(val: string): boolean {\n const c0 = val.charCodeAt(0);\n\n // Cheap first-character dispatch for the shapes that have one. A miss must\n // fall through rather than answer `false`: the CSS named colors start with\n // every letter these cases claim — `red`, `hotpink`, `lime`, `orange`,\n // `violet`, `coral`, `teal` — and each one is a color too.\n switch (c0) {\n case 35: // '#'\n return RE_HEX_COLOR.test(val);\n case 114: // 'r'\n if (val.charCodeAt(1) === 103 && val.charCodeAt(2) === 98) return true; // 'rgb'\n break;\n case 104: // 'h'\n if (val.charCodeAt(1) === 115 && val.charCodeAt(2) === 108) return true; // 'hsl'\n break;\n case 108: // 'l'\n if (val.charCodeAt(1) === 99 && val.charCodeAt(2) === 104) return true; // 'lch'\n break;\n case 111: // 'o'\n if (val.startsWith('oklch(')) return true;\n break;\n case 118: // 'v'\n if (RE_VAR_COLOR.test(val)) return true;\n break;\n case 99: // 'c'\n if (val === 'currentColor' || val === 'currentcolor') return true;\n break;\n case 116: // 't'\n if (val === 'transparent') return true;\n break;\n }\n\n return getNamedColorHex().has(val.toLowerCase());\n}\n\n// Rate limiting for dev warnings to avoid spam\nlet colorWarningCount = 0;\nconst MAX_COLOR_WARNINGS = 10;\n\nexport const CUSTOM_UNITS = {\n r: '6px',\n cr: '10px',\n bw: '1px',\n ow: '3px',\n x: '8px',\n sf: function sf(num: number) {\n return `minmax(0, ${num}fr)`;\n },\n};\n\nexport const DIRECTIONS = ['top', 'right', 'bottom', 'left'];\n\n// Lazy-initialized to break the circular dependency:\n// parser.ts → classify.ts → utils/styles.ts → parser.ts\nlet __tastyParser: StyleParser | null = null;\n\nfunction getOrCreateParser(): StyleParser {\n if (!__tastyParser) {\n __tastyParser = new StyleParser({ units: CUSTOM_UNITS });\n __tastyParser.setFunctions(__tastyParseFunctions);\n // Register built-in color functions (okhsl/okhst) as ordinary parse\n // functions. Done lazily here so zero-config usage works regardless of\n // module initialization order or tree-shaking.\n registerDefaultFunctions();\n }\n return __tastyParser;\n}\n\n// Registry for user-provided custom functions that the parser can call.\n// It is updated through the `customFunc` helper exported below and through\n// `configure()`. Built-in color functions (okhsl/okhst) are registered lazily\n// by `registerDefaultFunctions()` rather than seeded here, so they go through\n// the exact same path as any third-party plugin.\nconst __tastyParseFunctions: Record<\n string,\n (groups: StyleDetails[]) => string\n> = {};\n\n/**\n * Register a parse-time function.\n *\n * @internal Use `configure({ functions })`. This bypasses the configuration lock\n * and is kept only for the lazy default-function bootstrap and the `@function`\n * polyfill, both of which must register after `configure()` has run.\n */\nexport function customFunction(\n name: string,\n fn: (groups: StyleDetails[]) => string,\n) {\n __tastyParseFunctions[name] = fn;\n getOrCreateParser().setFunctions(__tastyParseFunctions);\n}\n\n/**\n * Reset parse functions back to the built-in set (okhsl/okhst).\n *\n * @internal Called by `resetConfig()`.\n */\nexport function resetGlobalParseFunctions(): void {\n for (const key of Object.keys(__tastyParseFunctions)) {\n delete __tastyParseFunctions[key];\n }\n // Re-register the default color functions so they survive a config reset.\n registerDefaultFunctions();\n getOrCreateParser().setFunctions(__tastyParseFunctions);\n}\n\n/**\n * Get the global StyleParser instance.\n * Used by configure() to apply parser configuration.\n */\nexport function getGlobalParser(): StyleParser {\n return getOrCreateParser();\n}\n\n/**\n * Get the current custom functions registry.\n * Used by configure() to merge with new functions.\n */\n/**\n * The live parse-function registry.\n *\n * @internal Returns the mutable internal map; writing to it bypasses the\n * parser's cache invalidation, so the write silently does not take effect.\n * Read-only, internal use.\n */\nexport function getGlobalParseFunctions(): Record<\n string,\n (groups: StyleDetails[]) => string\n> {\n return __tastyParseFunctions;\n}\n\n// ============================================================================\n// Global Predefined Tokens\n// ============================================================================\n\n/**\n * Storage for predefined tokens that are replaced during style parsing.\n * Keys are token names (with $ or # prefix), values are pre-processed CSS values.\n */\nlet __globalPredefinedTokens: Record<string, string> | null = null;\n\n/**\n * Set global predefined tokens.\n * Called from configure() after processing token values.\n * Merges with existing tokens (new tokens override existing ones with same key).\n * Keys are normalized to lowercase (parser lowercases input before classification).\n * @internal\n */\nexport function setGlobalPredefinedTokens(\n tokens: Record<string, string>,\n): void {\n // Normalize keys to lowercase for case-insensitive matching\n const normalizedTokens: Record<string, string> = {};\n for (const [key, value] of Object.entries(tokens)) {\n const lowerKey = key.toLowerCase();\n const lowerValue = value.toLowerCase();\n\n // Warn if trying to use bare #current to define other color tokens\n // #current represents currentcolor which cannot be used as a base for recursive token resolution\n // Note: #current.5 (with opacity) is allowed since it resolves to a concrete color-mix value\n if (lowerKey.startsWith('#') && lowerValue === '#current') {\n if (process.env.NODE_ENV !== 'production') {\n console.warn(\n `[Tasty] Using #current to define color token \"${key}\" is not supported. ` +\n `The #current token represents currentcolor which cannot be used as a base for other tokens.`,\n );\n }\n continue; // Skip this token\n }\n\n normalizedTokens[lowerKey] = value;\n }\n // Merge with existing tokens (consistent with how states, units, and parse functions are handled)\n __globalPredefinedTokens = __globalPredefinedTokens\n ? { ...__globalPredefinedTokens, ...normalizedTokens }\n : normalizedTokens;\n // Clear parser cache since token values affect parsing\n getOrCreateParser().clearCache();\n}\n\n/**\n * Get the current global predefined tokens.\n * Returns null if no tokens are configured.\n */\nexport function getGlobalPredefinedTokens(): Record<string, string> | null {\n return __globalPredefinedTokens;\n}\n\n/**\n * Reset global predefined tokens.\n * Used for testing.\n * @internal\n */\nexport function resetGlobalPredefinedTokens(): void {\n __globalPredefinedTokens = null;\n // Clear parser cache since token availability affects parsing\n getOrCreateParser().clearCache();\n}\n\n/**\n *\n * @param {String} value\n * @param {Number} mode\n * @returns {Object<String,String|Array>}\n */\nexport function parseStyle(value: StyleValue): ProcessedStyle {\n let str: string;\n\n if (typeof value === 'string') {\n str = value;\n } else if (typeof value === 'number') {\n str = String(value);\n } else {\n // boolean, null, undefined, objects etc. → empty string\n str = '';\n }\n\n return getOrCreateParser().process(str);\n}\n\n/** A `$`-prefixed custom-property reference — the only DSL syntax that starts with `$`. */\nconst RE_CUSTOM_PROPERTY_REF = /\\$[a-zA-Z_$]/;\n\n/**\n * Substitute custom-property references (`$ident` → `var(--ident)`) inside a\n * value a handler would otherwise emit to CSS verbatim.\n *\n * Handlers for keyword-valued properties (`display`, `align`, `text-transform`,\n * `overflow`, …) pass their input straight through, since there are no units or\n * color tokens to resolve. That leaked the raw DSL into the stylesheet:\n * `display: '$my-display'` emitted `display: $my-display`, which the browser\n * drops as invalid. The same applies to color props whose value the parser could\n * not classify as a color — `$ident` is a color only when the name ends with\n * `-color`, so `fill: '$my-fill'` fell back to the unparsed input.\n *\n * Values without a `$` skip the parser entirely, so pass-through behaviour (and\n * the parser's case folding) is unchanged for every value that was already\n * valid CSS.\n */\nexport function resolveCustomProperties(value: string): string {\n if (!RE_CUSTOM_PROPERTY_REF.test(value)) return value;\n\n return parseStyle(value).output || value;\n}\n\n/**\n * Parse color. Find it value, name and opacity.\n * Optimized to avoid heavy parseStyle calls for simple color patterns.\n */\nexport function parseColor(val: string, ignoreError = false): ParsedColor {\n // Early return for non-strings or empty values\n if (typeof val !== 'string') {\n val = String(val ?? '');\n }\n\n val = val.trim();\n if (!val) return {};\n\n // Fast path: Check if it's a simple color pattern that doesn't need full parsing\n const isSimpleColor = isSimpleColorFast(val);\n\n let firstColor: string;\n if (isSimpleColor) {\n // For simple colors, use the value directly without parsing\n firstColor = val;\n } else {\n const processed = parseStyle(val);\n const extractedColor = processed.groups.find((g) => g.colors.length)\n ?.colors[0];\n\n if (!extractedColor) {\n // Rate-limited warning to avoid spam\n if (!ignoreError && devMode && colorWarningCount < MAX_COLOR_WARNINGS) {\n console.warn('[Tasty] unable to parse color:', val);\n colorWarningCount++;\n if (colorWarningCount === MAX_COLOR_WARNINGS) {\n console.warn(\n '[Tasty] color parsing warnings will be suppressed from now on',\n );\n }\n }\n return {};\n }\n\n firstColor = extractedColor;\n }\n\n // `#name.alpha` fades the color with relative color syntax, so the name and the\n // opacity are read off the parts rather than the whole.\n const faded = parseAlphaOverride(firstColor);\n const baseColor = faded ? faded.color : firstColor;\n\n // Extract color name (if present) from variable pattern using precompiled regex\n const nameMatch = baseColor.match(COLOR_VAR_PATTERN);\n\n let opacity: number | undefined;\n if (faded) {\n // A `var()` alpha has no number to report.\n const { alpha } = faded;\n const v = parseFloat(alpha);\n if (!isNaN(v)) opacity = alpha.endsWith('%') ? v : v * 100;\n } else if (\n baseColor.startsWith('rgb') ||\n baseColor.startsWith('hsl') ||\n baseColor.startsWith('lch') ||\n baseColor.startsWith('oklch')\n ) {\n const alphaMatch = baseColor.match(RGB_ALPHA_PATTERN);\n if (alphaMatch) {\n const v = parseFloat(alphaMatch[1]);\n if (!isNaN(v)) opacity = v * 100;\n }\n }\n\n return {\n color: firstColor,\n name: nameMatch ? nameMatch[1] : undefined,\n opacity,\n };\n}\n\nexport function filterMods(\n mods: string[],\n allowedMods: readonly string[],\n): string[] {\n const filtered: string[] = [];\n\n for (const mod of mods) {\n if (allowedMods.includes(mod)) filtered.push(mod);\n }\n\n return filtered;\n}\n\n// ============================================================================\n// Style Stringification\n// ============================================================================\n\nconst _innerCache = new WeakMap();\nconst _topLevelCache = new WeakMap<object, string>();\n\nexport function stringifyStyles(styles: unknown): string {\n if (styles == null || typeof styles !== 'object') return '';\n\n const cached = _topLevelCache.get(styles as object);\n if (cached !== undefined) return cached;\n\n const obj = styles as Record<string, unknown>;\n const keys = Object.keys(obj).sort();\n const parts: string[] = [];\n for (const k of keys) {\n const v = obj[k];\n if (v === undefined || typeof v === 'function' || typeof v === 'symbol')\n continue;\n\n const c0 = k.charCodeAt(0);\n const needsInnerSort =\n ((c0 >= 65 && c0 <= 90) || c0 === 38) &&\n v &&\n typeof v === 'object' &&\n !Array.isArray(v);\n\n let sv: string;\n if (needsInnerSort) {\n sv = _innerCache.get(v);\n if (sv === undefined) {\n const innerObj = v as Record<string, unknown>;\n const innerKeys = Object.keys(innerObj).sort();\n const innerParts: string[] = [];\n for (const ik of innerKeys) {\n const ivs = JSON.stringify(innerObj[ik]);\n if (ivs !== undefined)\n innerParts.push(JSON.stringify(ik) + ':' + ivs);\n }\n sv = '{' + innerParts.join(',') + '}';\n _innerCache.set(v, sv);\n }\n } else {\n sv = JSON.stringify(v);\n }\n parts.push(JSON.stringify(k) + ':' + sv);\n }\n const result = '{' + parts.join(',') + '}';\n _topLevelCache.set(styles as object, result);\n return result;\n}\n","import { getGlobalParseFunctions, getGlobalParser } from './styles';\n\nconst RE_FUNC_NAME = /^([a-z][a-z0-9-]*)\\s*\\(/i;\nconst RE_COLOR_OUT =\n /^(?:rgb|hsl|hwb|lab|lch|oklab|oklch|color)\\(|^#|^var\\(--/i;\n\n/**\n * Resolve a `name(...)` value produced by a registered custom parse function\n * into its concrete color output.\n *\n * A color function is just a `functions` entry whose output is an already\n * supported color (`rgb`, `hsl`, `#…`, `oklch`, …). This helper delegates the\n * value to the global parser (which already runs the registered parse function)\n * and returns the result only when it looks like a color. Returns `null` when\n * `str` is not a registered custom function or its output is not a color.\n *\n * This is the generic replacement for the previously hardcoded okhsl/okhst\n * conversion branches scattered across `strToRgb`, `resolveToRgbaValues`, and\n * the `#token.alpha` injection path.\n */\nexport function resolveFunctionColor(str: string): string | null {\n const m = RE_FUNC_NAME.exec(str);\n if (!m) return null;\n\n const name = m[1].toLowerCase();\n // Ensure the global parser (and therefore the default color functions) is\n // initialized before consulting the function registry.\n getGlobalParser();\n const functions = getGlobalParseFunctions();\n if (!(name in functions)) return null;\n\n const out = getGlobalParser().process(str).output;\n if (!out || !RE_COLOR_OUT.test(out)) return null;\n\n return out;\n}\n","import { overrideColorAlpha } from './color-space';\n\nexport function color(name: string, opacity = 1) {\n if (opacity !== 1) {\n // The alpha slot takes a `<number>`, so the value goes in as authored —\n // no percentage conversion to introduce a float artifact.\n return overrideColorAlpha(`var(--${name}-color)`, String(opacity));\n }\n\n return `var(--${name}-color)`;\n}\n"],"mappings":";;AAAA,MAAa,iBAAiB,IAAI,IAAI;CACpC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;AAED,MAAa,oBAAoB,IAAI,IAAI;CACvC;CACA;CACA;CACA;CACA;AACF,CAAC;AAOD,MAAM,2BAA2B;CAC/B;CACA;CACA;CACA;AACF;AAEA,MAAa,sBAAsB,IAAI,IAAI,wBAAwB;AAOnE,MAAa,cAAc,IAAI,IAAI;CACjC;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA,GAAG;AACL,CAAC;AAUD,MAAa,eAAe;AAE5B,MAAa,cAAc;AAC3B,MAAa,YAAY;AACzB,MAAa,SAAS;AAEtB,MAAa,cAAc;AAE3B,MAAM,sBAAsB,IAAI,IAAI;CAClC,CAAC,cAAc,YAAY;CAC3B,CAAC,cAAc,YAAY;CAC3B,CAAC,cAAc,YAAY;CAC3B,CAAC,UAAU,QAAQ;CACnB,CAAC,UAAU,QAAQ;CACnB,CAAC,UAAU,QAAQ;CACnB,CAAC,WAAW,SAAS;CACrB,CAAC,WAAW,SAAS;CACrB,CAAC,WAAW,SAAS;CACrB,CAAC,SAAS,OAAO;CACjB,CAAC,SAAS,OAAO;AACnB,CAAC;AAED,SAAgB,kBAAkB,SAAyB;CACzD,OAAO,oBAAoB,IAAI,OAAO,KAAK;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AAK;AACvB"}
@@ -0,0 +1,41 @@
1
+ //#region src/injector/global-state.ts
2
+ const GLOBAL_INJECTOR_KEY = "__TASTY_GLOBAL_INJECTOR__";
3
+ function getStorage() {
4
+ return typeof window !== "undefined" ? window : globalThis;
5
+ }
6
+ function registerHydratedClasses(injector, classes) {
7
+ if (typeof document === "undefined") return;
8
+ const registry = injector._sheetManager.getRegistry(document);
9
+ for (const className of classes) {
10
+ if (registry.rules.has(className)) continue;
11
+ registry.rules.set(className, {
12
+ className,
13
+ ruleIndex: -2,
14
+ sheetIndex: -2
15
+ });
16
+ registry.pinCounts.set(className, 0);
17
+ }
18
+ }
19
+ function hydrateStoredGlobalInjector(classes) {
20
+ const storage = getStorage();
21
+ const injector = storage[GLOBAL_INJECTOR_KEY];
22
+ if (injector) {
23
+ registerHydratedClasses(injector, classes);
24
+ return;
25
+ }
26
+ if (storage.__TASTY__ === classes) return;
27
+ if (storage.__TASTY__) storage.__TASTY__.push(...classes);
28
+ else storage.__TASTY__ = [...classes];
29
+ }
30
+ //#endregion
31
+ //#region src/ssr/hydrate.ts
32
+ function hydrateTastyClasses(classes) {
33
+ if (typeof document === "undefined") return;
34
+ if (!classes) classes = typeof window !== "undefined" ? window.__TASTY__ : void 0;
35
+ if (!classes?.length) return;
36
+ hydrateStoredGlobalInjector(classes);
37
+ }
38
+ //#endregion
39
+ export { hydrateTastyClasses as t };
40
+
41
+ //# sourceMappingURL=hydration-TRcz5vnk.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"hydration-TRcz5vnk.js","names":[],"sources":["../../src/injector/global-state.ts","../../src/ssr/hydrate.ts"],"sourcesContent":["import type { StyleInjector } from './injector';\nimport { HYDRATED_RULE_INDEX } from './types';\n\nconst GLOBAL_INJECTOR_KEY = '__TASTY_GLOBAL_INJECTOR__';\n\ninterface TastyGlobalStorage {\n [GLOBAL_INJECTOR_KEY]?: StyleInjector;\n __TASTY__?: string[];\n}\n\nfunction getStorage(): TastyGlobalStorage {\n return (\n typeof window !== 'undefined' ? window : globalThis\n ) as TastyGlobalStorage;\n}\n\nfunction registerHydratedClasses(\n injector: StyleInjector,\n classes: string[],\n): void {\n if (typeof document === 'undefined') return;\n\n const registry = injector._sheetManager.getRegistry(document);\n for (const className of classes) {\n if (registry.rules.has(className)) continue;\n\n registry.rules.set(className, {\n className,\n ruleIndex: HYDRATED_RULE_INDEX,\n sheetIndex: HYDRATED_RULE_INDEX,\n });\n registry.pinCounts.set(className, 0);\n }\n}\n\n/** Register now when the runtime exists, otherwise defer until it initializes. */\nexport function hydrateStoredGlobalInjector(classes: string[]): void {\n const storage = getStorage();\n const injector = storage[GLOBAL_INJECTOR_KEY];\n\n if (injector) {\n registerHydratedClasses(injector, classes);\n return;\n }\n\n // `window.__TASTY__` is also what the runtime injector reads lazily. Keep an\n // explicit list there until configuration creates the global injector.\n if (storage.__TASTY__ === classes) return;\n if (storage.__TASTY__) {\n storage.__TASTY__.push(...classes);\n } else {\n storage.__TASTY__ = [...classes];\n }\n}\n","/**\n * Client-side cache hydration for SSR/RSC.\n *\n * Registers class names rendered on the server with the client injector. If\n * the runtime is not initialized yet, registration is deferred until its first\n * use. With hash-based naming, only the class name list needs to cross the\n * wire — no cache keys or counters.\n */\n\nimport { hydrateStoredGlobalInjector } from '../injector/global-state';\n\n/**\n * Hydrate the client-side style registry from the server's class name list.\n *\n * Call this before ReactDOM.hydrateRoot() or ensure it runs before\n * any tasty() component renders on the client.\n *\n * When called without arguments, reads the class list from `window.__TASTY__`\n * (populated by inline scripts emitted during SSR/RSC streaming).\n */\nexport function hydrateTastyClasses(classes?: string[]): void {\n if (typeof document === 'undefined') return;\n\n if (!classes) {\n classes = typeof window !== 'undefined' ? window.__TASTY__ : undefined;\n }\n\n if (!classes?.length) return;\n\n hydrateStoredGlobalInjector(classes);\n}\n"],"mappings":";AAGA,MAAM,sBAAsB;AAO5B,SAAS,aAAiC;CACxC,OACE,OAAO,WAAW,cAAc,SAAS;AAE7C;AAEA,SAAS,wBACP,UACA,SACM;CACN,IAAI,OAAO,aAAa,aAAa;CAErC,MAAM,WAAW,SAAS,cAAc,YAAY,QAAQ;CAC5D,KAAK,MAAM,aAAa,SAAS;EAC/B,IAAI,SAAS,MAAM,IAAI,SAAS,GAAG;EAEnC,SAAS,MAAM,IAAI,WAAW;GAC5B;GACA,WAAA;GACA,YAAA;EACF,CAAC;EACD,SAAS,UAAU,IAAI,WAAW,CAAC;CACrC;AACF;AAGA,SAAgB,4BAA4B,SAAyB;CACnE,MAAM,UAAU,WAAW;CAC3B,MAAM,WAAW,QAAQ;CAEzB,IAAI,UAAU;EACZ,wBAAwB,UAAU,OAAO;EACzC;CACF;CAIA,IAAI,QAAQ,cAAc,SAAS;CACnC,IAAI,QAAQ,WACV,QAAQ,UAAU,KAAK,GAAG,OAAO;MAEjC,QAAQ,YAAY,CAAC,GAAG,OAAO;AAEnC;;;ACjCA,SAAgB,oBAAoB,SAA0B;CAC5D,IAAI,OAAO,aAAa,aAAa;CAErC,IAAI,CAAC,SACH,UAAU,OAAO,WAAW,cAAc,OAAO,YAAY,KAAA;CAG/D,IAAI,CAAC,SAAS,QAAQ;CAEtB,4BAA4B,OAAO;AACrC"}