import { createSDTFEngine, SDTFEngine } from '@specifyapp/specify-design-token-format'; import type { ToJsonParserDefinition } from './definition.js'; import type { DeriveBuiltInParserHandlerFromDefinition } from '../../internals/createBuiltInParserDefinition.js'; import { SpecifyError, specifyErrors } from '../../../errors/index.js'; import { FilesOutput } from '../../../parsersEngine/definitions/parserOutput.js'; import { tokensToJson } from './tokenToJson.js'; export const toJsonHandler: DeriveBuiltInParserHandlerFromDefinition< ToJsonParserDefinition > = async (previousDataBox, toolbox, parserOptions, outputOptions, _context) => { let sdtfEngine: SDTFEngine; switch (previousDataBox.type) { case 'SDTF': { sdtfEngine = createSDTFEngine(previousDataBox.graph, previousDataBox.metadata); break; } case 'SDTF Engine': { sdtfEngine = previousDataBox.engine; break; } default: { throw new SpecifyError({ errorKey: specifyErrors.PARSERS_ENGINE_INVALID_PARSER_INPUT.errorKey, publicMessage: `${ (previousDataBox as any).type } is not a valid input for the to-json parser.`, }); } } if (outputOptions?.type !== 'file') throw new SpecifyError({ errorKey: specifyErrors.PARSERS_ENGINE_INVALID_OUTPUT_TYPE.errorKey, publicMessage: `The output type ${outputOptions?.type} is not supported by the to-json parser.`, }); let output: FilesOutput['files'] = []; const tokenStates = sdtfEngine.query.getAllTokenStates(); if (tokenStates.length === 0) { toolbox.populateMessage({ type: 'warning', content: `No design tokens found in the input`, errorKey: specifyErrors.PARSERS_ENGINE_PARSER_EXECUTION_FAILED.errorKey, }); output = []; } else { const outputType = parserOptions?.output ?? 'raw'; const json = tokensToJson(tokenStates, toolbox, outputType); output = [ { path: outputOptions.filePath, content: { type: 'text', text: JSON.stringify(json, null, 4), }, }, ]; } toolbox.populateOutput({ type: 'files', files: output, }); return { type: 'SDTF Engine', engine: sdtfEngine, }; };