@wmfs/asl-choice-processor 1.26.0 → 2.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.
- package/.circleci/config.yml +7 -0
- package/CHANGELOG.md +19 -0
- package/README.md +115 -25
- package/lib/Input-value-cache.js +29 -24
- package/lib/compile.js +151 -0
- package/lib/index.js +24 -32
- package/lib/operators/comparisons.js +51 -0
- package/lib/operators/extensions.js +12 -0
- package/lib/operators/guards.js +24 -0
- package/lib/operators/index.js +19 -22
- package/lib/operators/type-tests.js +19 -0
- package/lib/string-matches.js +26 -0
- package/lib/timestamp.js +52 -0
- package/package.json +1 -1
- package/test/data-test-expr-tests.js +3 -4
- package/test/spec-compliance-tests.js +343 -0
- package/lib/execute-operator.js +0 -20
- package/lib/find-operator.js +0 -27
- package/lib/operators/boolean-equals.js +0 -9
- package/lib/operators/includes.js +0 -9
- package/lib/operators/is-boolean.js +0 -11
- package/lib/operators/is-null.js +0 -13
- package/lib/operators/is-present.js +0 -6
- package/lib/operators/is-string.js +0 -13
- package/lib/operators/is-undefined.js +0 -13
- package/lib/operators/numeric-equals.js +0 -9
- package/lib/operators/numeric-greater-than-equals.js +0 -9
- package/lib/operators/numeric-greater-than.js +0 -9
- package/lib/operators/numeric-less-than-equals.js +0 -9
- package/lib/operators/numeric-less-than.js +0 -9
- package/lib/operators/string-equals.js +0 -9
- package/lib/operators/string-greater-than-equals.js +0 -9
- package/lib/operators/string-greater-than.js +0 -9
- package/lib/operators/string-less-than-equals.js +0 -9
- package/lib/operators/string-less-than.js +0 -9
- package/lib/operators/timestamp-equals.js +0 -9
- package/lib/operators/timestamp-greater-than-equals.js +0 -9
- package/lib/operators/timestamp-greater-than.js +0 -9
- package/lib/operators/timestamp-less-than-equals.js +0 -9
- package/lib/operators/timestamp-less-than.js +0 -9
package/.circleci/config.yml
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
version: 2.1
|
|
2
2
|
orbs:
|
|
3
3
|
gh-app: wmfs/github-app-token@1.0.0
|
|
4
|
+
tymly: wmfs/tymly-ci@1
|
|
4
5
|
jobs:
|
|
5
6
|
unit-test:
|
|
6
7
|
docker:
|
|
@@ -74,6 +75,12 @@ jobs:
|
|
|
74
75
|
workflows:
|
|
75
76
|
test_and_release:
|
|
76
77
|
jobs:
|
|
78
|
+
- tymly/commit-check:
|
|
79
|
+
context:
|
|
80
|
+
- docker-hub-creds
|
|
81
|
+
filters:
|
|
82
|
+
branches:
|
|
83
|
+
ignore: master
|
|
77
84
|
- unit-test:
|
|
78
85
|
context:
|
|
79
86
|
- docker-hub-creds
|
package/CHANGELOG.md
CHANGED
|
@@ -1,3 +1,22 @@
|
|
|
1
|
+
## [2.0.0](https://github.com/wmfs/asl-choice-processor/compare/v1.26.0...v2.0.0) (2026-11-30)
|
|
2
|
+
|
|
3
|
+
### ⚠ BREAKING CHANGES
|
|
4
|
+
|
|
5
|
+
* Choice definitions are now validated when the processor is
|
|
6
|
+
created and invalid ones throw ChoiceDefinitionError (unknown or multiple
|
|
7
|
+
operators, wrong comparison value types such as StringEquals: null or
|
|
8
|
+
NumericEquals: "5", non-boolean Is* values, missing Next). Comparisons no
|
|
9
|
+
longer coerce types, so values of the wrong type fall through to Default.
|
|
10
|
+
|
|
11
|
+
### New Feature(s) :rocket:
|
|
12
|
+
|
|
13
|
+
* [sc-34536] asl-choice-processor: fill States Language Choice rule gaps and fix comparison bugs ([#396](https://github.com/wmfs/asl-choice-processor/issues/396)) ([5153a70](https://github.com/wmfs/asl-choice-processor/commit/5153a7056ce5478e75e6acd251bd8329e76a0495))
|
|
14
|
+
|
|
15
|
+
### CICD Configuration Changes :construction_worker:
|
|
16
|
+
|
|
17
|
+
* add tymly-ci commit check [sc-34622] ([1ca2047](https://github.com/wmfs/asl-choice-processor/commit/1ca2047507509c5316796247f94b2b1b6cbd743f))
|
|
18
|
+
* use wmfs/tymly-ci@1 [sc-34622] ([#398](https://github.com/wmfs/asl-choice-processor/issues/398)) ([de8df00](https://github.com/wmfs/asl-choice-processor/commit/de8df0052271f48ba2c054d13650f78096bdff07))
|
|
19
|
+
|
|
1
20
|
## [1.26.0](https://github.com/wmfs/asl-choice-processor/compare/v1.25.1...v1.26.0) (2026-10-30)
|
|
2
21
|
|
|
3
22
|
### Build system dependencies :hammer:
|
package/README.md
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
# asl-choice-processor
|
|
2
|
-
[](https://tymly.io/) [](https://www.npmjs.com/package/@wmfs/asl-choice-processor) [](https://circleci.com/gh/wmfs/asl-choice-processor) [](https://codecov.io/gh/wmfs/asl-choice-processor) [](https://www.codefactor.io/repository/github/wmfs/asl-choice-processor) [](https://dependabot.com/) [](http://commitizen.github.io/cz-cli/) [](https://standardjs.com) [](https://github.com/wmfs/
|
|
2
|
+
[](https://tymly.io/) [](https://www.npmjs.com/package/@wmfs/asl-choice-processor) [](https://circleci.com/gh/wmfs/asl-choice-processor) [](https://codecov.io/gh/wmfs/asl-choice-processor) [](https://www.codefactor.io/repository/github/wmfs/asl-choice-processor) [](https://dependabot.com/) [](http://commitizen.github.io/cz-cli/) [](https://standardjs.com) [](https://github.com/wmfs/asl-choice-processor/blob/master/LICENSE)
|
|
3
3
|
> For determining the next state given an Amazon States Language "Choices" definition and a set of values.
|
|
4
4
|
|
|
5
5
|
### Useful links
|
|
@@ -9,39 +9,129 @@
|
|
|
9
9
|
|
|
10
10
|
## <a name="install"></a>Install
|
|
11
11
|
```bash
|
|
12
|
-
$ npm install asl-choice-processor --save
|
|
12
|
+
$ npm install @wmfs/asl-choice-processor --save
|
|
13
13
|
```
|
|
14
14
|
|
|
15
15
|
## <a name="usage"></a>Usage
|
|
16
16
|
```javascript
|
|
17
|
-
const choiceProcessor = require('asl-choice-processor')
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
calculateNextState(
|
|
38
|
-
calculateNextState(
|
|
17
|
+
const choiceProcessor = require('@wmfs/asl-choice-processor')
|
|
18
|
+
|
|
19
|
+
const calculateNextState = choiceProcessor({
|
|
20
|
+
Choices: [
|
|
21
|
+
{
|
|
22
|
+
Variable: '$.foo',
|
|
23
|
+
NumericEquals: 1,
|
|
24
|
+
Next: 'FirstMatchState'
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
And: [
|
|
28
|
+
{ Variable: '$.foo', NumericGreaterThan: 1 },
|
|
29
|
+
{ Not: { Variable: '$.bar', StringMatches: 'test-*' } }
|
|
30
|
+
],
|
|
31
|
+
Next: 'SecondMatchState'
|
|
32
|
+
}
|
|
33
|
+
],
|
|
34
|
+
Default: 'DefaultMatchState'
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
calculateNextState({ foo: 1 }) // 'FirstMatchState'
|
|
38
|
+
calculateNextState({ foo: 2, bar: 'live' }) // 'SecondMatchState'
|
|
39
|
+
calculateNextState({ foo: 2, bar: 'test-1' }) // 'DefaultMatchState'
|
|
40
|
+
```
|
|
41
|
+
|
|
42
|
+
`choiceProcessor(definition)` validates the Choice state definition and returns a `calculateNextState(input[, context])` function. That function returns the `Next` of the first Choice Rule that matches, otherwise `Default`, otherwise `null`. (Statebox raises `States.NoChoiceMatched` when it gets `null`.)
|
|
43
|
+
|
|
44
|
+
`context` is an optional [Context Object](https://states-language.net/spec.html#context-object). Paths starting with `$$` are applied to it, and all other Paths are applied to `input`.
|
|
45
|
+
|
|
46
|
+
### Invalid definitions
|
|
47
|
+
|
|
48
|
+
Definitions are checked when `choiceProcessor()` is called, not when a state runs. An invalid one throws a `ChoiceDefinitionError` saying where the problem is:
|
|
49
|
+
|
|
50
|
+
```javascript
|
|
51
|
+
const { ChoiceDefinitionError } = require('@wmfs/asl-choice-processor')
|
|
52
|
+
|
|
53
|
+
choiceProcessor({ Choices: [{ Variable: '$.x', NumericEqual: 1, Next: 'A' }] })
|
|
54
|
+
// ChoiceDefinitionError: Invalid Choice state: Choices[0]: no comparison or boolean operator found (unrecognised: NumericEqual)
|
|
39
55
|
```
|
|
40
56
|
|
|
57
|
+
The checks include: a non-empty `Choices` array, `Next` on every top-level rule, exactly one operator per rule, `Variable` being a Path, comparison values of the right type, and `...Path` values being Paths.
|
|
58
|
+
|
|
59
|
+
## <a name="operators"></a>Supported operators
|
|
60
|
+
|
|
61
|
+
Everything in the [States Language Choice state spec](https://states-language.net/spec.html#choice-state) (JSONPath):
|
|
62
|
+
|
|
63
|
+
| Kind | Operators |
|
|
64
|
+
|---|---|
|
|
65
|
+
| Boolean | `And`, `Or`, `Not` (nested to any depth) |
|
|
66
|
+
| Numeric | `NumericEquals`, `NumericGreaterThan`, `NumericGreaterThanEquals`, `NumericLessThan`, `NumericLessThanEquals` |
|
|
67
|
+
| String | `StringEquals`, `StringGreaterThan`, `StringGreaterThanEquals`, `StringLessThan`, `StringLessThanEquals`, `StringMatches` |
|
|
68
|
+
| Timestamp | `TimestampEquals`, `TimestampGreaterThan`, `TimestampGreaterThanEquals`, `TimestampLessThan`, `TimestampLessThanEquals` |
|
|
69
|
+
| Boolean value | `BooleanEquals` |
|
|
70
|
+
| Type tests | `IsBoolean`, `IsNull`, `IsNumeric`, `IsPresent`, `IsString`, `IsTimestamp` |
|
|
71
|
+
|
|
72
|
+
Every comparison operator except `StringMatches` also has a `...Path` variant, e.g. `NumericLessThanPath: '$.limit'`, which compares against a value read from the input (or the context object, with `$$`).
|
|
73
|
+
|
|
74
|
+
### How values are compared
|
|
75
|
+
|
|
76
|
+
- **No type coercion:** a comparison only matches when both values are the right type. `NumericGreaterThan: 5` doesn't match `"10"`, `true` or `null`, and `StringEquals` doesn't match numbers.
|
|
77
|
+
- **Strings** are compared by Unicode code point.
|
|
78
|
+
- **Timestamps** must be RFC3339 with an uppercase `T` and `Z`, e.g. `2016-03-14T01:59:00Z` or `2016-03-14T02:59:00.5+01:00`. They're compared as points in time, so different offsets and trailing fractional zeros don't matter. A value that isn't a valid timestamp never matches.
|
|
79
|
+
- **`StringMatches`:** `*` matches any run of characters (including none). Use `\\*` in JSON for a literal `*`, and `\\\\` for a literal `\`.
|
|
80
|
+
- **Missing values:** a Path that matches nothing is treated as missing. Missing values fail every comparison, `IsPresent: true` and the other type tests. An explicit `null` is present.
|
|
81
|
+
- **`Next` on nested rules** (inside `And`, `Or` or `Not`) is ignored.
|
|
82
|
+
|
|
83
|
+
### Tymly extensions
|
|
84
|
+
|
|
85
|
+
These aren't part of the spec and are kept for compatibility:
|
|
86
|
+
|
|
87
|
+
| Operator | Matches when |
|
|
88
|
+
|---|---|
|
|
89
|
+
| `Includes` / `IncludesPath` | the input is an array containing the value (compared deeply) |
|
|
90
|
+
| `IsUndefined` | the opposite of `IsPresent` |
|
|
91
|
+
| `IsBooleanPath`, `IsNullPath`, `IsPresentPath`, `IsStringPath` and the other `Is...Path` operators | `...Path` variants of the type tests, where the boolean is read from the input |
|
|
92
|
+
|
|
93
|
+
### Not supported
|
|
94
|
+
|
|
95
|
+
JSONata Choice states (`QueryLanguage: "JSONata"` and `Condition` rules) are rejected with a `ChoiceDefinitionError`.
|
|
96
|
+
|
|
97
|
+
## <a name="upgrading"></a>Upgrading from 1.x
|
|
98
|
+
|
|
99
|
+
2.0 follows the States Language spec strictly:
|
|
100
|
+
|
|
101
|
+
- **Invalid definitions now fail when they're loaded**, with a `ChoiceDefinitionError`. Before, they quietly did something odd at runtime.
|
|
102
|
+
- **Comparisons no longer convert types.** A value of the wrong type no longer matches, so the execution moves on to the next rule or `Default`.
|
|
103
|
+
|
|
104
|
+
### Finding affected state machines
|
|
105
|
+
|
|
106
|
+
Because definitions are checked when `choiceProcessor()` is called, loading your state machines shows any that need fixing. With statebox, every Choice state is checked when state machines are created, e.g. when Tymly starts, and the error names the rule (e.g. `Choices[1]`). Fix the errors first, then check rules that compare values whose type may vary (see [Checking comparisons](#checking-comparisons)).
|
|
107
|
+
|
|
108
|
+
### Fixing errors
|
|
109
|
+
|
|
110
|
+
| Error message contains | 1.x | Fix |
|
|
111
|
+
|---|---|---|
|
|
112
|
+
| `StringEquals must be a string, got null` | `"StringEquals": null` | `"IsNull": true` |
|
|
113
|
+
| `NumericEquals must be a number, got "5"` | `"NumericEquals": "5"` | `"NumericEquals": 5`. If the *input* is the string `"5"`, use `"StringEquals": "5"` instead. |
|
|
114
|
+
| `must be a boolean, got "true"` | `"IsPresent": "true"` | `"IsPresent": true` |
|
|
115
|
+
| `StringEquals must be a string, got false` | `"StringEquals": false` | `"BooleanEquals": false` |
|
|
116
|
+
| `must be an RFC3339 timestamp` | `"TimestampEquals": "2026-01-01"` | `"TimestampEquals": "2026-01-01T00:00:00Z"` |
|
|
117
|
+
| `unrecognised: …` | `"NumericEqual": 1` | Fix the operator name. See [Supported operators](#operators). |
|
|
118
|
+
| `only one operator is allowed per rule` | two operators in one rule | Split them with `And` |
|
|
119
|
+
| `top-level Choice Rules must have a Next` | a rule in `Choices` with no `Next` | Add `"Next"` |
|
|
120
|
+
| `Variable must be a Path starting with "$"` | `"Variable": "type"` | `"Variable": "$.type"` |
|
|
121
|
+
| `…Path must be a Path starting with "$"` | `"NumericEqualsPath": 5` | Use `"NumericEquals": 5` for a fixed value |
|
|
122
|
+
|
|
123
|
+
Every fix in the table also works on 1.x, so you can fix definitions before you upgrade.
|
|
124
|
+
|
|
125
|
+
### <a name="checking-comparisons"></a>Checking comparisons
|
|
126
|
+
|
|
127
|
+
- **`Numeric*`:** 1.x matched numeric strings, e.g. `"10"` was greater than `5`, and `null`, `false` and `[]` matched `NumericLessThan`. Now only numbers match. Save the value as a number, convert it in `Parameters` with `States.StringToJson`, or compare it with `StringEquals`.
|
|
128
|
+
- **`Timestamp*`:** values are compared as points in time, and anything that isn't a full RFC3339 timestamp never matches. `new Date().toISOString()` always produces a valid one.
|
|
129
|
+
- **`…Path` operators:** the value read from the input must be the right type too. For example, `StringEqualsPath` no longer matches `null` to `null` or missing to missing. If a rule compares a user's email with a record's, also check the email isn't blank, e.g. `{ "Variable": "$.email", "StringGreaterThan": "" }`, because `''` still equals `''`.
|
|
130
|
+
|
|
41
131
|
## <a name="tests"></a>Tests
|
|
42
132
|
```bash
|
|
43
133
|
$ npm test
|
|
44
134
|
```
|
|
45
135
|
|
|
46
136
|
## <a name="license"></a>License
|
|
47
|
-
[MIT](https://github.com/wmfs/
|
|
137
|
+
[MIT](https://github.com/wmfs/asl-choice-processor/blob/master/LICENSE)
|
package/lib/Input-value-cache.js
CHANGED
|
@@ -2,34 +2,39 @@
|
|
|
2
2
|
|
|
3
3
|
const jp = require('jsonpath')
|
|
4
4
|
|
|
5
|
+
// Resolves (and caches) Paths for one evaluation of the Choices.
|
|
6
|
+
// Paths starting "$$" are applied to the context object (with the first "$"
|
|
7
|
+
// removed); all other Paths are applied to the input.
|
|
8
|
+
// A Path that matches nothing resolves to undefined.
|
|
5
9
|
class InputValueCache {
|
|
6
|
-
constructor () {
|
|
7
|
-
this.
|
|
10
|
+
constructor (input, context) {
|
|
11
|
+
this.input = input
|
|
12
|
+
this.context = context
|
|
13
|
+
this.cache = new Map()
|
|
8
14
|
}
|
|
9
15
|
|
|
10
|
-
get (
|
|
11
|
-
if (
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
if (Array.isArray(value)) {
|
|
20
|
-
const l = value.length
|
|
21
|
-
switch (l) {
|
|
22
|
-
case 0:
|
|
23
|
-
value = undefined
|
|
24
|
-
break
|
|
25
|
-
case 1:
|
|
26
|
-
value = value[0]
|
|
27
|
-
break
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
this.cache[inputPath] = value
|
|
16
|
+
get (path) {
|
|
17
|
+
if (this.cache.has(path)) return this.cache.get(path)
|
|
18
|
+
|
|
19
|
+
const value = path.startsWith('$$')
|
|
20
|
+
? query(this.context, path.slice(1))
|
|
21
|
+
: query(this.input, path)
|
|
22
|
+
|
|
23
|
+
this.cache.set(path, value)
|
|
31
24
|
return value
|
|
25
|
+
} // get
|
|
26
|
+
} // class InputValueCache
|
|
27
|
+
|
|
28
|
+
function query (data, path) {
|
|
29
|
+
if (path === '$') return data
|
|
30
|
+
if (data === null || typeof data !== 'object') return undefined
|
|
31
|
+
|
|
32
|
+
const values = jp.query(data, path)
|
|
33
|
+
switch (values.length) {
|
|
34
|
+
case 0: return undefined
|
|
35
|
+
case 1: return values[0]
|
|
36
|
+
default: return values
|
|
32
37
|
}
|
|
33
|
-
} //
|
|
38
|
+
} // query
|
|
34
39
|
|
|
35
40
|
module.exports = InputValueCache
|
package/lib/compile.js
ADDED
|
@@ -0,0 +1,151 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
// Validates a Choice state definition and compiles each Choice Rule into a
|
|
4
|
+
// test function, once, when the processor is created.
|
|
5
|
+
// See https://states-language.net/spec.html#choice-state
|
|
6
|
+
const operators = require('./operators')
|
|
7
|
+
const compilePattern = require('./string-matches')
|
|
8
|
+
const { parseTimestamp } = require('./timestamp')
|
|
9
|
+
const { isNumber, isString, isBoolean } = require('./operators/guards')
|
|
10
|
+
|
|
11
|
+
const BOOLEAN_OPERATORS = ['And', 'Or', 'Not']
|
|
12
|
+
|
|
13
|
+
// What each operator's comparison value must look like
|
|
14
|
+
const VALUE_CHECKS = [
|
|
15
|
+
[/^Numeric/, isNumber, 'a number'],
|
|
16
|
+
[/^String/, isString, 'a string'],
|
|
17
|
+
[/^Timestamp/, v => parseTimestamp(v) !== null, 'an RFC3339 timestamp, e.g. "2016-03-14T01:59:00Z"'],
|
|
18
|
+
[/^BooleanEquals$/, isBoolean, 'a boolean'],
|
|
19
|
+
[/^Is/, isBoolean, 'a boolean']
|
|
20
|
+
]
|
|
21
|
+
|
|
22
|
+
class ChoiceDefinitionError extends Error {
|
|
23
|
+
constructor (location, message) {
|
|
24
|
+
super(`Invalid Choice state: ${location ? location + ': ' : ''}${message}`)
|
|
25
|
+
this.name = 'ChoiceDefinitionError'
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
function compileChoices (definition) {
|
|
30
|
+
if (!isPlainObject(definition)) {
|
|
31
|
+
throw new ChoiceDefinitionError('', 'definition must be an object')
|
|
32
|
+
}
|
|
33
|
+
if (definition.QueryLanguage === 'JSONata') {
|
|
34
|
+
throw new ChoiceDefinitionError('', 'JSONata Choice states (Condition rules) are not supported')
|
|
35
|
+
}
|
|
36
|
+
const { Choices, Default } = definition
|
|
37
|
+
if (!Array.isArray(Choices) || Choices.length === 0) {
|
|
38
|
+
throw new ChoiceDefinitionError('Choices', 'must be a non-empty array')
|
|
39
|
+
}
|
|
40
|
+
if (Default !== undefined && Default !== null && !isNonEmptyString(Default)) {
|
|
41
|
+
throw new ChoiceDefinitionError('Default', 'must be a state name')
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return Choices.map((rule, i) => {
|
|
45
|
+
const location = `Choices[${i}]`
|
|
46
|
+
if (isPlainObject(rule) && !isNonEmptyString(rule.Next)) {
|
|
47
|
+
throw new ChoiceDefinitionError(location, 'top-level Choice Rules must have a Next state name')
|
|
48
|
+
}
|
|
49
|
+
return {
|
|
50
|
+
test: compileRule(rule, location),
|
|
51
|
+
next: rule.Next
|
|
52
|
+
}
|
|
53
|
+
})
|
|
54
|
+
} // compileChoices
|
|
55
|
+
|
|
56
|
+
function compileRule (rule, location) {
|
|
57
|
+
if (!isPlainObject(rule)) {
|
|
58
|
+
throw new ChoiceDefinitionError(location, 'a Choice Rule must be an object')
|
|
59
|
+
}
|
|
60
|
+
if (rule.Condition !== undefined) {
|
|
61
|
+
throw new ChoiceDefinitionError(location, 'JSONata Condition rules are not supported')
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
const ruleOperators = Object.keys(rule).filter(isOperatorName)
|
|
65
|
+
if (ruleOperators.length === 0) {
|
|
66
|
+
const unknown = Object.keys(rule).filter(k => !['Variable', 'Next', 'Comment'].includes(k))
|
|
67
|
+
const hint = unknown.length ? ` (unrecognised: ${unknown.join(', ')})` : ''
|
|
68
|
+
throw new ChoiceDefinitionError(location, `no comparison or boolean operator found${hint}`)
|
|
69
|
+
}
|
|
70
|
+
if (ruleOperators.length > 1) {
|
|
71
|
+
throw new ChoiceDefinitionError(location, `only one operator is allowed per rule, found ${ruleOperators.join(', ')}`)
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
const operatorName = ruleOperators[0]
|
|
75
|
+
const value = rule[operatorName]
|
|
76
|
+
|
|
77
|
+
switch (operatorName) {
|
|
78
|
+
case 'And':
|
|
79
|
+
case 'Or': {
|
|
80
|
+
if (!Array.isArray(value) || value.length === 0) {
|
|
81
|
+
throw new ChoiceDefinitionError(`${location}.${operatorName}`, 'must be a non-empty array of Choice Rules')
|
|
82
|
+
}
|
|
83
|
+
const tests = value.map((r, i) => compileRule(r, `${location}.${operatorName}[${i}]`))
|
|
84
|
+
return operatorName === 'And'
|
|
85
|
+
? resolver => tests.every(t => t(resolver))
|
|
86
|
+
: resolver => tests.some(t => t(resolver))
|
|
87
|
+
}
|
|
88
|
+
case 'Not': {
|
|
89
|
+
const test = compileRule(value, `${location}.Not`)
|
|
90
|
+
return resolver => !test(resolver)
|
|
91
|
+
}
|
|
92
|
+
default:
|
|
93
|
+
return compileComparison(rule, operatorName, value, location)
|
|
94
|
+
}
|
|
95
|
+
} // compileRule
|
|
96
|
+
|
|
97
|
+
function compileComparison (rule, operatorName, value, location) {
|
|
98
|
+
const variable = rule.Variable
|
|
99
|
+
if (!isPath(variable)) {
|
|
100
|
+
throw new ChoiceDefinitionError(location, `Variable must be a Path starting with "$", got ${JSON.stringify(variable)}`)
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const isPathVariant = !operators[operatorName] && operatorName.endsWith('Path')
|
|
104
|
+
const baseName = isPathVariant ? operatorName.slice(0, -'Path'.length) : operatorName
|
|
105
|
+
|
|
106
|
+
if (isPathVariant) {
|
|
107
|
+
if (!isPath(value)) {
|
|
108
|
+
throw new ChoiceDefinitionError(location, `${operatorName} must be a Path starting with "$", got ${JSON.stringify(value)}`)
|
|
109
|
+
}
|
|
110
|
+
} else {
|
|
111
|
+
checkComparisonValue(baseName, value, location)
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
const fn = baseName === 'StringMatches' ? stringMatches(value) : operators[baseName]
|
|
115
|
+
|
|
116
|
+
return isPathVariant
|
|
117
|
+
? resolver => fn(resolver.get(variable), resolver.get(value))
|
|
118
|
+
: resolver => fn(resolver.get(variable), value)
|
|
119
|
+
} // compileComparison
|
|
120
|
+
|
|
121
|
+
function stringMatches (pattern) {
|
|
122
|
+
const regex = compilePattern(pattern)
|
|
123
|
+
return input => typeof input === 'string' && regex.test(input)
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
function checkComparisonValue (operatorName, value, location) {
|
|
127
|
+
for (const [match, check, description] of VALUE_CHECKS) {
|
|
128
|
+
if (match.test(operatorName)) {
|
|
129
|
+
if (!check(value)) {
|
|
130
|
+
throw new ChoiceDefinitionError(location, `${operatorName} must be ${description}, got ${JSON.stringify(value)}`)
|
|
131
|
+
}
|
|
132
|
+
return
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
} // checkComparisonValue
|
|
136
|
+
|
|
137
|
+
function isOperatorName (key) {
|
|
138
|
+
if (BOOLEAN_OPERATORS.includes(key) || key === 'StringMatches') return true
|
|
139
|
+
if (isComparisonOperator(key)) return true
|
|
140
|
+
return key.endsWith('Path') && operators.PATH_VARIANTS.has(key.slice(0, -'Path'.length))
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function isComparisonOperator (key) {
|
|
144
|
+
return typeof operators[key] === 'function'
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
const isPath = v => typeof v === 'string' && v.startsWith('$')
|
|
148
|
+
const isNonEmptyString = v => typeof v === 'string' && v.length > 0
|
|
149
|
+
const isPlainObject = v => v !== null && typeof v === 'object' && !Array.isArray(v)
|
|
150
|
+
|
|
151
|
+
module.exports = { compileChoices, ChoiceDefinitionError }
|
package/lib/index.js
CHANGED
|
@@ -1,39 +1,31 @@
|
|
|
1
1
|
'use strict'
|
|
2
2
|
|
|
3
|
+
const { compileChoices, ChoiceDefinitionError } = require('./compile')
|
|
3
4
|
const InputValueCache = require('./Input-value-cache')
|
|
4
|
-
const executeOperator = require('./execute-operator')
|
|
5
5
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
}
|
|
25
|
-
} else if (choice.Or) {
|
|
26
|
-
if (allNextStates.includes(choice.Next)) {
|
|
27
|
-
return choice.Next
|
|
28
|
-
}
|
|
29
|
-
}
|
|
30
|
-
} else {
|
|
31
|
-
const nextState = executeOperator(choice, inputCache, values)
|
|
32
|
-
|
|
33
|
-
if (nextState) return nextState
|
|
34
|
-
}
|
|
6
|
+
// Creates a function that works out the next state for a Choice state.
|
|
7
|
+
// The definition is validated up front, and an invalid one throws a
|
|
8
|
+
// ChoiceDefinitionError.
|
|
9
|
+
//
|
|
10
|
+
// const calculateNextState = choiceProcessor({ Choices: [...], Default: '...' })
|
|
11
|
+
// calculateNextState(input[, context])
|
|
12
|
+
//
|
|
13
|
+
// Returns the Next of the first matching Choice Rule, else Default, else null.
|
|
14
|
+
// context is the optional Context Object that "$$" Paths are applied to.
|
|
15
|
+
function choiceProcessor (definition) {
|
|
16
|
+
const rules = compileChoices(definition)
|
|
17
|
+
const defaultState = definition.Default || null
|
|
18
|
+
|
|
19
|
+
return function calculateNextState (input, context) {
|
|
20
|
+
const resolver = new InputValueCache(input, context)
|
|
21
|
+
|
|
22
|
+
for (const rule of rules) {
|
|
23
|
+
if (rule.test(resolver)) return rule.next
|
|
35
24
|
}
|
|
36
25
|
|
|
37
|
-
return
|
|
26
|
+
return defaultState
|
|
38
27
|
} // calculateNextState
|
|
39
|
-
} //
|
|
28
|
+
} // choiceProcessor
|
|
29
|
+
|
|
30
|
+
module.exports = choiceProcessor
|
|
31
|
+
module.exports.ChoiceDefinitionError = ChoiceDefinitionError
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
// Data-test comparison operators. Each takes (inputValue, comparisonValue)
|
|
4
|
+
// and returns true/false. Per the spec, a comparison is false when either
|
|
5
|
+
// value is the wrong type - there is no type coercion.
|
|
6
|
+
const { isNumber, isString, isBoolean, compareStrings } = require('./guards')
|
|
7
|
+
const { parseTimestamp, compareTimestamps } = require('../timestamp')
|
|
8
|
+
|
|
9
|
+
function numeric (test) {
|
|
10
|
+
return (a, b) => isNumber(a) && isNumber(b) && test(a - b)
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
function string (test) {
|
|
14
|
+
return (a, b) => isString(a) && isString(b) && test(compareStrings(a, b))
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
function timestamp (test) {
|
|
18
|
+
return (a, b) => {
|
|
19
|
+
const ta = parseTimestamp(a)
|
|
20
|
+
const tb = parseTimestamp(b)
|
|
21
|
+
return ta !== null && tb !== null && test(compareTimestamps(ta, tb))
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
const EQ = c => c === 0
|
|
26
|
+
const GT = c => c > 0
|
|
27
|
+
const GTE = c => c >= 0
|
|
28
|
+
const LT = c => c < 0
|
|
29
|
+
const LTE = c => c <= 0
|
|
30
|
+
|
|
31
|
+
module.exports = {
|
|
32
|
+
BooleanEquals: (a, b) => isBoolean(a) && isBoolean(b) && a === b,
|
|
33
|
+
|
|
34
|
+
NumericEquals: numeric(EQ),
|
|
35
|
+
NumericGreaterThan: numeric(GT),
|
|
36
|
+
NumericGreaterThanEquals: numeric(GTE),
|
|
37
|
+
NumericLessThan: numeric(LT),
|
|
38
|
+
NumericLessThanEquals: numeric(LTE),
|
|
39
|
+
|
|
40
|
+
StringEquals: string(EQ),
|
|
41
|
+
StringGreaterThan: string(GT),
|
|
42
|
+
StringGreaterThanEquals: string(GTE),
|
|
43
|
+
StringLessThan: string(LT),
|
|
44
|
+
StringLessThanEquals: string(LTE),
|
|
45
|
+
|
|
46
|
+
TimestampEquals: timestamp(EQ),
|
|
47
|
+
TimestampGreaterThan: timestamp(GT),
|
|
48
|
+
TimestampGreaterThanEquals: timestamp(GTE),
|
|
49
|
+
TimestampLessThan: timestamp(LT),
|
|
50
|
+
TimestampLessThanEquals: timestamp(LTE)
|
|
51
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
// Tymly extensions - these operators are not part of the States Language
|
|
4
|
+
// spec, and are kept for compatibility with existing state machines.
|
|
5
|
+
const isEqual = require('lodash/isEqual')
|
|
6
|
+
|
|
7
|
+
module.exports = {
|
|
8
|
+
// Matches when the input is an array containing the comparison value
|
|
9
|
+
Includes: (value, item) => Array.isArray(value) && value.some(v => isEqual(v, item)),
|
|
10
|
+
// The opposite of IsPresent
|
|
11
|
+
IsUndefined: (value, expected) => (value === undefined) === expected
|
|
12
|
+
}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const isNumber = v => typeof v === 'number' && !Number.isNaN(v)
|
|
4
|
+
const isString = v => typeof v === 'string'
|
|
5
|
+
const isBoolean = v => typeof v === 'boolean'
|
|
6
|
+
|
|
7
|
+
// Compares strings by Unicode code point, as the spec requires. (JavaScript's
|
|
8
|
+
// < and > compare UTF-16 code units, which differ for characters outside the
|
|
9
|
+
// Basic Multilingual Plane.)
|
|
10
|
+
function compareStrings (a, b) {
|
|
11
|
+
if (a === b) return 0
|
|
12
|
+
const ia = a[Symbol.iterator]()
|
|
13
|
+
const ib = b[Symbol.iterator]()
|
|
14
|
+
for (;;) {
|
|
15
|
+
const ca = ia.next()
|
|
16
|
+
const cb = ib.next()
|
|
17
|
+
if (ca.done || cb.done) return ca.done ? (cb.done ? 0 : -1) : 1
|
|
18
|
+
const pa = ca.value.codePointAt(0)
|
|
19
|
+
const pb = cb.value.codePointAt(0)
|
|
20
|
+
if (pa !== pb) return pa < pb ? -1 : 1
|
|
21
|
+
}
|
|
22
|
+
} // compareStrings
|
|
23
|
+
|
|
24
|
+
module.exports = { isNumber, isString, isBoolean, compareStrings }
|
package/lib/operators/index.js
CHANGED
|
@@ -1,24 +1,21 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
const comparisons = require('./comparisons')
|
|
4
|
+
const typeTests = require('./type-tests')
|
|
5
|
+
const extensions = require('./extensions')
|
|
6
|
+
|
|
7
|
+
// Operators that also have a "...Path" variant, where the comparison value is
|
|
8
|
+
// read from the input. The spec defines Path variants for the comparison
|
|
9
|
+
// operators; the type tests and Includes accept them too for compatibility.
|
|
10
|
+
const PATH_VARIANTS = new Set([
|
|
11
|
+
...Object.keys(comparisons),
|
|
12
|
+
...Object.keys(typeTests),
|
|
13
|
+
...Object.keys(extensions)
|
|
14
|
+
])
|
|
15
|
+
|
|
1
16
|
module.exports = {
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
IsNull: require('./is-null'),
|
|
7
|
-
IsPresent: require('./is-present'),
|
|
8
|
-
IsString: require('./is-string'),
|
|
9
|
-
NumericEquals: require('./numeric-equals'),
|
|
10
|
-
NumericGreaterThan: require('./numeric-greater-than'),
|
|
11
|
-
NumericGreaterThanEquals: require('./numeric-greater-than-equals'),
|
|
12
|
-
NumericLessThan: require('./numeric-less-than'),
|
|
13
|
-
NumericLessThanEquals: require('./numeric-less-than-equals'),
|
|
14
|
-
StringEquals: require('./string-equals'),
|
|
15
|
-
StringGreaterThan: require('./string-greater-than'),
|
|
16
|
-
StringGreaterThanEquals: require('./string-greater-than-equals'),
|
|
17
|
-
StringLessThan: require('./string-less-than'),
|
|
18
|
-
StringLessThanEquals: require('./string-less-than-equals'),
|
|
19
|
-
TimestampEquals: require('./timestamp-equals'),
|
|
20
|
-
TimestampGreaterThan: require('./timestamp-greater-than'),
|
|
21
|
-
TimestampGreaterThanEquals: require('./timestamp-greater-than-equals'),
|
|
22
|
-
TimestampLessThan: require('./timestamp-less-than'),
|
|
23
|
-
TimestampLessThanEquals: require('./timestamp-less-than-equals')
|
|
17
|
+
...comparisons,
|
|
18
|
+
...typeTests,
|
|
19
|
+
...extensions,
|
|
20
|
+
PATH_VARIANTS
|
|
24
21
|
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
'use strict'
|
|
2
|
+
|
|
3
|
+
// Type-test operators. The comparison value is a boolean: true means "matches
|
|
4
|
+
// when the test passes", false means "matches when the test fails".
|
|
5
|
+
const { isNumber, isString, isBoolean } = require('./guards')
|
|
6
|
+
const { parseTimestamp } = require('../timestamp')
|
|
7
|
+
|
|
8
|
+
function typeTest (test) {
|
|
9
|
+
return (value, expected) => test(value) === expected
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
module.exports = {
|
|
13
|
+
IsBoolean: typeTest(isBoolean),
|
|
14
|
+
IsNull: typeTest(v => v === null),
|
|
15
|
+
IsNumeric: typeTest(isNumber),
|
|
16
|
+
IsPresent: typeTest(v => v !== undefined),
|
|
17
|
+
IsString: typeTest(isString),
|
|
18
|
+
IsTimestamp: typeTest(v => parseTimestamp(v) !== null)
|
|
19
|
+
}
|