@jss-rule-engine/chat
Version:
225 lines (224 loc) • 11.9 kB
JavaScript
var __assign = (this && this.__assign) || function () {
__assign = Object.assign || function(t) {
for (var s, i = 1, n = arguments.length; i < n; i++) {
s = arguments[i];
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
t[p] = s[p];
}
return t;
};
return __assign.apply(this, arguments);
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
var __generator = (this && this.__generator) || function (thisArg, body) {
var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g;
return g = { next: verb(0), "throw": verb(1), "return": verb(2) }, typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g;
function verb(n) { return function (v) { return step([n, v]); }; }
function step(op) {
if (f) throw new TypeError("Generator is already executing.");
while (g && (g = 0, op[0] && (_ = 0)), _) try {
if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t;
if (y = 0, t) op = [op[0] & 2, t.value];
switch (op[0]) {
case 0: case 1: t = op; break;
case 4: _.label++; return { value: op[1], done: false };
case 5: _.label++; y = op[1]; op = [0]; continue;
case 7: op = _.ops.pop(); _.trys.pop(); continue;
default:
if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; }
if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; }
if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; }
if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; }
if (t[2]) _.ops.pop();
_.trys.pop(); continue;
}
op = body.call(thisArg, _);
} catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; }
if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true };
}
};
import { useEffect } from "react";
import { useBotId, useFlow, useMessages, useTextArea, useChatWindow } from "react-chatbotify";
import { ChatActionFactory } from "../chatActionFactory";
import { getRuleEngineInstance, RuleEngineSessionContext } from "@jss-rule-engine/core";
import { registerChatCommands } from "../../registerChatCommands";
/**
* Plugin hook that handles all the core logic.
*
* @param pluginConfig configurations for the plugin
*/
var useSitecoreChatPlugin = function (pluginConfig) {
var getBotId = useBotId().getBotId;
var _a = useMessages(), injectMessage = _a.injectMessage, simulateStreamMessage = _a.simulateStreamMessage;
var setTextAreaValue = useTextArea().setTextAreaValue;
var getFlow = useFlow().getFlow;
var toggleIsBotTyping = useChatWindow().toggleIsBotTyping;
var actionFactory = new ChatActionFactory();
useEffect(function () {
registerChatCommands(actionFactory);
});
var ruleEngine = getRuleEngineInstance();
var DefaultPluginConfig = {};
var mergedPluginConfig = __assign(__assign({}, pluginConfig), DefaultPluginConfig);
function executeClientActions(actions, chatContext) {
return __awaiter(this, void 0, void 0, function () {
var _this = this;
return __generator(this, function (_a) {
if (!actions || !Array.isArray(actions))
return [2 /*return*/];
console.log('Executing chat actions...', chatContext);
actions.forEach(function (action) { return __awaiter(_this, void 0, void 0, function () {
var actionCommand, commandContext;
return __generator(this, function (_a) {
actionCommand = actionFactory.getAction(action.type);
commandContext = {
action: action,
messageApis: {
injectMessage: injectMessage,
simulateStreamMessage: simulateStreamMessage,
toggleIsBotTyping: toggleIsBotTyping
}
};
console.log('Executing client action', actionCommand, commandContext);
actionCommand.execute(commandContext);
return [2 /*return*/];
});
}); });
return [2 /*return*/];
});
});
}
function getWorkflowResponse(sitecoreUrl, params) {
return __awaiter(this, void 0, void 0, function () {
var userInput, flow, response, data, error_1;
return __generator(this, function (_a) {
switch (_a.label) {
case 0:
userInput = params.userInput;
flow = params.flow;
_a.label = 1;
case 1:
_a.trys.push([1, 5, , 6]);
console.log('Calling /api/chat/message', sitecoreUrl, params);
return [4 /*yield*/, injectMessage(userInput, "user")];
case 2:
_a.sent();
return [4 /*yield*/, fetch("".concat(sitecoreUrl, "/api/chat/message"), {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify({
message: userInput,
visitorId: getBotId(),
workflowId: flow,
}),
})];
case 3:
response = _a.sent();
if (!response.ok) {
throw new Error("Error: ".concat(response.status, " ").concat(response.statusText));
}
return [4 /*yield*/, response.json()];
case 4:
data = _a.sent();
return [2 /*return*/, data];
case 5:
error_1 = _a.sent();
console.error("Failed to fetch reply from Sitecore:", error_1);
throw error_1;
case 6: return [2 /*return*/];
}
});
});
}
useEffect(function () {
var handleMessageEvent = function (event) { return __awaiter(void 0, void 0, void 0, function () {
var hostUrl, userInput, currPath, flow, currBlock, jsonBody, reply, chatContext;
var _a;
return __generator(this, function (_b) {
switch (_b.label) {
case 0:
console.log('handleMessageEvent', event);
hostUrl = mergedPluginConfig.hostUrl;
userInput = (_a = event === null || event === void 0 ? void 0 : event.data) === null || _a === void 0 ? void 0 : _a.inputText;
if (!userInput || userInput.length == 0) {
return [2 /*return*/];
}
currPath = event.detail.currPath;
flow = getFlow();
if (!currPath || !flow)
return [2 /*return*/];
currBlock = flow[currPath];
console.log("Current block ", currBlock);
if (!(currBlock && currBlock.flowId)) return [3 /*break*/, 4];
if (event.type == "rcb-user-submit-text") {
event.preventDefault();
event.stopPropagation();
}
if (event.type == "rcb-change-path") {
//load next path here and trigger event on workflow
}
if (event.type == "rcb-chat-load") {
//trigger workflow for the chatbot load event
}
console.log("Flow id: ", currBlock.flowId);
jsonBody = { flow: currBlock.flowId, userInput: userInput };
console.log('Calling Sitecore workflow api....', jsonBody);
return [4 /*yield*/, setTextAreaValue('')];
case 1:
_b.sent();
return [4 /*yield*/, getWorkflowResponse(hostUrl, jsonBody)];
case 2:
reply = _b.sent();
console.log('Reply - ', reply);
if (!reply.success) return [3 /*break*/, 4];
chatContext = {
injectMessage: injectMessage,
variables: new RuleEngineSessionContext(),
userInput: userInput,
ruleEngine: ruleEngine,
prevPath: event.detail.prevPath || undefined,
currPath: event.detail.currPath || undefined,
};
chatContext.variables.set("flow", flow);
return [4 /*yield*/, executeClientActions(reply.actions, chatContext)];
case 3:
_b.sent();
_b.label = 4;
case 4: return [2 /*return*/];
}
});
}); };
// Remove any existing event listeners first to prevent duplicates
window.removeEventListener("rcb-user-submit-text", handleMessageEvent);
// Add event listeners
window.addEventListener("rcb-user-submit-text", handleMessageEvent);
// Cleanup function to remove event listeners when component unmounts
return function () {
window.removeEventListener("rcb-user-submit-text", handleMessageEvent);
};
}, []); // Add dependencies to prevent stale closures
// initializes plugin metadata with plugin name
var pluginMetaData = {
name: "@rcb-plugins/sitecore-chat-plugin",
};
// adds required events in settings if auto config is true
if (mergedPluginConfig === null || mergedPluginConfig === void 0 ? void 0 : mergedPluginConfig.autoConfig) {
pluginMetaData.settings = {
event: {
rcbUserSubmitText: true
},
};
}
return pluginMetaData;
};
export default useSitecoreChatPlugin;