@botonic/plugin-flow-builder
Version:
Use Flow Builder to show your contents
79 lines • 3.33 kB
JavaScript
import { __awaiter } from "tslib";
import { NluType } from '@botonic/core';
import { REG_EXP_PATTERN } from '../constants';
import { EventAction, trackEvent } from '../tracking';
export class KeywordMatcher {
constructor({ cmsApi, locale, request }) {
this.cmsApi = cmsApi;
this.locale = locale;
this.request = request;
this.isRegExp = false;
}
getNodeByInput(userInput) {
return __awaiter(this, void 0, void 0, function* () {
const keywordNodes = this.cmsApi.getKeywordNodes();
const keywordNode = this.getNodeByKeyword(userInput, keywordNodes);
if (!keywordNode || !this.matchedKeyword) {
return undefined;
}
const targetPayload = this.cmsApi.getPayload(keywordNode.target);
this.request.input.nluResolution = {
type: NluType.Keyword,
matchedValue: this.matchedKeyword,
payload: targetPayload,
};
yield this.trackKeywordEvent();
return keywordNode;
});
}
getNodeByKeyword(userInput, keywordNodes) {
const matchedKeywordNode = keywordNodes.find(node => this.matchKeywords(userInput, node));
return (matchedKeywordNode === null || matchedKeywordNode === void 0 ? void 0 : matchedKeywordNode.target) ? matchedKeywordNode : undefined;
}
matchKeywords(userInput, node) {
const result = node.content.keywords.find(keywords => {
if (keywords.locale === this.locale) {
this.keywordNodeId = node.id;
this.flowId = this.cmsApi.getNodeById(node.id).flow_id;
return this.inputMatchesAnyKeyword(userInput, keywords.values);
}
return false;
});
return Boolean(result);
}
inputMatchesAnyKeyword(userInput, keywords) {
return keywords.some(keyword => {
const regExpMatchArray = keyword.match(REG_EXP_PATTERN);
if (regExpMatchArray) {
const keywordAsRegExp = this.resolveKeywordAsRegExp(regExpMatchArray);
const match = userInput.match(keywordAsRegExp);
this.isRegExp = true;
this.matchedKeyword = match ? match[0] : undefined;
}
else {
this.isRegExp = false;
this.matchedKeyword = userInput.includes(keyword) ? keyword : undefined;
}
return this.matchedKeyword !== undefined;
});
}
resolveKeywordAsRegExp(regExpMatchArray) {
const [, pattern, flags] = regExpMatchArray;
return new RegExp(pattern, flags);
}
trackKeywordEvent() {
return __awaiter(this, void 0, void 0, function* () {
const eventArgs = {
nluKeywordName: this.matchedKeyword,
nluKeywordIsRegex: this.isRegExp,
nluKeywordMessageId: this.request.input.message_id,
userInput: this.request.input.data,
flowThreadId: this.request.session.flow_thread_id,
flowId: this.flowId,
flowNodeId: this.keywordNodeId,
};
yield trackEvent(this.request, EventAction.Keyword, eventArgs);
});
}
}
//# sourceMappingURL=keyword.js.map