All files / packages/design-tokens/src/validators cross-platform-colors.js

93.19% Statements 438/470
78.12% Branches 250/320
100% Functions 31/31
95.19% Lines 416/437

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 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 668 669 670 671 672 673 674 675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739 740 741 742 743 744 745 746 747 748 749 750 751 752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770 771 772 773 774 775 776 777 778 779 780 781 782 783 784 785 786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036 1037 1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050 1051 1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070                                              2x     2x           2x     2x                               30x                   44x 44x                               59x     59x   3x 3x     59x 50x 20x       59x               141x     141x 13x   39x         141x 80x     141x                 3x 3x   3x     3x 3x 3x 66x 64x 62x 3x 3x         3x 3x 3x 138x 134x 6x 2x 2x   4x       3x   2x                       39x 39x 39x     39x 202x     202x   77x 77x   77x 77x   77x 77x   77x                     80x   65x           65x     15x 15x 15x   15x 15x     15x 2x     13x 13x 1x     12x     12x       39x   64x           64x   6x     58x       64x   64x     6x 6x 6x 6x 6x   6x       58x     58x 3x   3x   2x 2x     2x 2x 2x 2x         2x 2x 2x 2x             55x 55x 51x       51x 51x             39x                 92x     92x 8x     8x                         84x 84x 2x       84x 6x       84x 1260x       84x     84x     84x   84x                 38x 38x 38x 38x     38x     38x   38x 214x     214x   64x 64x 64x 64x           64x           150x 150x 80x 80x     80x 80x     8x 8x 8x       8x         80x 66x       80x 80x 66x 66x   80x       70x 70x 6x 6x 6x     6x   6x                       38x 38x   38x 41x 41x   12x 12x 12x 12x 6x         6x     6x 6x 6x     6x 6x   6x 6x                                   41x     38x                   80x   8x 8x                       72x                               38x 38x 38x 38x     38x     38x   38x 218x       218x         66x 66x 66x 66x           66x           152x       68x 68x   68x     68x 68x 68x   68x   68x 68x 68x     68x 204x         68x 68x     8x 8x   8x         68x 68x       68x     68x         68x 68x   68x 68x       84x           6x 6x 6x 6x   6x                     38x 38x   38x 41x 41x   12x 12x 12x 12x 6x           6x 6x 6x     6x 6x   6x 6x                                 41x     38x             44x 44x 44x 44x   44x 1x 1x 1x     43x 43x   43x 38x   5x     43x 38x   5x     43x 4x 4x 4x 4x 4x 4x     39x             39x 39x     39x 39x 39x   39x 39x     39x 39x 39x 39x     39x 39x 3x 3x 3x   3x 3x 3x       39x         39x   39x             39x 39x 39x 39x   39x 122x 122x 122x   122x 122x 122x 122x   122x 58x 58x     64x 186x   64x 60x   4x       39x                           39x 39x 39x 39x 39x 3x 3x   39x 39x 39x 39x 39x             39x 39x 16x   39x 2x               2x   2x             2x 2x 6x 6x 6x   6x 6x 6x   6x 6x 6x 6x     6x 2x   4x 10x 4x     6x     2x 2x             3x 1x   1x             1x 2x 2x 2x 2x 2x   2x     1x     3x 2x   2x             2x 4x 4x 12x 4x   4x 4x       4x     2x               39x   39x 39x 39x 39x 2x   39x 16x     39x 13x 13x 26x 3x 23x 2x                     44x 44x   44x 44x   39x     39x 2x 2x 2x   2x     39x         39x             39x 39x   39x 39x   39x 2x     39x 3x     39x     39x 39x         2x 2x      
#!/usr/bin/env node
 
/**
 * Cross-Platform Color Consistency Validator (Cosmos Theme)
 *
 * Validates that color tokens produce identical values across CSS, Android (Kotlin),
 * and iOS (Swift) outputs by comparing normalized color values.
 *
 * Note: This validator currently only supports the Cosmos theme. Android and iOS
 * do not have SLDS theme outputs at this time.
 */
 
import fs from 'fs';
import path from 'node:path';
import Color from 'colorjs.io';
import chalk from 'chalk';
import Table from 'cli-table3';
import { parseValidatorArgs, colorSwatch, exitWithStatus } from './validator-utils.js';
 
// ============================================================================
// CONSTANTS
// ============================================================================
 
const THEME = 'cosmos';
 
/** Mode string constants */
const MODE = {
  LIGHT: 'light',
  DARK: 'dark',
};
 
/** Length of 'light-dark(' string for substring operations */
const LIGHT_DARK_PREFIX_LENGTH = 'light-dark('.length;
 
/** Pre-compiled regex patterns for Android token normalization */
const COMPOUND_WORD_PATTERNS = [
  'container',
  'inverse',
  'disabled',
  'surface',
  'accent',
  'background',
  'selected',
  'hover',
  'active',
  'focus',
  'border',
  'error',
  'warning',
  'success',
  'info',
].map((word) => ({
  word,
  regex: new RegExp(`([a-z])${word}`, 'g'),
}));
 
/**
 * Resolve file paths relative to process.cwd() at call time.
 * This allows tests to change cwd without re-importing the module.
 */
