All files / packages/design-tokens/src/style-dictionary/formats android-tokens-split.ts

91.4% Statements 266/291
86.03% Branches 154/179
90.16% Functions 55/61
92.75% Lines 256/276

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                                                                                                                                      121x 121x 121x 121x 121x 121x 121x   121x   121x                                                 4x 4x 4x   4x 4x 1x 1x     3x               1x 1x           22x 22x 6x     16x 16x 16x 16x             54x     54x 3x     51x             45x     44x 3x 3x 2x   1x       41x 5x       36x 36x   36x 34x       2x                         53x     53x 119x     53x   119x   119x 53x   66x                                 33x 33x       33x   33x     33x   33x     62x   33x     37x 4x         29x 29x                   29x   29x     78x 29x     49x 49x                             123x     1x       27x   3x   2x       1x       7x   1x         44x                           22x 22x   22x                 22x       22x 3x   3x     3x             3x 3x       22x 6x   6x     11x       6x 6x       22x 2x   2x     1x   1x 1x             2x 2x       22x 2x   2x       3x     3x                     2x 2x       22x 4x     4x   6x     6x 6x                         6x 6x   12x 6x   6x 6x         4x     4x   1x       4x 4x       22x 3x   3x       3x       3x 3x     22x                                                                   33x   33x     33x           22x 22x           33x 33x 17x 1x   17x 2x   15x     33x     33x 33x 17x 1x   17x 2x   15x     33x   33x                             12x   12x   16x         2x 2x 2x 2x                                         7x   7x   9x                                         9x   9x   12x         2x 2x 2x 2x                                                   14x   14x   20x           14x     14x   14x 11x       11x 11x   11x   11x 9x     11x 11x 11x 11x       11x     11x 11x 11x           11x 11x 11x             14x   14x 9x 9x     9x 9x 11x     11x   9x     9x 9x 9x 11x     11x   9x       14x                     45x 45x 45x     45x 453x     453x 30x 30x       423x 29x       394x 59x       335x 20x 20x       45x                 1x 5x 5x           5x                     5x                       5x 45x 45x 45x 45x 45x     5x       1x                                 111x 111x   111x       111x   17x                   9x                   10x                   11x                   22x     12x     7x     9x     14x             66x   1x                   1x                      
/**
 * Android Split Tokens Format for Android/Jetpack Compose
 *
 * Generates multiple Kotlin files with structured token output:
 * - SalesforceCosmosSystemColors.kt - System color objects (Light/Dark)
 * - SalesforceCosmosReferenceColors.kt - Reference color objects (Light/Dark)
 * - SalesforceCosmosSemanticColors.kt - Semantic color objects (Light/Dark)
 * - SalesforceCosmosPaletteColors.kt - Palette color objects (per color family, Light/Dark)
 * - SalesforceCosmosFonts.kt - Font size/weight/family objects
 * - SalesforceCosmosShapes.kt - Border radius object
 * - SalesforceCosmosSpacing.kt - Spacing object
 * - SalesforceCosmosSizing.kt - Sizing object
 * - SalesforceCosmosMotionDuration.kt - Duration object
 *
 * Note: Deprecated tokens are included with @Deprecated annotation.
 */
 
import Color from 'colorjs.io';
import type { Dictionary, FormatFn, FormatFnArguments } from 'style-dictionary/types';
 
import {
  convertDurationToMs,
  getRawValueUnitValue,
  resolveTokenReference,
  isTokenReference,
  parseOklch,
  expandHexColor,
  getTokensForCategory,
  shouldSkipToken,
  isDeprecatedToken,
  isSystemColorToken,
  isReferenceColorToken,
  isSemanticColorToken,
  generateDimensionOutput,
  generateDurationOutput,
  groupFontTokens,
  generateFontFamilyOutput,
  generateFontWeightOutput,
  generateFontDimensionOutput,
  generateLineHeightOutput,
  generateTruncationOutput,
  getTokenDescription,
  PATH_INDEX,
  CATEGORY,
  FONT_SUBCATEGORY,
  FONT_MODIFIER,
} from '../utils/mobile-helpers.js';
import { MODE_EXTENSION_KEY } from '../utils/constants.js';
import { processColorTokens } from '../utils/mobile-color-helpers.js';
 
// ============================================================================
// FILE HEADER GENERATOR
// ============================================================================
 
/**
 * Generate file header with conditional imports based on what the file needs
 * @param {string} purpose - Description of the file's purpose
 * @param {Object} options - Import options
 * @param {boolean} options.needsColor - Whether Color import is needed
 * @param {boolean} options.needsDp - Whether dp import is needed
 * @param {boolean} options.needsSp - Whether sp import is needed
 * @returns {string} - File header with appropriate imports
 */
