-
Notifications
You must be signed in to change notification settings - Fork 0
/
propertiesMatcher.ts
275 lines (256 loc) · 9.72 KB
/
propertiesMatcher.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
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
import { matches } from "../dependencies.ts";
import { ConfigSpec, ValueSpecAny } from "../types.ts";
type TypeBoolean = "boolean";
type TypeString = "string";
type TypeNumber = "number";
type TypeObject = "object";
type TypeList = "list";
type TypeEnum = "enum";
type TypePointer = "pointer";
type TypeUnion = "union";
// prettier-ignore
// deno-fmt-ignore
type GuardDefaultNullable<A, Type> =
A extends { readonly default: unknown} ? Type :
A extends { readonly nullable: true} ? Type :
A extends {readonly nullable: false} ? Type | null | undefined :
Type
// prettier-ignore
// deno-fmt-ignore
type GuardNumber<A> =
A extends {readonly type:TypeNumber} ? GuardDefaultNullable<A, number> :
unknown
// prettier-ignore
// deno-fmt-ignore
type GuardString<A> =
A extends {readonly type:TypeString} ? GuardDefaultNullable<A, string> :
unknown
// prettier-ignore
// deno-fmt-ignore
type GuardBoolean<A> =
A extends {readonly type:TypeBoolean} ? GuardDefaultNullable<A, boolean> :
unknown
// prettier-ignore
// deno-fmt-ignore
type GuardObject<A> =
A extends {readonly type: TypeObject, readonly spec: infer B} ? (
B extends Record<string, unknown> ? {readonly [K in keyof B & string]: _<GuardAll<B[K]>>} :
{_error: "Invalid Spec"}
) :
unknown
// prettier-ignore
// deno-fmt-ignore
export type GuardList<A> =
A extends {readonly type:TypeList, readonly subtype: infer B, spec?: {spec?: infer C }} ? ReadonlyArray<GuardAll<Omit<A, "type" | "spec"> & ({type: B, spec: C})>> :
// deno-lint-ignore ban-types
A extends {readonly type:TypeList, readonly subtype: infer B, spec?: {}} ? ReadonlyArray<GuardAll<Omit<A, "type" > & ({type: B})>> :
unknown
// prettier-ignore
// deno-fmt-ignore
type GuardPointer<A> =
A extends {readonly type:TypePointer} ? {_UNKNOWN: "Pointer"} :
unknown
// prettier-ignore
// deno-fmt-ignore
type GuardEnum<A> =
A extends {readonly type:TypeEnum, readonly values: ArrayLike<infer B>} ? GuardDefaultNullable<A, B> :
unknown
// prettier-ignore
// deno-fmt-ignore
type GuardUnion<A> =
A extends {readonly type:TypeUnion, readonly tag: {id: infer Id & string}, variants: infer Variants & Record<string, unknown>} ? {[K in keyof Variants]: {[keyType in Id & string]: K}&TypeFromProps<Variants[K]>}[keyof Variants] :
unknown
type _<T> = T;
export type GuardAll<A> = GuardNumber<A> &
GuardString<A> &
GuardBoolean<A> &
GuardObject<A> &
GuardList<A> &
GuardPointer<A> &
GuardUnion<A> &
GuardEnum<A>;
// prettier-ignore
// deno-fmt-ignore
export type TypeFromProps<A> =
A extends Record<string, unknown> ? {readonly [K in keyof A & string]: _<GuardAll<A[K]>>} :
unknown;
const isType = matches.shape({ type: matches.string });
const recordString = matches.dictionary([matches.string, matches.unknown]);
const matchDefault = matches.shape({ default: matches.unknown });
const matchNullable = matches.shape({ nullable: matches.literal(true) });
const matchPattern = matches.shape({ pattern: matches.string });
const rangeRegex = /(\[|\()(\*|(\d|\.)+),(\*|(\d|\.)+)(\]|\))/;
const matchRange = matches.shape({ range: matches.regex(rangeRegex) });
const matchIntegral = matches.shape({ integral: matches.literal(true) });
const matchSpec = matches.shape({ spec: recordString });
const matchSubType = matches.shape({ subtype: matches.string });
const matchUnion = matches.shape({
tag: matches.shape({ id: matches.string }),
variants: recordString,
});
const matchValues = matches.shape({
values: matches.arrayOf(matches.string),
});
function charRange(value = "") {
const split = value
.split("-")
.filter(Boolean)
.map((x) => x.charCodeAt(0));
if (split.length < 1) return null;
if (split.length === 1) return [split[0], split[0]];
return [split[0], split[1]];
}
/**
*
* @param generate.charset Pattern like "a-z" or "a-z,1-5"
* @param generate.len Length to make random variable
* @param param1
* @returns
*/
export function generateDefault(generate: { charset: string; len: number }, { random = () => Math.random() } = {}) {
const validCharSets: number[][] = generate.charset.split(",").map(charRange).filter(Array.isArray);
if (validCharSets.length === 0) throw new Error("Expecing that we have a valid charset");
const max = validCharSets.reduce((acc, x) => x.reduce((x, y) => Math.max(x, y), acc), 0);
let i = 0;
const answer: string[] = Array(generate.len);
while (i < generate.len) {
const nextValue = Math.round(random() * max);
const inRange = validCharSets.reduce(
(acc, [lower, upper]) => acc || (nextValue >= lower && nextValue <= upper),
false
);
if (!inRange) continue;
answer[i] = String.fromCharCode(nextValue);
i++;
}
return answer.join("");
}
function withPattern<A>(value: unknown) {
if (matchPattern.test(value)) return matches.regex(RegExp(value.pattern));
return matches.string;
}
export function matchNumberWithRange(range: string) {
const matched = rangeRegex.exec(range);
if (!matched) return matches.number;
const [, left, leftValue, , rightValue, , right] = matched;
return matches.number
.validate(
leftValue === "*" ? (_) => true : left === "[" ? (x) => x >= Number(leftValue) : (x) => x > Number(leftValue),
leftValue === "*" ? "any" : left === "[" ? `greaterThanOrEqualTo${leftValue}` : `greaterThan${leftValue}`
)
.validate(
rightValue === "*" ? (_) => true : right === "]" ? (x) => x <= Number(rightValue) : (x) => x < Number(rightValue),
rightValue === "*" ? "any" : right === "]" ? `lessThanOrEqualTo${rightValue}` : `lessThan${rightValue}`
);
}
function withIntegral(parser: matches.Parser<unknown, number>, value: unknown) {
if (matchIntegral.test(value)) {
return parser.validate(Number.isInteger, "isIntegral");
}
return parser;
}
function withRange(value: unknown) {
if (matchRange.test(value)) {
return matchNumberWithRange(value.range);
}
return matches.number;
}
const isGenerator = matches.shape({ charset: matches.string, len: matches.number }).test;
function defaultNullable<A>(parser: matches.Parser<unknown, A>, value: unknown) {
if (matchDefault.test(value)) {
if (isGenerator(value.default)) return parser.defaultTo(parser.unsafeCast(generateDefault(value.default)));
return parser.defaultTo(value.default);
}
if (matchNullable.test(value)) return parser.optional();
return parser;
}
/**
* ConfigSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec.
* ValueSpecAny: This is any of the values in a config spec.
*
* Use this when we want to convert a value spec any into a parser for what a config will look like
* @param value
* @returns
*/
export function guardAll<A extends ValueSpecAny>(value: A): matches.Parser<unknown, GuardAll<A>> {
if (!isType.test(value)) {
// deno-lint-ignore no-explicit-any
return matches.unknown as any;
}
switch (value.type) {
case "boolean":
// deno-lint-ignore no-explicit-any
return defaultNullable(matches.boolean, value) as any;
case "string":
// deno-lint-ignore no-explicit-any
return defaultNullable(withPattern(value), value) as any;
case "number":
return defaultNullable(
withIntegral(withRange(value), value),
value
// deno-lint-ignore no-explicit-any
) as any;
case "object":
if (matchSpec.test(value)) {
// deno-lint-ignore no-explicit-any
return defaultNullable(typeFromProps(value.spec), value) as any;
}
// deno-lint-ignore no-explicit-any
return matches.unknown as any;
case "list": {
const spec = (matchSpec.test(value) && value.spec) || {};
const rangeValidate = (matchRange.test(value) && matchNumberWithRange(value.range).test) || (() => true);
const { ...arrayOfSpec } = spec;
const subtype = matchSubType.unsafeCast(value).subtype;
return defaultNullable(
matches
// deno-lint-ignore no-explicit-any
.arrayOf(guardAll({ type: subtype, ...arrayOfSpec } as any))
.validate((x) => rangeValidate(x.length), "valid length"),
value
// deno-lint-ignore no-explicit-any
) as any;
}
case "enum":
if (matchValues.test(value)) {
return defaultNullable(
matches.literals(value.values[0], ...value.values),
value
// deno-lint-ignore no-explicit-any
) as any;
}
// deno-lint-ignore no-explicit-any
return matches.unknown as any;
case "pointer":
// deno-lint-ignore no-explicit-any
return matches.unknown as any;
case "union":
if (matchUnion.test(value)) {
return matches.some(
...Object.entries(value.variants).map(([variant, spec]) =>
matches.shape({ [value.tag.id]: matches.literal(variant) }).concat(typeFromProps(spec))
) // deno-lint-ignore no-explicit-any
) as any;
}
// deno-lint-ignore no-explicit-any
return matches.unknown as any;
}
// deno-lint-ignore no-explicit-any
return matches.unknown as any;
}
/**
* ConfigSpec: Tells the UI how to ask for information, verification, and will send the service a config in a shape via the spec.
* ValueSpecAny: This is any of the values in a config spec.
*
* Use this when we want to convert a config spec into a parser for what a config will look like
* @param valueDictionary
* @returns
*/
export function typeFromProps<A extends ConfigSpec>(valueDictionary: A): matches.Parser<unknown, TypeFromProps<A>> {
// deno-lint-ignore no-explicit-any
if (!recordString.test(valueDictionary)) return matches.unknown as any;
return matches.shape(
Object.fromEntries(Object.entries(valueDictionary).map(([key, value]) => [key, guardAll(value)]))
// deno-lint-ignore no-explicit-any
) as any;
}