function resolvePaths() {
  const cwd = process.cwd();
  return {
    CSS_PATH: path.resolve(cwd, `dist/themes/${THEME}/${THEME}.hooks.custom-props.css`),
    CSS_REFERENCE_PATH: path.resolve(cwd, `dist/themes/${THEME}/${THEME}.reference.hooks.custom-props.css`),
    RAW_JSON_PATH: path.resolve(cwd, `dist/themes/${THEME}/${THEME}.hooks.raw.json`),
    ANDROID_PATH: path.resolve(cwd, `dist/themes/${THEME}/android/SalesforceCosmosTokensAll.kt`),
    IOS_PATH: path.resolve(cwd, `dist/themes/${THEME}/ios/SalesforceCosmosTokensAll.swift`),
  };
}
 
/**
 * Extract deprecated color token paths from the raw JSON
 * @param {object} obj - JSON object to traverse
 * @param {string} path - Current path in the object
 * @param {Set} deprecated - Set to collect deprecated paths
 */
function findDeprecatedColorTokens(obj, currentPath = '', deprecated = new Set()) {
  Iif (typeof obj !== 'object' || obj === null) return deprecated;
 
  // Check if this token is deprecated and is a color
  if (obj['$deprecated'] === true && currentPath.includes('.color.')) {
    // Convert path like slds.g.color.accent.light.1 to color-accent-light-1
    const normalizedPath = currentPath.replace(/^slds\.g\./, '').replace(/\./g, '-');
    deprecated.add(normalizedPath);
  }
 
  for (const [key, value] of Object.entries(obj)) {
    if (!key.startsWith('$')) {
      findDeprecatedColorTokens(value, currentPath ? `${currentPath}.${key}` : key, deprecated);
    }
  }
 
  return deprecated;
}
 
/**
 * Normalize a hex color to lowercase 6-character format
 */
function normalizeHex(hex) {
  // Remove # if present
  let normalized = hex.replace('#', '');
 
  // Expand 3-char shorthand to 6-char
  if (normalized.length === 3) {
    normalized = normalized
      .split('')
      .map((c) => c + c)
      .join('');
  }
 
  // Remove alpha channel if present (8-char)
  if (normalized.length === 8) {
    normalized = normalized.substring(2); // Remove AA from AARRGGBB
  }
 
  return normalized.toLowerCase();
}
 
/**
 * Parse a light-dark() CSS function and extract light and dark values
 * @param {string} value - CSS value containing light-dark()
 * @returns {{ lightValue: string, darkValue: string } | null} - Extracted values or null if parsing fails
 */
function parseLightDarkFunction(value) {
  const startIdx = value.indexOf('light-dark(');
  Iif (startIdx === -1) return null;
 
  const afterStart = value.substring(startIdx + LIGHT_DARK_PREFIX_LENGTH);
 
  // Find comma (accounting for nested parens)
  let commaIdx = -1;
  let parenDepth = 0;
  for (let i = 0; i < afterStart.length; i++) {
    if (afterStart[i] === '(') parenDepth++;
    else if (afterStart[i] === ')') parenDepth--;
    else if (afterStart[i] === ',' && parenDepth === 0) {
      commaIdx = i;
      break;
    }
  }
 
  // Find closing paren
  let closeIdx = -1;
  parenDepth = 0;
  for (let i = 0; i < afterStart.length; i++) {
    if (afterStart[i] === '(') parenDepth++;
    else if (afterStart[i] === ')') {
      if (parenDepth === 0) {
        closeIdx = i;
        break;
      }
      parenDepth--;
    }
  }
 
  if (commaIdx === -1 || closeIdx === -1) return null;
 
  return {
    lightValue: afterStart.substring(0, commaIdx).trim(),
    darkValue: afterStart.substring(commaIdx + 1, closeIdx).trim(),
  };
}
 
/**
 * Parse colors from CSS custom properties file
 * @param {string} cssContent - CSS file content
 * @returns {Map<string, string>} Map of token names to hex values (includes -light and -dark suffixes)
 */
