All files / packages/fds-uif/core/src/css metadata-generator.ts

96.94% Statements 127/131
88.23% Branches 60/68
100% Functions 5/5
97.39% Lines 112/115

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443                                                                10x                   107x 12x 8x               107x 107x     2691x 2688x 2691x     107x             107x 107x   107x                   157x 157x     157x 157x   107x 107x   107x   107x             3x       107x     157x             66x         51x 51x 51x     66x                     88x                       48x   48x 88x     48x                   26x   26x     26x       26x                   26x 24x   6x                               60x         66x 66x   66x                 66x 66x   66x         60x             34x       64x       34x             34x         44x     2x   11x               34x       14x       34x                       34x       48x       34x 34x   6x   34x   34x                     34x 34x   34x 279x 279x 279x     1x 1x   1x 1x 1x   1x   1x 1x         1x       34x                                       34x             34x         34x     34x 26x 26x 26x       18x 18x   2x 2x     6x   6x         34x   22x       34x 34x 34x 34x     34x     18x     2x     6x   34x     34x 34x 34x 34x 34x   34x                            
/**
 * @fds-uif/core - CSS Metadata Generator (Node.js only)
 *
 * Generates complete CSS metadata combining:
 * - Layer structure (for CSS transformation)
 * - Hook analysis (for documentation/theming)
 *
 * NOTE: This module uses PostCSS which has Node.js dependencies.
 * For browser-safe utilities, use './metadata-queries.js'.
 *
 * @see RFC: uif-styling-layer.md
 */
 
import postcss, { type Root, type AtRule, type Rule, type Declaration } from 'postcss';
import type {
  CssMetadata,
  CssRule,
  CssDeclaration,
  LayerContent,
  UnlayeredContent,
  ComponentHook,
  DeprecatedHook,
  ParseCssOptions,
  VariableReference,
  VariableType,
} from './types.js';
import { parseHookName, isComponentHook } from './hook-name-parser.js';
 
// ============================================================================
// Constants
// ============================================================================
 
const DEFAULT_SYSTEM = 'slds';
 
// ============================================================================
// Variable Extraction
// ============================================================================
 
/**
 * Classify a CSS variable by its naming convention.
 */
function classifyVariable(name: string): VariableType {
  if (name.startsWith('--slds-g-')) return 'global';
  if (name.startsWith('--slds-s-')) return 'shared';
  Eif (name.startsWith('--slds-c-')) return 'component';
  return 'custom';
}
 
/**
 * Find the matching closing parenthesis for var().
 */
function findVarEnd(value: string, startIndex: number): number {
  let depth = 1;
  let i = startIndex;
 
  while (i < value.length && depth > 0) {
    if (value[i] === '(') depth++;
    else if (value[i] === ')') depth--;
    i++;
  }
 
  return i;
}
 
/**
 * Parse a single var() expression.
 */
function parseVarExpression(expr: string): { name: string; fallback?: string } | null {
  const match = expr.match(/^var\(\s*(--[\w-]+)\s*(?:,\s*([\s\S]*))?\)$/);
  Iif (!match) return null;
 
  return {
    name: match[1],
    fallback: match[2]?.trim() || undefined,
  };
}
 
/**
 * Extract variable references from a CSS value.
 */
function extractVariableReferences(value: string): VariableReference[] {
  const refs: VariableReference[] = [];
  let searchStart = 0;
 
  while (searchStart < value.length) {
    const varIndex = value.indexOf('var(', searchStart);
    if (varIndex === -1) break;
 
    const endIndex = findVarEnd(value, varIndex + 4);
    const fullExpr = value.slice(varIndex, endIndex);
 
    const parsed = parseVarExpression(fullExpr);
    if (parsed) {
      refs.push({
        name: parsed.name,
        type: classifyVariable(parsed.name),
        ...(parsed.fallback && { fallback: parsed.fallback }),
      });
 
      if (parsed.fallback && parsed.fallback.includes('var(')) {
        refs.push(...extractVariableReferences(parsed.fallback));
      }
    }
 
    searchStart = endIndex;
  }
 
  return refs;
}
 
/**
 * Get first global and shared variable from a value.
 */
function getTokenReferences(value: string): { global?: string; shared?: string } {
  const refs = extractVariableReferences(value);
  let global: string | undefined;
  let shared: string | undefined;
 
  for (const ref of refs) {
    if (!global && ref.type === 'global') global = ref.name;
    if (!shared && ref.type === 'shared') shared = ref.name;
    if (global && shared) break;
  }
 
  return { global, shared };
}
 
