@theme-registry/refract-css 0.1.8 → 0.1.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs.js","sources":["../src/lowering.ts","../src/render.ts","../src/index.ts"],"sourcesContent":["/**\n * CSS lowering of the format-neutral Model → `CssNode[]`.\n *\n * Variable-node lowering (naming + value formatting + responsive expansion) and recipe-rule\n * lowering (a **forward** lowering — the Model rule-sets go straight to `CssRuleNode[]`, no\n * `generateRecipeCss` round-trip) both live here. Refs carry canonical token paths; a\n * `pathToVar` map turns each into its `var(--…)`. Byte-parity with the former token-based path\n * is the golden gate.\n */\nimport type {\n ContainerModel,\n Keyframe,\n MergedRuleSet,\n PropertyModel,\n PropertyResponsiveOverride,\n Ref,\n RuleSet,\n RuleSetGroup,\n RuleSetOverride,\n ShadowLayer,\n TransitionPart,\n} from \"@theme-registry/refract\";\nimport type { ShadowDimension } from \"@theme-registry/refract\";\nimport type { ContainerDescriptors, MediaDescriptor, MediaVariant } from \"@theme-registry/refract\";\nimport type { CssDeclaration, CssKeyframesNode, CssRuleNode, CssVariablesNode } from \"./nodes\";\nimport type { VarNamer } from \"./naming\";\n\nconst str = (value: unknown): string => (value == null ? \"\" : String(value));\n\n/**\n * A resolved length leaf → CSS text (§21). Units are baked into the Model by `resolveModelUnits`, so a\n * text adapter only concatenates: `unit` present → `<value><unit>`; absent → the bare value (unit-less\n * numbers like opacity, or a raw-string escape / keyword). Struct (shadow/transition) is composed by\n * its subsystem before this is reached.\n */\nconst dimensionCss = (ref: Ref): string =>\n ref.unit !== undefined ? `${ref.value}${ref.unit}` : str(ref.value);\n\n/** A shadow geometry field ({@link ShadowDimension}) → CSS text — pinned `{value,unit}` or a bare number. */\nconst shadowDimCss = (dim: ShadowDimension): string =>\n typeof dim === \"number\" ? String(dim) : `${dim.value}${dim.unit}`;\n\nconst DEFAULT_RESPONSIVE_QUERY: MediaVariant = \"exact\";\n\n// ---------------------------------------------------------------------------\n// Shared responsive expansion (property variables)\n// ---------------------------------------------------------------------------\n\ntype ResolveVariableName = (property: string, variant?: string, field?: string) => string;\n\nconst resolveMediaQuery = <TBreakpoint extends string>(\n media: MediaDescriptor<TBreakpoint>,\n breakpoint: TBreakpoint,\n query: MediaVariant,\n orientation?: \"portrait\" | \"landscape\",\n): string => {\n if (!orientation) {\n const group = media[breakpoint];\n return group?.[query] ?? \"\";\n }\n const opts = { orientation };\n if (query === \"min\") return media.min(breakpoint, opts);\n if (query === \"max\") return media.max(breakpoint, opts);\n return media.exact(breakpoint, opts);\n};\n\n/** dec.9 — combine two `@media …` conditions into one (`@media <a> and <b>`), e.g. a breakpoint\n * query AND a mode's OS-preference query. */\nconst combineMedia = (a: string, b: string): string => {\n const cond = (s: string) => s.replace(/^@media\\s*/, \"\");\n return `@media ${cond(a)} and ${cond(b)}`;\n};\n\nconst expandResponsiveVariableNodes = <TBreakpoint extends string>(\n properties: Record<string, PropertyModel>,\n media: MediaDescriptor<TBreakpoint>,\n resolveName: ResolveVariableName,\n formatValue: (ref: Ref) => string,\n): CssVariablesNode[] => {\n // Grouped by `<media>||<selector>` so a mode-gated override lands in its own block. A plain\n // (no-mode) override keeps selector `:root`, so its key/order is unchanged → goldens byte-identical.\n const byBlock = new Map<string, { media: string; selector: string; variables: Record<string, string> }>();\n const add = (mediaQuery: string, selector: string, updates: Record<string, string>): void => {\n const key = `${mediaQuery}||${selector}`;\n const existing = byBlock.get(key);\n if (existing) Object.assign(existing.variables, updates);\n else byBlock.set(key, { media: mediaQuery, selector, variables: { ...updates } });\n };\n\n for (const [propertyName, model] of Object.entries(properties)) {\n for (const entry of model.responsive ?? []) {\n const mediaQuery = resolveMediaQuery(\n media,\n entry.breakpoint as TBreakpoint,\n (entry.query ?? DEFAULT_RESPONSIVE_QUERY) as MediaVariant,\n entry.orientation,\n );\n if (!mediaQuery) continue;\n\n const updates = computeEntryUpdates(propertyName, entry, resolveName, formatValue);\n if (!Object.keys(updates).length) continue;\n\n const mode = entry.mode;\n if (!mode) {\n add(mediaQuery, \":root\", updates);\n } else {\n // dec.9 — the override applies only under `mode`: a `[data-theme]` block (manual toggle) always,\n // plus an OS-preference combined block for first-class modes (dark/light) — mirrors mode emit.\n add(mediaQuery, `:root[data-theme=\"${mode}\"]`, updates);\n const osMedia = MODE_MEDIA[mode];\n if (osMedia) add(combineMedia(mediaQuery, osMedia), \":root\", updates);\n }\n }\n }\n\n return Array.from(byBlock.values(), ({ media: m, selector, variables }): CssVariablesNode => ({\n kind: \"variables\",\n selector,\n media: m,\n variables,\n }));\n};\n\nconst computeEntryUpdates = (\n propertyName: string,\n entry: PropertyResponsiveOverride,\n resolveName: ResolveVariableName,\n formatValue: (ref: Ref) => string,\n): Record<string, string> => {\n // dec.5 — `ref` (READ source) swaps the destination var to that variant's var; `target` is the\n // WRITE destination (omit → the base var). They COMPOSE (no mutual-exclusion): read from `ref`,\n // write into `target`. Literal field overrides land on the same destination.\n const { ref, target } = entry;\n const updates: Record<string, string> = {};\n\n if (ref !== undefined) {\n updates[resolveName(propertyName, target)] = `var(${resolveName(propertyName, ref)})`;\n }\n\n for (const [field, r] of Object.entries(entry.overrides ?? {})) {\n const varName = field === \"base\" ? resolveName(propertyName, target) : resolveName(propertyName, target, field);\n // §15/§21: the formatter reads the whole ref (struct for shadow/transition, resolved `unit` for lengths).\n updates[varName] = formatValue(r);\n }\n\n return updates;\n};\n\nconst rootNode = (variables: Record<string, string>): CssVariablesNode[] =>\n Object.keys(variables).length ? [{ kind: \"variables\", selector: \":root\", variables }] : [];\n\n// ---------------------------------------------------------------------------\n// Shared appearance-mode expansion (§10.3)\n// ---------------------------------------------------------------------------\n\n/**\n * The OS-preference media query for a first-class mode. Named modes without an OS signal (e.g.\n * `hc`) get no media block — only the `[data-theme]` attribute block (a manual toggle).\n */\nconst MODE_MEDIA: Record<string, string> = {\n dark: \"@media (prefers-color-scheme: dark)\",\n light: \"@media (prefers-color-scheme: light)\",\n};\n\n/** Fetch (or create) the per-mode variable dict in a mode→vars accumulator, preserving mode order. */\nconst modeVars = (byMode: Map<string, Record<string, string>>, mode: string): Record<string, string> => {\n let vars = byMode.get(mode);\n if (!vars) {\n vars = {};\n byMode.set(mode, vars);\n }\n return vars;\n};\n\n/**\n * A mode→vars accumulator → its `CssVariablesNode[]`: per mode, an OS-preference `@media` block\n * (first-class modes only) re-declaring the mode's var names on `:root`, then a\n * `:root[data-theme=\"<mode>\"]` attribute block (higher specificity → a manual toggle wins; source\n * order last). Both redefine the SAME base var names, so every downstream `var(--…)` reference\n * flips through the cascade with one redefinition. Empty modes contribute nothing.\n */\nconst modeVariableNodes = (byMode: Map<string, Record<string, string>>): CssVariablesNode[] => {\n const nodes: CssVariablesNode[] = [];\n for (const [mode, variables] of byMode) {\n if (!Object.keys(variables).length) continue;\n const media = MODE_MEDIA[mode];\n if (media) nodes.push({ kind: \"variables\", selector: \":root\", media, variables: { ...variables } });\n nodes.push({ kind: \"variables\", selector: `:root[data-theme=\"${mode}\"]`, variables: { ...variables } });\n }\n return nodes;\n};\n\n// ---------------------------------------------------------------------------\n// Colors variable nodes\n// ---------------------------------------------------------------------------\n\nexport type ColorsLoweringContext<TBreakpoint extends string = string> = {\n varName: VarNamer;\n media: MediaDescriptor<TBreakpoint>;\n /** Formats a palette colour value for output (§20) — identity for `rgb`, else hex/oklch. */\n formatColor: (value: unknown) => string;\n};\n\n/**\n * A subsystem token-path → its uniform CSS variable name (§17): `[subsystem, property, variant, field]`\n * joined into a dotted path, then `varNameFromPath`. base = bare property (no `--base`); a variant and/or\n * a field append — `colors.primary` → `--<t>-colors-primary`, `colors.primary.dark` → `--…-primary-dark`,\n * `colors.primary.text` → `--…-primary-text`, and (dec.3) a variant's own extra\n * `colors.primary.loud.text` → `--…-primary-loud-text`.\n */\nconst subsystemVarName = (\n varName: VarNamer,\n subsystem: string,\n property: string,\n variant?: string,\n field?: string,\n): string =>\n varName([subsystem, property, variant, field].filter(Boolean).join(\".\"));\n\n/**\n * Colors property tokens → `:root` variable node(s) + responsive media nodes. base →\n * `--<t>-colors-<name>`, `extras.text` → `--<t>-colors-<name>-text`, variants →\n * `--<t>-colors-<name>-<variant>`, all in Model order.\n */\nexport const deriveColorsVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: ColorsLoweringContext<TBreakpoint>,\n): CssVariablesNode[] => {\n const { varName, formatColor } = ctx;\n const nameFor = (property: string, variant?: string, field?: string): string =>\n subsystemVarName(varName, \"colors\", property, variant, field);\n const variables: Record<string, string> = {};\n\n for (const [name, model] of Object.entries(properties)) {\n if (model.base.external !== undefined) continue; // §W6b — parent owns the var; emit no definition\n variables[nameFor(name)] = formatColor(model.base.value);\n const text = model.extras?.text;\n if (text && text.value != null && text.value !== \"\") {\n variables[nameFor(name, undefined, \"text\")] = formatColor(text.value);\n }\n for (const [variant, v] of Object.entries(model.variants ?? {})) {\n variables[nameFor(name, variant)] = formatColor(v.base.value);\n // dec.3 — the variant's own extras → `--<t>-colors-<name>-<variant>-<extra>`.\n for (const [ex, exRef] of Object.entries(v.extras ?? {})) {\n if (exRef.value != null && exRef.value !== \"\") variables[nameFor(name, variant, ex)] = formatColor(exRef.value);\n }\n }\n }\n\n return [\n ...rootNode(variables),\n ...expandResponsiveVariableNodes(properties, ctx.media, nameFor, ref => formatColor(ref.value)),\n ...deriveColorsModeNodes(properties, varName, formatColor),\n ];\n};\n\n/**\n * Colors appearance-mode blocks (§10.3). For each palette colour's modes, re-declare the affected\n * base var names — `--<t>-colors-<name>` for the `base` field and `--<t>-colors-<name>-text` for the\n * `text` extra — with the mode value, grouped per mode into the dual media + `[data-theme]` blocks.\n */\nconst deriveColorsModeNodes = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n formatColor: (value: unknown) => string,\n): CssVariablesNode[] => {\n const byMode = new Map<string, Record<string, string>>();\n for (const [name, model] of Object.entries(properties)) {\n if (!model.modes) continue;\n for (const entry of model.modes) {\n if (entry.mode === undefined) continue;\n const vars = modeVars(byMode, entry.mode);\n // WHERE — a `target` scopes the re-declaration onto that variant's var (`--colors-<name>-<target>`);\n // omit → the base var (byte-identical to the old field-map behaviour).\n const target = entry.target;\n const fields = entry.overrides ?? {};\n const baseRef = fields.base;\n if (baseRef && baseRef.value != null) {\n vars[subsystemVarName(varName, \"colors\", name, target)] = formatColor(baseRef.value);\n }\n for (const [field, ref] of Object.entries(fields)) {\n if (field === \"base\") continue;\n if (ref && ref.value != null && ref.value !== \"\") {\n vars[subsystemVarName(varName, \"colors\", name, target, field)] = formatColor(ref.value);\n }\n }\n }\n }\n return modeVariableNodes(byMode);\n};\n\n/**\n * Build a `tokenPath → cssVarName` map for a subsystem's property tokens (base + `text` extras +\n * variants), each named uniformly via {@link varNameFromPath}, so the recipe lowering renders a\n * Model rule-set whose refs are token paths. Works for colors (with the `text` extra) and every\n * regular subsystem alike.\n */\nconst buildSubsystemPathToVar = (\n subsystem: string,\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => {\n const map: Record<string, string> = {};\n for (const [name, model] of Object.entries(properties)) {\n // §W6b — an external token maps straight to the parent's var name, so refs lower to var(--…) verbatim.\n map[`${subsystem}.${name}`] = model.base.external ?? varName(`${subsystem}.${name}`);\n for (const [field, ref] of Object.entries(model.extras ?? {})) {\n if (ref?.value == null || ref.value === \"\") continue;\n map[`${subsystem}.${name}.${field}`] = varName(`${subsystem}.${name}.${field}`);\n }\n for (const [variant, v] of Object.entries(model.variants ?? {})) {\n map[`${subsystem}.${name}.${variant}`] = varName(`${subsystem}.${name}.${variant}`);\n for (const ex of Object.keys(v.extras ?? {})) {\n map[`${subsystem}.${name}.${variant}.${ex}`] = varName(`${subsystem}.${name}.${variant}.${ex}`);\n }\n }\n }\n return map;\n};\n\nexport const buildColorsPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildSubsystemPathToVar(\"colors\", properties, varName);\n\n// ---------------------------------------------------------------------------\n// Regular subsystems (typography / effects): base + variants only\n// ---------------------------------------------------------------------------\n\ntype RegularVariableSpec = {\n /** `:root` value formatting — reads the whole {@link Ref} (value / struct / resolved `unit`). */\n formatRoot: (propertyKey: string, ref: Ref) => string;\n /** Responsive value formatting (defaults to {@link dimensionCss}). */\n formatResponsive?: (ref: Ref) => string;\n};\n\ntype RegularLoweringContext<TBreakpoint extends string = string> = {\n varName: VarNamer;\n media: MediaDescriptor<TBreakpoint>;\n};\n\n/**\n * Regular subsystem properties → variable node(s) (§17 uniform naming). Each `(property, variant)`\n * names `--<t>-<subsystem>-<property>[-<variant>]` with the subsystem's value formatting (base first,\n * then authored variants, matching the token-map order). Responsive overrides + modes reuse the name.\n */\nconst deriveRegularVariableNodes = <TBreakpoint extends string = string>(\n subsystem: string,\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n spec: RegularVariableSpec,\n): CssVariablesNode[] => {\n const { varName } = ctx;\n const nameFor: ResolveVariableName = (property, variant, field) =>\n subsystemVarName(varName, subsystem, property, variant, field);\n\n const variables: Record<string, string> = {};\n for (const [name, model] of Object.entries(properties)) {\n if (model.base.external !== undefined) continue; // §W6b — parent owns the var; emit no definition\n variables[nameFor(name)] = spec.formatRoot(name, model.base);\n for (const [variant, v] of Object.entries(model.variants ?? {})) {\n variables[nameFor(name, variant)] = spec.formatRoot(name, v.base);\n // dec.3 — the variant's own extras → `--<t>-<subsystem>-<name>-<variant>-<extra>`.\n for (const [ex, exRef] of Object.entries(v.extras ?? {})) {\n variables[nameFor(name, variant, ex)] = spec.formatRoot(name, exRef);\n }\n }\n }\n\n const formatResponsive = spec.formatResponsive ?? dimensionCss;\n return [\n ...rootNode(variables),\n ...expandResponsiveVariableNodes(properties, ctx.media, nameFor, formatResponsive),\n ...deriveRegularModeNodes(properties, (key, variant) => nameFor(key, variant), spec.formatRoot),\n ];\n};\n\n/**\n * Regular-subsystem appearance-mode blocks (§10.3). Regular subsystems own no extras, so a mode\n * redefines only the property's base var (via the same `formatRoot` formatting the base emit uses);\n * any non-base mode field is ignored. Grouped per mode into the dual media/attr blocks.\n */\nconst deriveRegularModeNodes = (\n properties: Record<string, PropertyModel>,\n varNameFor: (property: string, variant?: string) => string,\n formatRoot: (propertyKey: string, ref: Ref) => string,\n): CssVariablesNode[] => {\n const byMode = new Map<string, Record<string, string>>();\n for (const [name, model] of Object.entries(properties)) {\n if (!model.modes) continue;\n for (const entry of model.modes) {\n if (entry.mode === undefined) continue;\n const baseRef = entry.overrides?.base;\n if (baseRef == null || (baseRef.struct == null && baseRef.value == null)) continue;\n // WHERE — a `target` scopes onto that variant's var; omit → the base var.\n modeVars(byMode, entry.mode)[varNameFor(name, entry.target)] = formatRoot(name, baseRef);\n }\n }\n return modeVariableNodes(byMode);\n};\n\n/** Build a `tokenPath → cssVarName` map for a regular subsystem (uniform naming). */\nconst buildRegularPathToVar = (\n subsystem: string,\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildSubsystemPathToVar(subsystem, properties, varName);\n\n// --- Typography ---\n\n/**\n * Typography property tokens → `:root` variable node(s). Length leaves (`fontSize`, `letterSpacing`)\n * carry a resolved `unit` from the §21 pass; unit-less numbers (`fontWeight`, `lineHeight` when un-unitted)\n * and strings (`fontFamily`) stringify raw — {@link dimensionCss} does both.\n */\nexport const deriveTypographyVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n): CssVariablesNode[] =>\n deriveRegularVariableNodes(\"typography\", properties, ctx, {\n formatRoot: (_propertyKey, ref) => dimensionCss(ref),\n });\n\nexport const buildTypographyPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildRegularPathToVar(\"typography\", properties, varName);\n\n// --- Effects ---\n\n// --- Structured effects value composition (§15) ---\n// The Model carries shadow/transition values as structure (`Ref.struct`); the CSS adapter is where\n// they become CSS text. A layer/part's `color` is a `colors.*` token path → `var(--…)` via the\n// global path→var map (colors processed before effects — the §14.4 cross-subsystem watch-point).\n// Shadow geometry fields carry a resolved unit (§21) — `shadowDimCss`; an absent (required) offset\n// defaults to `0` in the layer's unit ({@link layerUnit}), so a drop-shadow stays `0px …` not `0 …`.\n\n/** Resolve a shadow layer's `colors.*` color ref → `var(--…)`; falls back to the raw path if unmapped.\n * Translucency lives in the referenced colour (an `alpha` colour variant — §13.3), not here. */\nconst resolveColorRef = (color: string, pathToVar: Record<string, string>): string => {\n const varName = pathToVar[color];\n return varName ? `var(${varName})` : color;\n};\n\n/** The layer's shared length unit — read from the first resolved geometry field; `px` if none resolved. */\nconst layerUnit = (layer: ShadowLayer): string => {\n for (const field of [layer.offsetX, layer.offsetY, layer.blur, layer.spread]) {\n if (field !== undefined && typeof field !== \"number\") return field.unit;\n }\n return \"px\";\n};\n\n/** Compose one structured shadow layer → CSS `[inset] <x> <y> [blur] [spread] [color]` (§21 units). */\nconst composeShadowLayer = (\n layer: ShadowLayer,\n pathToVar: Record<string, string>,\n): string => {\n const zero = `0${layerUnit(layer)}`;\n const len = (dim: ShadowDimension | undefined): string => (dim === undefined ? zero : shadowDimCss(dim));\n const parts: string[] = [];\n if (layer.inset) parts.push(\"inset\");\n parts.push(len(layer.offsetX), len(layer.offsetY));\n // `spread` is only valid after a `blur` slot — emit `blur` (default 0) when spread is present.\n if (layer.spread != null) parts.push(len(layer.blur), len(layer.spread));\n else if (layer.blur != null) parts.push(len(layer.blur));\n if (layer.color) parts.push(resolveColorRef(layer.color, pathToVar));\n return parts.join(\" \");\n};\n\n/** Compose a shadow value (one or more layers) → a comma-joined `box-shadow` string. */\nconst composeShadow = (\n layers: ShadowLayer[],\n pathToVar: Record<string, string>,\n): string => layers.map(layer => composeShadowLayer(layer, pathToVar)).join(\", \");\n\n/** Compose one structured transition part → CSS `<property> <duration>ms [timing] [delay]ms`. */\nconst composeTransitionPart = (part: TransitionPart): string => {\n const parts: string[] = [part.property];\n // A bare `delay` needs a `duration` slot ahead of it (CSS reads the first time as duration).\n if (part.duration != null || part.delay != null) parts.push(`${part.duration ?? 0}ms`);\n if (part.timingFunction) parts.push(part.timingFunction);\n if (part.delay != null) parts.push(`${part.delay}ms`);\n return parts.join(\" \");\n};\n\n/** Compose a transition value (one or more parts) → a comma-joined `transition` string. */\nconst composeTransition = (parts: TransitionPart[]): string =>\n parts.map(composeTransitionPart).join(\", \");\n\n/** Compose a structured effects value → CSS by property (`transitions` vs shadow). */\nconst composeEffectsStruct = (\n propertyKey: string,\n value: readonly unknown[],\n pathToVar: Record<string, string>,\n): string =>\n propertyKey === \"transitions\"\n ? composeTransition(value as TransitionPart[])\n : composeShadow(value as ShadowLayer[], pathToVar);\n\n/**\n * Compose a structured effects value without a property key (the responsive path, where only the\n * value is in hand): a transition part carries a `property` field; a shadow layer does not.\n */\nconst composeEffectsStructAuto = (\n value: readonly unknown[],\n pathToVar: Record<string, string>,\n): string => {\n const first = value[0];\n const isTransition = !!first && typeof first === \"object\" && \"property\" in first;\n return isTransition\n ? composeTransition(value as TransitionPart[])\n : composeShadow(value as ShadowLayer[], pathToVar);\n};\n\n/**\n * Effects property tokens → `:root` variable node(s). `blur` carries a resolved length unit (§21);\n * `shadow` / `transitions` compose from their structured {@link Ref.struct} value (§15) into CSS text —\n * a layer/part `color` ref resolves via `ctx.pathToVar` (the global map, colors already merged); the\n * scalars (`opacity` / `zIndex`) are unit-less. {@link dimensionCss} covers blur + the unit-less scalars.\n */\nexport const deriveEffectsVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint> & { pathToVar?: Record<string, string> },\n): CssVariablesNode[] => {\n const pathToVar = ctx.pathToVar ?? {};\n return deriveRegularVariableNodes(\"effects\", properties, ctx, {\n formatRoot: (propertyKey, ref) =>\n ref.struct ? composeEffectsStruct(propertyKey, ref.struct, pathToVar) : dimensionCss(ref),\n formatResponsive: ref =>\n ref.struct ? composeEffectsStructAuto(ref.struct, pathToVar) : dimensionCss(ref),\n });\n};\n\nexport const buildEffectsPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildRegularPathToVar(\"effects\", properties, varName);\n\n// --- Borders (§14) ---\n\n/**\n * Borders property tokens → `:root` variable node(s). width/offset/radius carry a resolved length unit\n * (§21); `style` (a keyword string) has no unit. {@link dimensionCss} covers both.\n */\nexport const deriveBordersVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n): CssVariablesNode[] =>\n deriveRegularVariableNodes(\"borders\", properties, ctx, {\n formatRoot: (_propertyKey, ref) => dimensionCss(ref),\n });\n\nexport const buildBordersPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> =>\n buildRegularPathToVar(\"borders\", properties, varName);\n\n// --- Animation (§10.2) ---\n\n/** Motion-token keys whose numeric value formats as a `<n>ms` time. `easing` stays a raw string. */\nconst MS_ANIMATION_KEYS = new Set([\"duration\", \"delay\"]);\n\nconst formatMs = (value: unknown): string => (typeof value === \"number\" ? `${value}ms` : str(value));\n\n/** Animation motion tokens (duration/easing/delay) → `:root` variable node(s). Numeric durations/delays\n * format as ms (time, not length — animation is outside the §21 length registry, so no `unit` is baked). */\nexport const deriveAnimationVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n): CssVariablesNode[] =>\n deriveRegularVariableNodes(\"animation\", properties, ctx, {\n formatRoot: (propertyKey, ref) =>\n typeof ref.value === \"number\" && MS_ANIMATION_KEYS.has(propertyKey) ? `${ref.value}ms` : str(ref.value),\n formatResponsive: ref => formatMs(ref.value),\n });\n\nexport const buildAnimationPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildRegularPathToVar(\"animation\", properties, varName);\n\n// --- Layout ---\n\n/** A structural-config property key (`columns--size`, `container--inset`) vs a regular one (`spacing`). */\nconst isLayoutConfigKey = (key: string): boolean => key.includes(\"--\");\n\n/** Split layout's merged property map into the regular tokens and the structural-config tokens (order kept). */\nexport const splitLayoutProperties = (\n properties: Record<string, PropertyModel>,\n): { regular: Record<string, PropertyModel>; config: Record<string, PropertyModel> } => {\n const regular: Record<string, PropertyModel> = {};\n const config: Record<string, PropertyModel> = {};\n for (const [key, model] of Object.entries(properties)) {\n if (isLayoutConfigKey(key)) config[key] = model;\n else regular[key] = model;\n }\n return { regular, config };\n};\n\n/**\n * Layout regular property tokens → `:root` variable node(s). spacing/gutters carry a resolved length\n * unit (§21); `aspectRatio` is unit-less. {@link dimensionCss} covers both.\n */\nexport const deriveLayoutVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n): CssVariablesNode[] =>\n deriveRegularVariableNodes(\"layout\", properties, ctx, {\n formatRoot: (_propertyKey, ref) => dimensionCss(ref),\n });\n\n/** The fixed layout knobs that always get a canonical base var name, even when unauthored. */\nconst LAYOUT_BASE_KEYS = [\"spacing\", \"gutters\", \"aspectRatio\"] as const;\n\n/**\n * A `tokenPath → cssVarName` map for the whole layout subsystem — regular tokens via the uniform\n * naming (`layout.spacing.relaxed` → `--<t>-layout-spacing-relaxed`) **and** structural-config\n * tokens (`layout.container--inset` → `--<t>-layout-container-inset`), so the structural rule\n * declarations (which reference config tokens by path) resolve to the config `:root` var names.\n */\nexport const buildLayoutPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => {\n const { regular, config } = splitLayoutProperties(properties);\n const map = buildRegularPathToVar(\"layout\", regular, varName);\n // Seed the canonical base names for the fixed layout knobs (spacing/gutters/aspectRatio) so a\n // structural declaration referencing a base token (`layout.spacing`) always resolves to its var\n // name — even when no such property is authored (the default container with an empty `layout: {}`\n // references `layout.spacing`; the OLD generator hardcoded `var(--…-layout-spacing--base)`). For a\n // theme that DOES author these, the value is identical to the regular map entry — a no-op.\n for (const key of LAYOUT_BASE_KEYS) {\n const path = `layout.${key}`;\n if (!(path in map)) map[path] = varName(path);\n }\n for (const key of Object.keys(config)) {\n map[`layout.${key}`] = varName(`layout.${key}`);\n }\n return map;\n};\n\n/**\n * Layout structural-config tokens → `:root` variable node(s), one node per config group\n * (`columns`, `container`), grouped by the key's leading `<group>--` segment in first-seen order.\n * Each var is `--<t>-layout-<key>` (uniform); its value is the literal or a `var(--…)` (via\n * `pathToVar`) — so `--<t>-layout-columns-gutter: var(--<t>-layout-gutters)`.\n */\nexport const deriveLayoutConfigVariableNodes = (\n config: Record<string, PropertyModel>,\n ctx: { varName: VarNamer; pathToVar: Record<string, string> },\n): CssVariablesNode[] => {\n const byGroup = new Map<string, Record<string, string>>();\n for (const [key, model] of Object.entries(config)) {\n const group = key.split(\"--\")[0];\n let vars = byGroup.get(group);\n if (!vars) {\n vars = {};\n byGroup.set(group, vars);\n }\n vars[ctx.varName(`layout.${key}`)] = String(refToStyleValue(model.base, ctx.pathToVar));\n }\n return Array.from(byGroup.values(), (variables): CssVariablesNode => ({\n kind: \"variables\",\n selector: \":root\",\n variables,\n }));\n};\n\n// ---------------------------------------------------------------------------\n// Container rule lowering (two-pass: bases in reverse, medias forward)\n// ---------------------------------------------------------------------------\n\n/**\n * Lower a container {@link RuleSetGroup} to `CssRuleNode[]`. Unlike `lowerRecipeGroup` (which\n * interleaves base + medias per variant), the container generator emitted **all bases first**\n * (via `unshift`, so reverse of processing order) then **all medias** (forward). Reproduce that:\n * pass 1 emits base rules in reverse group order; pass 2 emits media overrides in forward order.\n * Byte-identical to the old `deriveContainerRules`, without the reverse node↔rule-set codec.\n */\nexport const lowerContainerGroup = <TBreakpoint extends string = string>(\n group: RuleSetGroup,\n options: LowerRecipeGroupOptions<TBreakpoint>,\n): LowerRecipeGroupResult => {\n const { media, selectorBuilder, pathToVar } = options;\n const entries = Object.entries(group);\n const variants: Record<string, string> = {};\n for (const [name] of entries) variants[name] = selectorBuilder(name);\n\n const baseNodes: CssRuleNode[] = [];\n for (let i = entries.length - 1; i >= 0; i--) {\n const [name, ruleSet] = entries[i];\n const declarations = declarationsFromRefs(ruleSet.declarations, pathToVar);\n if (declarations.length) baseNodes.push({ kind: \"rule\", selector: selectorBuilder(name), declarations });\n }\n\n const mediaNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of entries) {\n for (const override of ruleSet.overrides) {\n if (override.state !== undefined || !override.breakpoint) continue;\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (!mediaQuery) continue;\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n mediaNodes.push({ kind: \"rule\", selector: selectorBuilder(name), media: mediaQuery, declarations });\n }\n }\n\n return { nodes: [...baseNodes, ...mediaNodes], variants };\n};\n\n// ---------------------------------------------------------------------------\n// Recipe rule lowering (forward: Model rule-sets → CssRuleNode[])\n// ---------------------------------------------------------------------------\n\n/** A declaration ref → its CSS value: a `var(--…)` (via `pathToVar`), optionally wrapped; else the literal. */\nconst refToStyleValue = (ref: Ref, pathToVar: Record<string, string>): string | number => {\n if (ref.ref === undefined) return ref.value as string | number;\n const v = `var(${pathToVar[ref.ref] ?? ref.ref})`;\n return ref.wrap ? `${ref.wrap}(${v})` : v;\n};\n\nconst declarationsFromRefs = (\n decls: Record<string, Ref>,\n pathToVar: Record<string, string>,\n): CssDeclaration[] =>\n Object.entries(decls).map(([property, ref]) => ({ property, value: refToStyleValue(ref, pathToVar) }));\n\n// ---------------------------------------------------------------------------\n// Globals lowering (§9) — preset `kind:\"reset\"` (`:where(sel)`) + themed `kind:\"globals\"` elements\n// ---------------------------------------------------------------------------\n\n/**\n * Suffix each comma-part of a raw selector (`h1,h2` + `.subtle` → `h1.subtle,h2.subtle`; `a` +\n * `:hover` → `a:hover`). Applies a variant class or a state pseudo to every element in a grouped\n * selector, not just the last — so a globals variant/state on `h1,h2` scopes both.\n */\nconst suffixSelector = (selector: string, suffix: string): string =>\n selector\n .split(\",\")\n .map(part => `${part.trim()}${suffix}`)\n .join(\",\");\n\n/**\n * Lower one preset `kind:\"reset\"` rule-set → a specificity-0 `:where(sel) { … }` node. Literal\n * declarations pass through; token-path refs resolve via `globalPathToVar`, and an unresolved ref is\n * **dropped** (the opportunistic `defaults` `h1`–`h6` heading map / `static` layer — a ratio-less\n * theme drops the missing scale step). Never throws — the throw policy lives on themed elements.\n */\nconst lowerResetRuleSet = (\n ruleSet: RuleSet,\n globalPathToVar: Record<string, string>,\n): CssRuleNode[] => {\n const selector = ruleSet.selector;\n if (!selector) return [];\n const declarations: CssDeclaration[] = [];\n for (const [property, ref] of Object.entries(ruleSet.declarations)) {\n if (ref.ref === undefined) {\n declarations.push({ property, value: ref.value as string | number });\n continue;\n }\n const varName = globalPathToVar[ref.ref];\n if (varName) declarations.push({ property, value: `var(${varName})` });\n // else drop: the scale step / token isn't present → omit this declaration.\n }\n return declarations.length ? [{ kind: \"rule\", selector: `:where(${selector})`, declarations }] : [];\n};\n\n/**\n * Emit one themed rule (a globals element base, or one of its variants) at `selector`: the base\n * declarations, its breakpoint-only overrides as `@media` blocks, then its state overrides as\n * `selector:state` rules (canonical order, source-order-last so they win), then container overrides.\n * Refs are validated up-front in `createTheme` (`validateGlobalsRefs`), so `declarationsFromRefs`\n * lowers them without a per-adapter throw.\n */\nconst emitGlobalsRule = <TBreakpoint extends string>(\n nodes: CssRuleNode[],\n selector: string,\n declarations: Record<string, Ref>,\n overrides: RuleSetOverride[],\n pathToVar: Record<string, string>,\n media: MediaDescriptor<TBreakpoint>,\n containers: ContainerDescriptors | undefined,\n): void => {\n const base = declarationsFromRefs(declarations, pathToVar);\n if (base.length) nodes.push({ kind: \"rule\", selector, declarations: base });\n\n for (const override of overrides) {\n if (override.state !== undefined || override.container !== undefined || !override.breakpoint) continue;\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (!mediaQuery) continue;\n const decls = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (decls.length) nodes.push({ kind: \"rule\", selector, media: mediaQuery, declarations: decls });\n }\n\n const stateOverrides = overrides.filter(o => o.state !== undefined);\n for (const override of orderStateOverrides(stateOverrides)) {\n const stateSelector = CSS_STATE_SELECTORS[override.state as string];\n if (!stateSelector) continue;\n const decls = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!decls.length) continue;\n const node: CssRuleNode = { kind: \"rule\", selector: suffixSelector(selector, stateSelector), declarations: decls };\n if (override.breakpoint) {\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (mediaQuery) node.media = mediaQuery;\n }\n nodes.push(node);\n }\n\n for (const override of overrides) {\n if (!override.container) continue;\n const query = containerQueryFor(override, containers);\n if (!query) continue;\n const decls = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!decls.length) continue;\n nodes.push({ kind: \"rule\", selector, media: query, declarations: decls });\n }\n};\n\n/**\n * Lower the globals subsystem's rule-set groups to `CssRuleNode[]`. Two kinds coexist:\n * - `kind:\"reset\"` (preset `static` / `defaults`) → specificity-0 `:where(sel)` (drop policy).\n * - `kind:\"globals\"` (themed `elements`) → a bare `sel { … }` at a higher tier, its `states` /\n * `responsive` overrides, and each delta-only variant as a self-scoped `sel.<variant>` rule.\n * Groups render in insertion order (`static` → `defaults` → `elements`).\n */\nexport const lowerGlobalsGroups = <TBreakpoint extends string>(\n ruleSets: Record<string, RuleSetGroup>,\n globalPathToVar: Record<string, string>,\n media: MediaDescriptor<TBreakpoint>,\n containers?: ContainerDescriptors,\n): CssRuleNode[] => {\n const nodes: CssRuleNode[] = [];\n for (const ruleSetGroup of Object.values(ruleSets)) {\n for (const ruleSet of Object.values(ruleSetGroup)) {\n if (ruleSet.kind === \"globals\") {\n const selector = ruleSet.selector;\n if (!selector) continue;\n emitGlobalsRule(nodes, selector, ruleSet.declarations, ruleSet.overrides, globalPathToVar, media, containers);\n for (const [variantName, variant] of Object.entries(ruleSet.variants ?? {})) {\n const variantSelector = suffixSelector(selector, `.${variantName}`);\n emitGlobalsRule(nodes, variantSelector, variant.declarations, variant.overrides, globalPathToVar, media, containers);\n }\n } else {\n nodes.push(...lowerResetRuleSet(ruleSet, globalPathToVar));\n }\n }\n }\n return nodes;\n};\n\n// ---------------------------------------------------------------------------\n// Container context declaration (§10.5) — `.<prefix>-cq-<name> { container-type; container-name }`\n// ---------------------------------------------------------------------------\n\n/**\n * Lower the theme's `containers` config to the utility classes that establish each named containment\n * context: `.<classPrefix>-cq-<name> { container-type: <type>; container-name: <name>; }` (§10.5 D4).\n * A distinct `cq` segment avoids colliding with layout's `.<prefix>-container` max-width wrapper. Put\n * on a wrapper element; the recipe's `@container <name> (…)` rules then respond to it. The context\n * class routes through `containerClass` (§7B `kind:\"container\"`), so a naming override remaps it\n * consistently with `theme.classes.containers.context.<name>`.\n */\nexport const deriveContainerContextNodes = (\n containers: Record<string, ContainerModel> | undefined,\n containerClass: (name: string) => string,\n): CssRuleNode[] => {\n const nodes: CssRuleNode[] = [];\n for (const [name, container] of Object.entries(containers ?? {})) {\n nodes.push({\n kind: \"rule\",\n selector: `.${containerClass(name)}`,\n declarations: [\n { property: \"container-type\", value: container.type },\n { property: \"container-name\", value: name },\n ],\n });\n }\n return nodes;\n};\n\n// --- State → selector table + canonical ordering ---\n\nconst CSS_STATE_SELECTORS: Record<string, string> = {\n link: \":link\",\n visited: \":visited\",\n hover: \":hover\",\n focus: \":focus\",\n active: \":active\",\n disabled: \"[disabled]\",\n pressed: \"[aria-pressed]\",\n};\n\n/** The states the CSS adapter can render (the validation set for recipe normalization). */\nexport const CSS_KNOWN_STATES: ReadonlyArray<string> = Object.keys(CSS_STATE_SELECTORS);\n\nconst STATE_ORDER: Record<string, number> = CSS_KNOWN_STATES.reduce<Record<string, number>>(\n (acc, name, index) => {\n acc[name] = index;\n return acc;\n },\n {},\n);\n\nconst orderStateOverrides = (overrides: RuleSetOverride[]): RuleSetOverride[] =>\n [...overrides]\n .map((override, index) => ({ override, index }))\n .sort((a, b) => {\n const orderA = STATE_ORDER[a.override.state as string] ?? Number.MAX_SAFE_INTEGER;\n const orderB = STATE_ORDER[b.override.state as string] ?? Number.MAX_SAFE_INTEGER;\n if (orderA !== orderB) return orderA - orderB;\n const bpA = a.override.breakpoint ? 1 : 0;\n const bpB = b.override.breakpoint ? 1 : 0;\n if (bpA !== bpB) return bpA - bpB;\n return a.index - b.index;\n })\n .map(({ override }) => override);\n\nconst deriveStateNodes = <TBreakpoint extends string>(\n ruleSet: RuleSet,\n selector: string,\n media: MediaDescriptor<TBreakpoint>,\n pathToVar: Record<string, string>,\n): CssRuleNode[] => {\n // dec.8 — `target`ed state overrides emit against a SIBLING selector, appended last by the caller\n // so they win; the base state rules here are the un-targeted ones (byte-identical to before).\n const stateOverrides = ruleSet.overrides.filter(o => o.state !== undefined && !o.target);\n if (!stateOverrides.length) return [];\n\n const nodes: CssRuleNode[] = [];\n for (const override of orderStateOverrides(stateOverrides)) {\n const stateSelector = CSS_STATE_SELECTORS[override.state as string];\n if (!stateSelector) continue;\n\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n\n const node: CssRuleNode = { kind: \"rule\", selector: `${selector}${stateSelector}`, declarations };\n\n if (override.breakpoint) {\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (mediaQuery) node.media = mediaQuery;\n }\n\n nodes.push(node);\n }\n return nodes;\n};\n\nexport type LowerRecipeGroupOptions<TBreakpoint extends string = string> = {\n media: MediaDescriptor<TBreakpoint>;\n selectorBuilder: (variantName: string) => string;\n pathToVar: Record<string, string>;\n /** Container-query descriptors (§10.5) — resolve a `{ container, size, query }` override → `@container …`. */\n containers?: ContainerDescriptors;\n};\n\n/**\n * Resolve a container override's `{ container, size, query }` to its `@container <name> (…)` prelude\n * via the container descriptors, or `\"\"` when the container/size/descriptors are absent (§10.5).\n */\nconst containerQueryFor = (\n override: RuleSetOverride,\n containers: ContainerDescriptors | undefined,\n): string => {\n if (!override.container || !override.size) return \"\";\n const descriptor = containers?.[override.container];\n if (!descriptor) return \"\";\n const query = (override.query ?? \"min\") as MediaVariant;\n return descriptor[query](override.size);\n};\n\nexport type LowerRecipeGroupResult = {\n nodes: CssRuleNode[];\n variants: Record<string, string>;\n};\n\n/**\n * A Model recipe {@link RuleSetGroup} → recipe `CssRuleNode[]` (+ variant → selector map).\n * Forward lowering: base + breakpoint-conditioned overrides render first (per variant), then\n * state (+ state×breakpoint) overrides append as `:state` rules so they win by source order.\n */\nexport const lowerRecipeGroup = <TBreakpoint extends string = string>(\n group: RuleSetGroup,\n options: LowerRecipeGroupOptions<TBreakpoint>,\n): LowerRecipeGroupResult => {\n const { media, selectorBuilder, pathToVar } = options;\n const nodes: CssRuleNode[] = [];\n const variants: Record<string, string> = {};\n\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n variants[name] = selector;\n\n const baseDeclarations = declarationsFromRefs(ruleSet.declarations, pathToVar);\n if (baseDeclarations.length) nodes.push({ kind: \"rule\", selector, declarations: baseDeclarations });\n\n for (const override of ruleSet.overrides) {\n if (override.state !== undefined || !override.breakpoint) continue;\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (!mediaQuery) continue;\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n nodes.push({ kind: \"rule\", selector, media: mediaQuery, declarations });\n }\n }\n\n const stateNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n stateNodes.push(...deriveStateNodes(ruleSet, selectorBuilder(name), media, pathToVar));\n }\n\n // dec.8 — `target`ed state overrides: emit `<item>-<target>:state` against the desugared sibling\n // (§7A), collected across the whole group and appended LAST so they beat the sibling's inherited\n // (un-targeted) state rules by source order.\n const targetedStateNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n for (const override of ruleSet.overrides) {\n if (override.state === undefined || !override.target) continue;\n const stateSelector = CSS_STATE_SELECTORS[override.state];\n if (!stateSelector) continue;\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n const siblingSelector = selectorBuilder(`${name}-${override.target}`);\n const node: CssRuleNode = { kind: \"rule\", selector: `${siblingSelector}${stateSelector}`, declarations };\n if (override.breakpoint) {\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (mediaQuery) node.media = mediaQuery;\n }\n targetedStateNodes.push(node);\n }\n }\n\n // Container-query overrides (§10.5): each `{ container, size }` override → a rule wrapped in an\n // `@container <name> (…)` prelude (carried on the node's generic `media` field). Appended last so\n // they win by source order, like state rules. Skipped entirely when no `containers` are configured.\n const containerNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n for (const override of ruleSet.overrides) {\n if (!override.container) continue;\n const query = containerQueryFor(override, options.containers);\n if (!query) continue;\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n containerNodes.push({ kind: \"rule\", selector, media: query, declarations });\n }\n }\n\n return { nodes: [...nodes, ...stateNodes, ...containerNodes, ...targetedStateNodes], variants };\n};\n\n// ---------------------------------------------------------------------------\n// Animation lowering (§10.2) — keyframes at-rules + animation-shorthand recipes\n// ---------------------------------------------------------------------------\n\n/** The token-path prefix an `animation-name` ref carries — it resolves to the bare keyframe id. */\nconst KEYFRAME_REF_PREFIX = \"animation.keyframes.\";\n\n/**\n * Lower the animation subsystem's keyframes to `@keyframes` at-rule nodes. Each step keeps its\n * verbatim `stop`; declarations resolve through `globalPathToVar` — a literal `{ value }` passes\n * through, a token-path `{ ref }` (e.g. `colors.surface`) becomes `var(--…)` (so a keyframe can\n * animate a themed value). Keyframe identifiers are emitted raw (as authored).\n */\nexport const lowerKeyframes = (\n keyframes: Record<string, Keyframe>,\n globalPathToVar: Record<string, string>,\n): CssKeyframesNode[] => {\n const nodes: CssKeyframesNode[] = [];\n for (const [name, keyframe] of Object.entries(keyframes)) {\n const steps = keyframe.steps.map(step => ({\n stop: step.stop,\n declarations: Object.entries(step.declarations).map(([property, ref]): CssDeclaration => ({\n property,\n value: refToStyleValue(ref, globalPathToVar),\n })),\n }));\n nodes.push({ kind: \"keyframes\", name, steps });\n }\n return nodes;\n};\n\n/** The `animation:` shorthand sub-property order — first `<time>` = duration, second = delay; name last. */\nconst ANIMATION_LONGHAND_ORDER: ReadonlyArray<string> = [\n \"animation-duration\",\n \"animation-timing-function\",\n \"animation-delay\",\n \"animation-iteration-count\",\n \"animation-direction\",\n \"animation-fill-mode\",\n \"animation-play-state\",\n \"animation-name\",\n];\n\n/** Resolve an `animation-name` ref to its bare keyframe identifier, validating it against the known set. */\nconst resolveKeyframeName = (\n ref: Ref,\n keyframeNames: ReadonlySet<string>,\n selector: string,\n): string => {\n const name =\n ref.ref !== undefined\n ? ref.ref.startsWith(KEYFRAME_REF_PREFIX)\n ? ref.ref.slice(KEYFRAME_REF_PREFIX.length)\n : ref.ref\n : str(ref.value);\n if (!keyframeNames.has(name)) {\n throw new Error(\n `css adapter: animation recipe '${selector}' references unknown keyframe '${name}' — ` +\n `no matching entry in animation.keyframes`,\n );\n }\n return name;\n};\n\n/**\n * Compose one animation declaration set (base or override) into an `animation:` shorthand string in\n * canonical sub-property order. Duration/easing/delay refs → `var(--…)` (or literal); the\n * `animation-name` ref → the bare, validated keyframe identifier. Returns `\"\"` when nothing is set.\n */\nconst composeAnimationShorthand = (\n decls: Record<string, Ref>,\n pathToVar: Record<string, string>,\n keyframeNames: ReadonlySet<string>,\n selector: string,\n): string => {\n const parts: string[] = [];\n for (const longhand of ANIMATION_LONGHAND_ORDER) {\n const ref = decls[longhand];\n if (!ref) continue;\n parts.push(\n longhand === \"animation-name\"\n ? resolveKeyframeName(ref, keyframeNames, selector)\n : String(refToStyleValue(ref, pathToVar)),\n );\n }\n return parts.join(\" \");\n};\n\nexport type LowerAnimationGroupOptions<TBreakpoint extends string = string> =\n LowerRecipeGroupOptions<TBreakpoint> & { keyframeNames: ReadonlySet<string> };\n\n/**\n * Lower an animation recipe {@link RuleSetGroup} to class rules whose single declaration is the\n * composed `animation:` shorthand — base first, then breakpoint overrides, then state overrides\n * (canonical order, source-order wins) — mirroring {@link lowerRecipeGroup}'s node ordering with a\n * whole-set shorthand composer in place of the per-declaration lowering.\n */\nexport const lowerAnimationRecipeGroup = <TBreakpoint extends string = string>(\n group: RuleSetGroup,\n options: LowerAnimationGroupOptions<TBreakpoint>,\n): LowerRecipeGroupResult => {\n const { media, selectorBuilder, pathToVar, keyframeNames } = options;\n const nodes: CssRuleNode[] = [];\n const variants: Record<string, string> = {};\n\n const shorthandNode = (\n selector: string,\n decls: Record<string, Ref>,\n mediaQuery?: string,\n ): CssRuleNode | undefined => {\n const shorthand = composeAnimationShorthand(decls, pathToVar, keyframeNames, selector);\n if (!shorthand) return undefined;\n const node: CssRuleNode = { kind: \"rule\", selector, declarations: [{ property: \"animation\", value: shorthand }] };\n if (mediaQuery) node.media = mediaQuery;\n return node;\n };\n\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n variants[name] = selector;\n\n const base = shorthandNode(selector, ruleSet.declarations);\n if (base) nodes.push(base);\n\n for (const override of ruleSet.overrides) {\n if (override.state !== undefined || !override.breakpoint) continue;\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (!mediaQuery) continue;\n const node = shorthandNode(selector, override.declarations ?? {}, mediaQuery);\n if (node) nodes.push(node);\n }\n }\n\n const stateNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n const stateOverrides = ruleSet.overrides.filter(o => o.state !== undefined);\n for (const override of orderStateOverrides(stateOverrides)) {\n const stateSelector = CSS_STATE_SELECTORS[override.state as string];\n if (!stateSelector) continue;\n let mediaQuery: string | undefined;\n if (override.breakpoint) {\n mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n ) || undefined;\n }\n const node = shorthandNode(`${selector}${stateSelector}`, override.declarations ?? {}, mediaQuery);\n if (node) stateNodes.push(node);\n }\n }\n\n // Container-query overrides (§10.5): compose the shorthand and wrap it in `@container <name> (…)`.\n const containerNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n for (const override of ruleSet.overrides) {\n if (!override.container) continue;\n const query = containerQueryFor(override, options.containers);\n if (!query) continue;\n const node = shorthandNode(selector, override.declarations ?? {}, query);\n if (node) containerNodes.push(node);\n }\n }\n\n return { nodes: [...nodes, ...stateNodes, ...containerNodes], variants };\n};\n\n// ---------------------------------------------------------------------------\n// Merged (flattened) rule-set lowering — the `components` emit mode (§9d/9e)\n// ---------------------------------------------------------------------------\n\n/** Sort merged state keys by the canonical `CSS_STATE_SELECTORS` order (hover before disabled, …). */\nconst orderStateKeys = (keys: string[]): string[] =>\n [...keys].sort(\n (a, b) =>\n (STATE_ORDER[a] ?? Number.MAX_SAFE_INTEGER) - (STATE_ORDER[b] ?? Number.MAX_SAFE_INTEGER),\n );\n\nexport type LowerMergedRuleSetOptions<TBreakpoint extends string = string> = {\n /** The base selector for the flattened variant (e.g. `.app-buttons-primary`). */\n selector: string;\n media: MediaDescriptor<TBreakpoint>;\n pathToVar: Record<string, string>;\n /** Container-query descriptors (§10.5) — resolve a merged container bucket → `@container …`. */\n containers?: ContainerDescriptors;\n};\n\n/**\n * Lower one flattened {@link MergedRuleSet} to `CssRuleNode[]` — the format-neutral twin of\n * {@link lowerRecipeGroup} for the `components` emit mode. Reuses the same declaration lowering,\n * state→selector table, and media resolution: `base` → the base rule at `selector`; each `state`\n * → a `${selector}:hover`/`[disabled]`/… rule (canonical order); each responsive entry → an\n * `@media` block (with an optional state selector). Declarations stay as `var(--…)` refs — inline\n * baking is a render-time choice the adapter makes downstream (via `enrichDeclarationsWithRefs`).\n */\nexport const lowerMergedRuleSet = <TBreakpoint extends string = string>(\n merged: MergedRuleSet,\n options: LowerMergedRuleSetOptions<TBreakpoint>,\n): CssRuleNode[] => {\n const { selector, media, pathToVar, containers } = options;\n const nodes: CssRuleNode[] = [];\n\n const baseDeclarations = declarationsFromRefs(merged.base, pathToVar);\n if (baseDeclarations.length) nodes.push({ kind: \"rule\", selector, declarations: baseDeclarations });\n\n for (const state of orderStateKeys(Object.keys(merged.states))) {\n const stateSelector = CSS_STATE_SELECTORS[state];\n if (!stateSelector) continue;\n const declarations = declarationsFromRefs(merged.states[state], pathToVar);\n if (declarations.length) {\n nodes.push({ kind: \"rule\", selector: `${selector}${stateSelector}`, declarations });\n }\n }\n\n for (const entry of merged.responsive) {\n // A viewport bucket → `@media`; a container bucket (§10.5) → `@container` (carried on the same\n // generic `media` field). Both may still carry a state selector.\n const atRule = entry.container\n ? containerQueryFor(entry as RuleSetOverride, containers)\n : resolveMediaQuery(\n media,\n entry.breakpoint as TBreakpoint,\n (entry.query ?? \"exact\") as MediaVariant,\n entry.orientation,\n );\n if (!atRule) continue;\n const declarations = declarationsFromRefs(entry.declarations, pathToVar);\n if (!declarations.length) continue;\n const stateSelector = entry.state ? CSS_STATE_SELECTORS[entry.state] ?? \"\" : \"\";\n nodes.push({ kind: \"rule\", selector: `${selector}${stateSelector}`, media: atRule, declarations });\n }\n\n return nodes;\n};\n","/**\n * Render the CSS adapter's `CssNode[]` IR to a CSS string, plus the enrich/split\n * helpers the delivery modes need. Ported (copy, not rewrite) from the proven\n * `core/common/{cssRenderer,cssEnrich,cssRender}.ts`, self-contained (no core imports).\n */\nimport type { CssKeyframesNode, CssNode, CssRuleNode, CssVariablesNode } from \"./nodes\";\n\nexport type RenderCssOptions = {\n indent?: string;\n newline?: string;\n};\n\nconst DEFAULT_INDENT = \" \";\nconst DEFAULT_NEWLINE = \"\\n\";\n\n/**\n * Render an IR (`CssNode[]`) to a CSS string. Adjacent variable nodes sharing the same\n * `selector` + `media` merge into one block, so two subsystems that both contribute\n * `:root` variables produce one `:root { … }` block.\n */\nexport const renderToCssString = (nodes: CssNode[], options: RenderCssOptions = {}): string => {\n const indent = options.indent ?? DEFAULT_INDENT;\n const newline = options.newline ?? DEFAULT_NEWLINE;\n const blocks: string[] = [];\n\n const merged = mergeAdjacentVariableNodes(nodes);\n\n for (const node of merged) {\n if (node.kind === \"keyframes\") {\n const body = renderKeyframesBody(node, indent, newline);\n if (!body) continue;\n blocks.push(`@keyframes ${node.name} {${newline}${body}${newline}}`);\n continue;\n }\n\n const body =\n node.kind === \"variables\"\n ? renderVariableBody(node.variables, indent, newline)\n : renderRuleBody(node.declarations, indent, newline);\n\n if (!body) continue;\n\n const inner = `${node.selector} {${newline}${body}${newline}}`;\n if (node.media) {\n blocks.push(`${node.media} {${newline}${indentBlock(inner, indent, newline)}${newline}}`);\n } else {\n blocks.push(inner);\n }\n }\n\n return blocks.filter(Boolean).join(`${newline}${newline}`);\n};\n\nconst mergeAdjacentVariableNodes = (nodes: CssNode[]): CssNode[] => {\n const keyFor = (node: CssNode): string =>\n node.kind === \"variables\" ? `var:${node.media ?? \"\"}:${node.selector}` : \"\";\n\n const output: CssNode[] = [];\n for (const node of nodes) {\n if (node.kind !== \"variables\") {\n output.push(node);\n continue;\n }\n const key = keyFor(node);\n const previous = output[output.length - 1];\n if (previous && previous.kind === \"variables\" && keyFor(previous) === key) {\n previous.variables = { ...previous.variables, ...node.variables };\n } else {\n output.push({\n kind: \"variables\",\n selector: node.selector,\n media: node.media,\n variables: { ...node.variables },\n });\n }\n }\n return output;\n};\n\nconst renderVariableBody = (\n variables: Record<string, string>,\n indent: string,\n newline: string,\n): string => {\n const entries = Object.entries(variables);\n if (!entries.length) return \"\";\n return entries.map(([name, value]) => `${indent}${name}: ${value};`).join(newline);\n};\n\nconst renderRuleBody = (\n declarations: CssRuleNode[\"declarations\"],\n indent: string,\n newline: string,\n): string => {\n if (!declarations.length) return \"\";\n return declarations.map(({ property, value }) => `${indent}${property}: ${value};`).join(newline);\n};\n\n/** Render a keyframes at-rule body: one indented `<stop> { … }` block per step, in order. */\nconst renderKeyframesBody = (\n node: CssKeyframesNode,\n indent: string,\n newline: string,\n): string => {\n const steps = node.steps\n .map(step => {\n if (!step.declarations.length) return \"\";\n const decls = step.declarations\n .map(({ property, value }) => `${indent}${indent}${property}: ${value};`)\n .join(newline);\n return `${indent}${step.stop} {${newline}${decls}${newline}${indent}}`;\n })\n .filter(Boolean);\n return steps.join(newline);\n};\n\nconst indentBlock = (block: string, indent: string, newline: string): string =>\n block\n .split(newline)\n .map(line => (line.length ? `${indent}${line}` : line))\n .join(newline);\n\n// ---------------------------------------------------------------------------\n// split / render slices\n// ---------------------------------------------------------------------------\n\nexport const splitNodes = (nodes: CssNode[]): {\n variables: CssVariablesNode[];\n rules: CssNode[];\n} => {\n const variables: CssVariablesNode[] = [];\n const rules: CssNode[] = [];\n for (const node of nodes) {\n // Keyframes ride the rules stream (they are style output, never a variables block).\n if (node.kind === \"variables\") variables.push(node);\n else rules.push(node);\n }\n return { variables, rules };\n};\n\nexport const renderVariablesCss = (nodes: CssNode[]): string =>\n renderToCssString(splitNodes(nodes).variables);\n\nexport const renderRulesCss = (nodes: CssNode[]): string =>\n renderToCssString(splitNodes(nodes).rules);\n\n// ---------------------------------------------------------------------------\n// enrich (ref / resolved) — used by inline delivery\n// ---------------------------------------------------------------------------\n\nconst VAR_PATTERN = /var\\((--[^)]+)\\)/;\n\n/**\n * Build the `var name → resolved literal value` map from a node set's variable blocks: direct\n * literals first, then a second pass resolving one level of `var(--…)` indirection. Shared by\n * `enrichDeclarationsWithRefs` (inline baking) and the `components` non-inline tree-shaken\n * variables file, so both source values the same way (no re-derived formatting).\n */\nexport const buildVariableValueMap = (nodes: CssNode[]): Map<string, string> => {\n const variableMap = new Map<string, string>();\n for (const node of nodes) {\n if (node.kind !== \"variables\") continue;\n for (const [name, value] of Object.entries(node.variables)) {\n if (!VAR_PATTERN.test(value)) variableMap.set(name, value);\n }\n }\n\n for (const node of nodes) {\n if (node.kind !== \"variables\") continue;\n for (const [name, value] of Object.entries(node.variables)) {\n if (variableMap.has(name)) continue;\n const match = value.match(VAR_PATTERN);\n if (match) {\n const resolved = variableMap.get(match[1]);\n if (resolved) variableMap.set(name, resolved);\n }\n }\n }\n\n return variableMap;\n};\n\n/**\n * Enrich `CssRuleNode` declarations with `ref` (the CSS var they reference) and `resolved`\n * (its literal value), cross-referenced against the variable nodes. Mutates in place.\n */\nexport const enrichDeclarationsWithRefs = (nodes: CssNode[]): void => {\n const variableMap = buildVariableValueMap(nodes);\n\n const enrich = (decl: CssRuleNode[\"declarations\"][number]): void => {\n if (typeof decl.value !== \"string\") return;\n const match = decl.value.match(VAR_PATTERN);\n if (!match) return;\n decl.ref = match[1];\n const resolved = variableMap.get(match[1]);\n if (resolved !== undefined) decl.resolved = resolved;\n };\n\n for (const node of nodes) {\n if (node.kind === \"keyframes\") {\n for (const step of node.steps) for (const decl of step.declarations) enrich(decl);\n continue;\n }\n if (node.kind !== \"rule\") continue;\n for (const decl of node.declarations) enrich(decl);\n }\n};\n","/**\n * The CSS adapter — lowers the format-neutral {@link ThemeModel} to CSS.\n *\n * `bind(model, ctx)` curries the Model + context once, precomputes the per-subsystem\n * `CssNode[]` lowering (variables + recipe rules + class minting), and returns the render\n * surface (`recipeName` / `renderRecipe` / `renderVariables` / `join`) plus the aggregate\n * outputs the theme surfaces (`css` / `variablesCss` / `recipesCss` / `nodes` / `classes`)\n * via `extend`. Core stays CSS-independent; all naming, the node IR, state selectors, and\n * class minting live here.\n */\nimport type { ThemeModel } from \"@theme-registry/refract\";\nimport { mergeComponentRuleSet } from \"@theme-registry/refract\";\nimport { toHexColor, toOklchColor } from \"@theme-registry/refract/color-math\";\nimport type { AdapterSpec, RenderContext, ThemeAdapter, UsageRecipe } from \"@theme-registry/refract\";\nimport { defineAdapter } from \"@theme-registry/refract\";\nimport type { CssDeclaration, CssNode, CssRuleNode, CssVariablesNode } from \"./nodes\";\nimport {\n deriveColorsVariableNodes,\n buildColorsPathToVar,\n deriveTypographyVariableNodes,\n buildTypographyPathToVar,\n deriveEffectsVariableNodes,\n buildEffectsPathToVar,\n deriveBordersVariableNodes,\n buildBordersPathToVar,\n deriveAnimationVariableNodes,\n buildAnimationPathToVar,\n deriveLayoutVariableNodes,\n deriveLayoutConfigVariableNodes,\n buildLayoutPathToVar,\n splitLayoutProperties,\n lowerRecipeGroup,\n lowerContainerGroup,\n lowerMergedRuleSet,\n lowerGlobalsGroups,\n lowerKeyframes,\n lowerAnimationRecipeGroup,\n deriveContainerContextNodes,\n CSS_KNOWN_STATES,\n} from \"./lowering\";\nimport { resolveNaming, createNamer } from \"./naming\";\nimport type { NamingOverrides } from \"./naming\";\nimport {\n renderToCssString,\n renderVariablesCss,\n renderRulesCss,\n enrichDeclarationsWithRefs,\n buildVariableValueMap,\n} from \"./render\";\n\n/** CSS adapter options — two naming knobs (variables + classes) + value/delivery knobs (§18). */\nexport type CssAdapterOptions = {\n /**\n * Identifier prefix for every CSS **variable** name (`--<prefix>-colors-primary`). Default `dt`.\n * Subsystems are namespaced by the token path, not by separate options. For MFE isolation (two\n * bundles on one page), give each build a distinct `prefix` — that renames its variables without\n * touching another bundle's.\n */\n prefix?: string;\n /**\n * Class-name prefix for every **class** the adapter emits — recipe classes\n * (`.<classPrefix>-colors-solid-primary`) AND the container-query context classes\n * (`.<classPrefix>-cq-<name>`). Defaults to `prefix`.\n */\n classPrefix?: string;\n /** Inline resolved values instead of `var(--…)` references (drops the variable blocks). */\n inline?: boolean;\n /**\n * Output format for **palette colour** values in the emitted CSS (§20) — the `:root` colour\n * variables (base / `text` / variants / responsive / modes). `\"rgb\"` (default) emits\n * `rgb()`/`rgba()`; `\"hex\"` emits `#rrggbb`/`#rrggbbaa`; `\"oklch\"` emits CSS Color 4\n * `oklch(L% C H)`. The colour is identical — this is presentation only. Colours typed literally\n * into a recipe declaration pass through as authored; this applies to the synthesized tokens.\n */\n colorFormat?: \"rgb\" | \"hex\" | \"oklch\";\n /**\n * §7B — swap how class + variable names are generated. Two optional formatters (`className` /\n * `variableName`), each receiving the structured address + the built-in default (decorate or\n * replace). Omit it and naming is byte-identical to the default. The adapter enforces the contract:\n * deterministic (a pure fn of the address), collision-free (a duplicate output throws), and a valid\n * identifier (run through the segment sanitizer). Covers recipe classes AND the `-cq-<name>`\n * container-context utilities (via the `kind` discriminator).\n */\n naming?: NamingOverrides;\n /**\n * §W9 — wrap all emitted CSS in a named cascade `@layer`. `true` uses the layer name `\"refract\"`; a\n * string sets a custom name (e.g. `\"refract.recipes\"`). Off by default (byte-identical output). A\n * cascade layer gives refract's rules **deterministic precedence** below any unlayered app CSS or\n * utility framework, regardless of load order — the modern answer to source-order fragility. All\n * output (variables, globals, recipes) rides one layer; author your app CSS unlayered (or in a\n * later-declared layer) to win. Applies to single-file emit and the runtime `theme.css` surface.\n */\n layer?: string | boolean;\n /**\n * §W-motion — append a `@media (prefers-reduced-motion: reduce)` block that neutralizes animation +\n * transition durations for users who ask for less motion (the well-known global reset). Off by\n * default (byte-identical); opt in for an accessible default. Emitted outside any `layer` so its\n * `!important` behaves predictably. Applies to single-file emit and the runtime `theme.css` surface.\n */\n reducedMotion?: boolean;\n};\n\n/**\n * §W-motion — the standard \"kill motion\" block for `prefers-reduced-motion: reduce`. Appended to the\n * full document when the `reducedMotion` option is on.\n */\nconst REDUCED_MOTION_BLOCK =\n \"@media (prefers-reduced-motion: reduce) {\\n\" +\n \" *, *::before, *::after {\\n\" +\n \" animation-duration: 0.01ms !important;\\n\" +\n \" animation-iteration-count: 1 !important;\\n\" +\n \" transition-duration: 0.01ms !important;\\n\" +\n \" scroll-behavior: auto !important;\\n\" +\n \" }\\n\" +\n \"}\\n\";\n\n/** `.cls`, `.cls:state`, `.cls[attr]` all belong to the recipe whose base selector is `.cls`. */\nconst selectorBelongsToRecipe = (nodeSelector: string, base: string): boolean =>\n nodeSelector === base || nodeSelector.startsWith(`${base}:`) || nodeSelector.startsWith(`${base}[`);\n\ntype SubsystemLowering = {\n variableNodes: CssVariablesNode[];\n /** Class rules — plus, for animation, its `@keyframes` at-rule nodes (they ride the rules stream). */\n recipeNodes: CssNode[];\n /** group → variant → selector (`.dt-color-solid-primary`). */\n selectors: Record<string, Record<string, string>>;\n};\n\n/** The resolved composition class for one component variant (referenced classes + own delta). */\ntype ResolvedComponentClass = { className: string; classList: string[] };\n\n/** Parse a component reference (`\"colors:solid.primary\"`) into its address parts. */\nconst parseComponentReference = (\n reference: string,\n): { subsystem: string; group: string; variant: string } | undefined => {\n const [subsystem, rest] = reference.split(\":\");\n if (!subsystem || !rest) return undefined;\n const dot = rest.indexOf(\".\");\n if (dot < 0) return undefined;\n return { subsystem, group: rest.slice(0, dot), variant: rest.slice(dot + 1) };\n};\n\nexport const createCssAdapter = (options: CssAdapterOptions = {}): ThemeAdapter<string> => {\n const spec: AdapterSpec<string> = {\n name: \"css\",\n version: 1,\n // The CSS adapter owns the known-state set; core threads it into recipe normalization.\n allowedStates: CSS_KNOWN_STATES,\n bind(model: ThemeModel, ctx: RenderContext) {\n const media = ctx.media;\n const inline = options.inline ?? false;\n // §21: length units are resolved format-neutrally in core (`createTheme({ units })`) and baked\n // onto the Model's length leaves — the adapter only stringifies `value + unit`. No `length` here.\n // §17: the single adapter-wide naming pair. `varToken` leads every variable, `naming` drives\n // every recipe class (`.<classToken>-<subsystem>-<group>-<variant>`).\n const naming = resolveNaming({ prefix: options.prefix, classPrefix: options.classPrefix });\n // §7B: the override-aware namer owns the two pure choke points (var + class naming) plus the\n // collision Set. `varName` (a token path → its var name) threads through the variable lowering\n // in place of the raw `varToken`; `namer.className` mints every recipe + container-context class.\n const namer = createNamer(naming, options.naming);\n const varName = namer.variableName;\n\n // §20: palette-colour output format. `rgb` (default) passes the Model's canonical value\n // through unchanged; `hex` / `oklch` re-serialize the same colour for the emitted CSS vars.\n const colorFormat = options.colorFormat ?? \"rgb\";\n const formatColor = (value: unknown): string => {\n const s = value == null ? \"\" : String(value);\n if (!s || colorFormat === \"rgb\") return s;\n return colorFormat === \"hex\" ? toHexColor(s) : toOklchColor(s);\n };\n\n // ── Per-subsystem lowering (colors / typography / effects / layout / components) ──\n const lowered: Record<string, SubsystemLowering> = {};\n // Global token-path → var union (all subsystems): a component `css` delta can reference any\n // subsystem's token, so its refs must resolve against every subsystem's naming.\n const globalPathToVar: Record<string, string> = {};\n\n // Shared recipe loop: every subsystem lowers its rule-set groups the same way — the recipe\n // class name is uniform (`<classToken>-<subsystem>-<group>-<variant>`); only the token-path→var\n // map differs (some subsystems resolve refs against the global union).\n const lowerRecipes = (\n subsystem: string,\n ruleSets: NonNullable<ThemeModel[\"subsystems\"][string][\"ruleSets\"]>,\n pathToVar: Record<string, string>,\n ): { recipeNodes: CssRuleNode[]; selectors: Record<string, Record<string, string>> } => {\n const recipeNodes: CssRuleNode[] = [];\n const selectors: Record<string, Record<string, string>> = {};\n for (const [group, ruleSetGroup] of Object.entries(ruleSets)) {\n const { nodes, variants } = lowerRecipeGroup(ruleSetGroup, {\n media,\n selectorBuilder: variant => `.${namer.className(\"recipe\", subsystem, group, variant)}`,\n pathToVar,\n containers: ctx.containers,\n });\n recipeNodes.push(...nodes);\n selectors[group] = variants;\n }\n return { recipeNodes, selectors };\n };\n\n const colors = model.subsystems.colors;\n if (colors) {\n const props = colors.properties ?? {};\n const pathToVar = buildColorsPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const variableNodes = deriveColorsVariableNodes(props, { varName, media, formatColor });\n const { recipeNodes, selectors } = lowerRecipes(\"colors\", colors.ruleSets ?? {}, pathToVar);\n lowered.colors = { variableNodes, recipeNodes, selectors };\n }\n\n const typography = model.subsystems.typography;\n if (typography) {\n const props = typography.properties ?? {};\n const pathToVar = buildTypographyPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const variableNodes = deriveTypographyVariableNodes(props, { varName, media });\n const { recipeNodes, selectors } = lowerRecipes(\"typography\", typography.ruleSets ?? {}, pathToVar);\n lowered.typography = { variableNodes, recipeNodes, selectors };\n }\n\n const effects = model.subsystems.effects;\n if (effects) {\n const props = effects.properties ?? {};\n const pathToVar = buildEffectsPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n // §15: shadow/transition tokens compose from structure; a layer's `colors.*` color ref\n // resolves via the global map (colors processed first — the §14.4 cross-subsystem rule).\n const variableNodes = deriveEffectsVariableNodes(props, { varName, media, pathToVar: globalPathToVar });\n const { recipeNodes, selectors } = lowerRecipes(\"effects\", effects.ruleSets ?? {}, pathToVar);\n lowered.effects = { variableNodes, recipeNodes, selectors };\n }\n\n // ── Borders (§14): stroke geometry tokens (width/style/offset/radius) → `:root` vars, and\n // border/outline recipes → classes. A borders recipe declaration may carry a value-level\n // `colors.*` ref (border-color/outline-color, §14.4) — so its declarations resolve against\n // `globalPathToVar` (colors is processed first, its path→var already merged) rather than the\n // subsystem-local map, which only knows `borders.*`. ──\n const borders = model.subsystems.borders;\n if (borders) {\n const props = borders.properties ?? {};\n const pathToVar = buildBordersPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const variableNodes = deriveBordersVariableNodes(props, { varName, media });\n const { recipeNodes, selectors } = lowerRecipes(\"borders\", borders.ruleSets ?? {}, globalPathToVar);\n lowered.borders = { variableNodes, recipeNodes, selectors };\n }\n\n // ── Layout: regular vars + config `:root` vars, structural rule-sets (columns/grids/stacks\n // via lowerRecipeGroup, container via the two-pass lowerContainerGroup) + padding recipes ──\n const layout = model.subsystems.layout;\n if (layout) {\n const props = layout.properties ?? {};\n const pathToVar = buildLayoutPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const { regular, config } = splitLayoutProperties(props);\n\n const variableNodes = [\n ...deriveLayoutVariableNodes(regular, { varName, media }),\n ...deriveLayoutConfigVariableNodes(config, { varName, pathToVar }),\n ];\n\n const recipeNodes: CssRuleNode[] = [];\n const selectors: Record<string, Record<string, string>> = {};\n for (const [group, ruleSetGroup] of Object.entries(layout.ruleSets ?? {})) {\n // Structural groups (columns/grids/stacks/container) + padding recipes all take the uniform\n // recipe class `.<ct>-layout-<group>-<variant>` (§17).\n const selectorBuilder = (variant: string) =>\n `.${namer.className(\"recipe\", \"layout\", group, variant)}`;\n const lower = group === \"container\" ? lowerContainerGroup : lowerRecipeGroup;\n const { nodes, variants } = lower(ruleSetGroup, { media, selectorBuilder, pathToVar, containers: ctx.containers });\n recipeNodes.push(...nodes);\n selectors[group] = variants;\n }\n lowered.layout = { variableNodes, recipeNodes, selectors };\n }\n\n // ── Animation (§10.2): motion tokens (duration/easing/delay) → `:root` vars, keyframes →\n // `@keyframes` at-rules, animation recipes → a class with the composed `animation:`\n // shorthand. Processed after the base subsystems so keyframe step refs (e.g. `colors.*`)\n // resolve against the global path→var union. ──\n const animation = model.subsystems.animation;\n if (animation) {\n const props = animation.properties ?? {};\n const pathToVar = buildAnimationPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const variableNodes = deriveAnimationVariableNodes(props, { varName, media });\n\n const keyframes = animation.keyframes ?? {};\n const keyframeNodes = lowerKeyframes(keyframes, globalPathToVar);\n const keyframeNames = new Set(Object.keys(keyframes));\n\n const recipeNodes: CssNode[] = [...keyframeNodes];\n const selectors: Record<string, Record<string, string>> = {};\n for (const [group, ruleSetGroup] of Object.entries(animation.ruleSets ?? {})) {\n const { nodes, variants } = lowerAnimationRecipeGroup(ruleSetGroup, {\n media,\n selectorBuilder: variant => `.${namer.className(\"recipe\", \"animation\", group, variant)}`,\n pathToVar: globalPathToVar,\n keyframeNames,\n containers: ctx.containers,\n });\n recipeNodes.push(...nodes);\n selectors[group] = variants;\n }\n lowered.animation = { variableNodes, recipeNodes, selectors };\n }\n\n // ── Components (composition): no properties/variables — only recipes that reference other\n // subsystems' recipes (kept as Model `references`) + an own `css` delta on its own class.\n // The className list = the referenced recipe classes (looked up from the already-lowered\n // subsystems' selectors, so their `:hover` etc. ride along) + the own delta class. ──\n const componentClasses: Record<string, Record<string, ResolvedComponentClass>> = {};\n const components = model.subsystems.components;\n if (components) {\n const recipeNodes: CssRuleNode[] = [];\n const selectors: Record<string, Record<string, string>> = {};\n\n const resolveReferencedClass = (reference: string): string | undefined => {\n const parsed = parseComponentReference(reference);\n if (!parsed) return undefined;\n const selector = lowered[parsed.subsystem]?.selectors[parsed.group]?.[parsed.variant];\n return selector?.replace(/^\\./, \"\");\n };\n\n for (const [group, ruleSetGroup] of Object.entries(components.ruleSets ?? {})) {\n const { nodes, variants } = lowerRecipeGroup(ruleSetGroup, {\n media,\n selectorBuilder: variant => `.${namer.className(\"recipe\", \"components\", group, variant)}`,\n pathToVar: globalPathToVar,\n containers: ctx.containers,\n });\n recipeNodes.push(...nodes);\n selectors[group] = variants;\n\n componentClasses[group] = {};\n for (const [variant, ruleSet] of Object.entries(ruleSetGroup)) {\n const ownClass = variants[variant].replace(/^\\./, \"\");\n const referenced = (ruleSet.references ?? [])\n .map(resolveReferencedClass)\n .filter((cls): cls is string => cls !== undefined);\n const classList = [...referenced, ownClass];\n componentClasses[group][variant] = { className: classList.join(\" \"), classList };\n }\n }\n\n lowered.components = { variableNodes: [], recipeNodes, selectors };\n }\n\n // ── Globals (§9): preset `kind:\"reset\"` layers → `:where(sel){…}`; themed `kind:\"globals\"`\n // elements → bare `sel{…}` + `sel:state` + `sel.<variant>`. No properties/variables.\n // Lowered LAST (globalPathToVar now holds every subsystem's tokens) so its themed refs\n // resolve against them, then HOISTED ahead of all recipes in collectNodes. ──\n const globals = model.subsystems.globals;\n if (globals) {\n const recipeNodes = lowerGlobalsGroups(globals.ruleSets ?? {}, globalPathToVar, media, ctx.containers);\n lowered.globals = { variableNodes: [], recipeNodes, selectors: {} };\n }\n\n // ── Container context (§10.5): the `.dt-cq-<name>` utility classes that establish each named\n // containment context. Named via the §7B `kind:\"container\"` namer (default\n // `<classToken>-cq-<name>`); the `@container` rules that respond to them are lowered inline\n // on each recipe (via ctx.containers). The same `containerClass` fn feeds `theme.classes`. ──\n const containerClass = (name: string): string =>\n namer.className(\"container\", \"containers\", \"context\", name);\n const containerContextNodes = deriveContainerContextNodes(model.containers, containerClass);\n\n // ── Aggregate node collection (reset first, then container-context classes, then variables +\n // recipes per subsystem, in Model order). Reset's specificity-0 `:where()` rules lead so they\n // never fight recipe classes. ──\n const collectNodes = (): CssNode[] => {\n const nodes: CssNode[] = [];\n if (lowered.globals) nodes.push(...lowered.globals.recipeNodes);\n nodes.push(...containerContextNodes);\n for (const key of Object.keys(model.subsystems)) {\n if (key === \"globals\") continue;\n const sub = lowered[key];\n if (!sub) continue;\n nodes.push(...sub.variableNodes, ...sub.recipeNodes);\n }\n enrichDeclarationsWithRefs(nodes);\n return nodes;\n };\n\n // §W9 / §W-motion — full-document post-processing (single emit + runtime `css`): optional cascade\n // `@layer` wrap, then an optional `prefers-reduced-motion` block (outside the layer). Both off →\n // byte-identical.\n const layerName =\n options.layer === true ? \"refract\" : (typeof options.layer === \"string\" && options.layer) || undefined;\n const reducedMotion = options.reducedMotion ?? false;\n const finalizeDoc = (css: string): string => {\n let out = css;\n if (layerName) {\n const body = css\n .trimEnd()\n .split(\"\\n\")\n .map(line => (line ? ` ${line}` : line))\n .join(\"\\n\");\n out = `@layer ${layerName} {\\n${body}\\n}\\n`;\n }\n if (reducedMotion) out = `${out.trimEnd()}\\n\\n${REDUCED_MOTION_BLOCK}`;\n return out;\n };\n\n // ── Delivery-mode CSS rendering (default / inline) ──\n const renderCss = (nodes: CssNode[]): string => {\n if (!inline) return renderToCssString(nodes);\n // Bake resolved values into rule + keyframe declarations; drop the variable blocks. Resolve\n // EACH `var(--…)` within a value (not just the first) so a composed shorthand — e.g. the\n // animation `duration easing name` — bakes every part; single-var declarations are unchanged.\n const varMap = buildVariableValueMap(nodes);\n const bake = (decl: CssDeclaration): CssDeclaration => {\n if (typeof decl.value !== \"string\") return { property: decl.property, value: decl.value };\n const value = decl.value.replace(/var\\((--[^)]+)\\)/g, (whole, name: string) => {\n const resolved = varMap.get(name);\n return resolved !== undefined ? String(resolved) : whole;\n });\n return { property: decl.property, value };\n };\n const inlined: CssNode[] = [];\n for (const n of nodes) {\n if (n.kind === \"rule\") {\n inlined.push({ ...n, declarations: n.declarations.map(bake) });\n } else if (n.kind === \"keyframes\") {\n inlined.push({ ...n, steps: n.steps.map(s => ({ stop: s.stop, declarations: s.declarations.map(bake) })) });\n }\n }\n return renderToCssString(inlined);\n };\n\n // ── classes: subsystem → group → variant → className. Recipe subsystems map to the plain\n // class string; the composition subsystem maps to `{ className, classList }` (referenced\n // recipe classes + own delta), matching the OLD ResolvedComponentClass shape. ──\n const collectClasses = (): Record<string, Record<string, Record<string, unknown>>> => {\n const out: Record<string, Record<string, Record<string, unknown>>> = {};\n for (const [key, sub] of Object.entries(lowered)) {\n if (key === \"globals\") continue; // globals targets raw selectors — no minted classes\n if (key === \"components\") {\n out[key] = componentClasses;\n continue;\n }\n const groups: Record<string, Record<string, string>> = {};\n for (const [group, variants] of Object.entries(sub.selectors)) {\n groups[group] = Object.fromEntries(\n Object.entries(variants).map(([variant, selector]) => [variant, selector.replace(/^\\./, \"\")]),\n );\n }\n out[key] = groups;\n }\n // Container-context utility classes (§10.5): `containers.<name> → \".dt-cq-<name>\"` (no leading dot).\n if (model.containers && Object.keys(model.containers).length) {\n const containerGroup: Record<string, string> = {};\n for (const name of Object.keys(model.containers)) {\n containerGroup[name] = containerClass(name);\n }\n out.containers = { context: containerGroup };\n }\n return out;\n };\n\n const selectorFor = (subsystem: string, group: string, variant: string): string | undefined =>\n lowered[subsystem]?.selectors[group]?.[variant];\n\n // Class-name accessor mirroring `theme.classes` (single source of truth): the plain recipe\n // class for normal subsystems, and the space-joined composition string (`className`) for\n // `components` and the `containers.context.*` utilities. Returns `undefined` for an\n // unknown subsystem/group/variant address.\n const getClass = (subsystem: string, group: string, variant: string): string | undefined => {\n const leaf = collectClasses()[subsystem]?.[group]?.[variant];\n if (leaf === undefined) return undefined;\n return typeof leaf === \"string\" ? leaf : (leaf as ResolvedComponentClass).className;\n };\n\n // Per-recipe delivery: the subsystem's own rules for one variant (base + its state/breakpoint\n // rules — `selectorBelongsToRecipe` keeps `.cls`, `.cls:hover`, `.cls[disabled]`).\n const renderRecipe = (subsystem: string, group: string, variant: string): string => {\n const sub = lowered[subsystem];\n const base = selectorFor(subsystem, group, variant);\n if (!sub || !base) return \"\";\n const nodes = sub.recipeNodes.filter(\n (n): n is CssRuleNode => n.kind === \"rule\" && selectorBelongsToRecipe(n.selector, base),\n );\n return renderCss(nodes);\n };\n\n return {\n recipeName(subsystem, group, variant) {\n return (selectorFor(subsystem, group, variant) ?? \"\").replace(/^\\./, \"\");\n },\n renderRecipe,\n renderVariables(subsystem) {\n return renderToCssString(lowered[subsystem]?.variableNodes ?? []);\n },\n join(parts) {\n return parts.filter(Boolean).join(\"\\n\\n\");\n },\n\n // Aggregators overridden so the full document renders through the node IR (delivery-aware).\n renderAllVariables: () => renderVariablesCss(collectNodes()),\n renderAllRecipes: () => renderRulesCss(collectNodes()),\n renderAll: () => finalizeDoc(renderCss(collectNodes())),\n\n // Self-documentation: the REAL class names (composition strings for components) via getClass,\n // plus CSS-specific consumption prose for the emitted guide (llms.txt).\n describeUsage() {\n const recipes: UsageRecipe[] = [];\n for (const [subsystem, sub] of Object.entries(model.subsystems)) {\n for (const [group, ruleSet] of Object.entries(sub.ruleSets ?? {})) {\n for (const variant of Object.keys(ruleSet)) {\n const name = getClass(subsystem, group, variant);\n if (name) recipes.push({ subsystem, group, variant, name });\n }\n }\n }\n return {\n format: \"css\",\n summary: [\n \"Import the stylesheet once, then apply the recipe class names below to your elements.\",\n 'Example: `import \"./theme.css\";` then `<button class=\"<class>\">`.',\n \"Values are CSS custom properties (`var(--…)`), so runtime theming = override the variables under a selector or `[data-theme]`.\",\n ],\n recipes,\n };\n },\n\n // Human-facing preview (§20): CSS is the one format a browser loads as-is, so this is where\n // the live recipe plates come from. Both answers depend on the PLAN, which is why it's an\n // argument: `split` has a load-order contract (variables first), `subsystem`/`components`\n // name files through a user-supplied function, and `components` emits merged self-contained\n // rules keyed by the recipe's OWN class rather than the composition list every other mode uses.\n describePreview(plan, files) {\n const written = new Set(files);\n const keep = (...names: Array<string | false | undefined>): string[] =>\n names.filter((n): n is string => typeof n === \"string\" && written.has(n));\n\n // `components` emits ONLY the components subsystem, so every other subsystem's recipes have\n // no CSS in this output — listing them as renderable would be a lie.\n const renderable = (r: UsageRecipe): boolean =>\n plan.type !== \"components\" || r.subsystem === \"components\";\n\n const markup = (r: UsageRecipe) => {\n if (!renderable(r)) return undefined;\n // components mode: the merged rule targets the own class; every other mode wants the full\n // composition list `getClass` returns.\n const name =\n plan.type === \"components\"\n ? (selectorFor(r.subsystem, r.group, r.variant) ?? \"\").replace(/^\\./, \"\")\n : getClass(r.subsystem, r.group, r.variant);\n return name ? { attrs: { class: name } } : undefined;\n };\n\n const base = { markup, modeAttribute: \"data-theme\" } as const;\n\n switch (plan.type) {\n case \"single\":\n return { ...base, stylesheets: keep(plan.file) };\n\n case \"split\":\n // Load-order contract — the styles file references vars the variables file defines.\n return { ...base, stylesheets: keep(plan.variables, plan.file) };\n\n case \"subsystem\": {\n // Every subsystem's variables before any rules, for the same reason. Names come from the\n // plan's `filename` fn but are intersected with what was actually written.\n const subsystems = Object.keys(model.subsystems);\n return {\n ...base,\n stylesheets: [\n ...keep(...subsystems.map(s => plan.filename(s, \"variables\"))),\n ...keep(...subsystems.map(s => plan.filename(s, \"styles\"))),\n ],\n groupBy: r => r.subsystem,\n };\n }\n\n case \"components\": {\n const componentFile = (r: UsageRecipe): string =>\n plan.filename({ group: r.group, variant: r.variant });\n const variables = plan.variables === false ? [] : keep(plan.variables);\n // Every component file, in emit order, after the variables file (if any).\n const componentFiles = files.filter(f => !variables.includes(f));\n return {\n ...base,\n stylesheets: [...variables, ...componentFiles],\n groupBy: r => (renderable(r) ? componentFile(r) : \"not emitted in components mode\"),\n notes:\n plan.variables === false && plan.inline === false\n ? [\n \"This target emits component rules that reference CSS variables but no variables \" +\n \"file (`variables: false`), so the preview renders them undefined — supply the \" +\n \"variables yourself in the consuming app.\",\n ]\n : undefined,\n };\n }\n }\n },\n\n // Surface the CSS-named aggregate outputs on the theme (computed on demand — no stored bag),\n // plus `theme.media` = the plain core descriptor pass-through (an SC adapter would wrap it).\n extend() {\n return {\n media,\n // Per-recipe delivery helper: `theme.renderRecipe(subsystem, group, variant)` → that one\n // recipe's own CSS (base + its state/breakpoint rules). Bound to the model/ctx already.\n renderRecipe,\n // Class-name accessor: `theme.getClass(subsystem, group, variant)` → the class string you\n // drop into markup (composition classes joined for `components`). Mirrors `theme.classes`.\n getClass,\n // Token-var accessor: `theme.varName(\"colors.brand.dark\")` → its emitted CSS custom-property\n // name (`--dt-colors-brand-dark`, carrying the configured prefix), or `undefined` for a path\n // that mints no variable. The most useful question a CSS consumer/agent can ask a token path.\n varName: (path: string): string | undefined => globalPathToVar[path],\n get css() {\n return finalizeDoc(renderCss(collectNodes()));\n },\n get variablesCss() {\n return renderVariablesCss(collectNodes());\n },\n get recipesCss() {\n return renderRulesCss(collectNodes());\n },\n get nodes() {\n return collectNodes();\n },\n get classes() {\n return collectClasses();\n },\n };\n },\n\n // Self-contained build-time output: the full stylesheet (baked CSS variables + rules) a\n // downstream app links directly. The CSS adapter needs no *theme-specific* runtime helper of\n // its own, so `vendorHelpers` is empty — shared static helpers like `color-math` (the pure\n // `lighten`/`darken`) are vendored by the build layer from their single source (see\n // `src/build/vendor.ts`), not re-embedded here. (Adapters only emit vendorHelpers for helpers\n // whose source is theme-specific, e.g. the SC media module with baked `@media` strings.)\n emit(plan) {\n // `single` (the default when no plan is threaded) → one file, `plan.file` (default\n // theme.css). split / subsystem lower here (9b) by reusing the aggregate renderers over\n // the shared, ref-enriched node set; components lands in 9d–9e and still fails loud.\n const type = plan?.type ?? \"single\";\n\n // §W9 / §W-motion — the `layer` wrap + `reducedMotion` block target one self-contained\n // document; the multi-file modes split the cascade, so fail loud rather than emit a partial result.\n if ((layerName || reducedMotion) && type !== \"single\") {\n const opt = layerName ? \"layer\" : \"reducedMotion\";\n throw new Error(\n `The \\`${opt}\\` option is only supported with single-file emit (got \"${type}\"). ` +\n `Emit one file, or drop \\`${opt}\\` for split/subsystem/components.`,\n );\n }\n\n if (type === \"single\") {\n const file = plan?.type === \"single\" ? plan.file : \"theme.css\";\n return { files: { [file]: finalizeDoc(renderCss(collectNodes())) } };\n }\n\n // `inline` bakes resolved values into the rules, leaving NO variables to emit — which\n // contradicts every multi-file mode (each writes a separate variables file/side). Fail\n // loud rather than silently dropping the variables the author asked to split out.\n if (inline && (type === \"split\" || type === \"subsystem\")) {\n throw new Error(\n `css adapter: emit mode '${type}' cannot be combined with the global inline option ` +\n `(inline bakes values, leaving no variables file)`,\n );\n }\n\n if (plan?.type === \"split\") {\n // Two files under a load-order contract — NO `@import` (that re-joins what we split).\n // The styles file references vars by name and assumes the variables file loads first.\n const nodes = collectNodes();\n return {\n files: {\n [plan.file]: renderRulesCss(nodes),\n [plan.variables]: renderVariablesCss(nodes),\n },\n };\n }\n\n if (plan?.type === \"subsystem\") {\n // Per subsystem: its variables → `<sub>.variables.css`, its recipes → `<sub>.css`.\n // Enrich ONCE over the whole set (collectNodes mutates the lowered[key] node objects in\n // place, so cross-subsystem refs survive), then render each subsystem's slice. Skip\n // empties — the components subsystem owns no properties → styles file only.\n collectNodes();\n const files: Record<string, string> = {};\n for (const key of Object.keys(model.subsystems)) {\n const sub = lowered[key];\n if (!sub) continue;\n const variablesCss = renderVariablesCss(sub.variableNodes);\n const stylesCss = renderRulesCss(sub.recipeNodes);\n if (variablesCss) files[plan.filename(key, \"variables\")] = variablesCss;\n if (stylesCss) files[plan.filename(key, \"styles\")] = stylesCss;\n }\n return { files };\n }\n\n if (plan?.type === \"components\") {\n // The flattened/merged export: each component variant is lowered to ONE self-contained\n // rule (its referenced recipes' declarations + own `css` delta, merged in core by\n // `mergeComponentRuleSet`), rendered with baked values — zero `var(`, dependency-free.\n //\n // `inline` is the plan-level control (defaults true). The global adapter `inline` option\n // is irrelevant here — the plan decides.\n const componentRuleSets = model.subsystems.components?.ruleSets ?? {};\n\n // The subsystem variable nodes are the value source for BOTH paths: inline baking resolves\n // each merged `var(--…)` ref to its formatted value (`20px`, `#4dabf7`, …); non-inline\n // sources the tree-shaken variables file from the same map (no re-derived formatting).\n const variableNodes: CssVariablesNode[] = [];\n for (const key of Object.keys(model.subsystems)) {\n const sub = lowered[key];\n if (sub) variableNodes.push(...sub.variableNodes);\n }\n\n if (plan.inline === false) {\n // ── NON-INLINE (9e): merged rules rendered with `var(--…)` refs (NO enrich/bake) into\n // the styles file(s) — same filename bundling as inline — plus a tree-shaken variables\n // file defining ONLY the tokens the exported components reference (union of every\n // variant's `referencedPaths`), so every emitted `var(--…)` resolves. Load-order\n // contract — NO `@import`. ──\n const filesByName: Record<string, string[]> = {};\n const orderedVarNames: string[] = [];\n const referencedVars = new Set<string>();\n\n for (const [group, ruleSetGroup] of Object.entries(componentRuleSets)) {\n for (const variant of Object.keys(ruleSetGroup)) {\n const merged = mergeComponentRuleSet(model, group, variant);\n const selector = lowered.components?.selectors[group]?.[variant];\n if (!selector) continue;\n\n const ruleNodes = lowerMergedRuleSet(merged, { selector, media, pathToVar: globalPathToVar, containers: ctx.containers });\n const filename = plan.filename({ group, variant });\n (filesByName[filename] ??= []).push(renderToCssString(ruleNodes));\n\n // Tree-shake set: referenced token paths → var names, stable first-appearance order.\n for (const path of merged.referencedPaths) {\n const varName = globalPathToVar[path];\n if (varName && !referencedVars.has(varName)) {\n referencedVars.add(varName);\n orderedVarNames.push(varName);\n }\n }\n }\n }\n\n const files: Record<string, string> = {};\n for (const [name, parts] of Object.entries(filesByName)) files[name] = parts.join(\"\\n\\n\");\n\n // Tree-shaken variables file, unless `variables: false` (consumer supplies the vars).\n // Base `:root` = resolved literal per referenced var (reusing the enrichment value map —\n // built from the non-responsive nodes so base values aren't shadowed by overrides); then\n // any responsive `:root` @media override blocks, filtered to the referenced var names\n // (keeps breakpoint theming). Covered by the §11.5 responsive-overrides emit test\n // (the `responsiveComponents` fixture drives a component → responsive property var).\n if (plan.variables !== false) {\n const baseValueMap = buildVariableValueMap(variableNodes.filter(n => !n.media));\n const baseVars: Record<string, string> = {};\n for (const name of orderedVarNames) {\n const value = baseValueMap.get(name);\n if (value !== undefined) baseVars[name] = value;\n }\n\n const varsNodes: CssNode[] = [{ kind: \"variables\", selector: \":root\", variables: baseVars }];\n for (const node of variableNodes) {\n if (!node.media || node.selector !== \":root\") continue;\n const filtered: Record<string, string> = {};\n for (const [name, value] of Object.entries(node.variables)) {\n if (referencedVars.has(name)) filtered[name] = value;\n }\n if (Object.keys(filtered).length) {\n varsNodes.push({ kind: \"variables\", selector: node.selector, media: node.media, variables: filtered });\n }\n }\n\n const variablesCss = renderVariablesCss(varsNodes);\n if (variablesCss) files[plan.variables] = variablesCss;\n }\n\n return { files };\n }\n\n // Variants returning the same filename concatenate into that one file — so a per-group\n // `filename` fn bundles (buttons → buttons.css), and `() => \"components.css\"` collapses all.\n const filesByName: Record<string, string[]> = {};\n for (const [group, ruleSetGroup] of Object.entries(componentRuleSets)) {\n for (const variant of Object.keys(ruleSetGroup)) {\n const merged = mergeComponentRuleSet(model, group, variant);\n const selector = lowered.components?.selectors[group]?.[variant];\n if (!selector) continue;\n\n const ruleNodes = lowerMergedRuleSet(merged, { selector, media, pathToVar: globalPathToVar, containers: ctx.containers });\n // Populate `resolved` on each declaration from the variable map, then bake it.\n enrichDeclarationsWithRefs([...variableNodes, ...ruleNodes]);\n const inlined: CssNode[] = ruleNodes.map(rule => ({\n ...rule,\n declarations: rule.declarations.map(decl => {\n const baked = decl.resolved !== undefined ? decl.resolved : decl.value;\n // Every merged token ref must resolve to a baked value at this stage. A lingering\n // `var(` means an unresolved reference — surface it loud rather than emit a file\n // that silently depends on a variable the `components` mode never writes.\n if (typeof baked === \"string\" && baked.includes(\"var(\")) {\n throw new Error(\n `css adapter: emit mode 'components' (inline): '${decl.property}' on ` +\n `'${selector}' has an unresolved token reference (${baked}) — no baked value`,\n );\n }\n return { property: decl.property, value: baked };\n }),\n }));\n\n const filename = plan.filename({ group, variant });\n (filesByName[filename] ??= []).push(renderToCssString(inlined));\n }\n }\n\n const files: Record<string, string> = {};\n for (const [name, parts] of Object.entries(filesByName)) files[name] = parts.join(\"\\n\\n\");\n return { files };\n }\n\n throw new Error(`css adapter: emit mode '${type}' not yet implemented`);\n },\n };\n },\n };\n\n return defineAdapter(spec);\n};\n"],"names":["str","value","String","dimensionCss","ref","undefined","unit","resolveMediaQuery","media","breakpoint","query","orientation","group","_a","opts","min","max","exact","combineMedia","a","b","cond","s","replace","expandResponsiveVariableNodes","properties","resolveName","formatValue","byBlock","Map","add","mediaQuery","selector","updates","key","existing","get","Object","assign","variables","set","propertyName","model","entries","entry","responsive","_b","computeEntryUpdates","keys","length","mode","osMedia","MODE_MEDIA","Array","from","values","m","kind","target","field","r","overrides","rootNode","dark","light","modeVars","byMode","vars","modeVariableNodes","nodes","push","subsystemVarName","varName","subsystem","property","variant","filter","Boolean","join","deriveColorsModeNodes","formatColor","name","modes","fields","baseRef","base","buildSubsystemPathToVar","map","external","extras","v","_c","variants","ex","_d","deriveRegularVariableNodes","ctx","spec","nameFor","formatRoot","exRef","formatResponsive","deriveRegularModeNodes","varNameFor","struct","buildRegularPathToVar","composeShadowLayer","layer","pathToVar","zero","offsetX","offsetY","blur","spread","layerUnit","len","dim","shadowDimCss","parts","inset","color","resolveColorRef","composeShadow","layers","composeTransitionPart","part","duration","delay","timingFunction","composeTransition","deriveEffectsVariableNodes","propertyKey","composeEffectsStruct","first","composeEffectsStructAuto","MS_ANIMATION_KEYS","Set","deriveAnimationVariableNodes","has","formatMs","isLayoutConfigKey","includes","splitLayoutProperties","regular","config","deriveLayoutVariableNodes","_propertyKey","LAYOUT_BASE_KEYS","deriveLayoutConfigVariableNodes","byGroup","split","refToStyleValue","lowerContainerGroup","options","selectorBuilder","baseNodes","i","ruleSet","declarations","declarationsFromRefs","mediaNodes","override","state","wrap","decls","suffixSelector","suffix","trim","lowerResetRuleSet","globalPathToVar","emitGlobalsRule","containers","container","stateOverrides","o","orderStateOverrides","stateSelector","CSS_STATE_SELECTORS","node","containerQueryFor","_e","link","visited","hover","focus","active","disabled","pressed","CSS_KNOWN_STATES","STATE_ORDER","reduce","acc","index","sort","orderA","Number","MAX_SAFE_INTEGER","orderB","bpA","bpB","deriveStateNodes","size","descriptor","lowerRecipeGroup","baseDeclarations","stateNodes","targetedStateNodes","containerNodes","KEYFRAME_REF_PREFIX","ANIMATION_LONGHAND_ORDER","resolveKeyframeName","keyframeNames","startsWith","slice","Error","lowerAnimationRecipeGroup","shorthandNode","shorthand","longhand","composeAnimationShorthand","lowerMergedRuleSet","merged","states","atRule","renderToCssString","indent","newline","blocks","mergeAdjacentVariableNodes","body","renderKeyframesBody","renderVariableBody","renderRuleBody","inner","indentBlock","keyFor","output","previous","steps","step","stop","block","line","splitNodes","rules","renderVariablesCss","renderRulesCss","VAR_PATTERN","buildVariableValueMap","variableMap","test","match","resolved","enrichDeclarationsWithRefs","enrich","decl","version","allowedStates","bind","inline","naming","resolveNaming","prefix","classPrefix","namer","createNamer","variableName","colorFormat","toHexColor","toOklchColor","lowered","lowerRecipes","ruleSets","recipeNodes","selectors","ruleSetGroup","className","colors","subsystems","props","buildColorsPathToVar","variableNodes","text","deriveColorsVariableNodes","typography","buildTypographyPathToVar","deriveTypographyVariableNodes","_f","effects","_g","buildEffectsPathToVar","_h","borders","_j","buildBordersPathToVar","deriveBordersVariableNodes","_k","layout","_l","path","buildLayoutPathToVar","_m","lower","animation","_o","buildAnimationPathToVar","keyframes","_p","keyframeNodes","keyframe","lowerKeyframes","_q","componentClasses","components","resolveReferencedClass","reference","parsed","rest","dot","indexOf","parseComponentReference","_r","ownClass","classList","_s","references","cls","globals","variantName","variantSelector","lowerGlobalsGroups","_t","containerClass","containerContextNodes","type","deriveContainerContextNodes","collectNodes","sub","layerName","reducedMotion","_u","finalizeDoc","css","out","trimEnd","renderCss","varMap","bake","whole","inlined","n","collectClasses","groups","fromEntries","containerGroup","context","selectorFor","getClass","leaf","renderRecipe","nodeSelector","selectorBelongsToRecipe","recipeName","renderVariables","renderAllVariables","renderAllRecipes","renderAll","describeUsage","recipes","format","summary","describePreview","plan","files","written","keep","names","renderable","markup","attrs","class","modeAttribute","stylesheets","file","filename","groupBy","componentFile","componentFiles","f","notes","extend","variablesCss","recipesCss","classes","emit","opt","stylesCss","componentRuleSets","filesByName","orderedVarNames","referencedVars","mergeComponentRuleSet","ruleNodes","referencedPaths","baseValueMap","baseVars","varsNodes","filtered","rule","baked","defineAdapter"],"mappings":"uJA2BA,MAAMA,EAAOC,GAAqC,MAATA,EAAgB,GAAKC,OAAOD,GAQ/DE,EAAgBC,QACPC,IAAbD,EAAIE,KAAqB,GAAGF,EAAIH,QAAQG,EAAIE,OAASN,EAAII,EAAIH,OAczDM,EAAoB,CACxBC,EACAC,EACAC,EACAC,WAEA,IAAKA,EAAa,CAChB,MAAMC,EAAQJ,EAAMC,GACpB,OAAyB,QAAlBI,EAAAD,aAAK,EAALA,EAAQF,UAAU,IAAAG,EAAAA,EAAA,EAC1B,CACD,MAAMC,EAAO,CAAEH,eACf,MAAc,QAAVD,EAAwBF,EAAMO,IAAIN,EAAYK,GACpC,QAAVJ,EAAwBF,EAAMQ,IAAIP,EAAYK,GAC3CN,EAAMS,MAAMR,EAAYK,IAK3BI,EAAe,CAACC,EAAWC,KAC/B,MAAMC,EAAQC,GAAcA,EAAEC,QAAQ,aAAc,IACpD,MAAO,UAAUF,EAAKF,UAAUE,EAAKD,MAGjCI,EAAgC,CACpCC,EACAjB,EACAkB,E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S,QAC9C,MAAM,IAAIyE,MACR,kDAAkDyC,EAAKrL,iBACjD1C,yCAAgDyX,uBAG1D,MAAO,CAAE/U,SAAUqL,EAAKrL,SAAUzE,MAAOwZ,QAIvCzB,EAAWZ,EAAKY,SAAS,CAAEpX,QAAO+D,qBACxC0N,EAACyG,EAAYd,kBAAZc,EAAYd,GAAc,IAAI1T,KAAK0J,EAAkB6H,GACvD,CAGH,MAAMwB,EAAgC,CAAA,EACtC,IAAK,MAAOpS,EAAMqC,KAAUjF,OAAOM,QAAQmW,GAAczB,EAAMpS,GAAQqC,EAAMxC,KAAK,QAClF,MAAO,CAAEuS,QACV,CAED,MAAM,IAAI/J,MAAM,2BAA2BwH,yBAC5C,EAEJ,GAGH,OAAO4E,EAAAA,cAAczT"}
1
+ {"version":3,"file":"index.cjs.js","sources":["../src/lowering.ts","../src/render.ts","../src/index.ts"],"sourcesContent":["/**\n * CSS lowering of the format-neutral Model → `CssNode[]`.\n *\n * Variable-node lowering (naming + value formatting + responsive expansion) and recipe-rule\n * lowering (a **forward** lowering — the Model rule-sets go straight to `CssRuleNode[]`, no\n * `generateRecipeCss` round-trip) both live here. Refs carry canonical token paths; a\n * `pathToVar` map turns each into its `var(--…)`. Byte-parity with the former token-based path\n * is the golden gate.\n */\nimport type {\n ContainerModel,\n Keyframe,\n MergedRuleSet,\n PropertyModel,\n PropertyResponsiveOverride,\n Ref,\n RuleSet,\n RuleSetGroup,\n RuleSetOverride,\n ShadowLayer,\n TransitionPart,\n} from \"@theme-registry/refract\";\nimport type { ShadowDimension } from \"@theme-registry/refract\";\nimport type { ContainerDescriptors, MediaDescriptor, MediaVariant } from \"@theme-registry/refract\";\nimport type { CssDeclaration, CssKeyframesNode, CssRuleNode, CssVariablesNode } from \"./nodes\";\nimport type { VarNamer } from \"./naming\";\n\nconst str = (value: unknown): string => (value == null ? \"\" : String(value));\n\n/**\n * A resolved length leaf → CSS text (§21). Units are baked into the Model by `resolveModelUnits`, so a\n * text adapter only concatenates: `unit` present → `<value><unit>`; absent → the bare value (unit-less\n * numbers like opacity, or a raw-string escape / keyword). Struct (shadow/transition) is composed by\n * its subsystem before this is reached.\n */\nconst dimensionCss = (ref: Ref): string =>\n ref.unit !== undefined ? `${ref.value}${ref.unit}` : str(ref.value);\n\n/** A shadow geometry field ({@link ShadowDimension}) → CSS text — pinned `{value,unit}` or a bare number. */\nconst shadowDimCss = (dim: ShadowDimension): string =>\n typeof dim === \"number\" ? String(dim) : `${dim.value}${dim.unit}`;\n\nconst DEFAULT_RESPONSIVE_QUERY: MediaVariant = \"exact\";\n\n// ---------------------------------------------------------------------------\n// Shared responsive expansion (property variables)\n// ---------------------------------------------------------------------------\n\ntype ResolveVariableName = (property: string, variant?: string, field?: string) => string;\n\nconst resolveMediaQuery = <TBreakpoint extends string>(\n media: MediaDescriptor<TBreakpoint>,\n breakpoint: TBreakpoint,\n query: MediaVariant,\n orientation?: \"portrait\" | \"landscape\",\n): string => {\n if (!orientation) {\n const group = media[breakpoint];\n return group?.[query] ?? \"\";\n }\n const opts = { orientation };\n if (query === \"min\") return media.min(breakpoint, opts);\n if (query === \"max\") return media.max(breakpoint, opts);\n return media.exact(breakpoint, opts);\n};\n\n/** dec.9 — combine two `@media …` conditions into one (`@media <a> and <b>`), e.g. a breakpoint\n * query AND a mode's OS-preference query. */\nconst combineMedia = (a: string, b: string): string => {\n const cond = (s: string) => s.replace(/^@media\\s*/, \"\");\n return `@media ${cond(a)} and ${cond(b)}`;\n};\n\nconst expandResponsiveVariableNodes = <TBreakpoint extends string>(\n properties: Record<string, PropertyModel>,\n media: MediaDescriptor<TBreakpoint>,\n resolveName: ResolveVariableName,\n formatValue: (ref: Ref) => string,\n): CssVariablesNode[] => {\n // Grouped by `<media>||<selector>` so a mode-gated override lands in its own block. A plain\n // (no-mode) override keeps selector `:root`, so its key/order is unchanged → goldens byte-identical.\n const byBlock = new Map<string, { media: string; selector: string; variables: Record<string, string> }>();\n const add = (mediaQuery: string, selector: string, updates: Record<string, string>): void => {\n const key = `${mediaQuery}||${selector}`;\n const existing = byBlock.get(key);\n if (existing) Object.assign(existing.variables, updates);\n else byBlock.set(key, { media: mediaQuery, selector, variables: { ...updates } });\n };\n\n for (const [propertyName, model] of Object.entries(properties)) {\n for (const entry of model.responsive ?? []) {\n const mediaQuery = resolveMediaQuery(\n media,\n entry.breakpoint as TBreakpoint,\n (entry.query ?? DEFAULT_RESPONSIVE_QUERY) as MediaVariant,\n entry.orientation,\n );\n if (!mediaQuery) continue;\n\n const updates = computeEntryUpdates(propertyName, entry, resolveName, formatValue);\n if (!Object.keys(updates).length) continue;\n\n const mode = entry.mode;\n if (!mode) {\n add(mediaQuery, \":root\", updates);\n } else {\n // dec.9 — the override applies only under `mode`: a `[data-theme]` block (manual toggle) always,\n // plus an OS-preference combined block for first-class modes (dark/light) — mirrors mode emit.\n add(mediaQuery, `:root[data-theme=\"${mode}\"]`, updates);\n const osMedia = MODE_MEDIA[mode];\n if (osMedia) add(combineMedia(mediaQuery, osMedia), \":root\", updates);\n }\n }\n }\n\n return Array.from(byBlock.values(), ({ media: m, selector, variables }): CssVariablesNode => ({\n kind: \"variables\",\n selector,\n media: m,\n variables,\n }));\n};\n\nconst computeEntryUpdates = (\n propertyName: string,\n entry: PropertyResponsiveOverride,\n resolveName: ResolveVariableName,\n formatValue: (ref: Ref) => string,\n): Record<string, string> => {\n // dec.5 — `ref` (READ source) swaps the destination var to that variant's var; `target` is the\n // WRITE destination (omit → the base var). They COMPOSE (no mutual-exclusion): read from `ref`,\n // write into `target`. Literal field overrides land on the same destination.\n const { ref, target } = entry;\n const updates: Record<string, string> = {};\n\n if (ref !== undefined) {\n updates[resolveName(propertyName, target)] = `var(${resolveName(propertyName, ref)})`;\n }\n\n for (const [field, r] of Object.entries(entry.overrides ?? {})) {\n const varName = field === \"base\" ? resolveName(propertyName, target) : resolveName(propertyName, target, field);\n // §15/§21: the formatter reads the whole ref (struct for shadow/transition, resolved `unit` for lengths).\n updates[varName] = formatValue(r);\n }\n\n return updates;\n};\n\nconst rootNode = (variables: Record<string, string>): CssVariablesNode[] =>\n Object.keys(variables).length ? [{ kind: \"variables\", selector: \":root\", variables }] : [];\n\n// ---------------------------------------------------------------------------\n// Shared appearance-mode expansion (§10.3)\n// ---------------------------------------------------------------------------\n\n/**\n * The OS-preference media query for a first-class mode. Named modes without an OS signal (e.g.\n * `hc`) get no media block — only the `[data-theme]` attribute block (a manual toggle).\n */\nconst MODE_MEDIA: Record<string, string> = {\n dark: \"@media (prefers-color-scheme: dark)\",\n light: \"@media (prefers-color-scheme: light)\",\n};\n\n/** Fetch (or create) the per-mode variable dict in a mode→vars accumulator, preserving mode order. */\nconst modeVars = (byMode: Map<string, Record<string, string>>, mode: string): Record<string, string> => {\n let vars = byMode.get(mode);\n if (!vars) {\n vars = {};\n byMode.set(mode, vars);\n }\n return vars;\n};\n\n/**\n * A mode→vars accumulator → its `CssVariablesNode[]`: per mode, an OS-preference `@media` block\n * (first-class modes only) re-declaring the mode's var names on `:root`, then a\n * `:root[data-theme=\"<mode>\"]` attribute block (higher specificity → a manual toggle wins; source\n * order last). Both redefine the SAME base var names, so every downstream `var(--…)` reference\n * flips through the cascade with one redefinition. Empty modes contribute nothing.\n */\nconst modeVariableNodes = (byMode: Map<string, Record<string, string>>): CssVariablesNode[] => {\n const nodes: CssVariablesNode[] = [];\n for (const [mode, variables] of byMode) {\n if (!Object.keys(variables).length) continue;\n const media = MODE_MEDIA[mode];\n if (media) nodes.push({ kind: \"variables\", selector: \":root\", media, variables: { ...variables } });\n nodes.push({ kind: \"variables\", selector: `:root[data-theme=\"${mode}\"]`, variables: { ...variables } });\n }\n return nodes;\n};\n\n// ---------------------------------------------------------------------------\n// Colors variable nodes\n// ---------------------------------------------------------------------------\n\nexport type ColorsLoweringContext<TBreakpoint extends string = string> = {\n varName: VarNamer;\n media: MediaDescriptor<TBreakpoint>;\n /** Formats a palette colour value for output (§20) — identity for `rgb`, else hex/oklch. */\n formatColor: (value: unknown) => string;\n};\n\n/**\n * A subsystem token-path → its uniform CSS variable name (§17): `[subsystem, property, variant, field]`\n * joined into a dotted path, then `varNameFromPath`. base = bare property (no `--base`); a variant and/or\n * a field append — `colors.primary` → `--<t>-colors-primary`, `colors.primary.dark` → `--…-primary-dark`,\n * `colors.primary.text` → `--…-primary-text`, and (dec.3) a variant's own extra\n * `colors.primary.loud.text` → `--…-primary-loud-text`.\n */\nconst subsystemVarName = (\n varName: VarNamer,\n subsystem: string,\n property: string,\n variant?: string,\n field?: string,\n): string =>\n varName([subsystem, property, variant, field].filter(Boolean).join(\".\"));\n\n/**\n * Colors property tokens → `:root` variable node(s) + responsive media nodes. base →\n * `--<t>-colors-<name>`, `extras.text` → `--<t>-colors-<name>-text`, variants →\n * `--<t>-colors-<name>-<variant>`, all in Model order.\n */\nexport const deriveColorsVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: ColorsLoweringContext<TBreakpoint>,\n): CssVariablesNode[] => {\n const { varName, formatColor } = ctx;\n const nameFor = (property: string, variant?: string, field?: string): string =>\n subsystemVarName(varName, \"colors\", property, variant, field);\n const variables: Record<string, string> = {};\n\n for (const [name, model] of Object.entries(properties)) {\n if (model.base.external !== undefined) continue; // §W6b — parent owns the var; emit no definition\n variables[nameFor(name)] = formatColor(model.base.value);\n const text = model.extras?.text;\n if (text && text.value != null && text.value !== \"\") {\n variables[nameFor(name, undefined, \"text\")] = formatColor(text.value);\n }\n for (const [variant, v] of Object.entries(model.variants ?? {})) {\n variables[nameFor(name, variant)] = formatColor(v.base.value);\n // dec.3 — the variant's own extras → `--<t>-colors-<name>-<variant>-<extra>`.\n for (const [ex, exRef] of Object.entries(v.extras ?? {})) {\n if (exRef.value != null && exRef.value !== \"\") variables[nameFor(name, variant, ex)] = formatColor(exRef.value);\n }\n }\n }\n\n return [\n ...rootNode(variables),\n ...expandResponsiveVariableNodes(properties, ctx.media, nameFor, ref => formatColor(ref.value)),\n ...deriveColorsModeNodes(properties, varName, formatColor),\n ];\n};\n\n/**\n * Colors appearance-mode blocks (§10.3). For each palette colour's modes, re-declare the affected\n * base var names — `--<t>-colors-<name>` for the `base` field and `--<t>-colors-<name>-text` for the\n * `text` extra — with the mode value, grouped per mode into the dual media + `[data-theme]` blocks.\n */\nconst deriveColorsModeNodes = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n formatColor: (value: unknown) => string,\n): CssVariablesNode[] => {\n const byMode = new Map<string, Record<string, string>>();\n for (const [name, model] of Object.entries(properties)) {\n if (!model.modes) continue;\n for (const entry of model.modes) {\n if (entry.mode === undefined) continue;\n const vars = modeVars(byMode, entry.mode);\n // WHERE — a `target` scopes the re-declaration onto that variant's var (`--colors-<name>-<target>`);\n // omit → the base var (byte-identical to the old field-map behaviour).\n const target = entry.target;\n const fields = entry.overrides ?? {};\n const baseRef = fields.base;\n if (baseRef && baseRef.value != null) {\n vars[subsystemVarName(varName, \"colors\", name, target)] = formatColor(baseRef.value);\n }\n for (const [field, ref] of Object.entries(fields)) {\n if (field === \"base\") continue;\n if (ref && ref.value != null && ref.value !== \"\") {\n vars[subsystemVarName(varName, \"colors\", name, target, field)] = formatColor(ref.value);\n }\n }\n }\n }\n return modeVariableNodes(byMode);\n};\n\n/**\n * Build a `tokenPath → cssVarName` map for a subsystem's property tokens (base + `text` extras +\n * variants), each named uniformly via {@link varNameFromPath}, so the recipe lowering renders a\n * Model rule-set whose refs are token paths. Works for colors (with the `text` extra) and every\n * regular subsystem alike.\n */\nconst buildSubsystemPathToVar = (\n subsystem: string,\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => {\n const map: Record<string, string> = {};\n for (const [name, model] of Object.entries(properties)) {\n // §W6b — an external token maps straight to the parent's var name, so refs lower to var(--…) verbatim.\n map[`${subsystem}.${name}`] = model.base.external ?? varName(`${subsystem}.${name}`);\n for (const [field, ref] of Object.entries(model.extras ?? {})) {\n if (ref?.value == null || ref.value === \"\") continue;\n map[`${subsystem}.${name}.${field}`] = varName(`${subsystem}.${name}.${field}`);\n }\n for (const [variant, v] of Object.entries(model.variants ?? {})) {\n map[`${subsystem}.${name}.${variant}`] = varName(`${subsystem}.${name}.${variant}`);\n for (const ex of Object.keys(v.extras ?? {})) {\n map[`${subsystem}.${name}.${variant}.${ex}`] = varName(`${subsystem}.${name}.${variant}.${ex}`);\n }\n }\n }\n return map;\n};\n\nexport const buildColorsPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildSubsystemPathToVar(\"colors\", properties, varName);\n\n// ---------------------------------------------------------------------------\n// Regular subsystems (typography / effects): base + variants only\n// ---------------------------------------------------------------------------\n\ntype RegularVariableSpec = {\n /** `:root` value formatting — reads the whole {@link Ref} (value / struct / resolved `unit`). */\n formatRoot: (propertyKey: string, ref: Ref) => string;\n /** Responsive value formatting (defaults to {@link dimensionCss}). */\n formatResponsive?: (ref: Ref) => string;\n};\n\ntype RegularLoweringContext<TBreakpoint extends string = string> = {\n varName: VarNamer;\n media: MediaDescriptor<TBreakpoint>;\n};\n\n/**\n * Regular subsystem properties → variable node(s) (§17 uniform naming). Each `(property, variant)`\n * names `--<t>-<subsystem>-<property>[-<variant>]` with the subsystem's value formatting (base first,\n * then authored variants, matching the token-map order). Responsive overrides + modes reuse the name.\n */\nconst deriveRegularVariableNodes = <TBreakpoint extends string = string>(\n subsystem: string,\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n spec: RegularVariableSpec,\n): CssVariablesNode[] => {\n const { varName } = ctx;\n const nameFor: ResolveVariableName = (property, variant, field) =>\n subsystemVarName(varName, subsystem, property, variant, field);\n\n const variables: Record<string, string> = {};\n for (const [name, model] of Object.entries(properties)) {\n if (model.base.external !== undefined) continue; // §W6b — parent owns the var; emit no definition\n variables[nameFor(name)] = spec.formatRoot(name, model.base);\n for (const [variant, v] of Object.entries(model.variants ?? {})) {\n variables[nameFor(name, variant)] = spec.formatRoot(name, v.base);\n // dec.3 — the variant's own extras → `--<t>-<subsystem>-<name>-<variant>-<extra>`.\n for (const [ex, exRef] of Object.entries(v.extras ?? {})) {\n variables[nameFor(name, variant, ex)] = spec.formatRoot(name, exRef);\n }\n }\n }\n\n const formatResponsive = spec.formatResponsive ?? dimensionCss;\n return [\n ...rootNode(variables),\n ...expandResponsiveVariableNodes(properties, ctx.media, nameFor, formatResponsive),\n ...deriveRegularModeNodes(properties, (key, variant) => nameFor(key, variant), spec.formatRoot),\n ];\n};\n\n/**\n * Regular-subsystem appearance-mode blocks (§10.3). Regular subsystems own no extras, so a mode\n * redefines only the property's base var (via the same `formatRoot` formatting the base emit uses);\n * any non-base mode field is ignored. Grouped per mode into the dual media/attr blocks.\n */\nconst deriveRegularModeNodes = (\n properties: Record<string, PropertyModel>,\n varNameFor: (property: string, variant?: string) => string,\n formatRoot: (propertyKey: string, ref: Ref) => string,\n): CssVariablesNode[] => {\n const byMode = new Map<string, Record<string, string>>();\n for (const [name, model] of Object.entries(properties)) {\n if (!model.modes) continue;\n for (const entry of model.modes) {\n if (entry.mode === undefined) continue;\n const baseRef = entry.overrides?.base;\n if (baseRef == null || (baseRef.struct == null && baseRef.value == null)) continue;\n // WHERE — a `target` scopes onto that variant's var; omit → the base var.\n modeVars(byMode, entry.mode)[varNameFor(name, entry.target)] = formatRoot(name, baseRef);\n }\n }\n return modeVariableNodes(byMode);\n};\n\n/** Build a `tokenPath → cssVarName` map for a regular subsystem (uniform naming). */\nconst buildRegularPathToVar = (\n subsystem: string,\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildSubsystemPathToVar(subsystem, properties, varName);\n\n// --- Typography ---\n\n/**\n * Typography property tokens → `:root` variable node(s). Length leaves (`fontSize`, `letterSpacing`)\n * carry a resolved `unit` from the §21 pass; unit-less numbers (`fontWeight`, `lineHeight` when un-unitted)\n * and strings (`fontFamily`) stringify raw — {@link dimensionCss} does both.\n */\nexport const deriveTypographyVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n): CssVariablesNode[] =>\n deriveRegularVariableNodes(\"typography\", properties, ctx, {\n formatRoot: (_propertyKey, ref) => dimensionCss(ref),\n });\n\nexport const buildTypographyPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildRegularPathToVar(\"typography\", properties, varName);\n\n// --- Effects ---\n\n// --- Structured effects value composition (§15) ---\n// The Model carries shadow/transition values as structure (`Ref.struct`); the CSS adapter is where\n// they become CSS text. A layer/part's `color` is a `colors.*` token path → `var(--…)` via the\n// global path→var map (colors processed before effects — the §14.4 cross-subsystem watch-point).\n// Shadow geometry fields carry a resolved unit (§21) — `shadowDimCss`; an absent (required) offset\n// defaults to `0` in the layer's unit ({@link layerUnit}), so a drop-shadow stays `0px …` not `0 …`.\n\n/** Resolve a shadow layer's `colors.*` color ref → `var(--…)`; falls back to the raw path if unmapped.\n * Translucency lives in the referenced colour (an `alpha` colour variant — §13.3), not here. */\nconst resolveColorRef = (color: string, pathToVar: Record<string, string>): string => {\n const varName = pathToVar[color];\n return varName ? `var(${varName})` : color;\n};\n\n/** The layer's shared length unit — read from the first resolved geometry field; `px` if none resolved. */\nconst layerUnit = (layer: ShadowLayer): string => {\n for (const field of [layer.offsetX, layer.offsetY, layer.blur, layer.spread]) {\n if (field !== undefined && typeof field !== \"number\") return field.unit;\n }\n return \"px\";\n};\n\n/** Compose one structured shadow layer → CSS `[inset] <x> <y> [blur] [spread] [color]` (§21 units). */\nconst composeShadowLayer = (\n layer: ShadowLayer,\n pathToVar: Record<string, string>,\n): string => {\n const zero = `0${layerUnit(layer)}`;\n const len = (dim: ShadowDimension | undefined): string => (dim === undefined ? zero : shadowDimCss(dim));\n const parts: string[] = [];\n if (layer.inset) parts.push(\"inset\");\n parts.push(len(layer.offsetX), len(layer.offsetY));\n // `spread` is only valid after a `blur` slot — emit `blur` (default 0) when spread is present.\n if (layer.spread != null) parts.push(len(layer.blur), len(layer.spread));\n else if (layer.blur != null) parts.push(len(layer.blur));\n if (layer.color) parts.push(resolveColorRef(layer.color, pathToVar));\n return parts.join(\" \");\n};\n\n/** Compose a shadow value (one or more layers) → a comma-joined `box-shadow` string. */\nconst composeShadow = (\n layers: ShadowLayer[],\n pathToVar: Record<string, string>,\n): string => layers.map(layer => composeShadowLayer(layer, pathToVar)).join(\", \");\n\n/** Compose one structured transition part → CSS `<property> <duration>ms [timing] [delay]ms`. */\nconst composeTransitionPart = (part: TransitionPart): string => {\n const parts: string[] = [part.property];\n // A bare `delay` needs a `duration` slot ahead of it (CSS reads the first time as duration).\n if (part.duration != null || part.delay != null) parts.push(`${part.duration ?? 0}ms`);\n if (part.timingFunction) parts.push(part.timingFunction);\n if (part.delay != null) parts.push(`${part.delay}ms`);\n return parts.join(\" \");\n};\n\n/** Compose a transition value (one or more parts) → a comma-joined `transition` string. */\nconst composeTransition = (parts: TransitionPart[]): string =>\n parts.map(composeTransitionPart).join(\", \");\n\n/** Compose a structured effects value → CSS by property (`transitions` vs shadow). */\nconst composeEffectsStruct = (\n propertyKey: string,\n value: readonly unknown[],\n pathToVar: Record<string, string>,\n): string =>\n propertyKey === \"transitions\"\n ? composeTransition(value as TransitionPart[])\n : composeShadow(value as ShadowLayer[], pathToVar);\n\n/**\n * Compose a structured effects value without a property key (the responsive path, where only the\n * value is in hand): a transition part carries a `property` field; a shadow layer does not.\n */\nconst composeEffectsStructAuto = (\n value: readonly unknown[],\n pathToVar: Record<string, string>,\n): string => {\n const first = value[0];\n const isTransition = !!first && typeof first === \"object\" && \"property\" in first;\n return isTransition\n ? composeTransition(value as TransitionPart[])\n : composeShadow(value as ShadowLayer[], pathToVar);\n};\n\n/**\n * Effects property tokens → `:root` variable node(s). `blur` carries a resolved length unit (§21);\n * `shadow` / `transitions` compose from their structured {@link Ref.struct} value (§15) into CSS text —\n * a layer/part `color` ref resolves via `ctx.pathToVar` (the global map, colors already merged); the\n * scalars (`opacity` / `zIndex`) are unit-less. {@link dimensionCss} covers blur + the unit-less scalars.\n */\nexport const deriveEffectsVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint> & { pathToVar?: Record<string, string> },\n): CssVariablesNode[] => {\n const pathToVar = ctx.pathToVar ?? {};\n return deriveRegularVariableNodes(\"effects\", properties, ctx, {\n formatRoot: (propertyKey, ref) =>\n ref.struct ? composeEffectsStruct(propertyKey, ref.struct, pathToVar) : dimensionCss(ref),\n formatResponsive: ref =>\n ref.struct ? composeEffectsStructAuto(ref.struct, pathToVar) : dimensionCss(ref),\n });\n};\n\nexport const buildEffectsPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildRegularPathToVar(\"effects\", properties, varName);\n\n// --- Borders (§14) ---\n\n/**\n * Borders property tokens → `:root` variable node(s). width/offset/radius carry a resolved length unit\n * (§21); `style` (a keyword string) has no unit. {@link dimensionCss} covers both.\n */\nexport const deriveBordersVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n): CssVariablesNode[] =>\n deriveRegularVariableNodes(\"borders\", properties, ctx, {\n formatRoot: (_propertyKey, ref) => dimensionCss(ref),\n });\n\nexport const buildBordersPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> =>\n buildRegularPathToVar(\"borders\", properties, varName);\n\n// --- Animation (§10.2) ---\n\n/** Motion-token keys whose numeric value formats as a `<n>ms` time. `easing` stays a raw string. */\nconst MS_ANIMATION_KEYS = new Set([\"duration\", \"delay\"]);\n\nconst formatMs = (value: unknown): string => (typeof value === \"number\" ? `${value}ms` : str(value));\n\n/** Animation motion tokens (duration/easing/delay) → `:root` variable node(s). Numeric durations/delays\n * format as ms (time, not length — animation is outside the §21 length registry, so no `unit` is baked). */\nexport const deriveAnimationVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n): CssVariablesNode[] =>\n deriveRegularVariableNodes(\"animation\", properties, ctx, {\n formatRoot: (propertyKey, ref) =>\n typeof ref.value === \"number\" && MS_ANIMATION_KEYS.has(propertyKey) ? `${ref.value}ms` : str(ref.value),\n formatResponsive: ref => formatMs(ref.value),\n });\n\nexport const buildAnimationPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => buildRegularPathToVar(\"animation\", properties, varName);\n\n// --- Layout ---\n\n/** A structural-config property key (`columns--size`, `container--inset`) vs a regular one (`spacing`). */\nconst isLayoutConfigKey = (key: string): boolean => key.includes(\"--\");\n\n/** Split layout's merged property map into the regular tokens and the structural-config tokens (order kept). */\nexport const splitLayoutProperties = (\n properties: Record<string, PropertyModel>,\n): { regular: Record<string, PropertyModel>; config: Record<string, PropertyModel> } => {\n const regular: Record<string, PropertyModel> = {};\n const config: Record<string, PropertyModel> = {};\n for (const [key, model] of Object.entries(properties)) {\n if (isLayoutConfigKey(key)) config[key] = model;\n else regular[key] = model;\n }\n return { regular, config };\n};\n\n/**\n * Layout regular property tokens → `:root` variable node(s). spacing/gutters carry a resolved length\n * unit (§21); `aspectRatio` is unit-less. {@link dimensionCss} covers both.\n */\nexport const deriveLayoutVariableNodes = <TBreakpoint extends string = string>(\n properties: Record<string, PropertyModel>,\n ctx: RegularLoweringContext<TBreakpoint>,\n): CssVariablesNode[] =>\n deriveRegularVariableNodes(\"layout\", properties, ctx, {\n formatRoot: (_propertyKey, ref) => dimensionCss(ref),\n });\n\n/** The fixed layout knobs that always get a canonical base var name, even when unauthored. */\nconst LAYOUT_BASE_KEYS = [\"spacing\", \"gutters\", \"aspectRatio\"] as const;\n\n/**\n * A `tokenPath → cssVarName` map for the whole layout subsystem — regular tokens via the uniform\n * naming (`layout.spacing.relaxed` → `--<t>-layout-spacing-relaxed`) **and** structural-config\n * tokens (`layout.container--inset` → `--<t>-layout-container-inset`), so the structural rule\n * declarations (which reference config tokens by path) resolve to the config `:root` var names.\n */\nexport const buildLayoutPathToVar = (\n properties: Record<string, PropertyModel>,\n varName: VarNamer,\n): Record<string, string> => {\n const { regular, config } = splitLayoutProperties(properties);\n const map = buildRegularPathToVar(\"layout\", regular, varName);\n // Seed the canonical base names for the fixed layout knobs (spacing/gutters/aspectRatio) so a\n // structural declaration referencing a base token (`layout.spacing`) always resolves to its var\n // name — even when no such property is authored (the default container with an empty `layout: {}`\n // references `layout.spacing`; the OLD generator hardcoded `var(--…-layout-spacing--base)`). For a\n // theme that DOES author these, the value is identical to the regular map entry — a no-op.\n for (const key of LAYOUT_BASE_KEYS) {\n const path = `layout.${key}`;\n if (!(path in map)) map[path] = varName(path);\n }\n for (const key of Object.keys(config)) {\n map[`layout.${key}`] = varName(`layout.${key}`);\n }\n return map;\n};\n\n/**\n * Layout structural-config tokens → `:root` variable node(s), one node per config group\n * (`columns`, `container`), grouped by the key's leading `<group>--` segment in first-seen order.\n * Each var is `--<t>-layout-<key>` (uniform); its value is the literal or a `var(--…)` (via\n * `pathToVar`) — so `--<t>-layout-columns-gutter: var(--<t>-layout-gutters)`.\n */\nexport const deriveLayoutConfigVariableNodes = (\n config: Record<string, PropertyModel>,\n ctx: { varName: VarNamer; pathToVar: Record<string, string> },\n): CssVariablesNode[] => {\n const byGroup = new Map<string, Record<string, string>>();\n for (const [key, model] of Object.entries(config)) {\n const group = key.split(\"--\")[0];\n let vars = byGroup.get(group);\n if (!vars) {\n vars = {};\n byGroup.set(group, vars);\n }\n vars[ctx.varName(`layout.${key}`)] = String(refToStyleValue(model.base, ctx.pathToVar));\n }\n return Array.from(byGroup.values(), (variables): CssVariablesNode => ({\n kind: \"variables\",\n selector: \":root\",\n variables,\n }));\n};\n\n// ---------------------------------------------------------------------------\n// Container rule lowering (two-pass: bases in reverse, medias forward)\n// ---------------------------------------------------------------------------\n\n/**\n * Lower a container {@link RuleSetGroup} to `CssRuleNode[]`. Unlike `lowerRecipeGroup` (which\n * interleaves base + medias per variant), the container generator emitted **all bases first**\n * (via `unshift`, so reverse of processing order) then **all medias** (forward). Reproduce that:\n * pass 1 emits base rules in reverse group order; pass 2 emits media overrides in forward order.\n * Byte-identical to the old `deriveContainerRules`, without the reverse node↔rule-set codec.\n */\nexport const lowerContainerGroup = <TBreakpoint extends string = string>(\n group: RuleSetGroup,\n options: LowerRecipeGroupOptions<TBreakpoint>,\n): LowerRecipeGroupResult => {\n const { media, selectorBuilder, pathToVar } = options;\n const entries = Object.entries(group);\n const variants: Record<string, string> = {};\n for (const [name] of entries) variants[name] = selectorBuilder(name);\n\n const baseNodes: CssRuleNode[] = [];\n for (let i = entries.length - 1; i >= 0; i--) {\n const [name, ruleSet] = entries[i];\n const declarations = declarationsFromRefs(ruleSet.declarations, pathToVar);\n if (declarations.length) baseNodes.push({ kind: \"rule\", selector: selectorBuilder(name), declarations });\n }\n\n const mediaNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of entries) {\n for (const override of ruleSet.overrides) {\n if (override.state !== undefined || !override.breakpoint) continue;\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (!mediaQuery) continue;\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n mediaNodes.push({ kind: \"rule\", selector: selectorBuilder(name), media: mediaQuery, declarations });\n }\n }\n\n return { nodes: [...baseNodes, ...mediaNodes], variants };\n};\n\n// ---------------------------------------------------------------------------\n// Recipe rule lowering (forward: Model rule-sets → CssRuleNode[])\n// ---------------------------------------------------------------------------\n\n/** A declaration ref → its CSS value: a `var(--…)` (via `pathToVar`), optionally wrapped; else the literal. */\nconst refToStyleValue = (ref: Ref, pathToVar: Record<string, string>): string | number => {\n if (ref.ref === undefined) return ref.value as string | number;\n const v = `var(${pathToVar[ref.ref] ?? ref.ref})`;\n return ref.wrap ? `${ref.wrap}(${v})` : v;\n};\n\nconst declarationsFromRefs = (\n decls: Record<string, Ref>,\n pathToVar: Record<string, string>,\n): CssDeclaration[] =>\n Object.entries(decls).map(([property, ref]) => ({ property, value: refToStyleValue(ref, pathToVar) }));\n\n// ---------------------------------------------------------------------------\n// Globals lowering (§9) — preset `kind:\"reset\"` (`:where(sel)`) + themed `kind:\"globals\"` elements\n// ---------------------------------------------------------------------------\n\n/**\n * Suffix each comma-part of a raw selector (`h1,h2` + `.subtle` → `h1.subtle,h2.subtle`; `a` +\n * `:hover` → `a:hover`). Applies a variant class or a state pseudo to every element in a grouped\n * selector, not just the last — so a globals variant/state on `h1,h2` scopes both.\n */\nconst suffixSelector = (selector: string, suffix: string): string =>\n selector\n .split(\",\")\n .map(part => `${part.trim()}${suffix}`)\n .join(\",\");\n\n/**\n * Lower one preset `kind:\"reset\"` rule-set → a specificity-0 `:where(sel) { … }` node. Literal\n * declarations pass through; token-path refs resolve via `globalPathToVar`, and an unresolved ref is\n * **dropped** (the opportunistic `defaults` `h1`–`h6` heading map / `static` layer — a ratio-less\n * theme drops the missing scale step). Never throws — the throw policy lives on themed elements.\n */\nconst lowerResetRuleSet = (\n ruleSet: RuleSet,\n globalPathToVar: Record<string, string>,\n): CssRuleNode[] => {\n const selector = ruleSet.selector;\n if (!selector) return [];\n const declarations: CssDeclaration[] = [];\n for (const [property, ref] of Object.entries(ruleSet.declarations)) {\n if (ref.ref === undefined) {\n declarations.push({ property, value: ref.value as string | number });\n continue;\n }\n const varName = globalPathToVar[ref.ref];\n if (varName) declarations.push({ property, value: `var(${varName})` });\n // else drop: the scale step / token isn't present → omit this declaration.\n }\n return declarations.length ? [{ kind: \"rule\", selector: `:where(${selector})`, declarations }] : [];\n};\n\n/**\n * Emit one themed rule (a globals element base, or one of its variants) at `selector`: the base\n * declarations, its breakpoint-only overrides as `@media` blocks, then its state overrides as\n * `selector:state` rules (canonical order, source-order-last so they win), then container overrides.\n * Refs are validated up-front in `createTheme` (`validateGlobalsRefs`), so `declarationsFromRefs`\n * lowers them without a per-adapter throw.\n */\nconst emitGlobalsRule = <TBreakpoint extends string>(\n nodes: CssRuleNode[],\n selector: string,\n declarations: Record<string, Ref>,\n overrides: RuleSetOverride[],\n pathToVar: Record<string, string>,\n media: MediaDescriptor<TBreakpoint>,\n containers: ContainerDescriptors | undefined,\n): void => {\n const base = declarationsFromRefs(declarations, pathToVar);\n if (base.length) nodes.push({ kind: \"rule\", selector, declarations: base });\n\n for (const override of overrides) {\n if (override.state !== undefined || override.container !== undefined || !override.breakpoint) continue;\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (!mediaQuery) continue;\n const decls = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (decls.length) nodes.push({ kind: \"rule\", selector, media: mediaQuery, declarations: decls });\n }\n\n const stateOverrides = overrides.filter(o => o.state !== undefined);\n for (const override of orderStateOverrides(stateOverrides)) {\n const stateSelector = CSS_STATE_SELECTORS[override.state as string];\n if (!stateSelector) continue;\n const decls = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!decls.length) continue;\n const node: CssRuleNode = { kind: \"rule\", selector: suffixSelector(selector, stateSelector), declarations: decls };\n if (override.breakpoint) {\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (mediaQuery) node.media = mediaQuery;\n }\n nodes.push(node);\n }\n\n for (const override of overrides) {\n if (!override.container) continue;\n const query = containerQueryFor(override, containers);\n if (!query) continue;\n const decls = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!decls.length) continue;\n nodes.push({ kind: \"rule\", selector, media: query, declarations: decls });\n }\n};\n\n/**\n * Lower the globals subsystem's rule-set groups to `CssRuleNode[]`. Two kinds coexist:\n * - `kind:\"reset\"` (preset `static` / `defaults`) → specificity-0 `:where(sel)` (drop policy).\n * - `kind:\"globals\"` (themed `elements`) → a bare `sel { … }` at a higher tier, its `states` /\n * `responsive` overrides, and each delta-only variant as a self-scoped `sel.<variant>` rule.\n * Groups render in insertion order (`static` → `defaults` → `elements`).\n */\nexport const lowerGlobalsGroups = <TBreakpoint extends string>(\n ruleSets: Record<string, RuleSetGroup>,\n globalPathToVar: Record<string, string>,\n media: MediaDescriptor<TBreakpoint>,\n containers?: ContainerDescriptors,\n): CssRuleNode[] => {\n const nodes: CssRuleNode[] = [];\n for (const ruleSetGroup of Object.values(ruleSets)) {\n for (const ruleSet of Object.values(ruleSetGroup)) {\n if (ruleSet.kind === \"globals\") {\n const selector = ruleSet.selector;\n if (!selector) continue;\n emitGlobalsRule(nodes, selector, ruleSet.declarations, ruleSet.overrides, globalPathToVar, media, containers);\n for (const [variantName, variant] of Object.entries(ruleSet.variants ?? {})) {\n const variantSelector = suffixSelector(selector, `.${variantName}`);\n emitGlobalsRule(nodes, variantSelector, variant.declarations, variant.overrides, globalPathToVar, media, containers);\n }\n } else {\n nodes.push(...lowerResetRuleSet(ruleSet, globalPathToVar));\n }\n }\n }\n return nodes;\n};\n\n// ---------------------------------------------------------------------------\n// Container context declaration (§10.5) — `.<prefix>-cq-<name> { container-type; container-name }`\n// ---------------------------------------------------------------------------\n\n/**\n * Lower the theme's `containers` config to the utility classes that establish each named containment\n * context: `.<classPrefix>-cq-<name> { container-type: <type>; container-name: <name>; }` (§10.5 D4).\n * A distinct `cq` segment avoids colliding with layout's `.<prefix>-container` max-width wrapper. Put\n * on a wrapper element; the recipe's `@container <name> (…)` rules then respond to it. The context\n * class routes through `containerClass` (§7B `kind:\"container\"`), so a naming override remaps it\n * consistently with `theme.classes.containers.context.<name>`.\n */\nexport const deriveContainerContextNodes = (\n containers: Record<string, ContainerModel> | undefined,\n containerClass: (name: string) => string,\n): CssRuleNode[] => {\n const nodes: CssRuleNode[] = [];\n for (const [name, container] of Object.entries(containers ?? {})) {\n nodes.push({\n kind: \"rule\",\n selector: `.${containerClass(name)}`,\n declarations: [\n { property: \"container-type\", value: container.type },\n { property: \"container-name\", value: name },\n ],\n });\n }\n return nodes;\n};\n\n// --- State → selector table + canonical ordering ---\n\n/** state name → its CSS selector suffix. Exported so the preview can build pinnable twins. */\nexport const CSS_STATE_SELECTORS: Record<string, string> = {\n link: \":link\",\n visited: \":visited\",\n hover: \":hover\",\n focus: \":focus\",\n active: \":active\",\n disabled: \"[disabled]\",\n pressed: \"[aria-pressed]\",\n};\n\n/** The states the CSS adapter can render (the validation set for recipe normalization). */\nexport const CSS_KNOWN_STATES: ReadonlyArray<string> = Object.keys(CSS_STATE_SELECTORS);\n\nconst STATE_ORDER: Record<string, number> = CSS_KNOWN_STATES.reduce<Record<string, number>>(\n (acc, name, index) => {\n acc[name] = index;\n return acc;\n },\n {},\n);\n\nconst orderStateOverrides = (overrides: RuleSetOverride[]): RuleSetOverride[] =>\n [...overrides]\n .map((override, index) => ({ override, index }))\n .sort((a, b) => {\n const orderA = STATE_ORDER[a.override.state as string] ?? Number.MAX_SAFE_INTEGER;\n const orderB = STATE_ORDER[b.override.state as string] ?? Number.MAX_SAFE_INTEGER;\n if (orderA !== orderB) return orderA - orderB;\n const bpA = a.override.breakpoint ? 1 : 0;\n const bpB = b.override.breakpoint ? 1 : 0;\n if (bpA !== bpB) return bpA - bpB;\n return a.index - b.index;\n })\n .map(({ override }) => override);\n\nconst deriveStateNodes = <TBreakpoint extends string>(\n ruleSet: RuleSet,\n selector: string,\n media: MediaDescriptor<TBreakpoint>,\n pathToVar: Record<string, string>,\n): CssRuleNode[] => {\n // dec.8 — `target`ed state overrides emit against a SIBLING selector, appended last by the caller\n // so they win; the base state rules here are the un-targeted ones (byte-identical to before).\n const stateOverrides = ruleSet.overrides.filter(o => o.state !== undefined && !o.target);\n if (!stateOverrides.length) return [];\n\n const nodes: CssRuleNode[] = [];\n for (const override of orderStateOverrides(stateOverrides)) {\n const stateSelector = CSS_STATE_SELECTORS[override.state as string];\n if (!stateSelector) continue;\n\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n\n const node: CssRuleNode = { kind: \"rule\", selector: `${selector}${stateSelector}`, declarations };\n\n if (override.breakpoint) {\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (mediaQuery) node.media = mediaQuery;\n }\n\n nodes.push(node);\n }\n return nodes;\n};\n\nexport type LowerRecipeGroupOptions<TBreakpoint extends string = string> = {\n media: MediaDescriptor<TBreakpoint>;\n selectorBuilder: (variantName: string) => string;\n pathToVar: Record<string, string>;\n /** Container-query descriptors (§10.5) — resolve a `{ container, size, query }` override → `@container …`. */\n containers?: ContainerDescriptors;\n};\n\n/**\n * Resolve a container override's `{ container, size, query }` to its `@container <name> (…)` prelude\n * via the container descriptors, or `\"\"` when the container/size/descriptors are absent (§10.5).\n */\nconst containerQueryFor = (\n override: RuleSetOverride,\n containers: ContainerDescriptors | undefined,\n): string => {\n if (!override.container || !override.size) return \"\";\n const descriptor = containers?.[override.container];\n if (!descriptor) return \"\";\n const query = (override.query ?? \"min\") as MediaVariant;\n return descriptor[query](override.size);\n};\n\nexport type LowerRecipeGroupResult = {\n nodes: CssRuleNode[];\n variants: Record<string, string>;\n};\n\n/**\n * A Model recipe {@link RuleSetGroup} → recipe `CssRuleNode[]` (+ variant → selector map).\n * Forward lowering: base + breakpoint-conditioned overrides render first (per variant), then\n * state (+ state×breakpoint) overrides append as `:state` rules so they win by source order.\n */\nexport const lowerRecipeGroup = <TBreakpoint extends string = string>(\n group: RuleSetGroup,\n options: LowerRecipeGroupOptions<TBreakpoint>,\n): LowerRecipeGroupResult => {\n const { media, selectorBuilder, pathToVar } = options;\n const nodes: CssRuleNode[] = [];\n const variants: Record<string, string> = {};\n\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n variants[name] = selector;\n\n const baseDeclarations = declarationsFromRefs(ruleSet.declarations, pathToVar);\n if (baseDeclarations.length) nodes.push({ kind: \"rule\", selector, declarations: baseDeclarations });\n\n for (const override of ruleSet.overrides) {\n if (override.state !== undefined || !override.breakpoint) continue;\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (!mediaQuery) continue;\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n nodes.push({ kind: \"rule\", selector, media: mediaQuery, declarations });\n }\n }\n\n const stateNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n stateNodes.push(...deriveStateNodes(ruleSet, selectorBuilder(name), media, pathToVar));\n }\n\n // dec.8 — `target`ed state overrides: emit `<item>-<target>:state` against the desugared sibling\n // (§7A), collected across the whole group and appended LAST so they beat the sibling's inherited\n // (un-targeted) state rules by source order.\n const targetedStateNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n for (const override of ruleSet.overrides) {\n if (override.state === undefined || !override.target) continue;\n const stateSelector = CSS_STATE_SELECTORS[override.state];\n if (!stateSelector) continue;\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n const siblingSelector = selectorBuilder(`${name}-${override.target}`);\n const node: CssRuleNode = { kind: \"rule\", selector: `${siblingSelector}${stateSelector}`, declarations };\n if (override.breakpoint) {\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (mediaQuery) node.media = mediaQuery;\n }\n targetedStateNodes.push(node);\n }\n }\n\n // Container-query overrides (§10.5): each `{ container, size }` override → a rule wrapped in an\n // `@container <name> (…)` prelude (carried on the node's generic `media` field). Appended last so\n // they win by source order, like state rules. Skipped entirely when no `containers` are configured.\n const containerNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n for (const override of ruleSet.overrides) {\n if (!override.container) continue;\n const query = containerQueryFor(override, options.containers);\n if (!query) continue;\n const declarations = declarationsFromRefs(override.declarations ?? {}, pathToVar);\n if (!declarations.length) continue;\n containerNodes.push({ kind: \"rule\", selector, media: query, declarations });\n }\n }\n\n return { nodes: [...nodes, ...stateNodes, ...containerNodes, ...targetedStateNodes], variants };\n};\n\n// ---------------------------------------------------------------------------\n// Animation lowering (§10.2) — keyframes at-rules + animation-shorthand recipes\n// ---------------------------------------------------------------------------\n\n/** The token-path prefix an `animation-name` ref carries — it resolves to the bare keyframe id. */\nconst KEYFRAME_REF_PREFIX = \"animation.keyframes.\";\n\n/**\n * Lower the animation subsystem's keyframes to `@keyframes` at-rule nodes. Each step keeps its\n * verbatim `stop`; declarations resolve through `globalPathToVar` — a literal `{ value }` passes\n * through, a token-path `{ ref }` (e.g. `colors.surface`) becomes `var(--…)` (so a keyframe can\n * animate a themed value). Keyframe identifiers are emitted raw (as authored).\n */\nexport const lowerKeyframes = (\n keyframes: Record<string, Keyframe>,\n globalPathToVar: Record<string, string>,\n): CssKeyframesNode[] => {\n const nodes: CssKeyframesNode[] = [];\n for (const [name, keyframe] of Object.entries(keyframes)) {\n const steps = keyframe.steps.map(step => ({\n stop: step.stop,\n declarations: Object.entries(step.declarations).map(([property, ref]): CssDeclaration => ({\n property,\n value: refToStyleValue(ref, globalPathToVar),\n })),\n }));\n nodes.push({ kind: \"keyframes\", name, steps });\n }\n return nodes;\n};\n\n/** The `animation:` shorthand sub-property order — first `<time>` = duration, second = delay; name last. */\nconst ANIMATION_LONGHAND_ORDER: ReadonlyArray<string> = [\n \"animation-duration\",\n \"animation-timing-function\",\n \"animation-delay\",\n \"animation-iteration-count\",\n \"animation-direction\",\n \"animation-fill-mode\",\n \"animation-play-state\",\n \"animation-name\",\n];\n\n/** Resolve an `animation-name` ref to its bare keyframe identifier, validating it against the known set. */\nconst resolveKeyframeName = (\n ref: Ref,\n keyframeNames: ReadonlySet<string>,\n selector: string,\n): string => {\n const name =\n ref.ref !== undefined\n ? ref.ref.startsWith(KEYFRAME_REF_PREFIX)\n ? ref.ref.slice(KEYFRAME_REF_PREFIX.length)\n : ref.ref\n : str(ref.value);\n if (!keyframeNames.has(name)) {\n throw new Error(\n `css adapter: animation recipe '${selector}' references unknown keyframe '${name}' — ` +\n `no matching entry in animation.keyframes`,\n );\n }\n return name;\n};\n\n/**\n * Compose one animation declaration set (base or override) into an `animation:` shorthand string in\n * canonical sub-property order. Duration/easing/delay refs → `var(--…)` (or literal); the\n * `animation-name` ref → the bare, validated keyframe identifier. Returns `\"\"` when nothing is set.\n */\nconst composeAnimationShorthand = (\n decls: Record<string, Ref>,\n pathToVar: Record<string, string>,\n keyframeNames: ReadonlySet<string>,\n selector: string,\n): string => {\n const parts: string[] = [];\n for (const longhand of ANIMATION_LONGHAND_ORDER) {\n const ref = decls[longhand];\n if (!ref) continue;\n parts.push(\n longhand === \"animation-name\"\n ? resolveKeyframeName(ref, keyframeNames, selector)\n : String(refToStyleValue(ref, pathToVar)),\n );\n }\n return parts.join(\" \");\n};\n\nexport type LowerAnimationGroupOptions<TBreakpoint extends string = string> =\n LowerRecipeGroupOptions<TBreakpoint> & { keyframeNames: ReadonlySet<string> };\n\n/**\n * Lower an animation recipe {@link RuleSetGroup} to class rules whose single declaration is the\n * composed `animation:` shorthand — base first, then breakpoint overrides, then state overrides\n * (canonical order, source-order wins) — mirroring {@link lowerRecipeGroup}'s node ordering with a\n * whole-set shorthand composer in place of the per-declaration lowering.\n */\nexport const lowerAnimationRecipeGroup = <TBreakpoint extends string = string>(\n group: RuleSetGroup,\n options: LowerAnimationGroupOptions<TBreakpoint>,\n): LowerRecipeGroupResult => {\n const { media, selectorBuilder, pathToVar, keyframeNames } = options;\n const nodes: CssRuleNode[] = [];\n const variants: Record<string, string> = {};\n\n const shorthandNode = (\n selector: string,\n decls: Record<string, Ref>,\n mediaQuery?: string,\n ): CssRuleNode | undefined => {\n const shorthand = composeAnimationShorthand(decls, pathToVar, keyframeNames, selector);\n if (!shorthand) return undefined;\n const node: CssRuleNode = { kind: \"rule\", selector, declarations: [{ property: \"animation\", value: shorthand }] };\n if (mediaQuery) node.media = mediaQuery;\n return node;\n };\n\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n variants[name] = selector;\n\n const base = shorthandNode(selector, ruleSet.declarations);\n if (base) nodes.push(base);\n\n for (const override of ruleSet.overrides) {\n if (override.state !== undefined || !override.breakpoint) continue;\n const mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n );\n if (!mediaQuery) continue;\n const node = shorthandNode(selector, override.declarations ?? {}, mediaQuery);\n if (node) nodes.push(node);\n }\n }\n\n const stateNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n const stateOverrides = ruleSet.overrides.filter(o => o.state !== undefined);\n for (const override of orderStateOverrides(stateOverrides)) {\n const stateSelector = CSS_STATE_SELECTORS[override.state as string];\n if (!stateSelector) continue;\n let mediaQuery: string | undefined;\n if (override.breakpoint) {\n mediaQuery = resolveMediaQuery(\n media,\n override.breakpoint as TBreakpoint,\n (override.query ?? \"exact\") as MediaVariant,\n override.orientation,\n ) || undefined;\n }\n const node = shorthandNode(`${selector}${stateSelector}`, override.declarations ?? {}, mediaQuery);\n if (node) stateNodes.push(node);\n }\n }\n\n // Container-query overrides (§10.5): compose the shorthand and wrap it in `@container <name> (…)`.\n const containerNodes: CssRuleNode[] = [];\n for (const [name, ruleSet] of Object.entries(group)) {\n const selector = selectorBuilder(name);\n for (const override of ruleSet.overrides) {\n if (!override.container) continue;\n const query = containerQueryFor(override, options.containers);\n if (!query) continue;\n const node = shorthandNode(selector, override.declarations ?? {}, query);\n if (node) containerNodes.push(node);\n }\n }\n\n return { nodes: [...nodes, ...stateNodes, ...containerNodes], variants };\n};\n\n// ---------------------------------------------------------------------------\n// Merged (flattened) rule-set lowering — the `components` emit mode (§9d/9e)\n// ---------------------------------------------------------------------------\n\n/** Sort merged state keys by the canonical `CSS_STATE_SELECTORS` order (hover before disabled, …). */\nconst orderStateKeys = (keys: string[]): string[] =>\n [...keys].sort(\n (a, b) =>\n (STATE_ORDER[a] ?? Number.MAX_SAFE_INTEGER) - (STATE_ORDER[b] ?? Number.MAX_SAFE_INTEGER),\n );\n\nexport type LowerMergedRuleSetOptions<TBreakpoint extends string = string> = {\n /** The base selector for the flattened variant (e.g. `.app-buttons-primary`). */\n selector: string;\n media: MediaDescriptor<TBreakpoint>;\n pathToVar: Record<string, string>;\n /** Container-query descriptors (§10.5) — resolve a merged container bucket → `@container …`. */\n containers?: ContainerDescriptors;\n};\n\n/**\n * Lower one flattened {@link MergedRuleSet} to `CssRuleNode[]` — the format-neutral twin of\n * {@link lowerRecipeGroup} for the `components` emit mode. Reuses the same declaration lowering,\n * state→selector table, and media resolution: `base` → the base rule at `selector`; each `state`\n * → a `${selector}:hover`/`[disabled]`/… rule (canonical order); each responsive entry → an\n * `@media` block (with an optional state selector). Declarations stay as `var(--…)` refs — inline\n * baking is a render-time choice the adapter makes downstream (via `enrichDeclarationsWithRefs`).\n */\nexport const lowerMergedRuleSet = <TBreakpoint extends string = string>(\n merged: MergedRuleSet,\n options: LowerMergedRuleSetOptions<TBreakpoint>,\n): CssRuleNode[] => {\n const { selector, media, pathToVar, containers } = options;\n const nodes: CssRuleNode[] = [];\n\n const baseDeclarations = declarationsFromRefs(merged.base, pathToVar);\n if (baseDeclarations.length) nodes.push({ kind: \"rule\", selector, declarations: baseDeclarations });\n\n for (const state of orderStateKeys(Object.keys(merged.states))) {\n const stateSelector = CSS_STATE_SELECTORS[state];\n if (!stateSelector) continue;\n const declarations = declarationsFromRefs(merged.states[state], pathToVar);\n if (declarations.length) {\n nodes.push({ kind: \"rule\", selector: `${selector}${stateSelector}`, declarations });\n }\n }\n\n for (const entry of merged.responsive) {\n // A viewport bucket → `@media`; a container bucket (§10.5) → `@container` (carried on the same\n // generic `media` field). Both may still carry a state selector.\n const atRule = entry.container\n ? containerQueryFor(entry as RuleSetOverride, containers)\n : resolveMediaQuery(\n media,\n entry.breakpoint as TBreakpoint,\n (entry.query ?? \"exact\") as MediaVariant,\n entry.orientation,\n );\n if (!atRule) continue;\n const declarations = declarationsFromRefs(entry.declarations, pathToVar);\n if (!declarations.length) continue;\n const stateSelector = entry.state ? CSS_STATE_SELECTORS[entry.state] ?? \"\" : \"\";\n nodes.push({ kind: \"rule\", selector: `${selector}${stateSelector}`, media: atRule, declarations });\n }\n\n return nodes;\n};\n","/**\n * Render the CSS adapter's `CssNode[]` IR to a CSS string, plus the enrich/split\n * helpers the delivery modes need. Ported (copy, not rewrite) from the proven\n * `core/common/{cssRenderer,cssEnrich,cssRender}.ts`, self-contained (no core imports).\n */\nimport type { CssKeyframesNode, CssNode, CssRuleNode, CssVariablesNode } from \"./nodes\";\n\nexport type RenderCssOptions = {\n indent?: string;\n newline?: string;\n};\n\nconst DEFAULT_INDENT = \" \";\nconst DEFAULT_NEWLINE = \"\\n\";\n\n/**\n * Render an IR (`CssNode[]`) to a CSS string. Adjacent variable nodes sharing the same\n * `selector` + `media` merge into one block, so two subsystems that both contribute\n * `:root` variables produce one `:root { … }` block.\n */\nexport const renderToCssString = (nodes: CssNode[], options: RenderCssOptions = {}): string => {\n const indent = options.indent ?? DEFAULT_INDENT;\n const newline = options.newline ?? DEFAULT_NEWLINE;\n const blocks: string[] = [];\n\n const merged = mergeAdjacentVariableNodes(nodes);\n\n for (const node of merged) {\n if (node.kind === \"keyframes\") {\n const body = renderKeyframesBody(node, indent, newline);\n if (!body) continue;\n blocks.push(`@keyframes ${node.name} {${newline}${body}${newline}}`);\n continue;\n }\n\n const body =\n node.kind === \"variables\"\n ? renderVariableBody(node.variables, indent, newline)\n : renderRuleBody(node.declarations, indent, newline);\n\n if (!body) continue;\n\n const inner = `${node.selector} {${newline}${body}${newline}}`;\n if (node.media) {\n blocks.push(`${node.media} {${newline}${indentBlock(inner, indent, newline)}${newline}}`);\n } else {\n blocks.push(inner);\n }\n }\n\n return blocks.filter(Boolean).join(`${newline}${newline}`);\n};\n\nconst mergeAdjacentVariableNodes = (nodes: CssNode[]): CssNode[] => {\n const keyFor = (node: CssNode): string =>\n node.kind === \"variables\" ? `var:${node.media ?? \"\"}:${node.selector}` : \"\";\n\n const output: CssNode[] = [];\n for (const node of nodes) {\n if (node.kind !== \"variables\") {\n output.push(node);\n continue;\n }\n const key = keyFor(node);\n const previous = output[output.length - 1];\n if (previous && previous.kind === \"variables\" && keyFor(previous) === key) {\n previous.variables = { ...previous.variables, ...node.variables };\n } else {\n output.push({\n kind: \"variables\",\n selector: node.selector,\n media: node.media,\n variables: { ...node.variables },\n });\n }\n }\n return output;\n};\n\nconst renderVariableBody = (\n variables: Record<string, string>,\n indent: string,\n newline: string,\n): string => {\n const entries = Object.entries(variables);\n if (!entries.length) return \"\";\n return entries.map(([name, value]) => `${indent}${name}: ${value};`).join(newline);\n};\n\nconst renderRuleBody = (\n declarations: CssRuleNode[\"declarations\"],\n indent: string,\n newline: string,\n): string => {\n if (!declarations.length) return \"\";\n return declarations.map(({ property, value }) => `${indent}${property}: ${value};`).join(newline);\n};\n\n/** Render a keyframes at-rule body: one indented `<stop> { … }` block per step, in order. */\nconst renderKeyframesBody = (\n node: CssKeyframesNode,\n indent: string,\n newline: string,\n): string => {\n const steps = node.steps\n .map(step => {\n if (!step.declarations.length) return \"\";\n const decls = step.declarations\n .map(({ property, value }) => `${indent}${indent}${property}: ${value};`)\n .join(newline);\n return `${indent}${step.stop} {${newline}${decls}${newline}${indent}}`;\n })\n .filter(Boolean);\n return steps.join(newline);\n};\n\nconst indentBlock = (block: string, indent: string, newline: string): string =>\n block\n .split(newline)\n .map(line => (line.length ? `${indent}${line}` : line))\n .join(newline);\n\n// ---------------------------------------------------------------------------\n// split / render slices\n// ---------------------------------------------------------------------------\n\nexport const splitNodes = (nodes: CssNode[]): {\n variables: CssVariablesNode[];\n rules: CssNode[];\n} => {\n const variables: CssVariablesNode[] = [];\n const rules: CssNode[] = [];\n for (const node of nodes) {\n // Keyframes ride the rules stream (they are style output, never a variables block).\n if (node.kind === \"variables\") variables.push(node);\n else rules.push(node);\n }\n return { variables, rules };\n};\n\nexport const renderVariablesCss = (nodes: CssNode[]): string =>\n renderToCssString(splitNodes(nodes).variables);\n\nexport const renderRulesCss = (nodes: CssNode[]): string =>\n renderToCssString(splitNodes(nodes).rules);\n\n// ---------------------------------------------------------------------------\n// enrich (ref / resolved) — used by inline delivery\n// ---------------------------------------------------------------------------\n\nconst VAR_PATTERN = /var\\((--[^)]+)\\)/;\n\n/**\n * Build the `var name → resolved literal value` map from a node set's variable blocks: direct\n * literals first, then a second pass resolving one level of `var(--…)` indirection. Shared by\n * `enrichDeclarationsWithRefs` (inline baking) and the `components` non-inline tree-shaken\n * variables file, so both source values the same way (no re-derived formatting).\n */\nexport const buildVariableValueMap = (nodes: CssNode[]): Map<string, string> => {\n const variableMap = new Map<string, string>();\n for (const node of nodes) {\n if (node.kind !== \"variables\") continue;\n for (const [name, value] of Object.entries(node.variables)) {\n if (!VAR_PATTERN.test(value)) variableMap.set(name, value);\n }\n }\n\n for (const node of nodes) {\n if (node.kind !== \"variables\") continue;\n for (const [name, value] of Object.entries(node.variables)) {\n if (variableMap.has(name)) continue;\n const match = value.match(VAR_PATTERN);\n if (match) {\n const resolved = variableMap.get(match[1]);\n if (resolved) variableMap.set(name, resolved);\n }\n }\n }\n\n return variableMap;\n};\n\n/**\n * Enrich `CssRuleNode` declarations with `ref` (the CSS var they reference) and `resolved`\n * (its literal value), cross-referenced against the variable nodes. Mutates in place.\n */\nexport const enrichDeclarationsWithRefs = (nodes: CssNode[]): void => {\n const variableMap = buildVariableValueMap(nodes);\n\n const enrich = (decl: CssRuleNode[\"declarations\"][number]): void => {\n if (typeof decl.value !== \"string\") return;\n const match = decl.value.match(VAR_PATTERN);\n if (!match) return;\n decl.ref = match[1];\n const resolved = variableMap.get(match[1]);\n if (resolved !== undefined) decl.resolved = resolved;\n };\n\n for (const node of nodes) {\n if (node.kind === \"keyframes\") {\n for (const step of node.steps) for (const decl of step.declarations) enrich(decl);\n continue;\n }\n if (node.kind !== \"rule\") continue;\n for (const decl of node.declarations) enrich(decl);\n }\n};\n","/**\n * The CSS adapter — lowers the format-neutral {@link ThemeModel} to CSS.\n *\n * `bind(model, ctx)` curries the Model + context once, precomputes the per-subsystem\n * `CssNode[]` lowering (variables + recipe rules + class minting), and returns the render\n * surface (`recipeName` / `renderRecipe` / `renderVariables` / `join`) plus the aggregate\n * outputs the theme surfaces (`css` / `variablesCss` / `recipesCss` / `nodes` / `classes`)\n * via `extend`. Core stays CSS-independent; all naming, the node IR, state selectors, and\n * class minting live here.\n */\nimport type { ThemeModel } from \"@theme-registry/refract\";\nimport { mergeComponentRuleSet } from \"@theme-registry/refract\";\nimport { toHexColor, toOklchColor } from \"@theme-registry/refract/color-math\";\nimport type { AdapterSpec, PreviewDescriptor, RenderContext, ThemeAdapter, UsageRecipe } from \"@theme-registry/refract\";\nimport { defineAdapter } from \"@theme-registry/refract\";\nimport type { CssDeclaration, CssNode, CssRuleNode, CssVariablesNode } from \"./nodes\";\nimport {\n deriveColorsVariableNodes,\n buildColorsPathToVar,\n deriveTypographyVariableNodes,\n buildTypographyPathToVar,\n deriveEffectsVariableNodes,\n buildEffectsPathToVar,\n deriveBordersVariableNodes,\n buildBordersPathToVar,\n deriveAnimationVariableNodes,\n buildAnimationPathToVar,\n deriveLayoutVariableNodes,\n deriveLayoutConfigVariableNodes,\n buildLayoutPathToVar,\n splitLayoutProperties,\n lowerRecipeGroup,\n lowerContainerGroup,\n lowerMergedRuleSet,\n lowerGlobalsGroups,\n lowerKeyframes,\n lowerAnimationRecipeGroup,\n deriveContainerContextNodes,\n CSS_KNOWN_STATES,\n CSS_STATE_SELECTORS,\n} from \"./lowering\";\nimport { resolveNaming, createNamer } from \"./naming\";\nimport type { NamingOverrides } from \"./naming\";\nimport {\n renderToCssString,\n renderVariablesCss,\n renderRulesCss,\n enrichDeclarationsWithRefs,\n buildVariableValueMap,\n} from \"./render\";\n\n/** CSS adapter options — two naming knobs (variables + classes) + value/delivery knobs (§18). */\nexport type CssAdapterOptions = {\n /**\n * Identifier prefix for every CSS **variable** name (`--<prefix>-colors-primary`). Default `dt`.\n * Subsystems are namespaced by the token path, not by separate options. For MFE isolation (two\n * bundles on one page), give each build a distinct `prefix` — that renames its variables without\n * touching another bundle's.\n */\n prefix?: string;\n /**\n * Class-name prefix for every **class** the adapter emits — recipe classes\n * (`.<classPrefix>-colors-solid-primary`) AND the container-query context classes\n * (`.<classPrefix>-cq-<name>`). Defaults to `prefix`.\n */\n classPrefix?: string;\n /** Inline resolved values instead of `var(--…)` references (drops the variable blocks). */\n inline?: boolean;\n /**\n * Output format for **palette colour** values in the emitted CSS (§20) — the `:root` colour\n * variables (base / `text` / variants / responsive / modes). `\"rgb\"` (default) emits\n * `rgb()`/`rgba()`; `\"hex\"` emits `#rrggbb`/`#rrggbbaa`; `\"oklch\"` emits CSS Color 4\n * `oklch(L% C H)`. The colour is identical — this is presentation only. Colours typed literally\n * into a recipe declaration pass through as authored; this applies to the synthesized tokens.\n */\n colorFormat?: \"rgb\" | \"hex\" | \"oklch\";\n /**\n * §7B — swap how class + variable names are generated. Two optional formatters (`className` /\n * `variableName`), each receiving the structured address + the built-in default (decorate or\n * replace). Omit it and naming is byte-identical to the default. The adapter enforces the contract:\n * deterministic (a pure fn of the address), collision-free (a duplicate output throws), and a valid\n * identifier (run through the segment sanitizer). Covers recipe classes AND the `-cq-<name>`\n * container-context utilities (via the `kind` discriminator).\n */\n naming?: NamingOverrides;\n /**\n * §W9 — wrap all emitted CSS in a named cascade `@layer`. `true` uses the layer name `\"refract\"`; a\n * string sets a custom name (e.g. `\"refract.recipes\"`). Off by default (byte-identical output). A\n * cascade layer gives refract's rules **deterministic precedence** below any unlayered app CSS or\n * utility framework, regardless of load order — the modern answer to source-order fragility. All\n * output (variables, globals, recipes) rides one layer; author your app CSS unlayered (or in a\n * later-declared layer) to win. Applies to single-file emit and the runtime `theme.css` surface.\n */\n layer?: string | boolean;\n /**\n * §W-motion — append a `@media (prefers-reduced-motion: reduce)` block that neutralizes animation +\n * transition durations for users who ask for less motion (the well-known global reset). Off by\n * default (byte-identical); opt in for an accessible default. Emitted outside any `layer` so its\n * `!important` behaves predictably. Applies to single-file emit and the runtime `theme.css` surface.\n */\n reducedMotion?: boolean;\n};\n\n/**\n * §W-motion — the standard \"kill motion\" block for `prefers-reduced-motion: reduce`. Appended to the\n * full document when the `reducedMotion` option is on.\n */\nconst REDUCED_MOTION_BLOCK =\n \"@media (prefers-reduced-motion: reduce) {\\n\" +\n \" *, *::before, *::after {\\n\" +\n \" animation-duration: 0.01ms !important;\\n\" +\n \" animation-iteration-count: 1 !important;\\n\" +\n \" transition-duration: 0.01ms !important;\\n\" +\n \" scroll-behavior: auto !important;\\n\" +\n \" }\\n\" +\n \"}\\n\";\n\n/** `.cls`, `.cls:state`, `.cls[attr]` all belong to the recipe whose base selector is `.cls`. */\nconst selectorBelongsToRecipe = (nodeSelector: string, base: string): boolean =>\n nodeSelector === base || nodeSelector.startsWith(`${base}:`) || nodeSelector.startsWith(`${base}[`);\n\ntype SubsystemLowering = {\n variableNodes: CssVariablesNode[];\n /** Class rules — plus, for animation, its `@keyframes` at-rule nodes (they ride the rules stream). */\n recipeNodes: CssNode[];\n /** group → variant → selector (`.dt-color-solid-primary`). */\n selectors: Record<string, Record<string, string>>;\n};\n\n/** The resolved composition class for one component variant (referenced classes + own delta). */\ntype ResolvedComponentClass = { className: string; classList: string[] };\n\n/** Parse a component reference (`\"colors:solid.primary\"`) into its address parts. */\nconst parseComponentReference = (\n reference: string,\n): { subsystem: string; group: string; variant: string } | undefined => {\n const [subsystem, rest] = reference.split(\":\");\n if (!subsystem || !rest) return undefined;\n const dot = rest.indexOf(\".\");\n if (dot < 0) return undefined;\n return { subsystem, group: rest.slice(0, dot), variant: rest.slice(dot + 1) };\n};\n\nexport const createCssAdapter = (options: CssAdapterOptions = {}): ThemeAdapter<string> => {\n const spec: AdapterSpec<string> = {\n name: \"css\",\n version: 1,\n // The CSS adapter owns the known-state set; core threads it into recipe normalization.\n allowedStates: CSS_KNOWN_STATES,\n bind(model: ThemeModel, ctx: RenderContext) {\n const media = ctx.media;\n const inline = options.inline ?? false;\n // §21: length units are resolved format-neutrally in core (`createTheme({ units })`) and baked\n // onto the Model's length leaves — the adapter only stringifies `value + unit`. No `length` here.\n // §17: the single adapter-wide naming pair. `varToken` leads every variable, `naming` drives\n // every recipe class (`.<classToken>-<subsystem>-<group>-<variant>`).\n const naming = resolveNaming({ prefix: options.prefix, classPrefix: options.classPrefix });\n // §7B: the override-aware namer owns the two pure choke points (var + class naming) plus the\n // collision Set. `varName` (a token path → its var name) threads through the variable lowering\n // in place of the raw `varToken`; `namer.className` mints every recipe + container-context class.\n const namer = createNamer(naming, options.naming);\n const varName = namer.variableName;\n\n // §20: palette-colour output format. `rgb` (default) passes the Model's canonical value\n // through unchanged; `hex` / `oklch` re-serialize the same colour for the emitted CSS vars.\n const colorFormat = options.colorFormat ?? \"rgb\";\n const formatColor = (value: unknown): string => {\n const s = value == null ? \"\" : String(value);\n if (!s || colorFormat === \"rgb\") return s;\n return colorFormat === \"hex\" ? toHexColor(s) : toOklchColor(s);\n };\n\n // ── Per-subsystem lowering (colors / typography / effects / layout / components) ──\n const lowered: Record<string, SubsystemLowering> = {};\n // Global token-path → var union (all subsystems): a component `css` delta can reference any\n // subsystem's token, so its refs must resolve against every subsystem's naming.\n const globalPathToVar: Record<string, string> = {};\n\n // Shared recipe loop: every subsystem lowers its rule-set groups the same way — the recipe\n // class name is uniform (`<classToken>-<subsystem>-<group>-<variant>`); only the token-path→var\n // map differs (some subsystems resolve refs against the global union).\n const lowerRecipes = (\n subsystem: string,\n ruleSets: NonNullable<ThemeModel[\"subsystems\"][string][\"ruleSets\"]>,\n pathToVar: Record<string, string>,\n ): { recipeNodes: CssRuleNode[]; selectors: Record<string, Record<string, string>> } => {\n const recipeNodes: CssRuleNode[] = [];\n const selectors: Record<string, Record<string, string>> = {};\n for (const [group, ruleSetGroup] of Object.entries(ruleSets)) {\n const { nodes, variants } = lowerRecipeGroup(ruleSetGroup, {\n media,\n selectorBuilder: variant => `.${namer.className(\"recipe\", subsystem, group, variant)}`,\n pathToVar,\n containers: ctx.containers,\n });\n recipeNodes.push(...nodes);\n selectors[group] = variants;\n }\n return { recipeNodes, selectors };\n };\n\n const colors = model.subsystems.colors;\n if (colors) {\n const props = colors.properties ?? {};\n const pathToVar = buildColorsPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const variableNodes = deriveColorsVariableNodes(props, { varName, media, formatColor });\n const { recipeNodes, selectors } = lowerRecipes(\"colors\", colors.ruleSets ?? {}, pathToVar);\n lowered.colors = { variableNodes, recipeNodes, selectors };\n }\n\n const typography = model.subsystems.typography;\n if (typography) {\n const props = typography.properties ?? {};\n const pathToVar = buildTypographyPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const variableNodes = deriveTypographyVariableNodes(props, { varName, media });\n const { recipeNodes, selectors } = lowerRecipes(\"typography\", typography.ruleSets ?? {}, pathToVar);\n lowered.typography = { variableNodes, recipeNodes, selectors };\n }\n\n const effects = model.subsystems.effects;\n if (effects) {\n const props = effects.properties ?? {};\n const pathToVar = buildEffectsPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n // §15: shadow/transition tokens compose from structure; a layer's `colors.*` color ref\n // resolves via the global map (colors processed first — the §14.4 cross-subsystem rule).\n const variableNodes = deriveEffectsVariableNodes(props, { varName, media, pathToVar: globalPathToVar });\n const { recipeNodes, selectors } = lowerRecipes(\"effects\", effects.ruleSets ?? {}, pathToVar);\n lowered.effects = { variableNodes, recipeNodes, selectors };\n }\n\n // ── Borders (§14): stroke geometry tokens (width/style/offset/radius) → `:root` vars, and\n // border/outline recipes → classes. A borders recipe declaration may carry a value-level\n // `colors.*` ref (border-color/outline-color, §14.4) — so its declarations resolve against\n // `globalPathToVar` (colors is processed first, its path→var already merged) rather than the\n // subsystem-local map, which only knows `borders.*`. ──\n const borders = model.subsystems.borders;\n if (borders) {\n const props = borders.properties ?? {};\n const pathToVar = buildBordersPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const variableNodes = deriveBordersVariableNodes(props, { varName, media });\n const { recipeNodes, selectors } = lowerRecipes(\"borders\", borders.ruleSets ?? {}, globalPathToVar);\n lowered.borders = { variableNodes, recipeNodes, selectors };\n }\n\n // ── Layout: regular vars + config `:root` vars, structural rule-sets (columns/grids/stacks\n // via lowerRecipeGroup, container via the two-pass lowerContainerGroup) + padding recipes ──\n const layout = model.subsystems.layout;\n if (layout) {\n const props = layout.properties ?? {};\n const pathToVar = buildLayoutPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const { regular, config } = splitLayoutProperties(props);\n\n const variableNodes = [\n ...deriveLayoutVariableNodes(regular, { varName, media }),\n ...deriveLayoutConfigVariableNodes(config, { varName, pathToVar }),\n ];\n\n const recipeNodes: CssRuleNode[] = [];\n const selectors: Record<string, Record<string, string>> = {};\n for (const [group, ruleSetGroup] of Object.entries(layout.ruleSets ?? {})) {\n // Structural groups (columns/grids/stacks/container) + padding recipes all take the uniform\n // recipe class `.<ct>-layout-<group>-<variant>` (§17).\n const selectorBuilder = (variant: string) =>\n `.${namer.className(\"recipe\", \"layout\", group, variant)}`;\n const lower = group === \"container\" ? lowerContainerGroup : lowerRecipeGroup;\n const { nodes, variants } = lower(ruleSetGroup, { media, selectorBuilder, pathToVar, containers: ctx.containers });\n recipeNodes.push(...nodes);\n selectors[group] = variants;\n }\n lowered.layout = { variableNodes, recipeNodes, selectors };\n }\n\n // ── Animation (§10.2): motion tokens (duration/easing/delay) → `:root` vars, keyframes →\n // `@keyframes` at-rules, animation recipes → a class with the composed `animation:`\n // shorthand. Processed after the base subsystems so keyframe step refs (e.g. `colors.*`)\n // resolve against the global path→var union. ──\n const animation = model.subsystems.animation;\n if (animation) {\n const props = animation.properties ?? {};\n const pathToVar = buildAnimationPathToVar(props, varName);\n Object.assign(globalPathToVar, pathToVar);\n const variableNodes = deriveAnimationVariableNodes(props, { varName, media });\n\n const keyframes = animation.keyframes ?? {};\n const keyframeNodes = lowerKeyframes(keyframes, globalPathToVar);\n const keyframeNames = new Set(Object.keys(keyframes));\n\n const recipeNodes: CssNode[] = [...keyframeNodes];\n const selectors: Record<string, Record<string, string>> = {};\n for (const [group, ruleSetGroup] of Object.entries(animation.ruleSets ?? {})) {\n const { nodes, variants } = lowerAnimationRecipeGroup(ruleSetGroup, {\n media,\n selectorBuilder: variant => `.${namer.className(\"recipe\", \"animation\", group, variant)}`,\n pathToVar: globalPathToVar,\n keyframeNames,\n containers: ctx.containers,\n });\n recipeNodes.push(...nodes);\n selectors[group] = variants;\n }\n lowered.animation = { variableNodes, recipeNodes, selectors };\n }\n\n // ── Components (composition): no properties/variables — only recipes that reference other\n // subsystems' recipes (kept as Model `references`) + an own `css` delta on its own class.\n // The className list = the referenced recipe classes (looked up from the already-lowered\n // subsystems' selectors, so their `:hover` etc. ride along) + the own delta class. ──\n const componentClasses: Record<string, Record<string, ResolvedComponentClass>> = {};\n const components = model.subsystems.components;\n if (components) {\n const recipeNodes: CssRuleNode[] = [];\n const selectors: Record<string, Record<string, string>> = {};\n\n const resolveReferencedClass = (reference: string): string | undefined => {\n const parsed = parseComponentReference(reference);\n if (!parsed) return undefined;\n const selector = lowered[parsed.subsystem]?.selectors[parsed.group]?.[parsed.variant];\n return selector?.replace(/^\\./, \"\");\n };\n\n for (const [group, ruleSetGroup] of Object.entries(components.ruleSets ?? {})) {\n const { nodes, variants } = lowerRecipeGroup(ruleSetGroup, {\n media,\n selectorBuilder: variant => `.${namer.className(\"recipe\", \"components\", group, variant)}`,\n pathToVar: globalPathToVar,\n containers: ctx.containers,\n });\n recipeNodes.push(...nodes);\n selectors[group] = variants;\n\n componentClasses[group] = {};\n for (const [variant, ruleSet] of Object.entries(ruleSetGroup)) {\n const ownClass = variants[variant].replace(/^\\./, \"\");\n const referenced = (ruleSet.references ?? [])\n .map(resolveReferencedClass)\n .filter((cls): cls is string => cls !== undefined);\n const classList = [...referenced, ownClass];\n componentClasses[group][variant] = { className: classList.join(\" \"), classList };\n }\n }\n\n lowered.components = { variableNodes: [], recipeNodes, selectors };\n }\n\n // ── Globals (§9): preset `kind:\"reset\"` layers → `:where(sel){…}`; themed `kind:\"globals\"`\n // elements → bare `sel{…}` + `sel:state` + `sel.<variant>`. No properties/variables.\n // Lowered LAST (globalPathToVar now holds every subsystem's tokens) so its themed refs\n // resolve against them, then HOISTED ahead of all recipes in collectNodes. ──\n const globals = model.subsystems.globals;\n if (globals) {\n const recipeNodes = lowerGlobalsGroups(globals.ruleSets ?? {}, globalPathToVar, media, ctx.containers);\n lowered.globals = { variableNodes: [], recipeNodes, selectors: {} };\n }\n\n // ── Container context (§10.5): the `.dt-cq-<name>` utility classes that establish each named\n // containment context. Named via the §7B `kind:\"container\"` namer (default\n // `<classToken>-cq-<name>`); the `@container` rules that respond to them are lowered inline\n // on each recipe (via ctx.containers). The same `containerClass` fn feeds `theme.classes`. ──\n const containerClass = (name: string): string =>\n namer.className(\"container\", \"containers\", \"context\", name);\n const containerContextNodes = deriveContainerContextNodes(model.containers, containerClass);\n\n // ── Aggregate node collection (reset first, then container-context classes, then variables +\n // recipes per subsystem, in Model order). Reset's specificity-0 `:where()` rules lead so they\n // never fight recipe classes. ──\n const collectNodes = (): CssNode[] => {\n const nodes: CssNode[] = [];\n if (lowered.globals) nodes.push(...lowered.globals.recipeNodes);\n nodes.push(...containerContextNodes);\n for (const key of Object.keys(model.subsystems)) {\n if (key === \"globals\") continue;\n const sub = lowered[key];\n if (!sub) continue;\n nodes.push(...sub.variableNodes, ...sub.recipeNodes);\n }\n enrichDeclarationsWithRefs(nodes);\n return nodes;\n };\n\n // §W9 / §W-motion — full-document post-processing (single emit + runtime `css`): optional cascade\n // `@layer` wrap, then an optional `prefers-reduced-motion` block (outside the layer). Both off →\n // byte-identical.\n const layerName =\n options.layer === true ? \"refract\" : (typeof options.layer === \"string\" && options.layer) || undefined;\n const reducedMotion = options.reducedMotion ?? false;\n const finalizeDoc = (css: string): string => {\n let out = css;\n if (layerName) {\n const body = css\n .trimEnd()\n .split(\"\\n\")\n .map(line => (line ? ` ${line}` : line))\n .join(\"\\n\");\n out = `@layer ${layerName} {\\n${body}\\n}\\n`;\n }\n if (reducedMotion) out = `${out.trimEnd()}\\n\\n${REDUCED_MOTION_BLOCK}`;\n return out;\n };\n\n // ── Delivery-mode CSS rendering (default / inline) ──\n const renderCss = (nodes: CssNode[]): string => {\n if (!inline) return renderToCssString(nodes);\n // Bake resolved values into rule + keyframe declarations; drop the variable blocks. Resolve\n // EACH `var(--…)` within a value (not just the first) so a composed shorthand — e.g. the\n // animation `duration easing name` — bakes every part; single-var declarations are unchanged.\n const varMap = buildVariableValueMap(nodes);\n const bake = (decl: CssDeclaration): CssDeclaration => {\n if (typeof decl.value !== \"string\") return { property: decl.property, value: decl.value };\n const value = decl.value.replace(/var\\((--[^)]+)\\)/g, (whole, name: string) => {\n const resolved = varMap.get(name);\n return resolved !== undefined ? String(resolved) : whole;\n });\n return { property: decl.property, value };\n };\n const inlined: CssNode[] = [];\n for (const n of nodes) {\n if (n.kind === \"rule\") {\n inlined.push({ ...n, declarations: n.declarations.map(bake) });\n } else if (n.kind === \"keyframes\") {\n inlined.push({ ...n, steps: n.steps.map(s => ({ stop: s.stop, declarations: s.declarations.map(bake) })) });\n }\n }\n return renderToCssString(inlined);\n };\n\n // ── classes: subsystem → group → variant → className. Recipe subsystems map to the plain\n // class string; the composition subsystem maps to `{ className, classList }` (referenced\n // recipe classes + own delta), matching the OLD ResolvedComponentClass shape. ──\n const collectClasses = (): Record<string, Record<string, Record<string, unknown>>> => {\n const out: Record<string, Record<string, Record<string, unknown>>> = {};\n for (const [key, sub] of Object.entries(lowered)) {\n if (key === \"globals\") continue; // globals targets raw selectors — no minted classes\n if (key === \"components\") {\n out[key] = componentClasses;\n continue;\n }\n const groups: Record<string, Record<string, string>> = {};\n for (const [group, variants] of Object.entries(sub.selectors)) {\n groups[group] = Object.fromEntries(\n Object.entries(variants).map(([variant, selector]) => [variant, selector.replace(/^\\./, \"\")]),\n );\n }\n out[key] = groups;\n }\n // Container-context utility classes (§10.5): `containers.<name> → \".dt-cq-<name>\"` (no leading dot).\n if (model.containers && Object.keys(model.containers).length) {\n const containerGroup: Record<string, string> = {};\n for (const name of Object.keys(model.containers)) {\n containerGroup[name] = containerClass(name);\n }\n out.containers = { context: containerGroup };\n }\n return out;\n };\n\n const selectorFor = (subsystem: string, group: string, variant: string): string | undefined =>\n lowered[subsystem]?.selectors[group]?.[variant];\n\n // Class-name accessor mirroring `theme.classes` (single source of truth): the plain recipe\n // class for normal subsystems, and the space-joined composition string (`className`) for\n // `components` and the `containers.context.*` utilities. Returns `undefined` for an\n // unknown subsystem/group/variant address.\n const getClass = (subsystem: string, group: string, variant: string): string | undefined => {\n const leaf = collectClasses()[subsystem]?.[group]?.[variant];\n if (leaf === undefined) return undefined;\n return typeof leaf === \"string\" ? leaf : (leaf as ResolvedComponentClass).className;\n };\n\n // Per-recipe delivery: the subsystem's own rules for one variant (base + its state/breakpoint\n // rules — `selectorBelongsToRecipe` keeps `.cls`, `.cls:hover`, `.cls[disabled]`).\n const renderRecipe = (subsystem: string, group: string, variant: string): string => {\n const sub = lowered[subsystem];\n const base = selectorFor(subsystem, group, variant);\n if (!sub || !base) return \"\";\n const nodes = sub.recipeNodes.filter(\n (n): n is CssRuleNode => n.kind === \"rule\" && selectorBelongsToRecipe(n.selector, base),\n );\n return renderCss(nodes);\n };\n\n return {\n recipeName(subsystem, group, variant) {\n return (selectorFor(subsystem, group, variant) ?? \"\").replace(/^\\./, \"\");\n },\n renderRecipe,\n renderVariables(subsystem) {\n return renderToCssString(lowered[subsystem]?.variableNodes ?? []);\n },\n join(parts) {\n return parts.filter(Boolean).join(\"\\n\\n\");\n },\n\n // Aggregators overridden so the full document renders through the node IR (delivery-aware).\n renderAllVariables: () => renderVariablesCss(collectNodes()),\n renderAllRecipes: () => renderRulesCss(collectNodes()),\n renderAll: () => finalizeDoc(renderCss(collectNodes())),\n\n // Self-documentation: the REAL class names (composition strings for components) via getClass,\n // plus CSS-specific consumption prose for the emitted guide (llms.txt).\n describeUsage() {\n const recipes: UsageRecipe[] = [];\n for (const [subsystem, sub] of Object.entries(model.subsystems)) {\n for (const [group, ruleSet] of Object.entries(sub.ruleSets ?? {})) {\n for (const variant of Object.keys(ruleSet)) {\n const name = getClass(subsystem, group, variant);\n if (name) recipes.push({ subsystem, group, variant, name });\n }\n }\n }\n return {\n format: \"css\",\n summary: [\n \"Import the stylesheet once, then apply the recipe class names below to your elements.\",\n 'Example: `import \"./theme.css\";` then `<button class=\"<class>\">`.',\n \"Values are CSS custom properties (`var(--…)`), so runtime theming = override the variables under a selector or `[data-theme]`.\",\n ],\n recipes,\n };\n },\n\n // Human-facing preview (§20): CSS is the one format a browser loads as-is, so this is where\n // the live recipe plates come from. Both answers depend on the PLAN, which is why it's an\n // argument: `split` has a load-order contract (variables first), `subsystem`/`components`\n // name files through a user-supplied function, and `components` emits merged self-contained\n // rules keyed by the recipe's OWN class rather than the composition list every other mode uses.\n describePreview(plan, files): PreviewDescriptor {\n const written = new Set(files);\n const keep = (...names: Array<string | false | undefined>): string[] =>\n names.filter((n): n is string => typeof n === \"string\" && written.has(n));\n\n // `components` emits ONLY the components subsystem, so every other subsystem's recipes have\n // no CSS in this output — listing them as renderable would be a lie.\n const renderable = (r: UsageRecipe): boolean =>\n plan.type !== \"components\" || r.subsystem === \"components\";\n\n const markup = (r: UsageRecipe) => {\n if (!renderable(r)) return undefined;\n // components mode: the merged rule targets the own class; every other mode wants the full\n // composition list `getClass` returns.\n const name =\n plan.type === \"components\"\n ? (selectorFor(r.subsystem, r.group, r.variant) ?? \"\").replace(/^\\./, \"\")\n : getClass(r.subsystem, r.group, r.variant);\n return name ? { attrs: { class: name } } : undefined;\n };\n\n const ruleSetOf = (r: UsageRecipe) =>\n model.subsystems[r.subsystem]?.ruleSets?.[r.group]?.[r.variant];\n\n /** The states this rule-set actually declares, in the adapter's canonical order. */\n const states = (r: UsageRecipe): string[] => {\n if (!renderable(r)) return [];\n const declared = new Set(\n (ruleSetOf(r)?.overrides ?? [])\n .map(o => o.state)\n .filter((s): s is string => typeof s === \"string\"),\n );\n return CSS_KNOWN_STATES.filter(s => declared.has(s));\n };\n\n // A pseudo-class can't be switched on from markup, so a specimen sheet can never show\n // `:hover` at rest. The fix is a parallel rule keyed on a plain class: same declarations,\n // pinnable selector. These rules exist ONLY for the preview and are inlined into the page,\n // never added to the emitted stylesheet a consumer ships.\n const PIN_PREFIX = \"rfp-s-\";\n const statePinClass = (state: string): string | undefined =>\n CSS_STATE_SELECTORS[state] ? `${PIN_PREFIX}${state}` : undefined;\n\n const buildStatePinCss = (): string => {\n collectNodes(); // enrich once; recipeNodes are mutated in place\n const pinned: CssRuleNode[] = [];\n for (const sub of Object.values(lowered)) {\n for (const node of sub?.recipeNodes ?? []) {\n if (node.kind !== \"rule\") continue;\n for (const [state, suffix] of Object.entries(CSS_STATE_SELECTORS)) {\n if (!node.selector.includes(suffix)) continue;\n pinned.push({\n ...node,\n selector: node.selector.split(suffix).join(`.${PIN_PREFIX}${state}`),\n });\n break; // one state per selector — the first match is the suffix that built it\n }\n }\n }\n return pinned.length ? renderToCssString(pinned) : \"\";\n };\n\n /**\n * A composed component emits a class LIST: one class per referenced rule-set, then its own\n * delta last. `references` and `classList` are built in the same order, so they zip.\n */\n const composition = (r: UsageRecipe) => {\n const leaf = collectClasses()[r.subsystem]?.[r.group]?.[r.variant];\n if (!leaf || typeof leaf === \"string\") return undefined;\n const classList = (leaf as ResolvedComponentClass).classList;\n if (!classList || classList.length < 2) return undefined;\n const references = ruleSetOf(r)?.references ?? [];\n return classList.map((className, index) => {\n const parsed = references[index] ? parseComponentReference(references[index]) : undefined;\n return {\n className,\n from: parsed ? `${parsed.subsystem}.${parsed.group}.${parsed.variant}` : undefined,\n };\n });\n };\n\n const base = {\n markup,\n modeAttribute: \"data-theme\",\n // The emitted custom-property name for a token path — the thing a reader actually types.\n tokenName: (path: string): string | undefined => globalPathToVar[path],\n states,\n statePinClass,\n statePinCss: buildStatePinCss(),\n composition,\n } as const;\n\n switch (plan.type) {\n case \"single\":\n return { ...base, stylesheets: keep(plan.file) };\n\n case \"split\":\n // Load-order contract — the styles file references vars the variables file defines.\n return { ...base, stylesheets: keep(plan.variables, plan.file) };\n\n case \"subsystem\": {\n // Every subsystem's variables before any rules, for the same reason. Names come from the\n // plan's `filename` fn but are intersected with what was actually written.\n const subsystems = Object.keys(model.subsystems);\n return {\n ...base,\n stylesheets: [\n ...keep(...subsystems.map(sub => plan.filename(sub, \"variables\"))),\n ...keep(...subsystems.map(sub => plan.filename(sub, \"styles\"))),\n ],\n groupBy: r => r.subsystem,\n };\n }\n\n case \"components\": {\n const componentFile = (r: UsageRecipe): string =>\n plan.filename({ group: r.group, variant: r.variant });\n const variables = plan.variables === false ? [] : keep(plan.variables);\n const componentFiles = files.filter(f => !variables.includes(f));\n return {\n ...base,\n stylesheets: [...variables, ...componentFiles],\n groupBy: r => (renderable(r) ? componentFile(r) : \"not emitted in components mode\"),\n notes:\n plan.variables === false && plan.inline === false\n ? [\n \"This target emits component rules that reference CSS variables but no variables \" +\n \"file (`variables: false`), so the preview renders them undefined — supply the \" +\n \"variables yourself in the consuming app.\",\n ]\n : undefined,\n };\n }\n }\n },\n\n // Surface the CSS-named aggregate outputs on the theme (computed on demand — no stored bag),\n // plus `theme.media` = the plain core descriptor pass-through (an SC adapter would wrap it).\n extend() {\n return {\n media,\n // Per-recipe delivery helper: `theme.renderRecipe(subsystem, group, variant)` → that one\n // recipe's own CSS (base + its state/breakpoint rules). Bound to the model/ctx already.\n renderRecipe,\n // Class-name accessor: `theme.getClass(subsystem, group, variant)` → the class string you\n // drop into markup (composition classes joined for `components`). Mirrors `theme.classes`.\n getClass,\n // Token-var accessor: `theme.varName(\"colors.brand.dark\")` → its emitted CSS custom-property\n // name (`--dt-colors-brand-dark`, carrying the configured prefix), or `undefined` for a path\n // that mints no variable. The most useful question a CSS consumer/agent can ask a token path.\n varName: (path: string): string | undefined => globalPathToVar[path],\n get css() {\n return finalizeDoc(renderCss(collectNodes()));\n },\n get variablesCss() {\n return renderVariablesCss(collectNodes());\n },\n get recipesCss() {\n return renderRulesCss(collectNodes());\n },\n get nodes() {\n return collectNodes();\n },\n get classes() {\n return collectClasses();\n },\n };\n },\n\n // Self-contained build-time output: the full stylesheet (baked CSS variables + rules) a\n // downstream app links directly. The CSS adapter needs no *theme-specific* runtime helper of\n // its own, so `vendorHelpers` is empty — shared static helpers like `color-math` (the pure\n // `lighten`/`darken`) are vendored by the build layer from their single source (see\n // `src/build/vendor.ts`), not re-embedded here. (Adapters only emit vendorHelpers for helpers\n // whose source is theme-specific, e.g. the SC media module with baked `@media` strings.)\n emit(plan) {\n // `single` (the default when no plan is threaded) → one file, `plan.file` (default\n // theme.css). split / subsystem lower here (9b) by reusing the aggregate renderers over\n // the shared, ref-enriched node set; components lands in 9d–9e and still fails loud.\n const type = plan?.type ?? \"single\";\n\n // §W9 / §W-motion — the `layer` wrap + `reducedMotion` block target one self-contained\n // document; the multi-file modes split the cascade, so fail loud rather than emit a partial result.\n if ((layerName || reducedMotion) && type !== \"single\") {\n const opt = layerName ? \"layer\" : \"reducedMotion\";\n throw new Error(\n `The \\`${opt}\\` option is only supported with single-file emit (got \"${type}\"). ` +\n `Emit one file, or drop \\`${opt}\\` for split/subsystem/components.`,\n );\n }\n\n if (type === \"single\") {\n const file = plan?.type === \"single\" ? plan.file : \"theme.css\";\n return { files: { [file]: finalizeDoc(renderCss(collectNodes())) } };\n }\n\n // `inline` bakes resolved values into the rules, leaving NO variables to emit — which\n // contradicts every multi-file mode (each writes a separate variables file/side). Fail\n // loud rather than silently dropping the variables the author asked to split out.\n if (inline && (type === \"split\" || type === \"subsystem\")) {\n throw new Error(\n `css adapter: emit mode '${type}' cannot be combined with the global inline option ` +\n `(inline bakes values, leaving no variables file)`,\n );\n }\n\n if (plan?.type === \"split\") {\n // Two files under a load-order contract — NO `@import` (that re-joins what we split).\n // The styles file references vars by name and assumes the variables file loads first.\n const nodes = collectNodes();\n return {\n files: {\n [plan.file]: renderRulesCss(nodes),\n [plan.variables]: renderVariablesCss(nodes),\n },\n };\n }\n\n if (plan?.type === \"subsystem\") {\n // Per subsystem: its variables → `<sub>.variables.css`, its recipes → `<sub>.css`.\n // Enrich ONCE over the whole set (collectNodes mutates the lowered[key] node objects in\n // place, so cross-subsystem refs survive), then render each subsystem's slice. Skip\n // empties — the components subsystem owns no properties → styles file only.\n collectNodes();\n const files: Record<string, string> = {};\n for (const key of Object.keys(model.subsystems)) {\n const sub = lowered[key];\n if (!sub) continue;\n const variablesCss = renderVariablesCss(sub.variableNodes);\n const stylesCss = renderRulesCss(sub.recipeNodes);\n if (variablesCss) files[plan.filename(key, \"variables\")] = variablesCss;\n if (stylesCss) files[plan.filename(key, \"styles\")] = stylesCss;\n }\n return { files };\n }\n\n if (plan?.type === \"components\") {\n // The flattened/merged export: each component variant is lowered to ONE self-contained\n // rule (its referenced recipes' declarations + own `css` delta, merged in core by\n // `mergeComponentRuleSet`), rendered with baked values — zero `var(`, dependency-free.\n //\n // `inline` is the plan-level control (defaults true). The global adapter `inline` option\n // is irrelevant here — the plan decides.\n const componentRuleSets = model.subsystems.components?.ruleSets ?? {};\n\n // The subsystem variable nodes are the value source for BOTH paths: inline baking resolves\n // each merged `var(--…)` ref to its formatted value (`20px`, `#4dabf7`, …); non-inline\n // sources the tree-shaken variables file from the same map (no re-derived formatting).\n const variableNodes: CssVariablesNode[] = [];\n for (const key of Object.keys(model.subsystems)) {\n const sub = lowered[key];\n if (sub) variableNodes.push(...sub.variableNodes);\n }\n\n if (plan.inline === false) {\n // ── NON-INLINE (9e): merged rules rendered with `var(--…)` refs (NO enrich/bake) into\n // the styles file(s) — same filename bundling as inline — plus a tree-shaken variables\n // file defining ONLY the tokens the exported components reference (union of every\n // variant's `referencedPaths`), so every emitted `var(--…)` resolves. Load-order\n // contract — NO `@import`. ──\n const filesByName: Record<string, string[]> = {};\n const orderedVarNames: string[] = [];\n const referencedVars = new Set<string>();\n\n for (const [group, ruleSetGroup] of Object.entries(componentRuleSets)) {\n for (const variant of Object.keys(ruleSetGroup)) {\n const merged = mergeComponentRuleSet(model, group, variant);\n const selector = lowered.components?.selectors[group]?.[variant];\n if (!selector) continue;\n\n const ruleNodes = lowerMergedRuleSet(merged, { selector, media, pathToVar: globalPathToVar, containers: ctx.containers });\n const filename = plan.filename({ group, variant });\n (filesByName[filename] ??= []).push(renderToCssString(ruleNodes));\n\n // Tree-shake set: referenced token paths → var names, stable first-appearance order.\n for (const path of merged.referencedPaths) {\n const varName = globalPathToVar[path];\n if (varName && !referencedVars.has(varName)) {\n referencedVars.add(varName);\n orderedVarNames.push(varName);\n }\n }\n }\n }\n\n const files: Record<string, string> = {};\n for (const [name, parts] of Object.entries(filesByName)) files[name] = parts.join(\"\\n\\n\");\n\n // Tree-shaken variables file, unless `variables: false` (consumer supplies the vars).\n // Base `:root` = resolved literal per referenced var (reusing the enrichment value map —\n // built from the non-responsive nodes so base values aren't shadowed by overrides); then\n // any responsive `:root` @media override blocks, filtered to the referenced var names\n // (keeps breakpoint theming). Covered by the §11.5 responsive-overrides emit test\n // (the `responsiveComponents` fixture drives a component → responsive property var).\n if (plan.variables !== false) {\n const baseValueMap = buildVariableValueMap(variableNodes.filter(n => !n.media));\n const baseVars: Record<string, string> = {};\n for (const name of orderedVarNames) {\n const value = baseValueMap.get(name);\n if (value !== undefined) baseVars[name] = value;\n }\n\n const varsNodes: CssNode[] = [{ kind: \"variables\", selector: \":root\", variables: baseVars }];\n for (const node of variableNodes) {\n if (!node.media || node.selector !== \":root\") continue;\n const filtered: Record<string, string> = {};\n for (const [name, value] of Object.entries(node.variables)) {\n if (referencedVars.has(name)) filtered[name] = value;\n }\n if (Object.keys(filtered).length) {\n varsNodes.push({ kind: \"variables\", selector: node.selector, media: node.media, variables: filtered });\n }\n }\n\n const variablesCss = renderVariablesCss(varsNodes);\n if (variablesCss) files[plan.variables] = variablesCss;\n }\n\n return { files };\n }\n\n // Variants returning the same filename concatenate into that one file — so a per-group\n // `filename` fn bundles (buttons → buttons.css), and `() => \"components.css\"` collapses all.\n const filesByName: Record<string, string[]> = {};\n for (const [group, ruleSetGroup] of Object.entries(componentRuleSets)) {\n for (const variant of Object.keys(ruleSetGroup)) {\n const merged = mergeComponentRuleSet(model, group, variant);\n const selector = lowered.components?.selectors[group]?.[variant];\n if (!selector) continue;\n\n const ruleNodes = lowerMergedRuleSet(merged, { selector, media, pathToVar: globalPathToVar, containers: ctx.containers });\n // Populate `resolved` on each declaration from the variable map, then bake it.\n enrichDeclarationsWithRefs([...variableNodes, ...ruleNodes]);\n const inlined: CssNode[] = ruleNodes.map(rule => ({\n ...rule,\n declarations: rule.declarations.map(decl => {\n const baked = decl.resolved !== undefined ? decl.resolved : decl.value;\n // Every merged token ref must resolve to a baked value at this stage. A lingering\n // `var(` means an unresolved reference — surface it loud rather than emit a file\n // that silently depends on a variable the `components` mode never writes.\n if (typeof baked === \"string\" && baked.includes(\"var(\")) {\n throw new Error(\n `css adapter: emit mode 'components' (inline): '${decl.property}' on ` +\n `'${selector}' has an unresolved token reference (${baked}) — no baked value`,\n );\n }\n return { property: decl.property, value: baked };\n }),\n }));\n\n const filename = plan.filename({ group, variant });\n (filesByName[filename] ??= []).push(renderToCssString(inlined));\n }\n }\n\n const files: Record<string, string> = {};\n for (const [name, parts] of Object.entries(filesByName)) files[name] = parts.join(\"\\n\\n\");\n return { files };\n }\n\n throw new Error(`css adapter: emit mode '${type}' not yet implemented`);\n },\n };\n },\n };\n\n return defineAdapter(spec);\n};\n"],"names":["str","value","String","dimensionCss","ref","undefined","unit","resolveMediaQuery","media","breakpoint","query","orientation","group","_a","opts","min","max","exact","combineMedia","a","b","cond","s","replace","expandResponsiveVariableNodes","properties","resolveName","formatValue","byBlock","Map","add","mediaQuery","selector","updates","key","existing","get","Object","assign","variables","set","propertyName","model","entries","entry","responsive","_b","computeEntryUpdates","keys","length","mode","osMedia","MODE_MEDIA","Array","from","values","m","kind","target","field","r","overrides","rootNode","dark","light","modeVars","byMode","vars","modeVariableNodes","nodes","push","subsystemVarName","varName","subsystem","property","variant","filter","Boolean","join","deriveColorsModeNodes","formatColor","name","modes","fields","baseRef","base","buildSubsystemPathToVar","map","external","extras","v","_c","variants","ex","_d","deriveRegularVariableNodes","ctx","spec","nameFor","formatRoot","exRef","formatResponsive","deriveRegularModeNodes","varNameFor","struct","buildRegularPathToVar","composeShadowLayer","layer","pathToVar","zero","offsetX","offsetY","blur","spread","layerUnit","len","dim","shadowDimCss","parts","inset","color","resolveColorRef","composeShadow","layers","composeTransitionPart","part","duration","delay","timingFunction","composeTransition","deriveEffectsVariableNodes","propertyKey","composeEffectsStruct","first","composeEffectsStructAuto","MS_ANIMATION_KEYS","Set","deriveAnimationVariableNodes","has","formatMs","isLayoutConfigKey","includes","splitLayoutProperties","regular","config","deriveLayoutVariableNodes","_propertyKey","LAYOUT_BASE_KEYS","deriveLayoutConfigVariableNodes","byGroup","split","refToStyleValue","lowerContainerGroup","options","selectorBuilder","baseNodes","i","ruleSet","declarations","declarationsFromRefs","mediaNodes","override","state","wrap","decls","suffixSelector","suffix","trim","lowerResetRuleSet","globalPathToVar","emitGlobalsRule","containers","container","stateOverrides","o","orderStateOverrides","stateSelector","CSS_STATE_SELECTORS","node","containerQueryFor","_e","link","visited","hover","focus","active","disabled","pressed","CSS_KNOWN_STATES","STATE_ORDER","reduce","acc","index","sort","orderA","Number","MAX_SAFE_INTEGER","orderB","bpA","bpB","deriveStateNodes","size","descriptor","lowerRecipeGroup","baseDeclarations","stateNodes","targetedStateNodes","containerNodes","KEYFRAME_REF_PREFIX","ANIMATION_LONGHAND_ORDER","resolveKeyframeName","keyframeNames","startsWith","slice","Error","lowerAnimationRecipeGroup","shorthandNode","shorthand","longhand","composeAnimationShorthand","lowerMergedRuleSet","merged","states","atRule","renderToCssString","indent","newline","blocks","mergeAdjacentVariableNodes","body","renderKeyframesBody","renderVariableBody","renderRuleBody","inner","indentBlock","keyFor","output","previous","steps","step","stop","block","line","splitNodes","rules","renderVariablesCss","renderRulesCss","VAR_PATTERN","buildVariableValueMap","variableMap","test","match","resolved","enrichDeclarationsWithRefs","enrich","decl","parseComponentReference","reference","rest","dot","indexOf","version","allowedStates","bind","inline","naming","resolveNaming","prefix","classPrefix","namer","createNamer","variableName","colorFormat","toHexColor","toOklchColor","lowered","lowerRecipes","ruleSets","recipeNodes","selectors","ruleSetGroup","className","colors","subsystems","props","buildColorsPathToVar","variableNodes","text","deriveColorsVariableNodes","typography","buildTypographyPathToVar","deriveTypographyVariableNodes","_f","effects","_g","buildEffectsPathToVar","_h","borders","_j","buildBordersPathToVar","deriveBordersVariableNodes","_k","layout","_l","path","buildLayoutPathToVar","_m","lower","animation","_o","buildAnimationPathToVar","keyframes","_p","keyframeNodes","keyframe","lowerKeyframes","_q","componentClasses","components","resolveReferencedClass","parsed","_r","ownClass","classList","_s","references","cls","globals","variantName","variantSelector","lowerGlobalsGroups","_t","containerClass","containerContextNodes","type","deriveContainerContextNodes","collectNodes","sub","layerName","reducedMotion","_u","finalizeDoc","css","out","trimEnd","renderCss","varMap","bake","whole","inlined","n","collectClasses","groups","fromEntries","containerGroup","context","selectorFor","getClass","leaf","renderRecipe","nodeSelector","selectorBelongsToRecipe","recipeName","renderVariables","renderAllVariables","renderAllRecipes","renderAll","describeUsage","recipes","format","summary","describePreview","plan","files","written","keep","names","renderable","ruleSetOf","PIN_PREFIX","markup","attrs","class","modeAttribute","tokenName","declared","statePinClass","statePinCss","pinned","buildStatePinCss","composition","stylesheets","file","filename","groupBy","componentFile","componentFiles","f","notes","extend","variablesCss","recipesCss","classes","emit","opt","stylesCss","componentRuleSets","filesByName","orderedVarNames","referencedVars","mergeComponentRuleSet","ruleNodes","referencedPaths","baseValueMap","baseVars","varsNodes","filtered","rule","baked","defineAdapter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