function parseColorsFromCSS(cssContent) {
  const colors = new Map();
  const allProperties = new Map(); // Store all properties for var() resolution
  const lines = cssContent.split('\n');
 
  // First pass: collect all custom properties
  for (const line of lines) {
    const trimmed = line.trim();
 
    // Collect both global (--slds-g-) and reference (--slds-r-) tokens
    if (!trimmed.startsWith('--slds-g-') && !trimmed.startsWith('--slds-r-')) continue;
 
    const colonIdx = trimmed.indexOf(':');
    Iif (colonIdx === -1) continue;
 
    const semiIdx = trimmed.indexOf(';', colonIdx);
    Iif (semiIdx === -1) continue;
 
    const propName = trimmed.substring(0, colonIdx).trim();
    const value = trimmed.substring(colonIdx + 1, semiIdx).trim();
 
    allProperties.set(propName, value);
  }
 
  /**
   * Recursively resolve var() references to get actual color value
   * @param {string} value - CSS value (may contain var())
   * @param {Set} visited - Track visited properties to prevent infinite loops
   * @param {string} mode - 'light' or 'dark' - extracts the appropriate value from light-dark()
   * @returns {string} - Resolved value
   */
  function resolveVar(value, visited = new Set(), mode = null) {
    if (!value.startsWith('var(')) {
      // If the resolved value is a light-dark() and we have a mode, extract the appropriate value
      Iif (mode && value.includes('light-dark(')) {
        const parsed = parseLightDarkFunction(value);
        if (parsed) {
          return mode === MODE.LIGHT ? parsed.lightValue : parsed.darkValue;
        }
      }
      return value;
    }
 
    const varStart = value.indexOf('var(');
    const varEnd = value.indexOf(')', varStart);
    Iif (varEnd === -1) return value;
 
    const varContent = value.substring(varStart + 4, varEnd).trim();
    const refName = varContent.split(',')[0].trim(); // Handle fallback values
 
    // Prevent infinite loops
    if (visited.has(refName)) {
      return value;
    }
 
    const refValue = allProperties.get(refName);
    if (!refValue) {
      return value;
    }
 
    visited.add(refName);
 
    // Recursively resolve if the referenced value also contains var()
    return resolveVar(refValue, visited, mode);
  }
 
  // Second pass: process color properties
  for (const [propName, value] of allProperties.entries()) {
    // Handle both global colors (--slds-g-color-*) and reference colors (--slds-r-color-*)
    Iif (!propName.startsWith('--slds-g-color') && !propName.startsWith('--slds-r-color')) continue;
 
    // Convert CSS token name to standard format:
    // --slds-g-color-brand-primary → color-brand-primary
    // --slds-r-color-brand-10 → color-brand-10
    let tokenName;
    if (propName.startsWith('--slds-r-color-')) {
      // Reference tokens: --slds-r-color-brand-10 → color-brand-10
      tokenName = propName.replace('--slds-r-color-', 'color-');
    } else {
      // Global tokens: --slds-g-color-* → color-*
      tokenName = propName.replace('--slds-g-', '');
    }
 
    // For reference tokens, extract light/dark values from light-dark() if present
    const isReferenceToken = propName.startsWith('--slds-r-');
 
    if (isReferenceToken) {
      // Reference tokens might not have light-dark(), they're just direct hex values or var()
      // Resolve them and create entries with -light and -dark suffixes (same value for both)
      const resolvedHex = resolveVar(value, new Set(), null);
      Eif (resolvedHex && /^#[0-9a-f]{6}$/i.test(resolvedHex)) {
        const normalized = normalizeHex(resolvedHex);
        colors.set(`${tokenName}-${MODE.LIGHT}`, normalized);
        colors.set(`${tokenName}-${MODE.DARK}`, normalized);
      }
      continue;
    }
 
    // Resolve var() references to get actual color value
    const resolvedValue = resolveVar(value);
 
    // Handle light-dark() function - extract both light and dark values
    if (resolvedValue.includes('light-dark(')) {
      const parsed = parseLightDarkFunction(resolvedValue);
 
      if (parsed) {
        // Resolve any var() references in light and dark values
        const lightValue = resolveVar(parsed.lightValue, new Set(), MODE.LIGHT);
        const darkValue = resolveVar(parsed.darkValue, new Set(), MODE.DARK);
 
        // Parse both light and dark colors for semantic/system colors
        try {
          const lightColor = new Color(lightValue);
          const lightHex = normalizeHex(lightColor.to('srgb').toString({ format: 'hex' }));
          colors.set(`${tokenName}-${MODE.LIGHT}`, lightHex);
        } catch {
          // Light color failed to parse - skip silently
        }
 
        try {
          const darkColor = new Color(darkValue);
          const darkHex = normalizeHex(darkColor.to('srgb').toString({ format: 'hex' }));
          colors.set(`${tokenName}-${MODE.DARK}`, darkHex);
        } catch {
          // Dark color failed to parse - skip silently
        }
      }
    } else {
      // Single color value (no light-dark function) - static value like #a96504
      try {
        const color = new Color(resolvedValue);
        const hex = normalizeHex(color.to('srgb').toString({ format: 'hex' }));
 
        // All single-value colors get -light/-dark suffixes to match Android/iOS output
        // (mobile always generates both _Light and _Dark variants, even with the same value)
        colors.set(`${tokenName}-${MODE.LIGHT}`, hex);
        colors.set(`${tokenName}-${MODE.DARK}`, hex);
      } catch {
        // Not a valid color, skip silently
      }
    }
  }
 
  return colors;
}
 
/**
 * Convert Android token name to CSS format
 * @param {string} tokenName - Android token name (e.g., 'errorbase10', 'accentcontainer1', 'neutral50')
 * @returns {string} - Normalized CSS format (e.g., 'color-error-base-10', 'color-accent-container-1', 'color-neutral-50')
 */
function normalizeAndroidTokenName(tokenName) {
  let result = tokenName.toLowerCase();
 
  // Handle palette colors with 'palette' prefix: paletteNeutral0 -> color-palette-neutral-0
  if (tokenName.startsWith('palette')) {
    const paletteStr = tokenName.substring('palette'.length);
 
    // Has camelCase: Neutral0 -> neutral-0
    return (
      'color-palette-' +
      paletteStr
        .replace(/([a-z])([A-Z])/g, '$1-$2') // camelCase boundaries
        .replace(/([a-z])(\d)/g, '$1-$2') // letter before number
        .replace(/([A-Z])(\d)/g, '$1-$2') // uppercase before number
        .toLowerCase()
    );
  }
 
  // Legacy format: starts with 'color' prefix (e.g., 'colorerrorbase10')
  // New format: no 'color' prefix (e.g., 'errorbase10')
  // Handle both for backwards compatibility
  const hasColorPrefix = result.startsWith('color');
  if (hasColorPrefix) {
    result = result.replace(/^color/, '');
  }
 
  // Handle "on-" prefix specially (e.g., ondisabled, onsurface)
  if (result.startsWith('on')) {
    result = 'on-' + result.substring(2);
  }
 
  // Insert hyphens before compound words using pre-compiled patterns
  for (const { word, regex } of COMPOUND_WORD_PATTERNS) {
    result = result.replace(regex, `$1-${word}`);
  }
 
  // Insert hyphens before "base" when preceded by a letter
  result = result.replace(/([a-z])base(\d|$)/g, '$1-base-$2');
 
  // Insert hyphens before numbers
  result = result.replace(/([a-z])(\d)/g, '$1-$2');
 
  // Clean up any artifacts (e.g., double hyphens, trailing hyphens)
  result = result.replace(/--+/g, '-').replace(/-+$/g, '');
 
  return 'color-' + result;
}
 