function generateFileHeader(
  purpose,
  options: Partial<{ needsColor: boolean; needsDp: boolean; needsSp: boolean }> = {},
) {
  const needsColor = options.needsColor ?? false;
  const needsDp = options.needsDp ?? false;
  const needsSp = options.needsSp ?? false;
  const imports = [];
  if (needsColor) imports.push('import androidx.compose.ui.graphics.Color');
  if (needsDp) imports.push('import androidx.compose.ui.unit.dp');
  if (needsSp) imports.push('import androidx.compose.ui.unit.sp');
 
  const importSection = imports.length > 0 ? imports.join('\n') + '\n\n' : '';
 
  return `/*
 * AUTO-GENERATED FILE. DO NOT EDIT.
 *
 * ${purpose}
 *
 * This file is intended for Compose-based Android projects.
 *
 * Note: Deprecated tokens are marked with @Deprecated annotation.
 */
 
package com.salesforce.android.sharedui.tokens
 
${importSection}`;
}
 
// ============================================================================
// DEPRECATION ANNOTATION
// ============================================================================
 
/**
 * Generate Kotlin @Deprecated annotation for a token
 * @param {object} token - Token object
 * @returns {string} - Kotlin @Deprecated annotation
 */
function generateDeprecationAnnotation(token) {
  const description = token.$description || token.original?.$description || '';
  const message = description || `Token ${token.path.join('.')} is deprecated`;
  const escapedMessage = message.replace(/"/g, '\\"');
 
  const originalValue = token.original?.$value;
  if (originalValue && isTokenReference(originalValue)) {
    const replacement = originalValue.slice(1, -1);
    return `    @Deprecated("${escapedMessage}", replaceWith = ReplaceWith("${replacement}"))\n`;
  }
 
  return `    @Deprecated("${escapedMessage}")\n`;
}
 
// ============================================================================
// COLOR UTILITIES
// ============================================================================
 
// Constants for color conversions
const COMPOSE_COLOR_PREFIX = '0xFF';
const HEX_COLOR_LENGTH = 6;
 
/**
 * Convert OKLCH color format to hexadecimal
 */
function oklchToHex(oklch) {
  const components = parseOklch(oklch);
  if (!components) {
    throw new Error(`[Android-Split] Could not parse OKLCH color: ${JSON.stringify(oklch)}`);
  }
 
  const [L, C, H] = components;
  const color = new Color('oklch', [L, C, H]);
  const srgb = color.to('srgb');
  return srgb.toString({ format: 'hex' }).toUpperCase().replace('#', '');
}
 
/**
 * Convert hex color to Compose Color constructor format
 */
function toComposeColor(hex) {
  const cleanHex = expandHexColor(hex);
 
  // Validate hex length after expansion
  if (cleanHex.length !== HEX_COLOR_LENGTH) {
    throw new Error(`[Android-Split] Invalid hex color: "${hex}" (expected 3 or 6 character hex)`);
  }
 
  return `Color(${COMPOSE_COLOR_PREFIX}${cleanHex})`;
}
 
/**
 * Resolve a color value to uppercase hex
 */
function resolveColorToHex(colorValue, allTokens, visited = new Set()) {
  if (!colorValue) return null;
 
  // Handle token reference
  if (isTokenReference(colorValue)) {
    const refValue = resolveTokenReference(colorValue, allTokens, visited);
    if (refValue !== null) {
      return resolveColorToHex(refValue, allTokens, visited);
    }
    return null;
  }
 
  // Handle OKLCH (string or object)
  if (parseOklch(colorValue)) {
    return oklchToHex(colorValue);
  }
 
  // Handle hex string
  Eif (typeof colorValue === 'string') {
    const cleanHex = expandHexColor(colorValue);
    // Validate after expansion to ensure we have a 6-digit hex
    if (cleanHex.length === HEX_COLOR_LENGTH && /^[0-9a-f]{6}$/i.test(cleanHex)) {
      return cleanHex.toUpperCase();
    }
  }
 
  return null;
}
 
// ============================================================================
// NAMING UTILITIES
// ============================================================================
 
/**
 * Convert token path to short property name for objects
 * Example: ['slds', 'g', 'spacing', '1'] -> 'spacing1'
 */
function pathToShortPropertyName(path) {
  // Skip namespace and scope (slds.g), then take from category onwards
  const relevantPath = path.slice(PATH_INDEX.CATEGORY);
 
  // Helper to convert a segment with hyphens to camelCase
  const toCamelCase = (segment) => {
    return segment.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
  };
 
  return relevantPath
    .map((segment, index) => {
      const camelSegment = toCamelCase(segment);
      // First segment lowercase, subsequent segments capitalize first letter
      if (index === 0) {
        return camelSegment.toLowerCase();
      }
      return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
    })
    .join('');
}
 
/**
 * Convert token path to property name for scoped font objects
 * Skips category and subcategory since they're already in the class name
 * Example: ['slds', 'g', 'font', 'scale', '1'] -> 'scale1'
 */
function pathToScopedFontPropertyName(path) {
  // For font tokens, include subcategory + name for better clarity
  // Path structure: [slds, g, font, subcategory, name, ...]
  // Example: ['slds', 'g', 'font', 'scale', '1'] -> 'scale1'
  // Example: ['slds', 'g', 'font', 'weight', '1'] -> 'weight1'
  // Example: ['slds', 'g', 'font', 'weight', 'bold'] -> 'bold' (semantic names don't get prefix)
  // Example: ['slds', 'g', 'font', 'line-clamp'] -> 'lineclamp' (hyphen converted to camelCase)
  const subcategory = path[PATH_INDEX.SUBCATEGORY]; // e.g., 'scale', 'weight', 'line-clamp'
  const nameParts = path.slice(4); // Everything after subcategory
 
  // Check if this is a semantic name (non-numeric) - if so, don't prefix with subcategory
  // Note: 'base', 'var', 'ratio', and 'neg' tokens should always get the subcategory prefix for consistency
  const firstNamePart = nameParts[0];
  const isSemanticName =
    firstNamePart && !/^\d/.test(firstNamePart) && !['base', 'var', 'ratio', 'neg'].includes(firstNamePart);
 
  // For semantic names, use just the name parts. For numeric/structured names, include subcategory
  const allParts = isSemanticName ? nameParts : [subcategory, ...nameParts];
 
  return allParts
    .map((segment, index) => {
      // First segment lowercase, rest capitalize
      if (index === 0) {
        // Convert hyphens to camelCase for first segment
        return segment
          .split('-')
          .map((word, wordIndex) => {
            if (wordIndex === 0) return word.toLowerCase();
            return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase();
          })
          .join('');
      }
      // Convert hyphens to camelCase and capitalize the first letter for subsequent segments
      const camelSegment = segment.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
      return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
    })
    .join('');
}
 
/**
 * Convert token path to property name for scoped color objects
 */
function pathToScopedColorPropertyName(path) {
  // For color tokens, skip namespace, scope, and category (color)
  const relevantPath = path.slice(PATH_INDEX.SUBCATEGORY);
 
  return relevantPath
    .map((segment, index) => {
      // First segment lowercase, rest capitalize first letter
      if (index === 0) {
        return segment.toLowerCase();
      }
      // Convert hyphens to camelCase and capitalize the first letter for subsequent segments
      const camelSegment = segment.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
      return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
    })
    .join('');
}
 
// ============================================================================
// ANDROID PLATFORM CONFIG
// ============================================================================
 
/**
 * Format an inline comment for descriptions
 * @param {string|null} description - Description text
 * @returns {string} - Formatted inline comment or empty string
 */
function formatInlineComment(description) {
  return description ? ` // ${description}` : '';
}
 
const ANDROID_DIMENSION_CONFIG = {
  objectDeclaration: 'object {{name}} {',
  objectClose: '}',
  valueProperty: (propName, value, description) =>
    `    val ${propName} = ${value}.dp${formatInlineComment(description)}\n`,
  referenceProperty: (propName, refPropName, unit, description) =>
    `    val ${propName} get() = ${refPropName}${formatInlineComment(description)}\n`,
  percentProperty: (propName, value, description) =>
    `    val ${propName}Percent = ${value}${formatInlineComment(description)}\n`,
  deprecationAnnotation: generateDeprecationAnnotation,
};
 
const ANDROID_DURATION_CONFIG = {
  objectDeclaration: 'object {{name}} {',
  objectClose: '}',
  valueProperty: (propName, msValue, description) =>
    `    val ${propName} = ${msValue}L${formatInlineComment(description)}\n`,
  referenceProperty: (propName, refPropName, description) =>
    `    val ${propName} get() = ${refPropName}${formatInlineComment(description)}\n`,
  deprecationAnnotation: generateDeprecationAnnotation,
};
 
// Android pathToShortPropertyName ignores category parameter (simple version)
const androidPathToPropertyName = (path) => pathToShortPropertyName(path);
 
// ============================================================================
// FONTS OUTPUT HELPER
// ============================================================================
 
/**
 * Generate font tokens output for Android
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Kotlin code
 */
function generateFontsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
  const fontTokens = getTokensForCategory(tokens, CATEGORY.FONT);
 
  let output = generateFileHeader('Font design tokens for Android.', { needsSp: true });
 
  // Group font tokens by sub-category using shared helper
  const {
    sizes: fontSizes,
    weights: fontWeights,
    families: fontFamilies,
    lineHeights: fontLineHeights,
    scales: fontScales,
    truncation: fontTruncation,
  } = groupFontTokens(fontTokens);
 
  // Font Families - object with val
  if (fontFamilies.length > 0) {
    output += `object ${themePrefix}FontFamily {\n`;
 
    const familyOutputs = generateFontFamilyOutput(fontFamilies, tokens, {
      pathToPropertyName: pathToScopedFontPropertyName,
      formatValue: (propName, fontStack, description) =>
        `    val ${propName} = "${fontStack}"${formatInlineComment(description)}\n`,
      formatReference: (propName, refPropName, objectName, description) =>
        `    val ${propName} get() = ${objectName}.${refPropName}${formatInlineComment(description)}\n`,
      objectName: `${themePrefix}FontFamily`,
      deprecationAnnotation: generateDeprecationAnnotation,
    });
 
    output += familyOutputs.join('');
    output += '}\n\n';
  }
 
  // Font Weights - object with val
  if (fontWeights.length > 0) {
    output += `object ${themePrefix}FontWeight {\n`;
 
    const weightOutputs = generateFontWeightOutput(
      fontWeights,
      pathToScopedFontPropertyName,
      (propName, value, description) => `    val ${propName} = ${value}${formatInlineComment(description)}\n`,
      generateDeprecationAnnotation,
    );
 
    output += weightOutputs.join('');
    output += '}\n\n';
  }
 
  // Font Sizes - object with val
  if (fontSizes.length > 0) {
    output += `object ${themePrefix}FontSize {\n`;
 
    const sizeOutputs = generateFontDimensionOutput(fontSizes, tokens, {
      pathToPropertyName: pathToScopedFontPropertyName,
      formatValue: (propName, value, token, description) =>
        `    val ${propName} = ${value}.sp${formatInlineComment(description)}\n`,
      formatReference: (propName, refToken, allTokens, description) => {
        const refPropName = pathToScopedFontPropertyName(refToken.path);
        return `    val ${propName} get() = ${themePrefix}FontScale.${refPropName}${formatInlineComment(description)}\n`;
      },
      useDimensionConversion: true,
      expectedSubcategory: FONT_SUBCATEGORY.SCALE,
      deprecationAnnotation: generateDeprecationAnnotation,
    });
 
    output += sizeOutputs.join('');
    output += '}\n\n';
  }
 
  // Font Scales - object with val
  if (fontScales.length > 0) {
    output += `object ${themePrefix}FontScale {\n`;
 
    const scaleOutputs = generateFontDimensionOutput(fontScales, tokens, {
      pathToPropertyName: pathToScopedFontPropertyName,
      formatValue: (propName, value, token, description) => {
        // Check if this is a number type (like ratio) vs dimension type (like rem/px)
        Iif (token.$type === 'number') {
          return `    val ${propName} = ${value}f${formatInlineComment(description)}\n`;
        }
        return `    val ${propName} = ${value}.sp${formatInlineComment(description)}\n`;
      },
      formatReference: (propName, refToken, allTokens, description) => {
        const refPropName = pathToScopedFontPropertyName(refToken.path);
        return `    val ${propName} get() = ${refPropName}${formatInlineComment(description)}\n`;
      },
      useDimensionConversion: true, // Changed from false - Android scales need dimension conversion for px units
      expectedSubcategory: FONT_SUBCATEGORY.SCALE,
      deprecationAnnotation: generateDeprecationAnnotation,
    });
 
    output += scaleOutputs.join('');
    output += '}\n\n';
  }
 
  // Font Line Heights - object with val
  if (fontLineHeights.length > 0) {
    output += `object ${themePrefix}FontLineHeight {\n`;
 
    // Helper to build lineHeight property name from token path
    const buildLineHeightName = (path, isDeprecated = false) => {
      // eslint-disable-next-line no-useless-assignment
      let nameParts = [];
 
      // Current path: ['slds', 'g', 'font', 'line', 'height', ...]
      if (path[3] === FONT_SUBCATEGORY.LINE && path[4] === FONT_MODIFIER.HEIGHT) {
        nameParts = path.slice(5);
      } else Eif (path[3] === FONT_SUBCATEGORY.LINEHEIGHT) {
        // Deprecated path: ['slds', 'g', 'font', 'lineheight', ...]
        if (isDeprecated) {
          // Keep deprecated names distinct to avoid collisions with current line.height.* tokens.
          return pathToScopedFontPropertyName(path);
        }
        nameParts = path.slice(4);
      } else {
        // Fallback for unexpected structures
        nameParts = path.slice(4);
      }
 
      const prefix = 'lineHeight';
      return [prefix, ...nameParts]
        .map((segment, index) => {
          if (index === 0) {
            return segment;
          }
          const camelSegment = segment.replace(/-([a-z])/g, (g) => g[1].toUpperCase());
          return camelSegment.charAt(0).toUpperCase() + camelSegment.slice(1);
        })
        .join('');
    };
 
    const lineHeightOutputs = generateLineHeightOutput(fontLineHeights, tokens, {
      pathToPropertyName: buildLineHeightName,
      formatValue: (propName, value, description) =>
        `    val ${propName} = ${value}f${formatInlineComment(description)}\n`,
      formatReference: (propName, refPropName, description) =>
        `    val ${propName} get() = ${refPropName}${formatInlineComment(description)}\n`,
      deprecationAnnotation: generateDeprecationAnnotation,
    });
 
    output += lineHeightOutputs.join('');
    output += '}\n\n';
  }
 
  // Font Line Clamp - object with val
  if (fontTruncation.length > 0) {
    output += `object ${themePrefix}FontLineClamp {\n`;
 
    const truncationOutputs = generateTruncationOutput(
      fontTruncation,
      pathToScopedFontPropertyName,
      (propName, value, description) =>
        `    val ${propName} = ${value}f${formatInlineComment(description)}\n`,
      generateDeprecationAnnotation,
    );
 
    output += truncationOutputs.join('');
    output += '}\n\n';
  }
 
  return output.trimEnd() + '\n';
}
 
