-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
291 lines (266 loc) · 7.65 KB
/
index.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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
// @flow
const assert = require('assert')
const Immutable = require('immutable')
// Flow types
type FSMDescription = [Node]
type FSMState = Immutable.Record<{
stateName: string,
transitioning: boolean,
inputBuffer: ?[string],
}>
type FSMOptions = {
cancelOnInput?: Boolean
}
type Node = {
_fullName?: ?string,
name: string,
action: (state: ?any, input: ?string) => ?Promise<any>,
accepts?: string | RegExp | (x: string) => Boolean,
children?: [Node],
next?: string
}
// States
const States = {
START: 'START',
END: 'END'
}
// Actions
const Actions = {
_TRANSITIONED: 'TRANSITIONED',
_TRANSITIONING: 'TRANSITIONING',
_UPDATE_BUFFER: 'UPDATE_BUFFER',
_PROCESS_BUFFER: 'PROCESS_INPUT',
HANDLE_INPUT: 'HANDLE_INPUT'
}
/**
* Constructs an FSM based on a description object.
* (see the README for more details)
*
* @param {object} description - a tree of states that define the FSM
* @param {object} options - options object
*/
function FSM (key: string, description: FSMDescription, options?: FSMOptions) {
if (!(this instanceof FSM)) return new FSM(key, description, options)
this.key = key
this.options = options || {}
this.description = description
this._buildIndex()
}
/**
* Build an index so that node lookups are fast.
*
* This method will also mutate the description object so that all nodes contain
* an expanded name property with their complete prefixes.
*/
FSM.prototype._buildIndex = function () {
this.index = {}
this.index[FSM.States.START] = {
_fullName: FSM.States.START,
name: FSM.States.START,
children: this.description
}
this.index[FSM.States.END] = {
_fullName: FSM.States.END,
name: FSM.States.END
}
const self = this
function _indexNode (prefix: ?string, node: Node) {
const newPrefix = (prefix) ? (prefix + '.' + node.name) : node.name
node._fullName = newPrefix
self.index[newPrefix] = node
const children: ?[Node] = node.children
if (children && children.length !== 0) {
children.forEach(function (child) {
_indexNode(newPrefix, child)
})
}
}
// All top-level states are successors to START.
this.description.forEach(function (node) {
_indexNode(null, node)
})
}
/**
* Create a transitioned action signifying that a transition has completed.
*/
FSM.prototype._transitioned = function (stateName) {
return {
type: FSM.Actions._TRANSITIONED,
key: this.key,
nextState: stateName
}
}
/**
* Create a transitioning action signifying that an async action is in progress.
*/
FSM.prototype._transitioning = function () {
return {
type: FSM.Actions._TRANSITIONING,
key: this.key
}
}
/**
* Buffer input for processing once the in-progress async action is complete.
*/
FSM.prototype._updateBuffer = function (buffer) {
return {
type: FSM.Actions._UPDATE_BUFFER,
key: this.key,
buffer: buffer
}
}
FSM.prototype._handleInput = function (getState, dispatch, key, input) {
function _findMatchingChild (children: [Node], input: string): ?Node {
if (!children || children.length === 0) {
return null
}
for (var i = 0; i < children.length; i++) {
const child = children[i]
const accepts = child.accepts
if (!accepts) return child
if ((typeof accepts === 'string' && accepts === input) ||
(typeof accepts === 'function' && accepts(input)) ||
(accepts instanceof RegExp && accepts.test(input))) {
return child
}
}
return null
}
const nodePath = getState()[key].stateName
const node= this.index[nodePath]
if (!nodePath) {
throw new Error('Attempting to read the value of nonexistent state machine: ' + key)
}
if (node.name === FSM.States.END) {
const warning = 'State machine is in the END state and is not processing inputs.'
return console.warn(warning)
}
// If a state doesn't specify any successors, immediately transition to END.
if (!node.children || node.children.length === 0) {
return this._transitioned(FSM.States.END)
}
// If a state specifies an invalid successor, immediately transition to END.
if (node.next && !this.index[node.next]) {
console.warn('Attempting to transition into an invalid state:', node.next)
return this._transitioned(FSM.States.END)
}
const successor = _findMatchingChild(node.children, input)
if (!successor) {
throw new Error('Could not find a valid successor state for input: ' + input)
}
var nextState = successor._fullName
if (successor.next) {
if (!this.index[successor.next]) {
console.warn('Attempting to transition into an invalid state:', successor.next)
nextState = FSM.States.END
} else {
nextState = this.index[successor.next]._fullName
}
}
const promise = successor.action(getState, dispatch, input)
if (promise) {
if (!(promise instanceof Promise)) {
throw new Error('Action must return null or a Promise.')
}
const self = this
promise.then(function (res) {
dispatch(self._transitioned(nextState))
})
promise.catch(function (err) {
// TODO: handle error?
console.error(err)
dispatch(self._transitioned(nextState))
})
return this._transitioning()
}
dispatch(this._transitioned(nextState))
}
/**
* Creates an action to send input to the FSM specified by `key`.
*
* @param {string} key - the FSM key
* @param {string} input - an input string
*/
FSM.handleInput = function (key, input) {
return {
type: FSM.Actions.HANDLE_INPUT,
key: key,
input: input
}
}
/**
* Create a Redux reducer for updating a state machine's internal state.
*/
FSM.prototype.reducer = function () {
const self = this
return function (state, action) {
if (typeof state === 'undefined') {
return self.createEmpty()
}
if (action.key !== self.key) {
return state
}
switch (action.type) {
case FSM.Actions._TRANSITIONED:
return state.set('stateName', action.nextState)
.set('transitioning', false)
case FSM.Actions._TRANSITIONING:
return state.set('transitioning', true)
case FSM.Actions._UPDATE_BUFFER:
return state.set('inputBuffer', action.buffer)
default:
return state }
}
}
/**
* Creates an empty Redux state.
*/
FSM.prototype.createEmpty = function (): FSMState {
return new Immutable.Record({
stateName: FSM.States.START,
transitioning: false,
inputBuffer: new Immutable.List()
})()
}
/**
* Creates Redux middleware that intercepts actions for processing by a state
* machine.
*/
FSM.prototype.middleware = function () {
const self = this
return store => next => action => {
if (action.key !== self.key) {
return next(action)
}
const fsmState = store.getState()[self.key]
assert(fsmState)
var nextAction = null
switch (action.type) {
case FSM.Actions.HANDLE_INPUT:
assert(action.input)
if (fsmState.transitioning) {
return next(self._updateBuffer(
fsmState.inputBuffer.unshift(action.input)))
}
nextAction = self._handleInput(
store.getState, store.dispatch, action.key, action.input)
if (nextAction) return next(nextAction)
break
case FSM.Actions._TRANSITIONED:
next(action)
const nextInput = fsmState.inputBuffer.last()
if (nextInput) {
next(self._updateBuffer(fsmState.inputBuffer.pop()))
nextAction = self._handleInput(
store.getState, store.dispatch, action.key, nextInput)
if (nextAction) return next(nextAction)
}
break
default:
return next(action)
}
}
}
FSM.States = States
FSM.Actions = Actions
module.exports = FSM