/**
 * Parse colors from Kotlin file
 * @param {string} kotlinContent - Kotlin file content
 * @returns {Map<string, string>} Map of token names to hex values
 */
function parseColorsFromKotlin(kotlinContent) {
  const colors = new Map();
  const lines = kotlinContent.split('\n');
  let currentMode = null; // 'light' or 'dark'
  let currentClass = null; // Track which object we're in for palette tokens
 
  // First pass: collect all direct Color(0x...) definitions
  const directColors = new Map(); // tokenName -> hexValue
 
  // Second pass: collect reference assignments and resolve them
  const referenceAssignments = []; // { tokenName, reference, mode }
 
  for (const line of lines) {
    const trimmed = line.trim();
 
    // Track which object we're in (Light or Dark, including palette classes)
    if (trimmed.includes('object')) {
      // Extract the full class name, e.g., "SalesforceCosmosPaletteNeutralLight"
      const classMatch = trimmed.match(/object\s+(\w+)/);
      Eif (classMatch) {
        currentClass = classMatch[1];
        currentMode = currentClass.includes('Light')
          ? MODE.LIGHT
          : currentClass.includes('Dark')
            ? MODE.DARK
            : null;
      }
      continue;
    }
 
    // Match direct Color(0x...) values - handles both:
    // val tokenName = Color(0x...)
    // val tokenName get()= Color(0x...)
    const directColorMatch = trimmed.match(/val\s+(\w+)(?:\s+get\(\))?\s*=\s*Color\(0x([A-Fa-f0-9]+)\)/);
    if (directColorMatch) {
      const tokenName = directColorMatch[1];
      const hexValue = normalizeHex(directColorMatch[2]);
 
      // For palette tokens, we need to include the palette family info from the class name
      let fullTokenName = tokenName;
      if (currentClass && currentClass.includes('Palette')) {
        // Extract palette family from class name: PaletteBlueLight -> Blue
        // Property is already like 'blue10', so we construct 'paletteBlue10'
        const paletteMatch = currentClass.match(/Palette(.+?)(?:Light|Dark)$/);
        Eif (paletteMatch) {
          const family = paletteMatch[1]; // e.g., "Blue" or "CloudBlue"
          // Construct: palette + family (lowercase first letter) + scale
          // tokenName is already 'blue10' or 'cloudBlue10', but we want 'paletteBlue10'
          // Actually, we just need to prepend 'palette': blue10 -> paletteBlue10
          fullTokenName = `palette${tokenName.charAt(0).toUpperCase() + tokenName.slice(1)}`;
        }
      }
 
      // Store in directColors with mode suffix to avoid overwriting light with dark (or vice versa)
      if (currentMode) {
        directColors.set(`${fullTokenName}-${currentMode}`, hexValue);
      }
 
      // Also add to final colors map with mode suffix
      let standardName = normalizeAndroidTokenName(fullTokenName);
      if (standardName && currentMode) {
        standardName = `${standardName}-${currentMode}`;
        colors.set(standardName, hexValue);
      }
      continue;
    }
 
    // Match reference assignments: val coloraccent1 get() = SalesforceCosmosReferenceColorsLight.colorbrand50
    const refMatch = trimmed.match(/val\s+(\w+)(?:\s+get\(\))?\s*=\s*(\w+)\.(\w+)/);
    if (refMatch) {
      const tokenName = refMatch[1];
      const refClass = refMatch[2];
      const refProperty = refMatch[3];
 
      // Determine if reference is to Light or Dark based on class name
      const refMode = refClass.includes('Light') ? MODE.LIGHT : refClass.includes('Dark') ? MODE.DARK : null;
 
      referenceAssignments.push({
        tokenName,
        refClass,
        refProperty,
        mode: currentMode,
        refMode,
      });
    }
  }
 
  // Resolve references by looking up the referenced tokens
  // This may require multiple passes for chained references
  let maxIterations = 10; // Prevent infinite loops
  let resolvedCount = 0;
 
  do {
    resolvedCount = 0;
    referenceAssignments.forEach(({ tokenName, refProperty, mode, refMode }) => {
      // Skip if already resolved
      let standardName = normalizeAndroidTokenName(tokenName);
      Eif (standardName && mode) {
        standardName = `${standardName}-${mode}`;
        if (colors.has(standardName)) {
          return; // Already resolved
        }
      }
 
      // Look up the referenced token (it should be in directColors)
      const refTokenName = refProperty; // e.g., 'colorbrand50' or 'colorsuccessbase40'
 
      // Try to find in directColors using the reference's mode
      let refHexValue = null;
      Eif (refMode) {
        refHexValue = directColors.get(`${refTokenName}-${refMode}`);
      }
 
      if (refHexValue) {
        Eif (standardName && mode) {
          // Use the mode of the current object, not the reference mode
          colors.set(standardName, refHexValue);
          resolvedCount++;
        }
      } else E{
        // The reference itself might be a reference - check if it's already resolved
        let refStandardName = normalizeAndroidTokenName(refTokenName);
        if (refStandardName && refMode) {
          refStandardName = `${refStandardName}-${refMode}`;
          const resolvedRefValue = colors.get(refStandardName);
          if (resolvedRefValue) {
            // We found the reference's value in our resolved colors
            if (standardName && mode) {
              colors.set(standardName, resolvedRefValue);
              resolvedCount++;
            }
          }
        }
      }
    });
    maxIterations--;
  } while (resolvedCount > 0 && maxIterations > 0);
 
  return colors;
}
 