// ============================================================================
// CSS Parsing
// ============================================================================
 
/**
 * Parse a PostCSS Declaration into CssDeclaration.
 */
function parseDeclaration(decl: Declaration): CssDeclaration {
  return {
    property: decl.prop,
    value: decl.value,
    variableReferences: extractVariableReferences(decl.value),
    isHookAssignment: isComponentHook(decl.prop),
  };
}
 
/**
 * Parse a PostCSS Rule into CssRule.
 */
function parseRule(rule: Rule): CssRule {
  const declarations: CssDeclaration[] = [];
 
  rule.walkDecls((decl) => {
    declarations.push(parseDeclaration(decl));
  });
 
  return {
    selector: rule.selector,
    declarations,
  };
}
 
/**
 * Extract rules from a container (Root or AtRule).
 */
function extractRules(container: Root | AtRule): CssRule[] {
  const rules: CssRule[] = [];
 
  container.walkRules((rule) => {
    // Only include direct children for AtRules, or top-level for Root
    if (rule.parent === container) {
      rules.push(parseRule(rule));
    }
  });
 
  return rules;
}
 
/**
 * Parse layer name to determine type.
 */
function parseLayerName(name: string): {
  type: 'defaults' | 'theme' | 'themeOverride' | 'other';
  themeName?: string;
} {
  if (name === 'defaults') return { type: 'defaults' };
  if (name === 'theme') return { type: 'theme' };
  if (name.startsWith('theme.')) {
    return { type: 'themeOverride', themeName: name.slice('theme.'.length) };
  }
  return { type: 'other' };
}
 
// ============================================================================
// Hook Extraction
// ============================================================================
 
/**
 * Extract hooks from rules with context.
 */
function extractHooksFromRules(
  rules: CssRule[],
  layerName: string | null,
): ComponentHook[] {
  const hooks: ComponentHook[] = [];
 
  for (const rule of rules) {
    for (const decl of rule.declarations) {
      if (decl.isHookAssignment) {
        const parsed = parseHookName(decl.property);
        const { global, shared } = getTokenReferences(decl.value);
 
        const hook: ComponentHook = {
          name: decl.property,
          type: 'property',
          value: decl.value,
          selector: rule.selector,
          layer: layerName,
          ...parsed,
        };
 
        if (global) hook.globalValue = global;
        if (shared) hook.sharedValue = shared;
 
        hooks.push(hook);
      }
    }
  }
 
  return hooks;
}
 
/**
 * Deduplicate hooks by name, keeping the first occurrence.
 */
function deduplicateHooks(hooks: ComponentHook[]): ComponentHook[] {
  const seen = new Map<string, ComponentHook>();
 
  for (const hook of hooks) {
    if (!seen.has(hook.name)) {
      seen.set(hook.name, hook);
    }
  }
 
  return Array.from(seen.values());
}
 
/**
 * Sort hooks by component, category, element, then name.
 */
function sortHooks(hooks: ComponentHook[]): ComponentHook[] {
  return [...hooks].sort((a, b) => {
    if (a.component !== b.component) {
      return (a.component || '').localeCompare(b.component || '');
    }
    if (a.category !== b.category) {
      return (a.category || '').localeCompare(b.category || '');
    }
    if (a.element !== b.element) {
      return (a.element || '').localeCompare(b.element || '');
    }
    return a.name.localeCompare(b.name);
  });
}
 
/**
 * Extract unique element names from hooks.
 */
function extractElements(hooks: ComponentHook[]): string[] {
  const elements = new Set<string>();
 
  for (const hook of hooks) {
    if (hook.element) {
      elements.add(hook.element);
    }
  }
 
  return Array.from(elements).sort();
}
 
/**
 * Extract all unique selectors from rules.
 */
function extractSelectors(
  themeLayer: LayerContent | null,
  defaultsLayer: LayerContent | null,
  themeOverrides: Record<string, LayerContent>,
  unlayered: UnlayeredContent,
): string[] {
  const selectors = new Set<string>();
 
  const addFromRules = (rules: CssRule[]) => {
    for (const rule of rules) {
      selectors.add(rule.selector);
    }
  };
 
  if (themeLayer) addFromRules(themeLayer.rules);
  if (defaultsLayer) addFromRules(defaultsLayer.rules);
  for (const layer of Object.values(themeOverrides)) {
    addFromRules(layer.rules);
  }
  addFromRules(unlayered.rules);
 
  return Array.from(selectors).sort();
}
 
