UNPKG

jovo-v4-community-plugin-jexl-output

Version:

A Jovo V4 framework plugin which adds Jexl support for output strings.

77 lines 2.79 kB
"use strict"; var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.processJexlExpression = void 0; const jexl_1 = __importDefault(require("jexl")); const voca_1 = __importDefault(require("voca")); /** * Starting with a text string which contains "Jexl" expressions (described in * detail here: https://github.com/TomFrost/Jexl) this processor will iterate * and evaluate each expression. * * The evaluated expressions are then used to replace their Jexl originals. * * Examples and possible outcome: * * Input string "Your lucky number is ${1+Math.floor(Math.random()*10)}" * * Possible output: "Your lucky number is 7" * * @param text some string that may contain Jexl expressions * @param jexlContext some context which is used when evaluating an Jexl expresson * @returns original string with all expressions evaluated * */ function processJexlExpression(text, jexlContext) { Object.getOwnPropertyNames(Math).forEach((functionName) => { // @ts-ignore jexl_1.default.addFunction(functionName, Math[functionName]); }); Object.getOwnPropertyNames(voca_1.default).forEach((functionName) => { // @ts-ignore jexl_1.default.addFunction(functionName, voca_1.default[functionName]); }); jexl_1.default.addFunction("join", (array, joinString, lastJoinString) => { if (array === undefined || !Array.isArray(array)) { // Parameter for join is no array return ""; } const length = array.length; if (joinString === undefined) { joinString = ","; } if (lastJoinString === undefined) { lastJoinString = joinString; } if (length === 0) { return ""; } else if (length === 1) { return array[0]; } else if (length === 2) { return array.join(lastJoinString); } else { // length >= 3 const allButLast = array.slice(0, length - 1); const lastElement = array[length - 1]; return allButLast.join(joinString) + lastJoinString + lastElement; } }); let newText = text; const regEx = new RegExp(/\${(.+?)}/g); let matches = regEx.exec(text); while (matches !== null) { // matches[0] = ${4+4} // matches[1] = 4+4 const result = jexl_1.default.evalSync(matches[1], jexlContext); newText = newText.replace(matches[0], result); matches = regEx.exec(text); } return newText; } exports.processJexlExpression = processJexlExpression; //# sourceMappingURL=JexlOutputProcessor.js.map