/**
 * Convert iOS token name to CSS format
 * @param {string} tokenName - Swift token name (e.g., 'errorBase10', 'paletteNeutral0')
 * @returns {string} - Normalized CSS format (e.g., 'color-error-base-10', 'color-palette-neutral-0')
 */
function normalizeSwiftTokenName(tokenName) {
  // Handle palette colors (paletteNeutral0, paletteBlue5, etc.)
  if (tokenName.startsWith('palette')) {
    // paletteNeutral0 -> color-palette-neutral-0
    const withoutPrefix = tokenName.replace(/^palette/, '');
    return (
      'color-palette-' +
      withoutPrefix
        .replace(/([a-z])([A-Z])/g, '$1-$2') // lowercase before uppercase
        .replace(/([a-z])(\d)/g, '$1-$2') // lowercase before digit
        .replace(/([A-Z])(\d)/g, '$1-$2') // uppercase before digit
        .toLowerCase()
    );
  }
 
  // Regular colors: errorBase10 -> color-error-base-10
  // Convert camelCase to kebab-case
  return (
    'color-' +
    tokenName
      .replace(/([a-z])([A-Z])/g, '$1-$2') // lowercase before uppercase
      .replace(/([a-z])(\d)/g, '$1-$2') // lowercase before digit
      .replace(/([A-Z])(\d)/g, '$1-$2') // uppercase before digit
      .toLowerCase()
  );
}
 
/**
 * Parse colors from Swift file
 * @param {string} swiftContent - Swift file content
 * @returns {Map<string, string>} Map of token names to hex values
 */
function parseColorsFromSwift(swiftContent) {
  const colors = new Map();
  const lines = swiftContent.split('\n');
  let currentMode = null; // 'light' or 'dark'
  let currentClass = null; // Track which class/enum we're in for palette tokens
 
  // First pass: collect all direct Color(...) definitions
  const directColors = new Map(); // tokenName -> hexValue
 
  // Second pass: collect reference assignments and resolve them
  const referenceAssignments = []; // { tokenName, reference, mode }
 
  for (const line of lines) {
    const trimmed = line.trim();
 
    // Track which class/enum we're in (including palette enums)
    // Check for both 'class' and 'enum'
    if (
      (trimmed.includes('public class') || trimmed.includes('public enum')) &&
      (trimmed.includes('Light') || trimmed.includes('Dark'))
    ) {
      // Extract the full class/enum name
      const classMatch = trimmed.match(/(?:class|enum)\s+(\w+)/);
      Eif (classMatch) {
        currentClass = classMatch[1];
        currentMode = currentClass.includes('Light')
          ? MODE.LIGHT
          : currentClass.includes('Dark')
            ? MODE.DARK
            : null;
      }
      continue;
    }
 
    // Match direct color definitions with both 'let' and 'var':
    // public static let blue10 = Color(red: 0.000, green: 0.086, blue: 0.224)
    // public static var errorBase10: Color { Color(red: 0.216, green: 0.004, blue: 0.078) }
    if (
      (trimmed.includes('static let') || trimmed.includes('static var')) &&
      trimmed.includes('Color(red:')
    ) {
      const varMatch = trimmed.match(/static\s+(?:let|var)\s+(\w+)(?:\s*:\s*Color)?/);
      Iif (!varMatch) continue;
 
      const tokenName = varMatch[1];
 
      // Extract RGB values (0-1 floats)
      const redMatch = trimmed.match(/red:\s*([\d.]+)/);
      const greenMatch = trimmed.match(/green:\s*([\d.]+)/);
      const blueMatch = trimmed.match(/blue:\s*([\d.]+)/);
 
      Iif (!redMatch || !greenMatch || !blueMatch) continue;
 
      const red = Math.round(parseFloat(redMatch[1]) * 255);
      const green = Math.round(parseFloat(greenMatch[1]) * 255);
      const blue = Math.round(parseFloat(blueMatch[1]) * 255);
 
      // Convert to hex
      const hex = [red, green, blue]
        .map((v) => v.toString(16).padStart(2, '0'))
        .join('')
        .toLowerCase();
 
      // For palette tokens, we need to include the palette family info from the class name
      let fullTokenName = tokenName;
      if (currentClass && currentClass.includes('Palette')) {
        // Extract palette family from class name: BluePaletteLight -> Blue
        // Property is already like 'blue10', so we construct 'paletteBlue10'
        const paletteMatch = currentClass.match(/Cosmos(.+?)Palette/);
        Eif (paletteMatch) {
          // tokenName is already 'blue10' or 'cloudBlue10', we just prepend 'palette'
          fullTokenName = `palette${tokenName.charAt(0).toUpperCase() + tokenName.slice(1)}`;
        }
      }
 
      // Store in directColors with mode suffix to avoid overwriting light with dark (or vice versa)
      Eif (currentMode) {
        directColors.set(`${fullTokenName}-${currentMode}`, hex);
      }
 
      // Also add to final colors map with mode suffix
      let standardName = normalizeSwiftTokenName(fullTokenName);
 
      // Skip if normalization failed
      Iif (!standardName) {
        continue;
      }
 
      // Add light/dark suffix based on current class
      Eif (currentMode) {
        standardName = `${standardName}-${currentMode}`;
      }
      colors.set(standardName, hex);
      continue;
    }
 
    // Match reference assignments: public static var accent1: Color { SalesforceCosmosReferenceColorsLight.brand50 }
    if (
      trimmed.includes('static var') &&
      trimmed.includes(':') &&
      trimmed.includes('{') &&
      trimmed.includes('.')
    ) {
      const refMatch = trimmed.match(/static\s+var\s+(\w+)\s*:\s*Color\s*\{\s*\w+\.(\w+)\s*\}/);
      Eif (refMatch) {
        const tokenName = refMatch[1];
        const refProperty = refMatch[2]; // e.g., 'brand50', 'neutralBase50'
 
        referenceAssignments.push({
          tokenName,
          refProperty,
          mode: currentMode,
        });
      }
    }
  }
 
  // Resolve references by looking up the referenced tokens
  // This may require multiple passes for chained references
  let maxIterations = 10; // Prevent infinite loops
  let resolvedCount = 0;
 
  do {
    resolvedCount = 0;
    referenceAssignments.forEach(({ tokenName, refProperty, mode }) => {
      // Skip if already resolved
      let standardName = normalizeSwiftTokenName(tokenName);
      Eif (standardName && mode) {
        standardName = `${standardName}-${mode}`;
        if (colors.has(standardName)) {
          return; // Already resolved
        }
      }
 
      // Look up the referenced token (it should be in directColors)
      // Try to find in directColors using the token's mode
      let refHexValue = null;
      Eif (mode) {
        refHexValue = directColors.get(`${refProperty}-${mode}`);
      }
 
      if (refHexValue) {
        Eif (standardName && mode) {
          // Use the mode of the current object
          colors.set(standardName, refHexValue);
          resolvedCount++;
        }
      } else E{
        // The reference itself might be a reference - check if it's already resolved
        const refStandardName = normalizeSwiftTokenName(refProperty);
        if (refStandardName && mode) {
          // Use the same mode as the current token's mode
          const resolvedRefValue = colors.get(`${refStandardName}-${mode}`);
 
          if (resolvedRefValue && standardName) {
            // We found the reference's value in our resolved colors
            colors.set(standardName, resolvedRefValue);
            resolvedCount++;
          }
        }
      }
    });
    maxIterations--;
  } while (resolvedCount > 0 && maxIterations > 0);
 
  return colors;
}
 