// ============================================================================
// COLOR OUTPUT HELPERS
// ============================================================================
//
// Generic function to generate color format with light/dark objects
// Used by System, Semantic, and Reference color formats
//
// ============================================================================
 
/**
 * Generate Android color format with light/dark mode support
 * @param {object} config - Configuration object
 * @param {Array} config.tokens - All tokens from dictionary
 * @param {Function} config.filterFn - Function to filter tokens for this format
 * @param {string} config.fileHeader - Header comment for the file
 * @param {string} config.objectNameLight - Object name for light mode (e.g., 'SalesforceCosmosSystemColorsLight')
 * @param {string} config.objectNameDark - Object name for dark mode (e.g., 'SalesforceCosmosSystemColorsDark')
 * @param {Function} config.getRefProperty - Function to get reference property string for a token (refToken, isDark) => string | null
 * @param {boolean} config.useDarkFallback - Whether to use light value as fallback when dark value is missing (default: true)
 * @returns {string} - Generated Kotlin code
 */
function generateColorFormatWithModes({
  tokens,
  filterFn,
  fileHeader,
  objectNameLight,
  objectNameDark,
  getRefProperty,
  useDarkFallback = true,
  deprecationAnnotation,
}) {
  const colorTokens = tokens.filter(filterFn);
 
  let output = generateFileHeader(fileHeader, { needsColor: true });
 
  // Use shared helper to process color tokens
  const { lightColors, darkColors } = processColorTokens({
    tokens: colorTokens,
    allTokens: tokens,
    getPropName: pathToScopedColorPropertyName,
    getRefProperty,
    resolveColor: (colorValue, allTokens) => {
      const hex = resolveColorToHex(colorValue, allTokens);
      return hex ? toComposeColor(hex) : null;
    },
    useDarkFallback,
  });
 
  // Output Light object
  output += `object ${objectNameLight} {\n`;
  lightColors.forEach(({ name, color, description, token, deprecated }) => {
    if (deprecated && deprecationAnnotation) {
      output += deprecationAnnotation(token);
    }
    if (color.startsWith('Salesforce')) {
      output += `    val ${name} get() = ${color}${formatInlineComment(description)}\n`;
    } else {
      output += `    val ${name} = ${color}${formatInlineComment(description)}\n`;
    }
  });
  output += '}\n\n';
 
  // Output Dark object
  output += `object ${objectNameDark} {\n`;
  darkColors.forEach(({ name, color, description, token, deprecated }) => {
    if (deprecated && deprecationAnnotation) {
      output += deprecationAnnotation(token);
    }
    if (color.startsWith('Salesforce')) {
      output += `    val ${name} get() = ${color}${formatInlineComment(description)}\n`;
    } else {
      output += `    val ${name} = ${color}${formatInlineComment(description)}\n`;
    }
  });
  output += '}\n';
 
  return output;
}
 
