UNPKG

statement-parser-fab

Version:

Parse bank and credit card statements. Updated fork with FAB (First Abu Dhabi Bank) support and maintained dependencies.

71 lines (70 loc) 2.94 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.createParserStateMachine = void 0; const fsm_vir_1 = require("fsm-vir"); const parser_options_1 = require("./parser-options"); /** * This creates a state machine. The state machine is a Mealy machine but outputs are generated * independent of the state transition. As you can see in the arguments, the "action" function * (which generates outputs) is distinct from the "next" function, which calculates the next state. * The implementation of "action" is of course left to you though, so you can totally just ignore * the current value and make this a Moore machine. */ function createParserStateMachine({ action, next, initialState, endState, name, initOutput, parserOptions: inputParserOptions, defaultParserOptions, debug = false, }) { const handleError = (error) => { var _a, _b; const errorName = name !== null && name !== void 0 ? name : `${String((_a = error.currentValue) === null || _a === void 0 ? void 0 : _a[0]).substring(0, 10)}...`; const printError = (_b = error.stack) !== null && _b !== void 0 ? _b : error.message; throw new Error(`Error parsing ${errorName} at "${error.currentValue}": ${printError}`); }; const defaultOptions = (0, parser_options_1.collapseDefaultParserOptions)(defaultParserOptions); const parserOptions = { ...defaultOptions, ...(inputParserOptions !== null && inputParserOptions !== void 0 ? inputParserOptions : {}), }; const baseOutput = { incomes: [], expenses: [], name, yearPrefix: parserOptions.yearPrefix, accountSuffix: '', endDate: undefined, startDate: undefined, }; const startingOutput = { ...baseOutput, ...JSON.parse(JSON.stringify(initOutput || {})), }; const performStateAction = (currentState, input, lastOutput) => { return action(currentState, input, lastOutput, parserOptions); }; const calculateNextState = (currentState, input) => { return next(currentState, input, parserOptions); }; const stateMachine = (0, fsm_vir_1.createStateMachine)({ performStateAction, calculateNextState, initialState, endState, handleError, initialOutput: startingOutput, }); return (inputs) => { const machineResult = stateMachine.runMachine(inputs); if (debug) { machineResult.logs.forEach((log) => { console.log(log); }); } if (machineResult.aborted) { if (debug) { machineResult.errors.forEach((error) => { console.error(error); }); } throw new Error(machineResult.errors.join('\n')); } return machineResult.output; }; } exports.createParserStateMachine = createParserStateMachine;