All files / packages/design-tokens/src/validators theme-parity-core.js

100% Statements 111/111
100% Branches 75/75
100% Functions 21/21
100% Lines 103/103

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                                            45x 38x   43x 37x   19x                       40x 83x                     13x 8x 5x 2x   3x                   5x 5x     5x 5x     5x   5x             5x 10x 10x 10x   10x                 5x   5x 5x 5x 5x 9x                   31x 31x 31x                     15x   15x             15x 16x 9x   7x       15x 15x                       10x   10x 10x     10x 6x 5x               6x 2x                   10x 5x 3x               5x 3x                                                           16x   16x 16x     16x 11x 11x 10x       11x 4x         16x 5x 5x 4x       5x 4x                         15x 8x 7x 4x 3x 2x                               14x   14x     14x 2x 2x     14x     14x 14x     14x           14x         14x 14x 14x     14x 3x             14x     14x 14x 33x       14x 3x 3x 3x   11x                   11x     11x       14x 6x       14x                      
/**
 * Core theme parity validation logic
 *
 * This module contains pure functions for comparing theme tokens.
 * It's designed to be testable by accepting themes as parameters rather than
 * importing them statically.
 *
 * @module theme-parity-core
 */
 
import chalk from 'chalk';
import Table from 'cli-table3';
 
/**
 * Compares keys between two theme objects and returns arrays of missing keys
 * Only compares global scope tokens (slds-g-*)
 * @param {Object} theme1 - First theme object to compare (SLDS)
 * @param {Object} theme2 - Second theme object to compare (Cosmos)
 * @returns {Object} Object containing arrays of missing keys for each theme
 */
export function compareThemeKeys(theme1, theme2) {
  // Filter to only global scope tokens
  const theme1Keys = new Set(Object.keys(theme1).filter((key) => key.startsWith('slds-g-')));
  const theme2Keys = new Set(Object.keys(theme2).filter((key) => key.startsWith('slds-g-')));
 
  const missingInTheme2 = [...theme1Keys].filter((key) => !theme2Keys.has(key));
  const missingInTheme1 = [...theme2Keys].filter((key) => !theme1Keys.has(key));
 
  return {
    missingInTheme2,
    missingInTheme1,
  };
}
 
/**
 * Get global token keys from a theme
 * @param {Object} theme - Theme object
 * @returns {string[]} Sorted array of global token keys
 */
export function getGlobalKeys(theme) {
  return Object.keys(theme)
    .filter((key) => key.startsWith('slds-g-'))
    .sort();
}
 
/**
 * Determine the status of a token based on its presence in both themes
 * @param {boolean} inSlds - Whether token exists in SLDS theme
 * @param {boolean} inCosmos - Whether token exists in Cosmos theme
 * @returns {string} Status string with chalk formatting
 */
export function getTokenStatus(inSlds, inCosmos) {
  if (inCosmos && inSlds) {
    return chalk.green('āœ… Both');
  } else if (inCosmos && !inSlds) {
    return chalk.red('āŒ Missing SLDS');
  } else {
    return chalk.red('āŒ Missing Cosmos');
  }
}
 
/**
 * Print a comprehensive report of all tokens
 * @param {Object} sldsTheme - SLDS theme object
 * @param {Object} cosmosTheme - Cosmos theme object
 */
export function printReport(sldsTheme, cosmosTheme) {
  console.log(chalk.bold.blue('\nšŸ“Š Theme Parity Report\n'));
  console.log('Comparing global scope tokens (slds-g-*) between SLDS and Cosmos themes\n');
 
  // Get all global tokens from both themes
  const sldsKeys = getGlobalKeys(sldsTheme);
  const cosmosKeys = getGlobalKeys(cosmosTheme);
 
  // Get all unique tokens
  const allKeys = [...new Set([...sldsKeys, ...cosmosKeys])].sort();
 
  const table = new Table({
    head: ['#', 'Token', 'SLDS', 'Cosmos', 'Status'],
    colWidths: [5, 55, 10, 10, 15],
    style: { head: ['cyan'] },
    wordWrap: true,
  });
 
  allKeys.forEach((key, index) => {
    const inCosmos = cosmosKeys.includes(key);
    const inSlds = sldsKeys.includes(key);
    const status = getTokenStatus(inSlds, inCosmos);
 
    table.push([
      index + 1,
      `--${key}`,
      inSlds ? chalk.green('āœ“') : chalk.red('āœ—'),
      inCosmos ? chalk.green('āœ“') : chalk.red('āœ—'),
      status,
    ]);
  });
 
  console.log(table.toString());
 
  console.log(chalk.cyan('\nšŸ“ˆ Summary:'));
  console.log(`  Total unique tokens: ${allKeys.length}`);
  console.log(`  SLDS tokens: ${sldsKeys.length}`);
  console.log(`  Cosmos tokens: ${cosmosKeys.length}`);
  console.log(`  Matching tokens: ${sldsKeys.filter((k) => cosmosKeys.includes(k)).length}`);
}
 