// ============================================================================
// SYSTEM COLORS OUTPUT HELPER
// ============================================================================
 
/**
 * Generate system color tokens output for Android
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Kotlin code with Light and Dark color objects
 */
function generateSystemColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
 
  return generateColorFormatWithModes({
    tokens,
    filterFn: (token) => !shouldSkipToken(token) && isSystemColorToken(token),
    fileHeader: 'System color design tokens for Android.',
    objectNameLight: `${themePrefix}SystemColorsLight`,
    objectNameDark: `${themePrefix}SystemColorsDark`,
    getRefProperty: (refToken, isDark) => {
      Eif (isReferenceColorToken(refToken)) {
        const refPropName = pathToScopedColorPropertyName(refToken.path);
        const className = isDark ? `${themePrefix}ReferenceColorsDark` : `${themePrefix}ReferenceColorsLight`;
        return `${className}.${refPropName}`;
      }
      return null;
    },
    useDarkFallback: true,
    deprecationAnnotation: generateDeprecationAnnotation,
  });
}
 
// ============================================================================
// REFERENCE COLORS OUTPUT HELPER
// ============================================================================
 
/**
 * Generate reference color tokens output for Android
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Kotlin code with Light and Dark color objects
 */
function generateReferenceColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
 
  return generateColorFormatWithModes({
    tokens,
    filterFn: (token) => !shouldSkipToken(token) && isReferenceColorToken(token),
    fileHeader: 'Reference color design tokens for Android.',
    objectNameLight: `${themePrefix}ReferenceColorsLight`,
    objectNameDark: `${themePrefix}ReferenceColorsDark`,
    getRefProperty: () => null,
    deprecationAnnotation: generateDeprecationAnnotation,
  });
}
 
