@cleartrip/talos-use-chat-controller 1.5.0-beta-260618-7.0 → 1.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,8 +1,8 @@
1
1
  (function (global, factory) {
2
- typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('uuid'), require('@cleartrip/talos-general-utils'), require('@cleartrip/talos-widget-types'), require('@cleartrip/talos-network'), require('@cleartrip/talos-use-chat')) :
3
- typeof define === 'function' && define.amd ? define(['exports', 'react', 'uuid', '@cleartrip/talos-general-utils', '@cleartrip/talos-widget-types', '@cleartrip/talos-network', '@cleartrip/talos-use-chat'], factory) :
4
- (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TalosUseChatController = {}, global.React, global.uuid, global.talosGeneralUtils, global.talosWidgetTypes, global.talosNetwork, global.talosUseChat));
5
- })(this, (function (exports, require$$0, uuid, talosGeneralUtils, talosWidgetTypes, talosNetwork, talosUseChat) { 'use strict';
2
+ typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('react'), require('uuid'), require('@cleartrip/talos-use-chat'), require('@cleartrip/talos-general-utils'), require('@cleartrip/talos-widget-types'), require('@cleartrip/talos-network')) :
3
+ typeof define === 'function' && define.amd ? define(['exports', 'react', 'uuid', '@cleartrip/talos-use-chat', '@cleartrip/talos-general-utils', '@cleartrip/talos-widget-types', '@cleartrip/talos-network'], factory) :
4
+ (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.TalosUseChatController = {}, global.React, global.uuid, global.talosUseChat, global.talosGeneralUtils, global.talosWidgetTypes, global.talosNetwork));
5
+ })(this, (function (exports, require$$0, uuid, talosUseChat, talosGeneralUtils, talosWidgetTypes, talosNetwork) { 'use strict';
6
6
 
7
7
  function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
8
8
 
@@ -490,196 +490,6 @@
490
490
  return { dispatch: dispatch, dispatchAll: dispatchAll };
491
491
  };
492
492
 
493
- var replaceMerge = function (current, incoming) { return (__assign(__assign({}, current), { data: __assign(__assign({}, current.data), incoming) })); };
494
- var defaultResolver = function () { return replaceMerge; };
495
- var withStreamMeta = function (w, streamId, isStreaming) {
496
- var _a;
497
- return (__assign(__assign({}, w), { metaData: __assign(__assign({}, ((_a = w.metaData) !== null && _a !== void 0 ? _a : {})), { streamId: streamId, isStreaming: isStreaming }) }));
498
- };
499
- var WidgetStore = (function () {
500
- function WidgetStore(mergeFor) {
501
- if (mergeFor === void 0) { mergeFor = defaultResolver; }
502
- this.mergeFor = mergeFor;
503
- this.order = [];
504
- this.byId = new Map();
505
- this.autoKey = 0;
506
- }
507
- WidgetStore.prototype.reset = function () {
508
- this.order = [];
509
- this.byId = new Map();
510
- this.autoKey = 0;
511
- };
512
- WidgetStore.prototype.apply = function (op) {
513
- if (op.kind === talosWidgetTypes.StreamKind.STANDALONE) {
514
- this.push("w-".concat(this.autoKey++), op.widget);
515
- return;
516
- }
517
- if (op.kind === talosWidgetTypes.StreamKind.CHUNK) {
518
- var current = this.byId.get(op.streamId);
519
- if (!current) {
520
- this.push(op.streamId, withStreamMeta(op.widget, op.streamId, true));
521
- }
522
- else {
523
- this.push(op.streamId, this.mergeFor(current.type)(current, op.widget.data));
524
- }
525
- return;
526
- }
527
- var w = this.byId.get(op.streamId);
528
- if (w)
529
- this.push(op.streamId, withStreamMeta(w, op.streamId, false));
530
- };
531
- WidgetStore.prototype.closeOpenStreams = function () {
532
- var _this = this;
533
- this.order.forEach(function (key) {
534
- var _a, _b;
535
- var w = _this.byId.get(key);
536
- if ((_a = w === null || w === void 0 ? void 0 : w.metaData) === null || _a === void 0 ? void 0 : _a.isStreaming) {
537
- _this.push(key, withStreamMeta(w, (_b = w.metaData.streamId) !== null && _b !== void 0 ? _b : key, false));
538
- }
539
- });
540
- };
541
- WidgetStore.prototype.toArray = function () {
542
- var _this = this;
543
- return this.order
544
- .map(function (key) { return _this.byId.get(key); })
545
- .filter(function (w) { return Boolean(w); });
546
- };
547
- WidgetStore.prototype.push = function (key, widget) {
548
- if (!this.byId.has(key))
549
- this.order.push(key);
550
- this.byId.set(key, widget);
551
- };
552
- return WidgetStore;
553
- }());
554
-
555
- var initialParserState = function () { return ({ openStreamId: null }); };
556
- function frameToOp(frame, state) {
557
- if ("signal" in frame) {
558
- if (frame.signal === talosWidgetTypes.Signal.START) {
559
- state.openStreamId = frame.streamId;
560
- return null;
561
- }
562
- state.openStreamId = null;
563
- return { kind: talosWidgetTypes.StreamKind.CLOSE, streamId: frame.streamId };
564
- }
565
- return state.openStreamId
566
- ? { kind: talosWidgetTypes.StreamKind.CHUNK, streamId: state.openStreamId, widget: frame }
567
- : { kind: talosWidgetTypes.StreamKind.STANDALONE, widget: frame };
568
- }
569
-
570
- var scheduleOncePerFrame = function (fn) {
571
- var scheduled = false;
572
- var schedule = typeof requestAnimationFrame !== "undefined"
573
- ? requestAnimationFrame
574
- : function (cb) { return setTimeout(cb, 16); };
575
- return function () {
576
- if (scheduled)
577
- return;
578
- scheduled = true;
579
- schedule(function () {
580
- scheduled = false;
581
- fn();
582
- });
583
- };
584
- };
585
- var useChatTransport = function (props) {
586
- var _a = props.protocol, protocol = _a === void 0 ? talosWidgetTypes.Protocol.DEFAULT : _a, network = props.network, chatService = props.chatService, resolveMerge = props.resolveMerge, buildBody = props.buildBody;
587
- var _b = talosUseChat.useChat({ network: network, buildBody: buildBody }), chat = _b.chat, status = _b.status, chatSend = _b.send, stop = _b.stop;
588
- var storeRef = require$$0.useRef();
589
- if (!storeRef.current)
590
- storeRef.current = new WidgetStore(resolveMerge);
591
- var stateRef = require$$0.useRef(initialParserState());
592
- var sinkRef = require$$0.useRef(null);
593
- var flushRef = require$$0.useRef();
594
- if (!flushRef.current) {
595
- flushRef.current = scheduleOncePerFrame(function () {
596
- if (sinkRef.current)
597
- sinkRef.current.update(storeRef.current.toArray());
598
- });
599
- }
600
- require$$0.useEffect(function () {
601
- var store = storeRef.current;
602
- var onChunk = function (_a) {
603
- var chunk = _a.chunk;
604
- if (!sinkRef.current)
605
- return;
606
- var frame;
607
- try {
608
- frame = JSON.parse(chunk);
609
- }
610
- catch (_b) {
611
- return;
612
- }
613
- var op = frameToOp(frame, stateRef.current);
614
- if (op)
615
- store.apply(op);
616
- flushRef.current();
617
- };
618
- var onComplete = function () {
619
- var sink = sinkRef.current;
620
- if (!sink)
621
- return;
622
- store.closeOpenStreams();
623
- sink.update(store.toArray());
624
- sink.done();
625
- sinkRef.current = null;
626
- };
627
- var onError = function (_a) {
628
- var error = _a.error;
629
- var sink = sinkRef.current;
630
- if (!sink)
631
- return;
632
- store.closeOpenStreams();
633
- sink.error(error);
634
- sinkRef.current = null;
635
- };
636
- var offChunk = chat.on(talosUseChat.ChatEventName.CHUNK, onChunk);
637
- var offComplete = chat.on(talosUseChat.ChatEventName.COMPLETE, onComplete);
638
- var offError = chat.on(talosUseChat.ChatEventName.ERROR, onError);
639
- return function () {
640
- offChunk();
641
- offComplete();
642
- offError();
643
- };
644
- }, [chat]);
645
- var send = require$$0.useCallback(function (payload, sink) { return __awaiter(void 0, void 0, void 0, function () {
646
- var res, _a, _b, chunks, _c, metadata, error_1;
647
- var _d;
648
- return __generator(this, function (_e) {
649
- switch (_e.label) {
650
- case 0:
651
- if (protocol === talosWidgetTypes.Protocol.STREAMED) {
652
- storeRef.current.reset();
653
- stateRef.current = initialParserState();
654
- sinkRef.current = sink;
655
- chatSend(payload);
656
- return [2];
657
- }
658
- _e.label = 1;
659
- case 1:
660
- _e.trys.push([1, 3, , 4]);
661
- return [4, chatService.getBotResponse(payload)];
662
- case 2:
663
- res = _e.sent();
664
- _a = (_d = res === null || res === void 0 ? void 0 : res.data) !== null && _d !== void 0 ? _d : {}, _b = _a.chunks, chunks = _b === void 0 ? [] : _b, _c = _a.metadata, metadata = _c === void 0 ? {} : _c;
665
- sink.update(chunks);
666
- sink.done(metadata);
667
- return [3, 4];
668
- case 3:
669
- error_1 = _e.sent();
670
- sink.error(error_1);
671
- return [3, 4];
672
- case 4: return [2];
673
- }
674
- });
675
- }); }, [protocol, chatSend, chatService]);
676
- var abort = require$$0.useCallback(function () {
677
- stop();
678
- sinkRef.current = null;
679
- }, [stop]);
680
- return { chat: chat, status: status, send: send, abort: abort };
681
- };
682
-
683
493
  exports.ConversationMessageRole = void 0;
684
494
  (function (ConversationMessageRole) {
685
495
  ConversationMessageRole["USER"] = "USER";
@@ -853,13 +663,9 @@
853
663
  var ANIMATION_DURATION = 300;
854
664
 
855
665
  var useChatController = function (config) {
856
- var network = config.network, triggerTracking = config.triggerTracking, baseTrackingData = config.baseTrackingData, protocol = config.protocol, resolveMerge = config.resolveMerge, buildBody = config.buildBody;
666
+ var network = config.network, triggerTracking = config.triggerTracking, baseTrackingData = config.baseTrackingData;
667
+ var _a = talosUseChat.useChat(config), chat = _a.chat, status = _a.status, baseSendMessage = _a.sendMessage, stop = _a.stop;
857
668
  var chatService = require$$0.useMemo(function () { return new ChatService(network); }, [network]);
858
- var defaultBuildBody = require$$0.useCallback(function (payload) {
859
- var _a;
860
- return (__assign(__assign({}, payload), { payload: __assign(__assign({}, payload.payload), ((_a = network === null || network === void 0 ? void 0 : network.body) !== null && _a !== void 0 ? _a : {})) }));
861
- }, [network]);
862
- var _a = useChatTransport({ protocol: protocol, network: network, chatService: chatService, resolveMerge: resolveMerge, buildBody: buildBody !== null && buildBody !== void 0 ? buildBody : defaultBuildBody }), chat = _a.chat, status = _a.status, transportSend = _a.send, stop = _a.abort;
863
669
  var _b = require$$0.useState({}), messages = _b[0], setMessages = _b[1];
864
670
  var _c = require$$0.useState(false), isInitialLoading = _c[0], setIsInitialLoading = _c[1];
865
671
  var _d = require$$0.useState(false), isReplyLoading = _d[0], setIsReplyLoading = _d[1];
@@ -896,82 +702,82 @@
896
702
  var _a;
897
703
  return ((_a = chatStack[chatStack.length - 1]) === null || _a === void 0 ? void 0 : _a.id) || "";
898
704
  }, [chatStack]);
899
- var patchMessageChunks = function (chatId, messageId, widgets) {
900
- setMessages(function (prev) {
901
- var _a;
902
- var chat = prev[chatId];
903
- if (!chat)
904
- return prev;
905
- return __assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, chat), { messages: chat.messages.map(function (m) { return (m.id === messageId ? __assign(__assign({}, m), { chunks: widgets }) : m); }) }), _a));
906
- });
907
- };
908
705
  var handleBotMessage = function (variant, chatId) {
909
- var _a, _b;
910
706
  if (chatId === void 0) { chatId = currentChatId; }
911
- var isInit = variant.kind === exports.BotMessageKind.INIT;
912
- var turnSequence = getTurnSequence((_b = (_a = messages[chatId]) === null || _a === void 0 ? void 0 : _a.messages) !== null && _b !== void 0 ? _b : [], "BOT_MESSAGE") + 1;
913
- var messageId = uuid.v4();
914
- if (!isInit)
915
- setIsReplyLoading(true);
916
- if (isInit)
917
- seedPresented(chatId, [messageId]);
918
- setMessages(function (prev) {
919
- var _a;
920
- var _b, _c;
921
- return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { messages: __spreadArray(__spreadArray([], ((_c = (_b = prev[chatId]) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : []), true), [
922
- {
923
- id: messageId,
924
- type: "BOT_MESSAGE",
925
- chunks: [],
926
- metaData: { createdAt: talosGeneralUtils.formatISOTime(new Date().toISOString()), messageId: messageId },
927
- },
928
- ], false), status: exports.ChatStatus.ON_GOING }), _a)));
929
- });
930
- var trackResult = function (responseStatus, handedOffToAgent) {
931
- if (isInit)
932
- return;
933
- setIsReplyLoading(false);
934
- if (handedOffToAgent) {
935
- dispatch({
936
- type: talosWidgetTypes.ActionType.RAVEN_TRACKING,
937
- payload: {
938
- eventName: "u_ai_chat_agent_handoff",
939
- eventData: { action_name: "chat_agent_handoff", turn_sequence: turnSequence, chat_session_id: chatId },
940
- },
941
- });
942
- }
943
- else {
944
- dispatch({
945
- type: talosWidgetTypes.ActionType.RAVEN_TRACKING,
946
- payload: {
947
- eventName: "u_ai_chat_bot_response",
948
- eventData: { chat_session_id: chatId, response_status: responseStatus, turn_sequence: turnSequence },
949
- },
950
- });
951
- }
952
- };
953
- return new Promise(function (resolve) {
954
- var sink = {
955
- update: function (widgets) { return patchMessageChunks(chatId, messageId, widgets); },
956
- done: function (metadata) {
957
- var _a;
958
- trackResult("success", (_a = metadata === null || metadata === void 0 ? void 0 : metadata.handedOffToAgent) !== null && _a !== void 0 ? _a : false);
959
- resolve();
960
- },
961
- error: function () {
962
- setMessages(function (prev) {
963
- var _a;
964
- var chat = prev[chatId];
965
- if (!chat)
966
- return prev;
967
- var errorMsg = BOT_ERROR_RESPONSE(messageId, variant);
968
- return __assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, chat), { messages: chat.messages.map(function (m) { return (m.id === messageId ? errorMsg : m); }) }), _a));
969
- });
970
- trackResult("failed", false);
971
- resolve();
972
- },
973
- };
974
- transportSend(buildBotPayload(variant, chatId), sink);
707
+ return __awaiter(void 0, void 0, void 0, function () {
708
+ var isInit, responseStatus, handedOffToAgent, turnSequence, payload, response, _a, _b, _c, chunks_1, _d, metadata, messageId_1, errorId_1;
709
+ var _e, _f, _g;
710
+ return __generator(this, function (_h) {
711
+ switch (_h.label) {
712
+ case 0:
713
+ isInit = variant.kind === exports.BotMessageKind.INIT;
714
+ handedOffToAgent = false;
715
+ turnSequence = getTurnSequence((_f = (_e = messages[chatId]) === null || _e === void 0 ? void 0 : _e.messages) !== null && _f !== void 0 ? _f : [], "BOT_MESSAGE") + 1;
716
+ _h.label = 1;
717
+ case 1:
718
+ _h.trys.push([1, 3, 4, 5]);
719
+ if (!isInit) {
720
+ setIsReplyLoading(true);
721
+ }
722
+ payload = buildBotPayload(variant, chatId);
723
+ return [4, chatService.getBotResponse(payload)];
724
+ case 2:
725
+ response = _h.sent();
726
+ _a = response.data, _b = _a === void 0 ? {} : _a, _c = _b.chunks, chunks_1 = _c === void 0 ? [] : _c, _d = _b.metadata, metadata = _d === void 0 ? {} : _d;
727
+ responseStatus = 'success';
728
+ handedOffToAgent = (_g = metadata.handedOffToAgent) !== null && _g !== void 0 ? _g : false;
729
+ messageId_1 = uuid.v4();
730
+ if (isInit)
731
+ seedPresented(chatId, [messageId_1]);
732
+ setMessages(function (prev) {
733
+ var _a;
734
+ var _b, _c;
735
+ return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { messages: __spreadArray(__spreadArray([], ((_c = (_b = prev[chatId]) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : []), true), [
736
+ {
737
+ id: messageId_1,
738
+ type: "BOT_MESSAGE",
739
+ chunks: __spreadArray([], chunks_1, true),
740
+ metaData: { createdAt: talosGeneralUtils.formatISOTime(new Date().toISOString()), messageId: messageId_1 },
741
+ },
742
+ ], false), status: exports.ChatStatus.ON_GOING }), _a)));
743
+ });
744
+ return [3, 5];
745
+ case 3:
746
+ _h.sent();
747
+ errorId_1 = uuid.v4();
748
+ setMessages(function (prev) {
749
+ var _a;
750
+ var _b, _c;
751
+ return (__assign(__assign({}, prev), (_a = {}, _a[chatId] = __assign(__assign({}, prev[chatId]), { messages: __spreadArray(__spreadArray([], ((_c = (_b = prev[chatId]) === null || _b === void 0 ? void 0 : _b.messages) !== null && _c !== void 0 ? _c : []), true), [BOT_ERROR_RESPONSE(errorId_1, variant)], false) }), _a)));
752
+ });
753
+ responseStatus = 'failed';
754
+ return [3, 5];
755
+ case 4:
756
+ if (!isInit) {
757
+ setIsReplyLoading(false);
758
+ if (handedOffToAgent) {
759
+ dispatch({
760
+ type: talosWidgetTypes.ActionType.RAVEN_TRACKING,
761
+ payload: {
762
+ eventName: "u_ai_chat_agent_handoff",
763
+ eventData: { action_name: "chat_agent_handoff", turn_sequence: turnSequence, chat_session_id: chatId },
764
+ },
765
+ });
766
+ }
767
+ else {
768
+ dispatch({
769
+ type: talosWidgetTypes.ActionType.RAVEN_TRACKING,
770
+ payload: {
771
+ eventName: "u_ai_chat_bot_response",
772
+ eventData: { chat_session_id: chatId, response_status: responseStatus, turn_sequence: turnSequence },
773
+ },
774
+ });
775
+ }
776
+ }
777
+ return [7];
778
+ case 5: return [2];
779
+ }
780
+ });
975
781
  });
976
782
  };
977
783
  var handleRetryMessage = function (messageId) { return __awaiter(void 0, void 0, void 0, function () {
@@ -1056,6 +862,15 @@
1056
862
  require$$0.useEffect(function () {
1057
863
  seedInitialChat();
1058
864
  }, []);
865
+ var handleChunk = require$$0.useCallback(function (_a) {
866
+ _a.chunk; _a.chatId;
867
+ }, []);
868
+ require$$0.useEffect(function () {
869
+ var removeChunkListener = chat.on(talosUseChat.ChatEventName.CHUNK, handleChunk);
870
+ return function () {
871
+ removeChunkListener();
872
+ };
873
+ }, [chat, handleChunk]);
1059
874
  var pushUserMessage = function (message) {
1060
875
  var userMessageWidget = formUserMessageWidget({ message: message });
1061
876
  var id = uuid.v4();
@@ -1092,7 +907,7 @@
1092
907
  }
1093
908
  return [2];
1094
909
  });
1095
- }); }, [pushUserMessage]);
910
+ }); }, [baseSendMessage, pushUserMessage]);
1096
911
  var resetPreviousChats = function () {
1097
912
  setPreviousChatError(false);
1098
913
  setPreviousChats(null);