@atlaskit/rovo-triggers 1.0.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.
Files changed (34) hide show
  1. package/CHANGELOG.md +9 -0
  2. package/LICENSE.md +11 -0
  3. package/README.md +172 -0
  4. package/dist/cjs/common/utils/params/constants.js +8 -0
  5. package/dist/cjs/common/utils/params/index.js +153 -0
  6. package/dist/cjs/common/utils/params/types.js +1 -0
  7. package/dist/cjs/index.js +67 -0
  8. package/dist/cjs/main.js +169 -0
  9. package/dist/cjs/types.js +15 -0
  10. package/dist/es2019/common/utils/params/constants.js +2 -0
  11. package/dist/es2019/common/utils/params/index.js +121 -0
  12. package/dist/es2019/common/utils/params/types.js +0 -0
  13. package/dist/es2019/index.js +2 -0
  14. package/dist/es2019/main.js +159 -0
  15. package/dist/es2019/types.js +9 -0
  16. package/dist/esm/common/utils/params/constants.js +2 -0
  17. package/dist/esm/common/utils/params/index.js +146 -0
  18. package/dist/esm/common/utils/params/types.js +0 -0
  19. package/dist/esm/index.js +2 -0
  20. package/dist/esm/main.js +162 -0
  21. package/dist/esm/types.js +9 -0
  22. package/dist/types/common/utils/params/constants.d.ts +3 -0
  23. package/dist/types/common/utils/params/index.d.ts +15 -0
  24. package/dist/types/common/utils/params/types.d.ts +20 -0
  25. package/dist/types/index.d.ts +4 -0
  26. package/dist/types/main.d.ts +15 -0
  27. package/dist/types/types.d.ts +79 -0
  28. package/dist/types-ts4.5/common/utils/params/constants.d.ts +3 -0
  29. package/dist/types-ts4.5/common/utils/params/index.d.ts +15 -0
  30. package/dist/types-ts4.5/common/utils/params/types.d.ts +20 -0
  31. package/dist/types-ts4.5/index.d.ts +4 -0
  32. package/dist/types-ts4.5/main.d.ts +15 -0
  33. package/dist/types-ts4.5/types.d.ts +79 -0
  34. package/package.json +90 -0