// ============================================================================
// SEMANTIC COLORS OUTPUT HELPER
// ============================================================================
 
/**
 * Generate semantic color tokens output for Android
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Kotlin code with Light and Dark color objects
 */
function generateSemanticColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
 
  return generateColorFormatWithModes({
    tokens,
    filterFn: (token) => !shouldSkipToken(token) && isSemanticColorToken(token),
    fileHeader: 'Semantic color design tokens for Android.',
    objectNameLight: `${themePrefix}SemanticColorsLight`,
    objectNameDark: `${themePrefix}SemanticColorsDark`,
    getRefProperty: (refToken, isDark) => {
      Eif (isSystemColorToken(refToken)) {
        const refPropName = pathToScopedColorPropertyName(refToken.path);
        const className = isDark ? `${themePrefix}SystemColorsDark` : `${themePrefix}SystemColorsLight`;
        return `${className}.${refPropName}`;
      }
      if (isReferenceColorToken(refToken)) {
        const refPropName = pathToScopedColorPropertyName(refToken.path);
        const className = isDark ? `${themePrefix}ReferenceColorsDark` : `${themePrefix}ReferenceColorsLight`;
        return `${className}.${refPropName}`;
      }
      return null;
    },
    useDarkFallback: true,
    deprecationAnnotation: generateDeprecationAnnotation,
  });
}
 
