import { SDTFEngine, TokenState } from '@specifyapp/specify-design-token-format'; import { groupBy } from 'lodash-es'; import { textStylesToScssMap } from './tokenTypes/textStyles.js'; import { dimensionsToScssMap } from './tokenTypes/dimension.js'; import { colorsToScssMap } from './tokenTypes/color.js'; import { SpecifyError, specifyErrors } from '../../../errors/index.js'; import { ToScssMapParserOptions } from './definition.js'; export function convertTokens( engine: SDTFEngine, basePath: string, parserOptions: Omit< Required>, 'shouldExecuteRemotely' >, ) { const tokens = engine.query.run({ where: { token: '.*', withTypes: { include: ['textStyle', 'color', 'breakpoint', 'spacing', 'dimension'], }, select: true, }, }) as Array; const tokensByType = groupBy(tokens, token => token.type); return Object.entries(tokensByType).map(([type, tokens]) => { let map; switch (type) { case 'textStyle': { map = textStylesToScssMap( // @ts-ignore - Expression produces a union type that is too complex to represent tokens as Array>, parserOptions.tokenNameTemplate, ); break; } case 'color': { map = colorsToScssMap( tokens as Array>, parserOptions.tokenNameTemplate, ); break; } case 'dimension': case 'breakpoint': case 'spacing': { map = dimensionsToScssMap( type, tokens as Array< TokenState<'dimension'> | TokenState<'breakpoint'> | TokenState<'spacing'> >, parserOptions.tokenNameTemplate, ); break; } default: { throw new SpecifyError({ errorKey: specifyErrors.PARSERS_ENGINE_UNKNOWN_ERROR.errorKey, publicMessage: `The token type "${type}" is not supported by the to-scss-map parser. This error is supposed to be unreachable, please contact the support if you face it`, }); } } return { path: `${basePath}${basePath.endsWith('/') ? '' : '/'}_${type}.scss`, content: { type: 'text', text: '@use "sass:map";\n\n' + map, }, } as const; }); }