import { BuiltInParserName, getBuiltInParserDefinition } from '../../builtInParsers/index.js'; import { pickLastParserInParserRule } from '../../builtInParsers/utils/pickLastParserInParserRule.js'; import { createRPCClient } from '../../httpApi/clients/createRPCClient.js'; import { ParserFunction } from '../definitions/ParserFunction.js'; import { SerializedParsersEngineDataBox } from '../definitions/parsersEngineDataBox.js'; import { handleSerializedParsersEngineResult } from './handleSerializedParsersEngineResult.js'; import { SpecifyError, specifyErrors } from '../../errors/index.js'; import { serializeParsersEngineDataBox } from '../utils/serializeParsersEngineDataBox.js'; import { BuiltInParserRuleSignature } from '../../builtInParsers/internals/BuiltInParserRuleSignature.js'; import { SerializedParsersEngineResults } from './SerializedParsersEngineResult.js'; /** * Build a list of ParserFunctions for HTTP RPC execution wrapping all Rules to use a single HTTP request * @param rules * @param context */ export function makeRemoteParsersPipelinesFromRules( rules: Array, context: { personalAccessToken?: string; }, ): Array { let futureResults: Promise | undefined; function getOrFetchResults( rules: Array, dataBox: SerializedParsersEngineDataBox, ) { if (futureResults) { return futureResults; } futureResults = createRPCClient(context.personalAccessToken).executeParsersEngine({ body: { rules, dataBox, returnedKeys: { next: false, }, }, }); return futureResults; } return rules.map((rule, i) => { async function executeRPC( dataBox: Parameters[0], toolbox: Parameters[1], ) { return getOrFetchResults(rules, serializeParsersEngineDataBox(dataBox)).then(httpPayload => { const result = httpPayload[i]; if (!result) { throw new SpecifyError({ errorKey: specifyErrors.PARSERS_ENGINE_RPC_EXECUTION_FAILED.errorKey, publicMessage: `RPC result not found for parsers "${rule.parsers .map(p => p.name) .join(', ')}"${rule.name ? ` on rule "${rule.name}"` : ''}.`, }); } const parserDefinition = getBuiltInParserDefinition( pickLastParserInParserRule(rule).name as BuiltInParserName, ); return handleSerializedParsersEngineResult( httpPayload[i], toolbox, parserDefinition.outType, ); }); } return executeRPC; }); }