import { createSDTFEngine, type SDTFEngine, SpecifyDesignTokenFormat, } from '@specifyapp/specify-design-token-format'; import type { SelectModesParserDefinition } from './definition.js'; import { specifyErrors } from '../../../errors/specifyErrors.js'; import { SpecifyError } from '../../../errors/SpecifyError.js'; import { DeriveBuiltInParserHandlerFromDefinition } from '../../internals/createBuiltInParserDefinition.js'; export const selectModesHandler: DeriveBuiltInParserHandlerFromDefinition< SelectModesParserDefinition > = async (previousResult, toolbox, parserOptions, _) => { let sdtfEngine: SDTFEngine; switch (previousResult.type) { case 'SDTF': { sdtfEngine = createSDTFEngine(previousResult.graph, previousResult.metadata); break; } case 'SDTF Engine': { sdtfEngine = previousResult.engine; break; } default: { throw new SpecifyError({ errorKey: specifyErrors.PARSERS_ENGINE_INVALID_INPUT_TYPE.errorKey, publicMessage: `The input type "${ (previousResult as any).type }" is not supported by the select-modes parser.`, }); } } const { modes } = parserOptions; if (modes.length === 0) { throw new SpecifyError({ errorKey: specifyErrors.PARSERS_ENGINE_INVALID_OPTION.errorKey, publicMessage: `The option "modes" cannot be an empty array.`, }); } const result = sdtfEngine.query.run({ where: { token: '.*', withModes: { include: modes, }, select: { token: true, parents: true, }, }, }); const details = result.render(); if (details.length === 0) { toolbox.populateMessage({ type: 'warning', errorKey: specifyErrors.PARSERS_ENGINE_RULE_EXECUTION_FAILED.errorKey, content: `The query does not match any node.`, }); } const filteredEngine = createSDTFEngine(details[0].sdtf); filteredEngine.query.getAllCollectionStates().forEach(collection => { collection.allowedModes.forEach(mode => { if (!modes.includes(mode)) { filteredEngine.mutation.deleteCollectionMode({ mode, atPath: collection.path, }); } }); }); filteredEngine.query.getAllTokenStates().forEach(token => { token.modes.forEach(mode => { if (!modes.includes(mode)) { filteredEngine.mutation.deleteTokenModeValue({ mode, atPath: token.path, }); } }); }); return { type: 'SDTF Engine', engine: filteredEngine, }; };