forked from muralco/mural-schema
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompile.ts
130 lines (112 loc) · 3.24 KB
/
compile.ts
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
import {
ArrayAst,
Ast,
FunctionAst,
LiteralAst,
ObjectAst,
ObjectPropertyAst,
RegExpAst,
UnionAst,
ValueAst,
} from './ast';
import {
InvalidSchemaError,
Key,
ValidationError,
ValidationFn,
} from './types';
import {
allOf,
error,
expected,
flatten,
isPlainObject,
noExtraKeys,
oneOf,
valueIs,
} from './util';
const compileRegExp = (ast: RegExpAst): ValidationFn =>
(obj) => {
if (typeof obj !== 'string') return [expected(ast.key, 'string')];
return obj.match(ast.value)
? []
: [error(ast.key, `Value does not match: ${ast.value}`)];
};
const compileUnion = (ast: UnionAst): ValidationFn =>
oneOf(ast.key, ast.items.map(compile));
const compileFunction = (ast: FunctionAst): ValidationFn => ast.fn;
const compileValue = <T>(ast: ValueAst<T>): ValidationFn =>
valueIs(ast.key, ast.value, ast.name);
function compileObjectWithAnyProp(prop: ObjectPropertyAst): ValidationFn {
const anyFn = compile(prop.ast);
return (obj: any) => flatten(
Object
.keys(obj)
.map(p => anyFn(obj[p]).map(error => ({
...error,
// error.key is ['$any', 'a', 'b'] and we need to replace `$any` with
// the actual property name (p). For example { x: { a: { b: 1 } } }
// should error with ['x', 'a', 'b']
key: [p, ...error.key.slice(1)],
}))),
);
}
function compileObject(ast: ObjectAst): ValidationFn {
const anyProp = ast.properties.find(p => p.anyKey);
const fns: ValidationFn[] = ast.properties
.filter(p => p !== anyProp)
.map(p => ({ ...p, fn: compile(p.ast) }))
.map(p => (obj: any) => p.fn(obj[p.objectKey]));
const allFns = ast.strict
? [...fns, noExtraKeys(ast.key, ast.properties.map(p => p.objectKey))]
: fns;
const allFnsWithAny = anyProp
? [...allFns, compileObjectWithAnyProp(anyProp)]
: allFns;
const fn = allOf(allFnsWithAny);
return obj =>
isPlainObject(obj)
? fn(obj)
: [expected(ast.key, 'object')];
}
const addIndex = (key: Key, index: number) =>
(e: ValidationError): ValidationError => ({
...e,
key: [
...key,
index,
...e.key.slice(key.length),
],
});
function compileArray(ast: ArrayAst): ValidationFn {
const fn = compile(ast.item);
return (obj) => {
if (!Array.isArray(obj)) return [expected(ast.key, 'array')];
const errors = obj.map(
(v, i) => fn(v).map(addIndex(ast.key, i)),
);
return flatten(errors);
};
}
const quoteLiteral = (value: LiteralAst['value']): string =>
typeof value === 'string'
? `'${value}'`
: `${value}`;
const compileLiteral = (ast: LiteralAst): ValidationFn =>
obj =>
obj === ast.value
? []
: [expected(ast.key, quoteLiteral(ast.value))];
// === Global =============================================================== //
export function compile(ast: Ast): ValidationFn {
switch (ast.type) {
case 'array': return compileArray(ast);
case 'function': return compileFunction(ast);
case 'literal': return compileLiteral(ast);
case 'object': return compileObject(ast);
case 'regexp': return compileRegExp(ast);
case 'union': return compileUnion(ast);
case 'value': return compileValue(ast);
}
throw new InvalidSchemaError(`Unknown AST: ${JSON.stringify(ast)}`);
}