/**
 * Filter tokens into new and known issues
 * @param {string[]} missingTokens - Array of missing token keys
 * @param {string[]} knownIssuesList - Array of known issue token keys (with -- prefix)
 * @returns {Object} Object with newIssues and knownIssues arrays
 */
export function filterKnownIssues(missingTokens, knownIssuesList) {
  const newIssues = missingTokens.filter((token) => !knownIssuesList.includes(`--${token}`));
  const knownIssues = missingTokens.filter((token) => knownIssuesList.includes(`--${token}`));
  return { newIssues, knownIssues };
}
 
/**
 * Print a detailed issues table
 * @param {string} title - Table title
 * @param {string[]} tokens - Array of token keys
 * @param {boolean} missingInCosmos - Whether tokens are missing in Cosmos (true) or SLDS (false)
 * @param {string} headColor - Color for table header ('red' or 'yellow')
 */
export function printIssuesTable(title, tokens, missingInCosmos, headColor) {
  console.log(title);
 
  const table = new Table({
    head: ['#', 'Token', 'SLDS', 'Cosmos'],
    colWidths: [5, 55, 10, 10],
    style: { head: [headColor] },
    wordWrap: true,
  });
 
  tokens.forEach((token, index) => {
    if (missingInCosmos) {
      table.push([index + 1, `--${token}`, chalk.green('āœ“'), chalk.red('āœ—')]);
    } else {
      table.push([index + 1, `--${token}`, chalk.red('āœ—'), chalk.green('āœ“')]);
    }
  });
 
  console.log(table.toString());
  console.log('');
}
 
/**
 * Print detailed issues in verbose mode
 * @param {Object} issues - Object containing categorized issues
 * @param {string[]} issues.newMissingInCosmos - New tokens missing in Cosmos
 * @param {string[]} issues.knownMissingInCosmos - Known tokens missing in Cosmos
 * @param {string[]} issues.newMissingInSlds - New tokens missing in SLDS
 * @param {string[]} issues.knownMissingInSlds - Known tokens missing in SLDS
 */
export function printVerboseIssues(issues) {
  const { newMissingInCosmos, knownMissingInCosmos, newMissingInSlds, knownMissingInSlds } = issues;
 
  console.log(chalk.bold.blue('\nšŸ“‹ Detailed Issues:'));
  console.log('='.repeat(50));
 
  // Group by theme - Cosmos issues (tokens missing in Cosmos)
  if (newMissingInCosmos.length > 0 || knownMissingInCosmos.length > 0) {
    if (newMissingInCosmos.length > 0) {
      printIssuesTable(
        chalk.bold.red(`\nāŒ COSMOS - NEW ISSUES (Missing in Cosmos):`),
        newMissingInCosmos,
        true,
        'red',
      );
    }
 
    if (knownMissingInCosmos.length > 0) {
      printIssuesTable(
        chalk.bold.yellow(`\nāš ļø  COSMOS - KNOWN ISSUES (Missing in Cosmos):`),
        knownMissingInCosmos,
        true,
        'yellow',
      );
    }
  }
 
  // Group by theme - SLDS issues (tokens missing in SLDS)
  if (newMissingInSlds.length > 0 || knownMissingInSlds.length > 0) {
    if (newMissingInSlds.length > 0) {
      printIssuesTable(
        chalk.bold.red(`\nāŒ SLDS - NEW ISSUES (Missing in SLDS):`),
        newMissingInSlds,
        false,
        'red',
      );
    }
 
    if (knownMissingInSlds.length > 0) {
      printIssuesTable(
        chalk.bold.yellow(`\nāš ļø  SLDS - KNOWN ISSUES (Missing in SLDS):`),
        knownMissingInSlds,
        false,
        'yellow',
      );
    }
  }
}
 
/**
 * Print the summary section
 * @param {Object} params - Summary parameters
 * @param {number} params.matchingCount - Number of matching tokens
 * @param {number} params.totalNew - Total new issues
 * @param {number} params.totalKnown - Total known issues
 * @param {number} params.newMissingInCosmosCount - New tokens missing in Cosmos
 * @param {number} params.newMissingInSldsCount - New tokens missing in SLDS
 * @param {number} params.knownMissingInCosmosCount - Known tokens missing in Cosmos
 * @param {number} params.knownMissingInSldsCount - Known tokens missing in SLDS
 */
export function printSummary(params) {
  const {
    matchingCount,
    totalNew,
    totalKnown,
    newMissingInCosmosCount,
    newMissingInSldsCount,
    knownMissingInCosmosCount,
    knownMissingInSldsCount,
  } = params;
 
  console.log(chalk.bold.blue('\nšŸ“Š Summary:'));
  console.log(`${chalk.green('āœ…')} Matching: ${matchingCount}`);
 
  // Show counts for new issues
  if (totalNew > 0) {
    console.log(`${chalk.red('āŒ')} New failures: ${totalNew}`);
    if (newMissingInCosmosCount > 0) {
      console.log(
        `   ${chalk.red('āŒ')} Missing in Cosmos: ${newMissingInCosmosCount} (present in SLDS only)`,
      );
    }
    if (newMissingInSldsCount > 0) {
      console.log(`   ${chalk.red('āŒ')} Missing in SLDS: ${newMissingInSldsCount} (present in Cosmos only)`);
    }
  }
 
  // Show counts for known issues
  if (totalKnown > 0) {
    console.log(`${chalk.yellow('āš ļø')}  Known issues: ${totalKnown}`);
    if (knownMissingInCosmosCount > 0) {
      console.log(
        `   ${chalk.yellow('āš ļø')}  Missing in Cosmos: ${knownMissingInCosmosCount} (present in SLDS only)`,
      );
    }
    if (knownMissingInSldsCount > 0) {
      console.log(
        `   ${chalk.yellow('āš ļø')}  Missing in SLDS: ${knownMissingInSldsCount} (present in Cosmos only)`,
      );
    }
  }
}
 
