All files / packages/sds-customization-compliance/src/checks/helpers themeDataAccess.ts

73.58% Statements 39/53
42.85% Branches 15/35
87.5% Functions 7/8
84.44% Lines 38/45

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                                9x                               12x 12x 11x 11x 11x 11x   11x   12x 11x 11x 11x 11x 11x 11x 11x 11x   17x     12x                                                                 65x 36x   29x           36x 36x 36x 36x 36x                       36x       29x 29x 29x 27x 58x                       29x                                       11x   15x   11x 11x          
/**
 * Readers that adapt the themeData JSON shape into the structures the
 * checks consume. Pure — themeData is already an in-memory object when
 * these run.
 */
 
import type { ThemeData } from '../../types.js';
import { selectorRole, type SelectorRole } from './selectorRole.js';
 
/**
 * Shared detail string used when a check depends on `themeData` but none is
 * on disk yet — the common explanation being that the component has not
 * migrated to the theme-layer architecture (no `themes/base.css`). Checks
 * reuse this so users see a consistent, educational message everywhere.
 */
export const NOT_MIGRATED_DETAIL =
  'Component has not been migrated to the theme-layer architecture yet — no `themes/base.css` file found, so there is nothing to evaluate.';
 
/** One hook read on a particular selector, grouped by category. */
export interface HookReadEntry {
  hook: string;
  selector: string;
}
 
/** `{ role -> { category -> HookReadEntry[] } }`. */
export type HookReadsByRole = Map<SelectorRole, Map<string, HookReadEntry[]>>;
 
/**
 * Theme-layer hooks the base file reads via `var()` on any paint property —
 * the component's public hook API surface as captured in `themeData.selectors`.
 */
export function hookReadsByRole(name: string, themeData: ThemeData): HookReadsByRole {
  const byRole: HookReadsByRole = new Map();
  const ensureRole = (role: SelectorRole): Map<string, HookReadEntry[]> => {
    let entry = byRole.get(role);
    Eif (!entry) {
      entry = new Map();
      byRole.set(role, entry);
    }
    return entry;
  };
  for (const [sel, categories] of Object.entries(themeData.selectors ?? {})) {
    const role = selectorRole(sel, name);
    const catMap = ensureRole(role);
    for (const [cat, hooks] of Object.entries(categories)) {
      Iif (!Array.isArray(hooks) || hooks.length === 0) continue;
      let bucket = catMap.get(cat);
      Eif (!bucket) {
        bucket = [];
        catMap.set(cat, bucket);
      }
      for (const h of hooks) bucket.push({ hook: h, selector: sel });
    }
  }
  return byRole;
}
 
/** Row emitted by {@link hookDefsFromThemeData}. */
export interface HookDefRow {
  prop: string;
  selector: string;
  /** Relative-to-component file path the assignment lives in (e.g. `themes/cosmos.css`). */
  file: string;
  theme: string;
  rawValue: string;
  /**
   * Absolute path of the file the declaration was authored in, threaded
   * through from postcss source positions. `null` when source-position
   * info wasn't available (browser path / synthesized fixtures).
   */
  source: string | null;
  /** 1-based line number where the declaration was authored, or `null`. */
  line: number | null;
}
 
/**
 * Flatten themeData theme assignments into a list of rows. Only the fields
 * compliance actually consumes are populated; `resolvedValue` /
 * `resolvedByTheme` are intentionally omitted — themeData doesn't resolve
 * token chains, that's `color-audit.json`'s job.
 *
 * Prefers the source-enriched `themeAssignmentRows` projection when the
 * CLI populated it; falls back to the bare-string `themes[*].selectors`
 * shape so on-disk themeData JSON (without source-position info) still
 * yields rows (with `source` / `line` set to `null`).
 */
export function hookDefsFromThemeData(themeData: ThemeData): HookDefRow[] {
  if (themeData.themeAssignmentRows) {
    return hookDefsFromRichRows(themeData.themeAssignmentRows);
  }
  return hookDefsFromBareThemes(themeData.themes);
}
 
function hookDefsFromRichRows(
  themeAssignmentRows: NonNullable<ThemeData['themeAssignmentRows']>,
): HookDefRow[] {
  const rows: HookDefRow[] = [];
  for (const [theme, tBlock] of Object.entries(themeAssignmentRows)) {
    for (const [sel, hookMap] of Object.entries(tBlock.selectors ?? {})) {
      for (const [hook, row] of Object.entries(hookMap)) {
        rows.push({
          prop: hook,
          selector: sel,
          file: `themes/${theme}.css`,
          theme,
          rawValue: row.value,
          source: row.source,
          line: row.line,
        });
      }
    }
  }
  return rows;
}
 
function hookDefsFromBareThemes(themes: ThemeData['themes']): HookDefRow[] {
  const rows: HookDefRow[] = [];
  for (const [theme, tBlock] of Object.entries(themes ?? {})) {
    for (const [sel, hookMap] of Object.entries(tBlock.selectors ?? {})) {
      for (const [hook, rawValue] of Object.entries(hookMap)) {
        rows.push({
          prop: hook,
          selector: sel,
          file: `themes/${theme}.css`,
          theme,
          rawValue: String(rawValue ?? ''),
          source: null,
          line: null,
        });
      }
    }
  }
  return rows;
}
 
/**
 * Best-effort color-category inference for a non-canonical hook name so
 * check (1) can still report gaps against e.g. legacy
 * `--slds-c-spinner-brand-color` without a matching canonical.
 */
export function inferColorCategoryFromHook(hook: string): string | null {
  if (/-color-background(?:$|-)/.test(hook)) return 'background';
  if (/-color-foreground(?:$|-)/.test(hook)) return 'foreground';
  if (/-color-border(?:$|-)/.test(hook)) return 'border';
  if (/(?:^|-)background(?:$|-)/.test(hook)) return 'background';
  if (/(?:^|-)foreground(?:$|-)/.test(hook)) return 'foreground';
  if (/(?:^|-)border(?:$|-)/.test(hook)) return 'border';
  return null;
}
 
/** Format a short `hooks-sample` string with a trailing `+N more` indicator. */
export function sampleHooks(hooks: string[], limit = 3): string {
  const shown = hooks
    .slice(0, limit)
    .map((h) => `\`${h}\``)
    .join(', ');
  const extra = hooks.length - limit;
  return extra > 0 ? `${shown} +${extra} more` : shown;
}
 
/** Ergonomic re-export so helper consumers don't need deep imports. */
export type { SelectorRole } from './selectorRole.js';