// ============================================================================
// PALETTE COLORS OUTPUT HELPER
// ============================================================================
 
/**
 * Generate palette color tokens output for Android
 * @param {object} params - Parameters
 * @param {object} params.dictionary - Token dictionary
 * @param {string} [params.themePrefix='SalesforceCosmos'] - Theme-specific class name prefix
 * @returns {string} - Generated Kotlin code with Light and Dark color objects per palette family
 */
function generatePaletteColorsOutput({ dictionary, themePrefix = 'SalesforceCosmos' }) {
  const tokens = dictionary.allTokens;
  // Filter for slds.g.color.palette.* tokens, not alias.palette.*
  const paletteTokens = tokens.filter(
    (token) =>
      token.path[0] === 'slds' &&
      token.path[1] === 'g' &&
      token.path[2] === 'color' &&
      token.path[3] === 'palette',
  );
 
  let output = generateFileHeader('Palette color design tokens for Android.', { needsColor: true });
 
  // Group by color family
  const colorFamilies = new Map();
 
  paletteTokens.forEach((token) => {
    Iif (shouldSkipToken(token)) return;
 
    // Palette tokens have path: ['slds', 'g', 'color', 'palette', '{family}', '{scale}']
    // e.g., ['slds', 'g', 'color', 'palette', 'neutral', '0']
    const family = token.path[4]; // 'neutral', 'blue', 'red', etc.
    const scale = token.path[5]; // '0', '10', '50', etc.
 
    Iif (!family || !scale) return;
 
    if (!colorFamilies.has(family)) {
      colorFamilies.set(family, { light: [], dark: [] });
    }
 
    const tokenValue = getRawValueUnitValue(token);
    const darkValue = token.$extensions?.[MODE_EXTENSION_KEY]?.dark?.$value;
    const description = getTokenDescription(token);
    const deprecated = isDeprecatedToken(token);
 
    // Property name is just the family + scale since they're in family-specific objects
    // e.g., 'neutral50', 'blue10' within SalesforceCosmospaletteNeutralLight
    const propName = `${family}${scale}`;
 
    // Light value - pass full tokens array so references can be resolved
    const lightHex = resolveColorToHex(tokenValue, tokens);
    Eif (lightHex) {
      colorFamilies
        .get(family)
        .light.push({ name: propName, color: toComposeColor(lightHex), description, token, deprecated });
    }
 
    // Dark value - fallback to light value if dark doesn't resolve
    const darkHex = darkValue ? resolveColorToHex(darkValue, tokens) : lightHex;
    Eif (darkHex) {
      colorFamilies
        .get(family)
        .dark.push({ name: propName, color: toComposeColor(darkHex), description, token, deprecated });
    }
  });
 
  // Output each color family as separate objects
  const sortedFamilies = Array.from(colorFamilies.keys()).sort();
 
  sortedFamilies.forEach((family) => {
    const familyName = family.charAt(0).toUpperCase() + family.slice(1);
    const { light, dark } = colorFamilies.get(family);
 
    // Light object
    output += `object ${themePrefix}Palette${familyName}Light {\n`;
    light.forEach(({ name, color, description, token, deprecated }) => {
      Iif (deprecated) {
        output += generateDeprecationAnnotation(token);
      }
      output += `    val ${name} = ${color}${formatInlineComment(description)}\n`;
    });
    output += '}\n\n';
 
    // Dark object - only create if there are dark colors
    Eif (dark.length > 0) {
      output += `object ${themePrefix}Palette${familyName}Dark {\n`;
      dark.forEach(({ name, color, description, token, deprecated }) => {
        Iif (deprecated) {
          output += generateDeprecationAnnotation(token);
        }
        output += `    val ${name} = ${color}${formatInlineComment(description)}\n`;
      });
      output += '}\n\n';
    }
  });
 
  return output.trimEnd() + '\n';
}
 