/**
 * Print helpful hint messages based on flags
 * @param {boolean} isVerbose - Whether verbose mode is enabled
 * @param {boolean} isReport - Whether report mode is enabled
 */
export function printHelpfulHints(isVerbose, isReport) {
  if (!isVerbose && !isReport) {
    console.log(chalk.gray('\nRun with --verbose to see detailed issues or --report to see all tokens'));
  } else if (isVerbose && !isReport) {
    console.log(chalk.gray('\nRun with --report to see all tokens'));
  } else if (isReport && !isVerbose) {
    console.log(chalk.gray('\nRun with --verbose to see detailed list'));
  }
}
 
/**
 * Main validation function
 * @param {Object} sldsTheme - SLDS theme object
 * @param {Object} cosmosTheme - Cosmos theme object
 * @param {Object} options - Validation options
 * @param {boolean} options.isVerbose - Show detailed output
 * @param {boolean} options.isReport - Show full report
 * @param {Object} options.knownIssues - Known issues configuration
 * @param {Function} options.exitFn - Function to call for exit (defaults to process.exit)
 * @returns {Object} Validation result with counts and exit code
 */
export function validateThemes(sldsTheme, cosmosTheme, options = {}) {
  const { isVerbose = false, isReport = false, knownIssues = {}, exitFn = null } = options;
 
  const { missingInTheme2, missingInTheme1 } = compareThemeKeys(sldsTheme, cosmosTheme);
 
  // Show full report if requested
  if (isReport) {
    printReport(sldsTheme, cosmosTheme);
    console.log(''); // Empty line before validation results
  }
 
  console.log(chalk.bold.blue('šŸ” Theme Parity Validation\n'));
 
  // Filter tokens into known vs new issues
  const cosmosKnownIssues = knownIssues.theme_parity?.cosmos?.missing || [];
  const sldsKnownIssues = knownIssues.theme_parity?.slds?.missing || [];
 
  // Filter missing in Cosmos (missingInTheme2)
  const { newIssues: newMissingInCosmos, knownIssues: knownMissingInCosmos } = filterKnownIssues(
    missingInTheme2,
    cosmosKnownIssues,
  );
 
  // Filter missing in SLDS (missingInTheme1)
  const { newIssues: newMissingInSlds, knownIssues: knownMissingInSlds } = filterKnownIssues(
    missingInTheme1,
    sldsKnownIssues,
  );
 
  const totalNew = newMissingInCosmos.length + newMissingInSlds.length;
  const totalKnown = knownMissingInCosmos.length + knownMissingInSlds.length;
  const totalMissing = missingInTheme1.length + missingInTheme2.length;
 
  // Show detailed tables in verbose mode
  if (isVerbose && totalMissing > 0) {
    printVerboseIssues({
      newMissingInCosmos,
      knownMissingInCosmos,
      newMissingInSlds,
      knownMissingInSlds,
    });
  }
  console.log('');
 
  // Calculate matching count
  const sldsKeys = getGlobalKeys(sldsTheme);
  const cosmosKeys = getGlobalKeys(cosmosTheme);
  const matchingCount = sldsKeys.filter((k) => cosmosKeys.includes(k)).length;
 
  // Determine exit code
  let exitCode;
  if (totalMissing === 0) {
    console.log(chalk.bold.blue('\nšŸ“Š Summary:'));
    console.log(`${chalk.green('āœ…')} Matching: ${matchingCount}`);
    exitCode = 0;
  } else {
    printSummary({
      matchingCount,
      totalNew,
      totalKnown,
      newMissingInCosmosCount: newMissingInCosmos.length,
      newMissingInSldsCount: newMissingInSlds.length,
      knownMissingInCosmosCount: knownMissingInCosmos.length,
      knownMissingInSldsCount: knownMissingInSlds.length,
    });
 
    printHelpfulHints(isVerbose, isReport);
 
    // Exit with 1 if there are new issues, 0 if only known issues
    exitCode = totalNew > 0 ? 1 : 0;
  }
 
  // Call exit function if provided
  if (exitFn) {
    exitFn(exitCode, totalKnown);
  }
 
  // Return result for testing
  return {
    exitCode,
    matchingCount,
    totalNew,
    totalKnown,
    newMissingInCosmos,
    knownMissingInCosmos,
    newMissingInSlds,
    knownMissingInSlds,
  };
}