-
Notifications
You must be signed in to change notification settings - Fork 92
/
Copy pathruntype.ts
200 lines (174 loc) · 5.58 KB
/
runtype.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
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
import {
Result,
Union,
Union2,
Intersect,
Intersect2,
Constraint,
ConstraintCheck,
Brand,
} from './index';
import { Reflect } from './reflect';
import show from './show';
import { ValidationError } from './errors';
/**
* A runtype determines at runtime whether a value conforms to a type specification.
*/
export interface Runtype<A = unknown> {
/**
* Verifies that a value conforms to this runtype. When given a value that does
* not conform to the runtype, throws an exception.
*/
assert(x: any): asserts x is A;
/**
* Verifies that a value conforms to this runtype. If so, returns the same value,
* statically typed. Otherwise throws an exception.
*/
check(x: any): A;
/**
* Validates that a value conforms to this type, and returns a result indicating
* success or failure (does not throw).
*/
validate(x: any): Result<A>;
/**
* A type guard for this runtype.
*/
guard(x: any): x is A;
/**
* Union this Runtype with another.
*/
Or<B extends Runtype>(B: B): Union2<this, B>;
/**
* Intersect this Runtype with another.
*/
And<B extends Runtype>(B: B): Intersect2<this, B>;
/**
* Use an arbitrary constraint function to validate a runtype, and optionally
* to change its name and/or its static type.
*
* @template T - Optionally override the static type of the resulting runtype
* @param {(x: Static<this>) => boolean | string} constraint - Custom function
* that returns `true` if the constraint is satisfied, `false` or a custom
* error message if not.
* @param [options]
* @param {string} [options.name] - allows setting the name of this
* constrained runtype, which is helpful in reflection or diagnostic
* use-cases.
*/
withConstraint<T extends Static<this>, K = unknown>(
constraint: ConstraintCheck<this>,
options?: { name?: string; args?: K },
): Constraint<this, T, K>;
/**
* Helper function to convert an underlying Runtype into another static type
* via a type guard function. The static type of the runtype is inferred from
* the type of the guard function.
*
* @template T - Typically inferred from the return type of the type guard
* function, so usually not needed to specify manually.
* @param {(x: Static<this>) => x is T} guard - Type guard function (see
* https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards)
*
* @param [options]
* @param {string} [options.name] - allows setting the name of this
* constrained runtype, which is helpful in reflection or diagnostic
* use-cases.
*/
withGuard<T extends Static<this>, K = unknown>(
guard: (x: Static<this>) => x is T,
options?: { name?: string; args?: K },
): Constraint<this, T, K>;
/**
* Adds a brand to the type.
*/
withBrand<B extends string>(brand: B): Brand<B, this>;
/**
* Convert this to a Reflect, capable of introspecting the structure of the type.
*/
reflect: Reflect;
/* @internal */ _falseWitness: A;
}
/**
* Obtains the static type associated with a Runtype.
*/
export type Static<A extends Runtype> = A['_falseWitness'];
export function create<A extends Runtype>(
validate: (x: any, visited: VisitedState) => Result<Static<A>>,
A: any,
): A {
A.check = check;
A.assert = check;
A._innerValidate = (value: any, visited: VisitedState) => {
if (visited.has(value, A)) return { success: true, value };
return validate(value, visited);
};
A.validate = (value: any) => A._innerValidate(value, VisitedState());
A.guard = guard;
A.Or = Or;
A.And = And;
A.withConstraint = withConstraint;
A.withGuard = withGuard;
A.withBrand = withBrand;
A.reflect = A;
A.toString = () => `Runtype<${show(A)}>`;
return A;
function check(x: any) {
const validated = A.validate(x);
if (validated.success) {
return validated.value;
}
throw new ValidationError(validated.message, validated.key);
}
function guard(x: any): x is A {
return A.validate(x).success;
}
function Or<B extends Runtype>(B: B): Union2<A, B> {
return Union(A, B);
}
function And<B extends Runtype>(B: B): Intersect2<A, B> {
return Intersect(A, B);
}
function withConstraint<T extends Static<A>, K = unknown>(
constraint: ConstraintCheck<A>,
options?: { name?: string; args?: K },
): Constraint<A, T, K> {
return Constraint<A, T, K>(A, constraint, options);
}
function withGuard<T extends Static<A>, K = unknown>(
guard: (x: Static<A>) => x is T,
options?: { name?: string; args?: K },
): Constraint<A, T, K> {
return Constraint<A, T, K>(A, guard, options);
}
function withBrand<B extends string>(B: B): Brand<B, A> {
return Brand(B, A);
}
}
export function innerValidate<A extends Runtype>(
targetType: A,
value: any,
visited: VisitedState,
): Result<Static<A>> {
return (targetType as any)._innerValidate(value, visited);
}
type VisitedState = {
has: (candidate: object, type: Runtype) => boolean;
};
function VisitedState(): VisitedState {
const members: WeakMap<object, WeakMap<Runtype, true>> = new WeakMap();
const add = (candidate: object, type: Runtype) => {
if (candidate === null || !(typeof candidate === 'object')) return;
const typeSet = members.get(candidate);
members.set(
candidate,
typeSet ? typeSet.set(type, true) : (new WeakMap() as WeakMap<Runtype, true>).set(type, true),
);
};
const has = (candidate: object, type: Runtype) => {
const typeSet = members.get(candidate);
const value = (typeSet && typeSet.get(type)) || false;
add(candidate, type);
return value;
};
return { has };
}