package/CHANGELOG.md ADDED
@@ -0,0 +1,9 @@
1
+ # @atlaskit/rovo-triggers
2
+
3
+ ## 1.0.0
4
+
5
+ ### Major Changes
6
+
7
+ - [#153462](https://stash.atlassian.com/projects/CONFCLOUD/repos/confluence-frontend/pull-requests/153462)
8
+ [`6c079f0811ae0`](https://stash.atlassian.com/projects/CONFCLOUD/repos/confluence-frontend/commits/6c079f0811ae0) -
9
+ Initialize rovo-triggers
package/LICENSE.md ADDED
@@ -0,0 +1,11 @@
1
+ Copyright 2023 Atlassian Pty Ltd
2
+
3
+ Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in
4
+ compliance with the License. You may obtain a copy of the License at
5
+
6
+ http://www.apache.org/licenses/LICENSE-2.0
7
+
8
+ Unless required by applicable law or agreed to in writing, software distributed under the License is
9
+ distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
10
+ implied. See the License for the specific language governing permissions and limitations under the
11
+ License.
package/README.md ADDED
@@ -0,0 +1,172 @@
1
+ # Rovo Triggers
2
+
3
+ _(formerly conversation-assistant-pubsub)_
4
+
5
+ Provides various trigger events to drive Rovo Chat functionality, such as a publish-subscribe and
6
+ URL parameter hooks
7
+
8
+ ## Example usage
9
+
10
+ ### Publish
11
+
12
+ ```ts
13
+ import { usePublish } from "@atlaskit/rovo-triggers";
14
+
15
+ const YourComponent = () => {
16
+ const publish = usePublish('ai-mate');
17
+
18
+ const handleClick = () => {
19
+ publish({
20
+ type: "message-send",
21
+ data: "hello Rovo Chat",
22
+ source: "my-source", // source is used for analytics
23
+ })
24
+ }
25
+
26
+ return (
27
+ <div>
28
+ <button onClick={handleClick}>
29
+ Send message onbehalf of user in Rovo Chat
30
+ </button>
31
+ </div>
32
+ );
33
+ }
34
+ ```
35
+
36
+ ### Subscribe
37
+
38
+ ```ts
39
+ import { useSubscribe } from "@atlaskit/rovo-triggers";
40
+
41
+ const YourComponent = () => {
42
+ const [message, setMessage] = useState('Waiting for messages...');
43
+
44
+ useSubscribe({ topic: 'ai-mate' }, ({ type, data }) => {
45
+ if(type === 'message-received') {
46
+ setMessage(data)
47
+ }
48
+ });
49
+
50
+ return (<div>{message}</div>);
51
+ }
52
+ ```
53
+
54
+ #### Subscribe (TriggerLatest)
55
+
56
+ ```ts
57
+ import { useSubscribe } from "@atlaskit/rovo-triggers";
58
+
59
+ const YourComponent = () => {
60
+ const [message, setMessage] = useState('Waiting for messages...');
61
+
62
+ // This subscription will trigger immediately if an event has already been published to the 'ai-mate' topic
63
+ useSubscribe({ topic: 'ai-mate', triggerLatest: true }, ({ type, data, source }) => {
64
+ if(type === 'message-received') {
65
+ setMessage(data)
66
+ }
67
+ });
68
+
69
+ return (<div>{message}</div>);
70
+ }
71
+ ```
72
+
73
+ ### Subscribe All
74
+
75
+ **Note** - Avoid using this. Right now it's only intended to be a proxy for Rovo Chat to trigger
76
+ open when new events are published, if it isn't already open.
77
+
78
+ ```ts
79
+ import { useSubscribeAll } from "@atlaskit/rovo-triggers";
80
+
81
+ const YourComponent = () => {
82
+ useSubscribeAll(() => {
83
+ console.log('pubsub received an event')
84
+ // do something like open the Rovo Chat panel
85
+ });
86
+ });
87
+ }
88
+ ```
89
+
90
+ ### Conditionally run subscriptions
91
+
92
+ You can conditionally call a subscription that uses `triggerLatest` by conditionally rendering the
93
+ `<Subscriber />` component. This can be useful to ensure your state is in the optimal place before
94
+ triggering it's the subscription (e.g no longer loading)
95
+
96
+ ```ts
97
+ const YourComponent = ({ startSubscription }: { startSubscription: boolean }) => startSubscription ? (
98
+ <Subscriber
99
+ topic={topic}
100
+ triggerLatest={true}
101
+ onEvent={({ type, data }) => {
102
+ if (type === 'message-send') {
103
+ setMsg(`${data} received at ${new Date().toLocaleTimeString()}`);
104
+ setCount(count + 1);
105
+ }
106
+ }}
107
+ />
108
+ ) : null
109
+ ```
110
+
111
+ ## Registering new events
112
+
113
+ Events are a combination of a topic and an event type. As such you can register a new event type by
114
+ either:
115
+
116
+ - Creating a new `Topic`, and leveraging the existing `EventTypes`
117
+ - Creating a new `Topic`, and also creating some new `EventTypes` to be used
118
+ - Creating another `EventType` to be used against an existing `Topic`
119
+
120
+ This may change as the utility and typings evolve when continuing to build integrations with this
121
+ package.
122
+
123
+ ### Topics
124
+
125
+ The `ai-mate` topic is reserved for `conversation-assistant` events and is the only one that
126
+ currently exists. Watch this space.
127
+
128
+ ### EventTypes
129
+
130
+ Event types represent actions that have taken place in Rovo Chat, or actions you'd like to trigger
131
+ within Rovo Chat. As long as there's a registered `publish` event to the `ai-mate` topic, you can
132
+ subscribe to it.
133
+
134
+ This will be documented as integrations are developed.
135
+
136
+ ## Params utility
137
+
138
+ Rovo Chat uses a strongly typed set of query params encoded to `rovoChat` which can be used
139
+ consistently across products.
140
+
141
+ These values can be used to trigger state changes, routing, actions, for example.
142
+
143
+ - `clearPageRovoParams` - Removes rovoChat param and it’s value from the address bar.
144
+
145
+ - `updatePageRovoParams` - Easily add properties to the `rovoChat` param in the address bar; this is
146
+ helpful to continually update the URL for bookmarking or sharing. This method uses
147
+ `addRovoParamsToUrl` under the hood.
148
+
149
+ - `addRovoParamsToUrl` - The previous function uses this under the hood, but you can call it
150
+ directly to add them to an arbitrary URL string, so let’s say you want to redirect from embedded
151
+ panel to Atlas and do a certain thing, you can call this and pass all the required data to ensure
152
+ its’ picked up and triggers the right thing on Atlas
153
+
154
+ - `getRovoParams` - The main method you’d use to execute on the values in the rovo params, so you
155
+ can do Atlas page routing, or trigger actions in the embedded experience (differentiated by
156
+ `UIConfig.fullScreen=false`)
157
+
158
+ Here are some examples of how you might use `getRovoParams` resulting value:
159
+
160
+ - Open new chat `{ pathway: 'chat' }`
161
+ - Open specific chat `{ pathway: 'chat', conversationId: '123' }`
162
+ - Open new chat with specific agent `{ pathway: 'chat', agentId: '456' }`
163
+ - Open specific chat with specific agent
164
+ `{ pathway: 'chat', conversationId: '123', agentId: '456' }`
165
+ - Open new chat and send message `{ pathway: 'chat', prompt: 'What should I work on next?' }`
166
+ - Open specific chat and send message
167
+ `{ pathway: 'chat', conversationId: '123', prompt: 'What should I work on next?' }`
168
+ - Open specific chat with specific agent and send message
169
+ `{ pathway: 'chat', conversationId: '123', agentId: '456', prompt: 'What should I work on next?' }`
170
+ - Browse agents `{ pathway: 'agents-browse' }`
171
+ - View agent details `{ pathway: 'agents-browse', agentId: '456' }`
172
+ - Open create agent experience `{ pathway: 'agents-create' }`
@@ -0,0 +1,8 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.ROVO_VALID_PARAMS = exports.ROVO_PARAM_PREFIX = void 0;
7
+ var ROVO_PARAM_PREFIX = exports.ROVO_PARAM_PREFIX = 'rovoChat';
8
+ var ROVO_VALID_PARAMS = exports.ROVO_VALID_PARAMS = ['pathway', 'agentId', 'conversationId', 'prompt', 'cloudId', 'triggerOpen'];
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.updatePageRovoParams = exports.removePrefix = exports.getRovoParams = exports.getListOfRovoParams = exports.firstCharUpper = exports.firstCharLower = exports.encodeRovoParams = exports.assertOnlySpecificFieldsDefined = exports.addRovoParamsToUrl = exports.addPrefix = void 0;
8
+ var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));
9
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
10
+ var _constants = require("./constants");
11
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
12
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
13
+ var firstCharUpper = exports.firstCharUpper = function firstCharUpper(str) {
14
+ return str.charAt(0).toUpperCase() + str.slice(1);
15
+ };
16
+ var firstCharLower = exports.firstCharLower = function firstCharLower(str) {
17
+ return str.charAt(0).toLowerCase() + str.slice(1);
18
+ };
19
+ var isValidURL = function isValidURL(url) {
20
+ try {
21
+ new URL(url);
22
+ return true;
23
+ } catch (error) {
24
+ return false;
25
+ }
26
+ };
27
+
28
+ // For new style camelCase params
29
+ var addPrefix = exports.addPrefix = function addPrefix(param) {
30
+ return "".concat(_constants.ROVO_PARAM_PREFIX).concat(firstCharUpper(param));
31
+ };
32
+ var removePrefix = exports.removePrefix = function removePrefix(param) {
33
+ return firstCharLower(param.replace(_constants.ROVO_PARAM_PREFIX, ''));
34
+ };
35
+
36
+ // Creates RovoChatParams from URLSearchParams
37
+ // Optionally filter to specific params
38
+ var processParams = function processParams(input) {
39
+ var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {
40
+ filter: []
41
+ };
42
+ var output = {};
43
+ var safeSearchParamsInput = typeof input === 'string' ? isValidURL(input) ? new URLSearchParams(new URL(input).search) : new URLSearchParams(input) : input;
44
+ var processedInput = new URLSearchParams(safeSearchParamsInput);
45
+ var extracted = new URLSearchParams();
46
+ safeSearchParamsInput.forEach(function (value, key) {
47
+ var _options$filter;
48
+ // Only look at rovoChat params
49
+ if (!key.startsWith(_constants.ROVO_PARAM_PREFIX)) {
50
+ return;
51
+ }
52
+ var paramKey = removePrefix(key);
53
+ if (options !== null && options !== void 0 && (_options$filter = options.filter) !== null && _options$filter !== void 0 && _options$filter.length) {
54
+ if (options.filter.includes(paramKey)) {
55
+ output[paramKey] = decodeURIComponent(value);
56
+ extracted.append(key, value);
57
+ }
58
+ } else {
59
+ output[paramKey] = decodeURIComponent(value);
60
+ }
61
+
62
+ // Remove rovoParam from processed input
63
+ processedInput.delete(key);
64
+ });
65
+ var combinedQueryString = [processedInput, extracted].map(function (params) {
66
+ return params.toString();
67
+ }).filter(function (part) {
68
+ return part.length > 0;
69
+ }).join('&');
70
+ return {
71
+ processed: processedInput,
72
+ rovoParams: output,
73
+ combinedQueryString: combinedQueryString
74
+ };
75
+ };
76
+
77
+ // Get all rovoChat params from a URL or the current window location if undefined
78
+ var getRovoParams = exports.getRovoParams = function getRovoParams(url) {
79
+ try {
80
+ var search = url ? new URL(url).search : window.location.search;
81
+ var q = new URLSearchParams(search);
82
+ return processParams(q).rovoParams;
83
+ } catch (error) {
84
+ return {};
85
+ }
86
+ };
87
+
88
+ // Update the address bar without reloading the page
89
+ var updatePageRovoParams = exports.updatePageRovoParams = function updatePageRovoParams(params) {
90
+ window.history.pushState({}, '', addRovoParamsToUrl(window.location.pathname, params));
91
+ };
92
+
93
+ // Add any valid rovoChat params to a URL
94
+ var addRovoParamsToUrl = exports.addRovoParamsToUrl = function addRovoParamsToUrl(url, params) {
95
+ var _processParams = processParams(url),
96
+ processed = _processParams.processed,
97
+ rovoParams = _processParams.rovoParams;
98
+ var rovoParamsWithExisting = _objectSpread(_objectSpread({}, rovoParams), params);
99
+ var baseUrl = url.includes('?') ? url.split('?')[0] : url;
100
+ var baseQuery = Array.from(processed).length ? "?".concat(processed.toString(), "&") : '?';
101
+ var updatedRovoParamsString = encodeRovoParams(rovoParamsWithExisting);
102
+ return "".concat(baseUrl).concat(baseQuery).concat(updatedRovoParamsString);
103
+ };
104
+ var encodeRovoParams = exports.encodeRovoParams = function encodeRovoParams(params, encodeAsObject) {
105
+ if (encodeAsObject) {
106
+ return Object.entries(params).reduce(function (acc, _ref) {
107
+ var _ref2 = (0, _slicedToArray2.default)(_ref, 2),
108
+ key = _ref2[0],
109
+ value = _ref2[1];
110
+ acc[addPrefix(key)] = encodeURIComponent(value);
111
+ return acc;
112
+ }, {});
113
+ }
114
+ return Object.entries(params).map(function (_ref3) {
115
+ var _ref4 = (0, _slicedToArray2.default)(_ref3, 2),
116
+ key = _ref4[0],
117
+ value = _ref4[1];
118
+ return "".concat(addPrefix(key), "=").concat(encodeURIComponent(value));
119
+ }).join('&');
120
+ };
121
+ var assertOnlySpecificFieldsDefined = exports.assertOnlySpecificFieldsDefined = function assertOnlySpecificFieldsDefined(params, fields) {
122
+ return Object.entries(params).every(function (_ref5) {
123
+ var _ref6 = (0, _slicedToArray2.default)(_ref5, 2),
124
+ key = _ref6[0],
125
+ value = _ref6[1];
126
+ var field = fields.find(function (field) {
127
+ return field === key;
128
+ });
129
+ if (field) {
130
+ return value !== undefined;
131
+ } else {
132
+ return value === undefined;
133
+ }
134
+ });
135
+ };
136
+ var getListOfRovoParams = exports.getListOfRovoParams = function getListOfRovoParams() {
137
+ var _ref7 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {},
138
+ _ref7$resourceRouterQ = _ref7.resourceRouterQuery,
139
+ resourceRouterQuery = _ref7$resourceRouterQ === void 0 ? false : _ref7$resourceRouterQ;
140
+ /*
141
+ For products using react-resource-router (e.g Atlas) to
142
+ pass as the value of `query` on the route definition. It ensures that our parameters
143
+ are not stripped from the URL when loading the page, or through redirect hops
144
+ Any new parameters we want to maintain should be added here as well, which means
145
+ only a version bump is needed in those products to support the latest param list
146
+ The !=false simply means that the parameter is supported but is optional, and should
147
+ not contain a value of 'false'
148
+ */
149
+ var suffix = resourceRouterQuery ? '!=false' : '';
150
+ return _constants.ROVO_VALID_PARAMS.map(function (param) {
151
+ return "".concat(addPrefix(param)).concat(suffix);
152
+ });
153
+ };
@@ -0,0 +1 @@
1
+ "use strict";
@@ -0,0 +1,67 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ Object.defineProperty(exports, "Subscriber", {
7
+ enumerable: true,
8
+ get: function get() {
9
+ return _main.Subscriber;
10
+ }
11
+ });
12
+ Object.defineProperty(exports, "addRovoParamsToUrl", {
13
+ enumerable: true,
14
+ get: function get() {
15
+ return _params.addRovoParamsToUrl;
16
+ }
17
+ });
18
+ Object.defineProperty(exports, "assertOnlySpecificFieldsDefined", {
19
+ enumerable: true,
20
+ get: function get() {
21
+ return _params.assertOnlySpecificFieldsDefined;
22
+ }
23
+ });
24
+ Object.defineProperty(exports, "encodeRovoParams", {
25
+ enumerable: true,
26
+ get: function get() {
27
+ return _params.encodeRovoParams;
28
+ }
29
+ });
30
+ Object.defineProperty(exports, "getListOfRovoParams", {
31
+ enumerable: true,
32
+ get: function get() {
33
+ return _params.getListOfRovoParams;
34
+ }
35
+ });
36
+ Object.defineProperty(exports, "getRovoParams", {
37
+ enumerable: true,
38
+ get: function get() {
39
+ return _params.getRovoParams;
40
+ }
41
+ });
42
+ Object.defineProperty(exports, "updatePageRovoParams", {
43
+ enumerable: true,
44
+ get: function get() {
45
+ return _params.updatePageRovoParams;
46
+ }
47
+ });
48
+ Object.defineProperty(exports, "usePublish", {
49
+ enumerable: true,
50
+ get: function get() {
51
+ return _main.usePublish;
52
+ }
53
+ });
54
+ Object.defineProperty(exports, "useSubscribe", {
55
+ enumerable: true,
56
+ get: function get() {
57
+ return _main.useSubscribe;
58
+ }
59
+ });
60
+ Object.defineProperty(exports, "useSubscribeAll", {
61
+ enumerable: true,
62
+ get: function get() {
63
+ return _main.useSubscribeAll;
64
+ }
65
+ });
66
+ var _main = require("./main");
67
+ var _params = require("./common/utils/params");
@@ -0,0 +1,169 @@
1
+ "use strict";
2
+
3
+ var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");
4
+ Object.defineProperty(exports, "__esModule", {
5
+ value: true
6
+ });
7
+ exports.useSubscribeAll = exports.useSubscribe = exports.usePublish = exports.Subscriber = void 0;
8
+ var _toConsumableArray2 = _interopRequireDefault(require("@babel/runtime/helpers/toConsumableArray"));
9
+ var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));
10
+ var _react = require("react");
11
+ function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
12
+ function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { (0, _defineProperty2.default)(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
13
+ var ignoredTriggerLatestEvents = new Set(['editor-context-payload']);
14
+ var createPubSub = function createPubSub() {
15
+ var subscribedEvents = {};
16
+ var publishQueue = {};
17
+ var wildcardEvents = [];
18
+ var subscribe = function subscribe(_ref, callback) {
19
+ var _subscribedEvents$top;
20
+ var topic = _ref.topic,
21
+ triggerLatest = _ref.triggerLatest;
22
+ var events = (_subscribedEvents$top = subscribedEvents[topic]) !== null && _subscribedEvents$top !== void 0 ? _subscribedEvents$top : [];
23
+ var subId = events.length.toString();
24
+ var subExists = events.some(function (_ref2) {
25
+ var id = _ref2.id;
26
+ return id === subId;
27
+ });
28
+
29
+ // Push to Topic stack if not already there
30
+ if (!subExists) {
31
+ subscribedEvents = _objectSpread(_objectSpread({}, subscribedEvents), {}, (0, _defineProperty2.default)({}, topic, [].concat((0, _toConsumableArray2.default)(events), [{
32
+ callback: callback,
33
+ id: subId
34
+ }])));
35
+ // If this Topic already has a published event and `triggerLatest` is true, trigger the callback then clear the publishQueue for that Topic
36
+ if (triggerLatest && !!publishQueue[topic]) {
37
+ var _payload = publishQueue[topic];
38
+ callback(_payload);
39
+ delete publishQueue[topic];
40
+ }
41
+ }
42
+ return function () {
43
+ // Remove from Topic stack
44
+ subscribedEvents = _objectSpread(_objectSpread({}, subscribedEvents), {}, (0, _defineProperty2.default)({}, topic, (subscribedEvents[topic] || []).filter(function (_ref3) {
45
+ var id = _ref3.id;
46
+ return id !== subId;
47
+ })));
48
+ };
49
+ };
50
+ var subscribeAll = function subscribeAll(callback) {
51
+ var subId = wildcardEvents.length.toString();
52
+ wildcardEvents = [].concat((0, _toConsumableArray2.default)(wildcardEvents), [{
53
+ callback: callback,
54
+ id: subId
55
+ }]);
56
+ return function () {
57
+ wildcardEvents = wildcardEvents.filter(function (_ref4) {
58
+ var id = _ref4.id;
59
+ return id !== subId;
60
+ });
61
+ };
62
+ };
63
+ var publish = function publish(topic, payload) {
64
+ /**
65
+ * Log that this Topic received a published event, regardless of whether it has subscribers or not.
66
+ * This ensures new subscribers can trigger their callback if `triggerLatest` is true, and the event hasn't already been triggered.
67
+ */
68
+ // This `ignoredTriggerLatestEvents` is a quick fix to prevent triggering the latest event for certain events
69
+ if (!ignoredTriggerLatestEvents.has(payload.type)) {
70
+ publishQueue[topic] = payload;
71
+ }
72
+
73
+ // Notify `subscribeAll` subscribers as they are Topic agnostic
74
+ wildcardEvents.forEach(function (_ref5) {
75
+ var callback = _ref5.callback;
76
+ return callback(payload);
77
+ });
78
+ var topicSubs = subscribedEvents[topic] || [];
79
+
80
+ // If there are no subscribers for this Topic, nothing to do.
81
+ if (!topicSubs.length) {
82
+ return;
83
+ }
84
+
85
+ // Notify all Topic subscribers of this event
86
+ topicSubs.forEach(function (_ref6) {
87
+ var callback = _ref6.callback;
88
+ return callback(payload);
89
+ });
90
+ };
91
+ var flushQueue = function flushQueue() {
92
+ publishQueue = {};
93
+ };
94
+ return {
95
+ subscribe: subscribe,
96
+ subscribeAll: subscribeAll,
97
+ publish: publish,
98
+ flushQueue: flushQueue
99
+ };
100
+ };
101
+ var pubSub = createPubSub();
102
+ var usePubSub = function usePubSub() {
103
+ return pubSub;
104
+ };
105
+ var useSubscribe = exports.useSubscribe = function useSubscribe(_ref7, callback) {
106
+ var topic = _ref7.topic,
107
+ triggerLatest = _ref7.triggerLatest;
108
+ var _usePubSub = usePubSub(),
109
+ subscribe = _usePubSub.subscribe;
110
+ var callbackRef = (0, _react.useRef)(callback);
111
+ callbackRef.current = callback;
112
+ (0, _react.useEffect)(function () {
113
+ var unsubscribe = subscribe({
114
+ topic: topic,
115
+ triggerLatest: triggerLatest
116
+ }, function () {
117
+ return callbackRef.current.apply(callbackRef, arguments);
118
+ });
119
+ return unsubscribe;
120
+ },
121
+ // eslint-disable-next-line react-hooks/exhaustive-deps
122
+ [topic]);
123
+ };
124
+ var useSubscribeAll = exports.useSubscribeAll = function useSubscribeAll(callback) {
125
+ var _usePubSub2 = usePubSub(),
126
+ subscribeAll = _usePubSub2.subscribeAll;
127
+ var callbackRef = (0, _react.useRef)(callback);
128
+ callbackRef.current = callback;
129
+ (0, _react.useEffect)(function () {
130
+ var unsubscribe = subscribeAll(function () {
131
+ return callbackRef.current.apply(callbackRef, arguments);
132
+ });
133
+ return unsubscribe;
134
+ },
135
+ // eslint-disable-next-line react-hooks/exhaustive-deps
136
+ []);
137
+ };
138
+ var useFlushOnUnmount = function useFlushOnUnmount() {
139
+ var active = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
140
+ var _usePubSub3 = usePubSub(),
141
+ flushQueue = _usePubSub3.flushQueue;
142
+ (0, _react.useLayoutEffect)(function () {
143
+ return function () {
144
+ if (active) {
145
+ flushQueue();
146
+ }
147
+ };
148
+ }, [active, flushQueue]);
149
+ };
150
+ var usePublish = exports.usePublish = function usePublish(topic) {
151
+ var _usePubSub4 = usePubSub(),
152
+ publish = _usePubSub4.publish;
153
+ var publishFn = (0, _react.useCallback)(function (payload) {
154
+ return publish(topic, payload);
155
+ }, [publish, topic]);
156
+ return publishFn;
157
+ };
158
+ var Subscriber = exports.Subscriber = function Subscriber(_ref8) {
159
+ var topic = _ref8.topic,
160
+ triggerLatest = _ref8.triggerLatest,
161
+ onEvent = _ref8.onEvent,
162
+ flushQueueOnUnmount = _ref8.flushQueueOnUnmount;
163
+ useSubscribe({
164
+ topic: topic,
165
+ triggerLatest: triggerLatest
166
+ }, onEvent);
167
+ useFlushOnUnmount(flushQueueOnUnmount);
168
+ return null;
169
+ };
@@ -0,0 +1,15 @@
1
+ "use strict";
2
+
3
+ Object.defineProperty(exports, "__esModule", {
4
+ value: true
5
+ });
6
+ exports.Topics = void 0;
7
+ var Topics = exports.Topics = {
8
+ AI_MATE: 'ai-mate'
9
+ };
10
+
11
+ // Not using the PayloadCore because the `data: type | undefined` is necessary
12
+ // but `| undefined` will cause `data` to be removed by PayloadCore
13
+
14
+ // Not using the PayloadCore because the `data: type | undefined` is necessary
15
+ // but `| undefined` will cause `data` to be removed by PayloadCore
@@ -0,0 +1,2 @@
1
+ export const ROVO_PARAM_PREFIX = 'rovoChat';
2
+ export const ROVO_VALID_PARAMS = ['pathway', 'agentId', 'conversationId', 'prompt', 'cloudId', 'triggerOpen'];