// ============================================================================
// COMBINED FORMAT (all tokens in one file)
// ============================================================================
 
/**
 * Helper to extract the content after the package and imports from a format output
 */
function stripFileHeader(content) {
  const lines = content.split('\n');
  let startIndex = 0;
  let foundPackage = false;
 
  // Find everything after the header comment, package, and imports
  for (let i = 0; i < lines.length; i++) {
    const line = lines[i].trim();
 
    // Skip until we find package declaration
    if (line.startsWith('package ')) {
      foundPackage = true;
      continue;
    }
 
    // After package, skip import lines
    if (foundPackage && line.startsWith('import ')) {
      continue;
    }
 
    // After package and imports, skip blank lines
    if (foundPackage && line === '') {
      continue;
    }
 
    // Found the first real content line (not header, package, import, or blank)
    if (foundPackage && line !== '') {
      startIndex = i;
      break;
    }
  }
 
  return lines.slice(startIndex).join('\n');
}
 
/** Arguments for split mobile formatters (subset of {@link FormatFnArguments}). */
type MobileSplitFormatInput = {
  dictionary: Dictionary;
  options?: FormatFnArguments['options'] & { tokenType?: string; themePrefix?: string };
};
 
export const androidTokensAllFormat: FormatFn = ({ dictionary, options }) => {
  const { themePrefix = 'SalesforceCosmos' } = options || {};
  let output = generateFileHeader('All design tokens combined for comparison.', {
    needsColor: true,
    needsDp: true,
    needsSp: true,
  });
 
  const tokenTypes = [
    'spacing',
    'sizing',
    'shapes',
    'motion-duration',
    'fonts',
    'system-colors',
    'reference-colors',
    'semantic-colors',
    'palette-colors',
  ];
  const sectionLabels = [
    'SPACING',
    'SIZING',
    'SHAPES',
    'MOTION DURATION',
    'FONTS',
    'SYSTEM COLORS',
    'REFERENCE COLORS',
    'SEMANTIC COLORS',
    'PALETTE COLORS',
  ];
 
  tokenTypes.forEach((tokenType, index) => {
    if (index > 0) output += '\n';
    output += `// ============================================================================\n`;
    output += `// ${sectionLabels[index]}\n`;
    output += `// ============================================================================\n\n`;
    output += stripFileHeader(androidFormatBody({ dictionary, options: { tokenType, themePrefix } }));
  });
 
  return output;
};
 