/**
 * Check platform file availability and exit if insufficient
 */
function checkPlatformAvailability(paths) {
  const { CSS_PATH, ANDROID_PATH, IOS_PATH } = paths;
  const cssExists = fs.existsSync(CSS_PATH);
  const androidExists = fs.existsSync(ANDROID_PATH);
  const iosExists = fs.existsSync(IOS_PATH);
 
  if (!cssExists) {
    console.error(`❌ CSS file not found: ${CSS_PATH}`);
    process.exit(1);
    return null;
  }
 
  const availablePlatforms = ['CSS'];
  const missingPlatforms = [];
 
  if (androidExists) {
    availablePlatforms.push('Android');
  } else {
    missingPlatforms.push({ name: 'Android', path: ANDROID_PATH });
  }
 
  if (iosExists) {
    availablePlatforms.push('iOS');
  } else {
    missingPlatforms.push({ name: 'iOS', path: IOS_PATH });
  }
 
  if (availablePlatforms.length < 2) {
    console.error(`❌ Need at least 2 platforms to compare. Only found: ${availablePlatforms.join(', ')}`);
    console.log(`\n   CSS:     ${cssExists ? '✓' : '✗'}`);
    console.log(`   Android: ${androidExists ? '✓' : '✗'}`);
    console.log(`   iOS:     ${iosExists ? '✓' : '✗'}\n`);
    process.exit(1);
    return null;
  }
 
  return { availablePlatforms, missingPlatforms, cssExists, androidExists, iosExists };
}
 
/**
 * Load and parse colors from all available platforms
 */
function loadPlatformColors(paths, platformAvailability) {
  const { CSS_PATH, CSS_REFERENCE_PATH, RAW_JSON_PATH, ANDROID_PATH, IOS_PATH } = paths;
  const { androidExists, iosExists } = platformAvailability;
 
  // Load CSS colors
  let cssContent = fs.readFileSync(CSS_PATH, 'utf8');
  Eif (fs.existsSync(CSS_REFERENCE_PATH)) {
    cssContent += '\n' + fs.readFileSync(CSS_REFERENCE_PATH, 'utf8');
  }
  const cssColors = parseColorsFromCSS(cssContent);
  const rawCssCount = cssColors.size;
 
  // Load and remove deprecated tokens
  let deprecatedTokens = new Set();
  Eif (fs.existsSync(RAW_JSON_PATH)) {
    const rawJson = JSON.parse(fs.readFileSync(RAW_JSON_PATH, 'utf8'));
    deprecatedTokens = findDeprecatedColorTokens(rawJson);
  }
 
  let deprecatedCount = 0;
  for (const deprecatedToken of deprecatedTokens) {
    Iif (cssColors.has(deprecatedToken)) deprecatedCount++;
    Eif (cssColors.has(`${deprecatedToken}-light`)) deprecatedCount++;
    Eif (cssColors.has(`${deprecatedToken}-dark`)) deprecatedCount++;
 
    cssColors.delete(deprecatedToken);
    cssColors.delete(`${deprecatedToken}-light`);
    cssColors.delete(`${deprecatedToken}-dark`);
  }
 
  // Load Android colors
  const androidColors = androidExists
    ? parseColorsFromKotlin(fs.readFileSync(ANDROID_PATH, 'utf8'))
    : new Map();
 
  // Load iOS colors
  const iosColors = iosExists ? parseColorsFromSwift(fs.readFileSync(IOS_PATH, 'utf8')) : new Map();
 
  return { cssColors, androidColors, iosColors, rawCssCount, deprecatedCount };
}
 
