All files / packages/design-tokens/src/validators temp-compare-brand-refs.js

0% Statements 0/166
0% Branches 0/75
0% Functions 0/16
0% Lines 0/165

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
#!/usr/bin/env node
 
/**
 * TEMPORARY Brand Reference Token Comparison Tool (TO BE REMOVED AFTER MIGRATION)
 *
 * Compare brand reference token usage: sds-styling-hooks (source of truth) vs design-tokens
 * Focuses specifically on tokens that reference --slds-r-color-brand-* tokens
 * to ensure both packages use themeable brand references consistently
 *
 * COMPARES: Global CSS custom properties that use brand reference tokens
 * NOT: The reference tokens themselves, only the tokens that USE them
 *
 * NOTE: This is a temporary migration tool that should be deleted once the
 * design token migration from legacy (Theo) to modern (Style Dictionary + W3C)
 * is complete and verified.
 *
 * Usage:
 *   yarn temp:compare:brand-refs           # Summary only
 *   yarn temp:compare:brand-refs --verbose # Show detailed issue tables
 *   yarn temp:compare:brand-refs --report  # Show full table of all brand reference tokens
 */
 
import fs from 'fs';
import path from 'node:path';
import { fileURLToPath } from 'url';
import chalk from 'chalk';
import Table from 'cli-table3';
import { parseValidatorArgs, colorSwatch } from './validator-utils.js';
 
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
 
const { isVerbose, isReport } = parseValidatorArgs();
 
console.log(chalk.bold.blue('\nšŸ” Comparing brand reference token usage\n'));
console.log(chalk.gray('sds-styling-hooks (source of truth) vs design-tokens\n'));
 
const themes = ['slds', 'cosmos'];
 
// Extract all CSS custom properties from a file
const extractAllProperties = (css) => {
  const properties = new Map();
  const regex = /--([\w-]+)\s*:\s*([^;]+);/g;
  let match;
 
  while ((match = regex.exec(css)) !== null) {
    properties.set(match[1], match[2].trim());
  }
 
  return properties;
};
 
// Extract properties that reference brand tokens
const extractBrandRefProperties = (css) => {
  const properties = new Map();
  const lines = css.split('\n');
 
  for (const line of lines) {
    if (line.includes('--slds-r-color-brand-')) {
      // Extract ALL property declarations on this line
      const regex = /--(slds-[a-zA-Z][\w-]*)\s*:\s*([^;]+);/g;
      let match;
 
      while ((match = regex.exec(line)) !== null) {
        const name = match[1];
        const value = match[2].trim();
 
        // Only store if it contains brand reference
        if (value.includes('--slds-r-color-brand-')) {
          properties.set(name, value);
        }
      }
    }
  }
 
  return properties;
};
 
// Resolve var() references to actual values
const resolveVarReferences = (value, allProperties) => {
  const varRegex = /var\((--[\w-]+)\)/g;
  let resolved = value;
  let match;
 
  while ((match = varRegex.exec(value)) !== null) {
    const varName = match[1].replace('--', '');
    const varValue = allProperties.get(varName);
    if (varValue) {
      resolved = resolved.replace(match[0], varValue);
    }
  }
 
  return resolved;
};
 
