RuleSetCompiler.js
8.7 KB
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
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const { SyncHook } = require("tapable");
/**
* @typedef {Object} RuleCondition
* @property {string | string[]} property
* @property {boolean} matchWhenEmpty
* @property {function(string): boolean} fn
*/
/**
* @typedef {Object} Condition
* @property {boolean} matchWhenEmpty
* @property {function(string): boolean} fn
*/
/**
* @typedef {Object} CompiledRule
* @property {RuleCondition[]} conditions
* @property {(Effect|function(object): Effect[])[]} effects
* @property {CompiledRule[]=} rules
* @property {CompiledRule[]=} oneOf
*/
/**
* @typedef {Object} Effect
* @property {string} type
* @property {any} value
*/
/**
* @typedef {Object} RuleSet
* @property {Map<string, any>} references map of references in the rule set (may grow over time)
* @property {function(object): Effect[]} exec execute the rule set
*/
class RuleSetCompiler {
constructor(plugins) {
this.hooks = Object.freeze({
/** @type {SyncHook<[string, object, Set<string>, CompiledRule, Map<string, any>]>} */
rule: new SyncHook([
"path",
"rule",
"unhandledProperties",
"compiledRule",
"references"
])
});
if (plugins) {
for (const plugin of plugins) {
plugin.apply(this);
}
}
}
/**
* @param {object[]} ruleSet raw user provided rules
* @returns {RuleSet} compiled RuleSet
*/
compile(ruleSet) {
const refs = new Map();
const rules = this.compileRules("ruleSet", ruleSet, refs);
/**
* @param {object} data data passed in
* @param {CompiledRule} rule the compiled rule
* @param {Effect[]} effects an array where effects are pushed to
* @returns {boolean} true, if the rule has matched
*/
const execRule = (data, rule, effects) => {
for (const condition of rule.conditions) {
const p = condition.property;
if (Array.isArray(p)) {
let current = data;
for (const subProperty of p) {
if (
current &&
typeof current === "object" &&
Object.prototype.hasOwnProperty.call(current, subProperty)
) {
current = current[subProperty];
} else {
current = undefined;
break;
}
}
if (current !== undefined) {
if (!condition.fn(current)) return false;
continue;
}
} else if (p in data) {
const value = data[p];
if (value !== undefined) {
if (!condition.fn(value)) return false;
continue;
}
}
if (!condition.matchWhenEmpty) {
return false;
}
}
for (const effect of rule.effects) {
if (typeof effect === "function") {
const returnedEffects = effect(data);
for (const effect of returnedEffects) {
effects.push(effect);
}
} else {
effects.push(effect);
}
}
if (rule.rules) {
for (const childRule of rule.rules) {
execRule(data, childRule, effects);
}
}
if (rule.oneOf) {
for (const childRule of rule.oneOf) {
if (execRule(data, childRule, effects)) {
break;
}
}
}
return true;
};
return {
references: refs,
exec: data => {
/** @type {Effect[]} */
const effects = [];
for (const rule of rules) {
execRule(data, rule, effects);
}
return effects;
}
};
}
/**
* @param {string} path current path
* @param {object[]} rules the raw rules provided by user
* @param {Map<string, any>} refs references
* @returns {CompiledRule[]} rules
*/
compileRules(path, rules, refs) {
return rules.map((rule, i) =>
this.compileRule(`${path}[${i}]`, rule, refs)
);
}
/**
* @param {string} path current path
* @param {object} rule the raw rule provided by user
* @param {Map<string, any>} refs references
* @returns {CompiledRule} normalized and compiled rule for processing
*/
compileRule(path, rule, refs) {
const unhandledProperties = new Set(
Object.keys(rule).filter(key => rule[key] !== undefined)
);
/** @type {CompiledRule} */
const compiledRule = {
conditions: [],
effects: [],
rules: undefined,
oneOf: undefined
};
this.hooks.rule.call(path, rule, unhandledProperties, compiledRule, refs);
if (unhandledProperties.has("rules")) {
unhandledProperties.delete("rules");
const rules = rule.rules;
if (!Array.isArray(rules))
throw this.error(path, rules, "Rule.rules must be an array of rules");
compiledRule.rules = this.compileRules(`${path}.rules`, rules, refs);
}
if (unhandledProperties.has("oneOf")) {
unhandledProperties.delete("oneOf");
const oneOf = rule.oneOf;
if (!Array.isArray(oneOf))
throw this.error(path, oneOf, "Rule.oneOf must be an array of rules");
compiledRule.oneOf = this.compileRules(`${path}.oneOf`, oneOf, refs);
}
if (unhandledProperties.size > 0) {
throw this.error(
path,
rule,
`Properties ${Array.from(unhandledProperties).join(", ")} are unknown`
);
}
return compiledRule;
}
/**
* @param {string} path current path
* @param {any} condition user provided condition value
* @returns {Condition} compiled condition
*/
compileCondition(path, condition) {
if (condition === "") {
return {
matchWhenEmpty: true,
fn: str => str === ""
};
}
if (!condition) {
throw this.error(
path,
condition,
"Expected condition but got falsy value"
);
}
if (typeof condition === "string") {
return {
matchWhenEmpty: condition.length === 0,
fn: str => typeof str === "string" && str.startsWith(condition)
};
}
if (typeof condition === "function") {
try {
return {
matchWhenEmpty: condition(""),
fn: condition
};
} catch (err) {
throw this.error(
path,
condition,
"Evaluation of condition function threw error"
);
}
}
if (condition instanceof RegExp) {
return {
matchWhenEmpty: condition.test(""),
fn: v => typeof v === "string" && condition.test(v)
};
}
if (Array.isArray(condition)) {
const items = condition.map((c, i) =>
this.compileCondition(`${path}[${i}]`, c)
);
return this.combineConditionsOr(items);
}
if (typeof condition !== "object") {
throw this.error(
path,
condition,
`Unexpected ${typeof condition} when condition was expected`
);
}
const conditions = [];
for (const key of Object.keys(condition)) {
const value = condition[key];
switch (key) {
case "or":
if (value) {
if (!Array.isArray(value)) {
throw this.error(
`${path}.or`,
condition.and,
"Expected array of conditions"
);
}
conditions.push(this.compileCondition(`${path}.or`, value));
}
break;
case "and":
if (value) {
if (!Array.isArray(value)) {
throw this.error(
`${path}.and`,
condition.and,
"Expected array of conditions"
);
}
let i = 0;
for (const item of value) {
conditions.push(this.compileCondition(`${path}.and[${i}]`, item));
i++;
}
}
break;
case "not":
if (value) {
const matcher = this.compileCondition(`${path}.not`, value);
const fn = matcher.fn;
conditions.push({
matchWhenEmpty: !matcher.matchWhenEmpty,
fn: v => !fn(v)
});
}
break;
default:
throw this.error(
`${path}.${key}`,
condition[key],
`Unexpected property ${key} in condition`
);
}
}
if (conditions.length === 0) {
throw this.error(
path,
condition,
"Expected condition, but got empty thing"
);
}
return this.combineConditionsAnd(conditions);
}
/**
* @param {Condition[]} conditions some conditions
* @returns {Condition} merged condition
*/
combineConditionsOr(conditions) {
if (conditions.length === 0) {
return {
matchWhenEmpty: false,
fn: () => false
};
} else if (conditions.length === 1) {
return conditions[0];
} else {
return {
matchWhenEmpty: conditions.some(c => c.matchWhenEmpty),
fn: v => conditions.some(c => c.fn(v))
};
}
}
/**
* @param {Condition[]} conditions some conditions
* @returns {Condition} merged condition
*/
combineConditionsAnd(conditions) {
if (conditions.length === 0) {
return {
matchWhenEmpty: false,
fn: () => false
};
} else if (conditions.length === 1) {
return conditions[0];
} else {
return {
matchWhenEmpty: conditions.every(c => c.matchWhenEmpty),
fn: v => conditions.every(c => c.fn(v))
};
}
}
/**
* @param {string} path current path
* @param {any} value value at the error location
* @param {string} message message explaining the problem
* @returns {Error} an error object
*/
error(path, value, message) {
return new Error(
`Compiling RuleSet failed: ${message} (at ${path}: ${value})`
);
}
}
module.exports = RuleSetCompiler;