/**
 * Categorize tokens into matching, mismatched, and missing
 */
function categorizeTokens(cssColors, androidColors, iosColors, availablePlatforms) {
  const allTokens = new Set([...cssColors.keys(), ...androidColors.keys(), ...iosColors.keys()]);
  const matching = [];
  const mismatched = [];
  const missing = [];
 
  for (const token of allTokens) {
    const cssHex = cssColors.get(token);
    const androidHex = androidColors.get(token);
    const iosHex = iosColors.get(token);
 
    const platforms = [];
    if (cssHex) platforms.push('CSS');
    if (androidHex) platforms.push('Android');
    if (iosHex) platforms.push('iOS');
 
    if (platforms.length < availablePlatforms.length) {
      missing.push({ token, platforms, cssHex, androidHex, iosHex });
      continue;
    }
 
    const hexValues = [cssHex, androidHex, iosHex].filter(Boolean);
    const allMatch = hexValues.every((hex) => hex === hexValues[0]);
 
    if (allMatch) {
      matching.push(token);
    } else {
      mismatched.push({ token, cssHex, androidHex, iosHex });
    }
  }
 
  return { allTokens, matching, mismatched, missing };
}
 
/**
 * Print summary header with token counts
 */
function printSummaryHeader(
  availablePlatforms,
  cssColors,
  androidColors,
  iosColors,
  rawCssCount,
  deprecatedCount,
) {
  console.log(chalk.bold.blue('\nCross-Platform Color Validation\n'));
  console.log(`Comparing platforms: ${availablePlatforms.join(', ')}\n`);
  console.log('Token counts:');
  console.log(`  CSS (raw):     ${rawCssCount} tokens`);
  if (deprecatedCount > 0) {
    console.log(chalk.gray(`    - ${deprecatedCount} deprecated tokens (not output by mobile)`));
    console.log(`  CSS (active):  ${cssColors.size} tokens`);
  }
  if (androidColors.size > 0) console.log(`  Android:       ${androidColors.size} tokens`);
  if (iosColors.size > 0) console.log(`  iOS:           ${iosColors.size} tokens`);
  console.log(chalk.gray('\nNote: All platforms output -light/-dark variants for each token.'));
  console.log(chalk.gray('      CSS uses light-dark() function, mobile outputs separate tokens.'));
  console.log('');
}
 
/**
 * Print validation results summary
 */
function printResultsSummary(matching, mismatched, missing, totalTokens) {
  console.log(`${chalk.green('✅')} Matching: ${matching.length}/${totalTokens} tokens`);
  if (missing.length > 0) {
    console.log(`${chalk.yellow('⚠️')}  Missing: ${missing.length} tokens not in all platforms`);
  }
  if (mismatched.length > 0) {
    console.log(`${chalk.red('❌')} Mismatched: ${mismatched.length} tokens have different values`);
  }
}
 
/**
 * Print complete token report table
 */
function printReportTable(allTokens, cssColors, androidColors, iosColors, availablePlatforms) {
  console.log(chalk.bold.blue('\n📊 Complete Token Report:\n'));
 
  const reportTable = new Table({
    head: ['#', 'Token', 'CSS', 'Android', 'iOS', 'Status'],
    colWidths: [5, 40, 18, 18, 18, 18],
    style: { head: ['cyan'] },
    wordWrap: true,
  });
 
  const sortedTokens = Array.from(allTokens).sort();
  sortedTokens.forEach((token, index) => {
    const cssHex = cssColors.get(token);
    const androidHex = androidColors.get(token);
    const iosHex = iosColors.get(token);
 
    const cssDisplay = cssHex ? `${colorSwatch(`#${cssHex}`)} #${cssHex}` : chalk.gray('—');
    const androidDisplay = androidHex ? `${colorSwatch(`#${androidHex}`)} #${androidHex}` : chalk.gray('—');
    const iosDisplay = iosHex ? `${colorSwatch(`#${iosHex}`)} #${iosHex}` : chalk.gray('—');
 
    const platforms = [];
    Eif (cssHex) platforms.push('CSS');
    if (androidHex) platforms.push('Android');
    if (iosHex) platforms.push('iOS');
 
    let status;
    if (platforms.length < availablePlatforms.length) {
      status = chalk.yellow('⚠️  Missing');
    } else {
      const hexValues = [cssHex, androidHex, iosHex].filter(Boolean);
      const allMatch = hexValues.every((hex) => hex === hexValues[0]);
      status = allMatch ? chalk.green('✅ Match') : chalk.red('❌ Mismatch');
    }
 
    reportTable.push([index + 1, token, cssDisplay, androidDisplay, iosDisplay, status]);
  });
 
  console.log(reportTable.toString());
  console.log('');
}
 
/**
 * Print detailed verbose tables for mismatches and missing tokens
 */
