import { SDTFEngine, createSDTFEngine } from '@specifyapp/specify-design-token-format'; import { regexOfOption } from './regexOfOption.js'; import type { ReplaceStringParserDefinition, ReplaceStringParserOptions } from './definition.js'; import { specifyErrors } from '../../../errors/specifyErrors.js'; import { getSdtfQuery } from '../../utils/getSdtfQuery.js'; import { SpecifyError } from '../../../errors/SpecifyError.js'; import { DeriveBuiltInParserHandlerFromDefinition } from '../../internals/createBuiltInParserDefinition.js'; export const replaceStringHandler: DeriveBuiltInParserHandlerFromDefinition< ReplaceStringParserDefinition > = 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 filter parser.`, }); } } // TODO: Manage XOR logic if ( !('all' in parserOptions) && !parserOptions.token && !parserOptions.group && !parserOptions.collection ) { toolbox.populateMessage({ type: 'warning', content: "Couldn't find a pattern in all, token, group or collection, so nothing will be replaced", errorKey: specifyErrors.PARSERS_ENGINE_INVALID_OPTION.errorKey, }); return { type: 'SDTF Engine', engine: sdtfEngine, }; } const resultEngine = sdtfEngine.clone(); replaceStringInner(resultEngine, parserOptions); return { type: 'SDTF Engine', engine: resultEngine, }; }; export function replaceStringInner(engine: SDTFEngine, options: ReplaceStringParserOptions) { const query = getSdtfQuery(options.applyTo); (options.applyTo ? engine.query.run(query) : engine.query.getAllNodeStates()).forEach(node => { if ('all' in options) { const result = node.name.replace(regexOfOption(options.all), options.all?.replaceBy ?? ''); node.rename(options.all?.trim ? result.trim() : result); } else if (node.isToken && options.token) { const result = node.name.replace(regexOfOption(options.token), options.token.replaceBy); node.rename(options.token.trim ? result.trim() : result); } else if (node.isGroup && options.group) { const result = node.name.replace(regexOfOption(options.group), options.group.replaceBy); node.rename(options.group.trim ? result.trim() : result); } else if (node.isCollection && options.collection) { const result = node.name.replace( regexOfOption(options.collection), options.collection.replaceBy, ); node.rename(options.collection.trim ? result.trim() : result); } }); }