-
Notifications
You must be signed in to change notification settings - Fork 2
/
flowchat.js
266 lines (237 loc) · 7.41 KB
/
flowchat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
/**
* @external {Subject} http://reactivex.io/documentation/subject.html
*/
import { createStore, applyMiddleware } from 'redux';
import createSagaMiddleware, { takeEvery } from 'redux-saga';
import { call } from 'redux-saga/effects';
import { Subject } from 'rx-lite';
/**
* Flowchat chat bot class
*
* @export
* @class Flowchat
*/
export class Flowchat {
/**
* Creates an instance of Flowchat.
*
* @memberOf Flowchat
*/
constructor() {
const self = this;
this._inputSubscription = null;
this.setInput(new Subject());
this._state = new Subject();
this._output = new Subject();
this._memStore = {};
this._activators = [];
this._paths = [];
this._reducers = {};
this._sagas = {};
this._sagaMiddleware = createSagaMiddleware();
this._store = createStore(
(state) => state,
applyMiddleware(this._sagaMiddleware)
);
// Set up internal sagas.
// Send.
this._sendSaga = function* sendSaga({ data, sessionId }) {
const state = self._memStore[sessionId];
yield self._send(data, state, sessionId);
}
this._sendSagaRunner = function* sendSagaRunner() {
yield takeEvery('send', self._sendSaga);
};
this._sagaMiddleware.run(this._sendSagaRunner);
// Input.
this._inputSaga = function* inputSaga({ data, state, sessionId }) {
yield self._receive({ data, state, sessionId });
}
this._inputSagaRunner = function* inputSagaRunner() {
yield takeEvery('input', self._inputSaga);
};
this._sagaMiddleware.run(this._inputSagaRunner);
// Run.
this._runSaga = function* runSaga({ flow, data, state, sessionId }) {
yield self._run(flow, data, state, sessionId);
}
this._runSagaRunner = function* runSagaRunner() {
yield takeEvery('run', self._runSaga);
};
this._sagaMiddleware.run(this._runSagaRunner);
}
/**
* Chat bot's input Subject.
* Requires the input object passed to contain "state" and "sessionId". Use "data" for the actual
* input data.
*
* @type {Subject}
* @readonly
*
* @example <caption>Passing input to the chat bot</caption>
* bot.input.onNext({data: "Hey, chat bot!", state: {saidHello: false}, 123});
*
* @memberOf Flowchat
*/
get input() {
return this._input;
}
/**
* Chat bot's output Subject.
* Passes an object containing "data" (the actual output sent by a saga) and "sessionId" to map
* the output to the correct user.
*
* @type {Subject}
* @readonly
*
* @example <caption>Reading the bot's output and logging it to the console</caption>
* bot.output.subscribe(({ data, sessionId }) => console.log(data));
*
* @memberOf Flowchat
*/
get output() {
return this._output;
}
/**
* Conversation state Subject.
* Passes state updates for a specific sessionId.
* The update state needs to be stored and passed with future inputs to correctly maintain the
* logic.
*
* @type {Subject}
* @readonly
*
* @example <caption>Subscribe to state updates</caption>
* bot.state.subscribe(({ state, sessionId }) => {
* console.log('New state:', state, 'for', sessionId);
* });
*
* @example <caption>Simple local session (example only, not a production solution)</caption>
* let sessionId = 1; // assume the user's sessionId is 1
* const session = {}; // create a local in-memory session store
* const INITIAL_STATE = { saidHello: false }; // define initial state for each user
* session[sessionId] = Object.assign({}, INITIAL_STATE); // set a copy of the initial state for
* // the user
* // ...
* // store state updates
* bot.state.subscribe(({ state, sessionId }) => session[sessionId] = state;
*
* @memberOf Flowchat
*/
get state() {
return this._state;
}
/**
* Allows replacing the bot's input with a different Subject.
*
* @param {Subject} input the new input
*
* @memberOf Flowchat
*/
setInput(input) {
if (this._input) {
this._input.dispose();
this._inputSubscription.dispose();
}
this._input = input;
this._inputSubscription = this._input.subscribe(this._receive.bind(this));
}
/**
* Defines a new flow.
*
* @param {string} flowPath flow identifier / path
* @param {function} activator function that will determine whether the flow should run
* @param {function} reducer redux reducer for state updates
* @param {Generator} saga redux-saga saga, the main flow body
*
* @memberOf Flowchat
*/
flow(flowPath, activator, reducer, saga) {
if (arguments.length !== 4) {
throw new Error('flow requires exactly 4 arguments');
}
if (Flowchat.RESTRICTED_FLOWS.indexOf(flowPath) !== -1) {
throw new Error(`Flow ${flowPath} is restricted for internal use`);
}
this._paths.push(flowPath);
this._activators.push(activator);
this._reducers[flowPath] = reducer;
const watchableSaga = function* wSaga({ data, state, sessionId }) {
// TODO: watch this saga for end.
yield call(saga, data, state, sessionId);
}
this._sagas[flowPath] = function* flowSaga() {
yield takeEvery(flowPath, watchableSaga);
};
this._sagaMiddleware.run(this._sagas[flowPath]);
}
/**
* Allows specifying multiple flows with a map object.
*
* @param {Object} flowsMap {path: [activator, reducer, saga]}
*
* @memberof Flowchat
*/
flows(flowsMap) {
for(let key of Object.keys(flowsMap)) {
this.flow(key, ...flowsMap[key]);
}
}
_receive({ data, state, sessionId }) {
if (typeof state === 'undefined') {
throw new Error('Input state must be defined');
}
if (typeof sessionId === 'undefined') {
throw new Error('Input sessionId must be defined');
}
// Activate flows.
const activationPromises = this._activators.map(activator => activator(data, state, sessionId));
return Promise.all(activationPromises)
.then(toActivate => {
let activeIndices = toActivate
.map((activate, index) => activate ? index : undefined)
.filter(index => index !== undefined);
// TODO: for now have only one flow active at a time
activeIndices = activeIndices.length === 0 ? [] : [activeIndices[0]];
if (activeIndices.length === 0) {
this._run('*', data, state, sessionId);
} else {
activeIndices.forEach(index => {
this._run(this._paths[index], data, state, sessionId);
});
}
});
}
_run(flow, data, state, sessionId) {
const newState = this._reduce(flow, data, state, sessionId);
this._memStore[sessionId] = newState;
const runNext = () => {
this._store.dispatch({ type: flow, data, state: newState, sessionId });
}
let waitFor = [];
const wait = (promise) => {
waitFor.push(promise);
}
this._state.onNext({ state: newState, sessionId, wait });
Promise.all(waitFor).then(runNext);
}
_reduce(flow, data, state, sessionId) {
const subReducer = this._reducers[flow];
if (typeof subReducer === 'function') {
return subReducer(data, state, sessionId);
}
if (Flowchat.RESTRICTED_FLOWS.indexOf(flow) === -1) {
console.warn('Unhandled flow', flow);
this._send(null, sessionId);
}
return state;
}
_send(data, state, sessionId) {
this._output.onNext({ data, state, sessionId });
}
}
Flowchat.RESTRICTED_FLOWS = [
'send',
'input',
'run'
];