function printVerboseTables(mismatched, missing, availablePlatforms) {
  if (mismatched.length > 0) {
    console.log(chalk.bold.blue('\n📋 Mismatched Colors:\n'));
 
    const mismatchTable = new Table({
      head: ['#', 'Token', 'CSS', 'Android', 'iOS'],
      colWidths: [5, 40, 25, 25, 25],
      style: { head: ['red'] },
      wordWrap: true,
    });
 
    mismatched.forEach((item, index) => {
      const { token, cssHex, androidHex, iosHex } = item;
      const tokenDisplay = `${chalk.red('❌')} ${token}`;
      const cssDisplay = cssHex ? `${colorSwatch(`#${cssHex}`)} #${cssHex}` : chalk.gray('—');
      const androidDisplay = androidHex ? `${colorSwatch(`#${androidHex}`)} #${androidHex}` : chalk.gray('—');
      const iosDisplay = iosHex ? `${colorSwatch(`#${iosHex}`)} #${iosHex}` : chalk.gray('—');
 
      mismatchTable.push([index + 1, tokenDisplay, cssDisplay, androidDisplay, iosDisplay]);
    });
 
    console.log(mismatchTable.toString());
  }
 
  if (missing.length > 0) {
    console.log(chalk.bold.blue('\n📋 Missing Tokens:\n'));
 
    const missingTable = new Table({
      head: ['#', 'Token', 'Present In', 'Missing From', 'Values'],
      colWidths: [5, 40, 20, 20, 30],
      style: { head: ['yellow'] },
      wordWrap: true,
    });
 
    missing.forEach((item, index) => {
      const { token, platforms, cssHex, androidHex, iosHex } = item;
      const presentIn = platforms.join(', ');
      const missingFrom = availablePlatforms.filter((p) => !platforms.includes(p)).join(', ');
      const tokenDisplay = `${chalk.yellow('⚠️')}  ${token}`;
 
      let valueDisplay = '';
      if (cssHex) valueDisplay = `CSS: ${colorSwatch(`#${cssHex}`)} #${cssHex}`;
      else Eif (androidHex) valueDisplay = `Android: ${colorSwatch(`#${androidHex}`)} #${androidHex}`;
      else if (iosHex) valueDisplay = `iOS: ${colorSwatch(`#${iosHex}`)} #${iosHex}`;
 
      missingTable.push([index + 1, tokenDisplay, presentIn, missingFrom, valueDisplay]);
    });
 
    console.log(missingTable.toString());
  }
}
 
/**
 * Print final summary and usage hints
 */
function printFinalSummary(matching, mismatched, missing, totalTokens, isReport, isVerbose) {
  const totalIssues = mismatched.length + missing.length;
 
  console.log(chalk.bold.blue('\n📊 Summary:'));
  console.log(`${matching.length}/${totalTokens} tests passed`);
  console.log(`${chalk.green('✅')} Matching: ${matching.length}`);
  if (mismatched.length > 0) {
    console.log(`${chalk.red('❌')} Mismatched: ${mismatched.length}`);
  }
  if (missing.length > 0) {
    console.log(`${chalk.yellow('⚠️')}  Missing: ${missing.length}`);
  }
 
  if (!isReport && !isVerbose && totalIssues > 0) {
    console.log(chalk.gray('\nRun with --verbose to see detailed issue tables'));
    console.log(chalk.gray('Run with --report to see all tokens'));
  } else if (!isReport && isVerbose) {
    console.log(chalk.gray('\nRun with --report to see all tokens'));
  } else if (isReport && !isVerbose && totalIssues > 0) {
    console.log(chalk.gray('\nRun with --verbose to see detailed issue tables'));
  }
}
 
/**
 * Main validation function
 *
 * Resolves file paths from process.cwd() and parses CLI flags at call time,
 * allowing tests to call this function directly without re-importing the module.
 */
export function validateCrossPlatformColors() {
  const { isVerbose, isReport } = parseValidatorArgs();
  const paths = resolvePaths();
 
  const platformAvailability = checkPlatformAvailability(paths);
  if (!platformAvailability) return;
 
  const { availablePlatforms, missingPlatforms } = platformAvailability;
 
  // Show warnings for missing platforms
  if (missingPlatforms.length > 0) {
    missingPlatforms.forEach(({ name, path }) => {
      console.log(`🟡 Warning: ${name} output not found - skipping ${name} validation`);
      console.log(`   Expected: ${path}`);
    });
    console.log('');
  }
 
  const { cssColors, androidColors, iosColors, rawCssCount, deprecatedCount } = loadPlatformColors(
    paths,
    platformAvailability,
  );
 
  const { allTokens, matching, mismatched, missing } = categorizeTokens(
    cssColors,
    androidColors,
    iosColors,
    availablePlatforms,
  );
 
  const totalTokens = allTokens.size;
  const totalIssues = mismatched.length + missing.length;
 
  printSummaryHeader(availablePlatforms, cssColors, androidColors, iosColors, rawCssCount, deprecatedCount);
  printResultsSummary(matching, mismatched, missing, totalTokens);
 
  if (isReport) {
    printReportTable(allTokens, cssColors, androidColors, iosColors, availablePlatforms);
  }
 
  if (isVerbose && totalIssues > 0) {
    printVerboseTables(mismatched, missing, availablePlatforms);
  }
 
  printFinalSummary(matching, mismatched, missing, totalTokens, isReport, isVerbose);
 
  // Both mismatched and missing tokens should fail CI
  const failureCount = mismatched.length + missing.length;
  exitWithStatus(failureCount, 0);
}
 
// Auto-execute only when run directly (not when imported by tests)
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
Iif (process.argv[1] === __filename) {
  validateCrossPlatformColors();
}