// Add color swatches to a value string
const addColorSwatches = (value, allProperties) => {
  // First resolve any var() references
  const resolved = resolveVarReferences(value, allProperties);
 
  // Check if it's a light-dark() function
  const lightDarkMatch = resolved.match(/light-dark\(([^,]+),\s*([^)]+)\)/);
  if (lightDarkMatch) {
    const lightValue = lightDarkMatch[1].trim();
    const darkValue = lightDarkMatch[2].trim();
 
    // Extract hex colors from both values
    const lightHex = lightValue.match(/#[0-9a-fA-F]{3,6}/);
    const darkHex = darkValue.match(/#[0-9a-fA-F]{3,6}/);
 
    if (lightHex && darkHex) {
      return `${colorSwatch(lightHex[0])} ${lightHex[0]} / ${colorSwatch(darkHex[0])} ${darkHex[0]}`;
    }
  }
 
  // Check for direct hex colors
  if (resolved.includes('#')) {
    const hexColors = resolved.match(/#[0-9a-fA-F]{3,6}/g);
    if (hexColors) {
      let result = resolved;
      hexColors.forEach((hex) => {
        result = result.replace(hex, `${colorSwatch(hex)} ${hex}`);
      });
      return result;
    }
  }
 
  return value; // Return original if no colors found
};
 
// Normalize value for comparison (remove comments, extra whitespace)
const normalizeValue = (value) => {
  return value
    .replace(/\/\*.*?\*\//g, '') // Remove comments
    .replace(/\s+/g, ' ') // Normalize whitespace
    .trim();
};
 
let allMatch = true;
const allResults = [];
 
themes.forEach((theme) => {
  console.log(chalk.bold(`šŸ“ Testing ${theme.toUpperCase()} theme:`));
 
  const designTokensPath = path.join(__dirname, `../../dist/themes/${theme}/${theme}.hooks.custom-props.css`);
  const designTokensRefPath = path.join(
    __dirname,
    `../../dist/themes/${theme}/${theme}.reference.hooks.custom-props.css`,
  );
  const stylingHooksPath = path.join(
    __dirname,
    `../../../sds-styling-hooks/dist/themes/${theme}/${theme}.hooks.custom-props.css`,
  );
 
  // Check if files exist
  if (!fs.existsSync(stylingHooksPath)) {
    console.log(chalk.yellow(`  āš ļø  sds-styling-hooks file not found`));
    allMatch = false;
    console.log('');
    return;
  }
 
  if (!fs.existsSync(designTokensPath)) {
    console.log(chalk.yellow(`  āš ļø  design-tokens file not found`));
    allMatch = false;
    console.log('');
    return;
  }
 
  const designTokensCSS = fs.readFileSync(designTokensPath, 'utf8');
  const stylingHooksCSS = fs.readFileSync(stylingHooksPath, 'utf8');
 
  // Read reference file for color resolution
  let allProperties = new Map();
  if (fs.existsSync(designTokensRefPath)) {
    const refCSS = fs.readFileSync(designTokensRefPath, 'utf8');
    allProperties = extractAllProperties(refCSS);
  }
 
  const dtProps = extractBrandRefProperties(designTokensCSS);
  const shProps = extractBrandRefProperties(stylingHooksCSS);
 
  console.log(chalk.gray(`  sds-styling-hooks: ${shProps.size} tokens using brand references`));
  console.log(chalk.gray(`  design-tokens:     ${dtProps.size} tokens using brand references`));
 
  // Find differences
  const allKeys = new Set([...dtProps.keys(), ...shProps.keys()]);
  const mismatches = [];
  const onlyInDT = [];
  const onlyInSH = [];
 
  for (const key of allKeys) {
    const dtValue = dtProps.get(key);
    const shValue = shProps.get(key);
 
    if (!dtValue) {
      onlyInSH.push({ theme, key, value: shValue });
    } else if (!shValue) {
      onlyInDT.push({ theme, key, value: dtValue });
    } else {
      const normDT = normalizeValue(dtValue);
      const normSH = normalizeValue(shValue);
 
      if (normDT !== normSH) {
        mismatches.push({ theme, key, dtValue, shValue });
      }
    }
  }
 
  allResults.push({ theme, mismatches, onlyInDT, onlyInSH, shProps, dtProps, allProperties });
 
  // Report results for this theme
  const hasIssues = mismatches.length > 0 || onlyInDT.length > 0 || onlyInSH.length > 0;
 
  if (hasIssues) {
    if (mismatches.length > 0) {
      console.log(chalk.red(`  āŒ ${mismatches.length} value mismatches`));
    }
    if (onlyInSH.length > 0) {
      console.log(chalk.yellow(`  āš ļø  ${onlyInSH.length} only in sds-styling-hooks`));
    }
    if (onlyInDT.length > 0) {
      console.log(chalk.yellow(`  āš ļø  ${onlyInDT.length} only in design-tokens`));
    }
    allMatch = false;
  } else {
    console.log(chalk.green(`  āœ… All ${shProps.size} tokens match`));
  }
 
  console.log('');
});
 
if (!allMatch && !isVerbose && !isReport) {
  console.log(chalk.gray('\nRun with --verbose to see detailed issue tables or --report to see all tokens'));
}
 
// Display detailed results
if (!allMatch && isVerbose) {
  allResults.forEach(({ theme, mismatches, onlyInDT, onlyInSH }) => {
    if (mismatches.length === 0 && onlyInDT.length === 0 && onlyInSH.length === 0) {
      return;
    }
 
    console.log(chalk.bold.red(`\nšŸ“‹ Issues in ${theme.toUpperCase()} theme:\n`));
 
    // Verbose: show tables
    if (mismatches.length > 0) {
      console.log(chalk.bold.red(`Value Mismatches (${mismatches.length}):\n`));
      const table = new Table({
        head: ['Property', 'sds-styling-hooks', 'design-tokens'],
        colWidths: [35, 40, 40],
        style: { head: ['red'] },
        wordWrap: true,
      });
 
      mismatches.forEach(({ key, shValue, dtValue }) => {
        table.push([`--${key}`, shValue, dtValue]);
      });
 
      console.log(table.toString());
      console.log('');
    }
 
    if (onlyInSH.length > 0) {
      console.log(chalk.bold.yellow(`Only in sds-styling-hooks (${onlyInSH.length}):\n`));
      const table = new Table({
        head: ['Property', 'Value'],
        colWidths: [35, 50],
        style: { head: ['yellow'] },
        wordWrap: true,
      });
 
      onlyInSH.forEach(({ key, value }) => {
        table.push([`--${key}`, value]);
      });
 
      console.log(table.toString());
      console.log('');
    }
 
    if (onlyInDT.length > 0) {
      console.log(chalk.bold.yellow(`Only in design-tokens (${onlyInDT.length}):\n`));
      const table = new Table({
        head: ['Property', 'Value'],
        colWidths: [35, 50],
        style: { head: ['yellow'] },
        wordWrap: true,
      });
 
      onlyInDT.forEach(({ key, value }) => {
        table.push([`--${key}`, value]);
      });
 
      console.log(table.toString());
      console.log('');
    }
  });
 
  console.log(chalk.red('āŒ Differences found: Brand reference token usage does not match\n'));
}
 
// Show all tokens in report mode (regardless of match status)
if (isReport) {
  // Collect all unique properties across themes
  const allPropertiesByKey = new Map();
 
  allResults.forEach(({ theme, shProps, allProperties }) => {
    const sortedKeys = Array.from(shProps.keys()).sort();
    sortedKeys.forEach((key) => {
      if (!allPropertiesByKey.has(key)) {
        allPropertiesByKey.set(key, { slds: null, cosmos: null });
      }
      const value = shProps.get(key);
      const valueWithSwatch = addColorSwatches(value, allProperties);
      allPropertiesByKey.get(key)[theme] = { value, valueWithSwatch };
    });
  });
 
  const totalProperties = allPropertiesByKey.size;
  console.log(chalk.bold.blue(`šŸ“‹ All Tokens using brand references (${totalProperties} properties):\n`));
 
  const table = new Table({
    head: ['#', 'Property', 'Hook Value', 'SLDS Color', 'Cosmos Color'],
    colWidths: [5, 35, 40, 25, 30],
    style: { head: ['cyan'] },
    wordWrap: true,
  });
 
  let rowNumber = 1;
  const sortedProperties = Array.from(allPropertiesByKey.keys()).sort();
 
  sortedProperties.forEach((key) => {
    const themes = allPropertiesByKey.get(key);
 
    // Get the hook value (should be the same or similar across themes)
    const hookValue = themes.slds ? themes.slds.value : themes.cosmos ? themes.cosmos.value : '';
 
    const sldsColor = themes.slds ? themes.slds.valueWithSwatch : chalk.gray('—');
    const cosmosColor = themes.cosmos ? themes.cosmos.valueWithSwatch : chalk.gray('—');
 
    // Check if there's a mismatch for this property
    const hasMismatch = allResults.some((result) => {
      return result.mismatches.some((m) => m.key === key);
    });
 
    const propertyDisplay = hasMismatch ? chalk.red(`āŒ --${key}`) : `--${key}`;
 
    table.push([rowNumber++, propertyDisplay, hookValue, sldsColor, cosmosColor]);
  });
 
  console.log(table.toString());
  console.log('');
}
 
if (allMatch) {
  process.exit(0);
} else {
  process.exit(1);
}