All files / packages/design-tokens/src/style-dictionary/formats json-flat-metadata.ts

100% Statements 14/14
100% Branches 0/0
100% Functions 5/5
100% Lines 14/14

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                        1x 3x 3x 3x   3x                 1x 3x   3x 3x     3x               1x 2x   1x         1x      
import type { Dictionary, FormatFn } from 'style-dictionary/types';
 
import type { StyleDictionaryHost } from '../style-dictionary-host.js';
import { flatTokenFields } from '../utils/flat-token-fields.js';
 
/**
 * Sort top-level keys only so token-name order matches across OS / Style Dictionary
 * iteration order, without reordering keys inside each token object (snapshot stability).
 *
 * @param {Record<string, object>} flatTokens
 * @returns {Record<string, object>}
 */
const sortTopLevelKeysOnly = (flatTokens) => {
  const sorted = {};
  for (const key of Object.keys(flatTokens).sort()) {
    sorted[key] = flatTokens[key];
  }
  return sorted;
};
 
/**
 * Formatter for the JSON flat metadata format
 *
 * @param {Object} dictionary
 * @returns {string}
 */
const jsonFlatMetadataFormatter = (dictionary: Dictionary) => {
  const flatTokens = {};
 
  dictionary.allTokens.forEach((token) => {
    flatTokens[token.name] = flatTokenFields(token);
  });
 
  return JSON.stringify(sortTopLevelKeysOnly(flatTokens), null, 2);
};
 
/**
 * Style Dictionary registration for the JSON flat metadata format
 *
 * @param {StyleDictionary} StyleDictionary
 */
export const jsonFlatMetadataFormat = (StyleDictionary: StyleDictionaryHost) => {
  StyleDictionary.registerFormat({
    name: 'json/flat-full',
    format: (({ dictionary }) => jsonFlatMetadataFormatter(dictionary)) satisfies FormatFn,
  });
};
 
// Export internal functions for testing
export const _testExports = {
  jsonFlatMetadataFormatter,
};