// ============================================================================
// Deprecation Parsing
// ============================================================================
 
/**
 * Parse deprecation comments from CSS content.
 */
function parseDeprecations(cssContent: string): DeprecatedHook[] {
  const deprecations: DeprecatedHook[] = [];
  const lines = cssContent.split('\n');
 
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i];
    const regex = /\/\*\s*@deprecated\s+(\S+)\s+(--[\w-]+)\s*\*\//g;
    const match = regex.exec(line);
 
    if (match) {
      const release = match[1];
      const oldHook = match[2];
 
      let replacement = '';
      for (let j = i + 1; j < lines.length && j < i + 5; j++) {
        const nextLine = lines[j].trim();
        if (nextLine && nextLine.startsWith('--slds-c-')) {
          const colonIndex = nextLine.indexOf(':');
          if (colonIndex > 0) {
            replacement = nextLine.substring(0, colonIndex).trim();
            break;
          }
        }
      }
 
      deprecations.push({ name: oldHook, replacement, deprecatedIn: release });
    }
  }
 
  return deprecations;
}
 
// ============================================================================
// Main API
// ============================================================================
 
/**
 * Generate complete CSS metadata from CSS content.
 *
 * @param cssContent - Raw CSS content
 * @param cssSource - Path to CSS file (for metadata)
 * @param options - Parser options
 * @returns Complete CSS metadata with layers and hooks
 */
export function generateCssMetadata(
  cssContent: string,
  cssSource: string,
  options: ParseCssOptions = {},
): CssMetadata {
  const root = postcss.parse(cssContent);
 
  // Extract layer structure using mutable container to work around TS narrowing
  const layers: {
    theme: LayerContent | null;
    defaults: LayerContent | null;
    overrides: Record<string, LayerContent>;
  } = {
    theme: null,
    defaults: null,
    overrides: {},
  };
  const unlayeredRules: CssRule[] = [];
 
  // Process @layer blocks
  root.walkAtRules('layer', (atRule) => {
    const layerName = atRule.params.trim();
    const { type, themeName } = parseLayerName(layerName);
    const rules = extractRules(atRule);
 
    switch (type) {
      case 'theme':
        layers.theme = { name: layerName, rules };
        break;
      case 'defaults':
        layers.defaults = { name: layerName, rules };
        break;
      case 'themeOverride':
        if (themeName) {
          layers.overrides[themeName] = { name: layerName, rules };
        }
        break;
    }
  });
 
  // Collect unlayered rules (rules at root level, not inside @layer)
  root.walkRules((rule) => {
    if (rule.parent === root) {
      unlayeredRules.push(parseRule(rule));
    }
  });
 
  const themeLayer = layers.theme;
  const defaultsLayer = layers.defaults;
  const themeOverrides = layers.overrides;
  const unlayered: UnlayeredContent = { rules: unlayeredRules };
 
  // Extract hooks from all sources
  const allHooks: ComponentHook[] = [];
 
  if (themeLayer) {
    allHooks.push(...extractHooksFromRules(themeLayer.rules, 'theme'));
  }
  if (defaultsLayer) {
    allHooks.push(...extractHooksFromRules(defaultsLayer.rules, 'defaults'));
  }
  for (const [name, layer] of Object.entries(themeOverrides)) {
    allHooks.push(...extractHooksFromRules(layer.rules, `theme.${name}`));
  }
  allHooks.push(...extractHooksFromRules(unlayeredRules, null));
 
  // Process hooks
  const uniqueHooks = deduplicateHooks(allHooks);
  const sortedHooks = sortHooks(uniqueHooks);
  const elements = extractElements(sortedHooks);
  const selectors = extractSelectors(themeLayer, defaultsLayer, themeOverrides, unlayered);
  const deprecated = parseDeprecations(cssContent);
 
  return {
    sourceFile: cssSource,
    system: options.system || DEFAULT_SYSTEM,
    themeLayer,
    defaultsLayer,
    themeOverrides,
    unlayered,
    selectors,
    totalHooks: sortedHooks.length,
    elements,
    hooks: sortedHooks,
    deprecated,
  };
}