// Mark formats as nested to avoid collision warnings
androidTokensAllFormat.nested = true;
 
// ============================================================================
// UNIFIED MOBILE FORMAT
// ============================================================================
 
/**
 * Unified Android format that routes to appropriate rendering based on tokenType option.
 * Uses pre-filtered tokens from Style Dictionary file-level filters.
 *
 * @param {object} params - Format parameters
 * @param {object} params.dictionary - Style Dictionary dictionary object
 * @param {object} params.options - Options object containing tokenType
 * @param {string} params.options.tokenType - Type of tokens to format (spacing, sizing, shapes, etc.)
 * @returns {string} - Formatted output for the specified token type
 */
function androidFormatBody({ dictionary, options }: MobileSplitFormatInput): string {
  const tokens = dictionary.allTokens;
  const { tokenType, themePrefix = 'SalesforceCosmos' } = options || {};
 
  Iif (!tokenType) {
    throw new Error('[androidFormat] options.tokenType is required');
  }
 
  switch (tokenType) {
    case 'spacing':
      return generateDimensionOutput({
        tokens,
        category: CATEGORY.SPACING,
        fileHeader: generateFileHeader('Spacing tokens for Android.', { needsDp: true }),
        objectName: `${themePrefix}Spacing`,
        config: ANDROID_DIMENSION_CONFIG,
        pathToPropertyName: androidPathToPropertyName,
      });
 
    case 'sizing':
      return generateDimensionOutput({
        tokens,
        category: CATEGORY.SIZING,
        fileHeader: generateFileHeader('Sizing tokens for Android.', { needsDp: true }),
        objectName: `${themePrefix}Sizing`,
        config: ANDROID_DIMENSION_CONFIG,
        pathToPropertyName: androidPathToPropertyName,
      });
 
    case 'shapes':
      return generateDimensionOutput({
        tokens,
        category: CATEGORY.RADIUS,
        fileHeader: generateFileHeader('Shape tokens (border radius) for Android.', { needsDp: true }),
        objectName: `${themePrefix}Shapes`,
        config: ANDROID_DIMENSION_CONFIG,
        pathToPropertyName: androidPathToPropertyName,
      });
 
    case 'motion-duration':
      return generateDurationOutput({
        tokens,
        fileHeader: generateFileHeader('Motion duration tokens for Android.'),
        objectName: `${themePrefix}MotionDuration`,
        config: ANDROID_DURATION_CONFIG,
        pathToPropertyName: androidPathToPropertyName,
        convertDuration: convertDurationToMs,
      });
 
    case 'fonts':
      return generateFontsOutput({ dictionary, themePrefix });
 
    case 'system-colors':
      return generateSystemColorsOutput({ dictionary, themePrefix });
 
    case 'reference-colors':
      return generateReferenceColorsOutput({ dictionary, themePrefix });
 
    case 'semantic-colors':
      return generateSemanticColorsOutput({ dictionary, themePrefix });
 
    case 'palette-colors':
      return generatePaletteColorsOutput({ dictionary, themePrefix });
 
    default:
      throw new Error(`[androidFormat] Unknown tokenType: ${tokenType}`);
  }
}
 
export const androidFormat: FormatFn = (args) => androidFormatBody(args);
 
androidFormat.nested = true;
 
// ============================================================================
// TEST EXPORTS
// ============================================================================
 
/**
 * Export internal functions for testing purposes only.
 * These are not part of the public API.
 */
export const _testExports = {
  oklchToHex,
  toComposeColor,
  resolveColorToHex,
  pathToShortPropertyName,
  pathToScopedFontPropertyName,
  pathToScopedColorPropertyName,
  generateColorFormatWithModes,
  COMPOSE_COLOR_PREFIX,
  HEX_COLOR_LENGTH,
};