-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.ts
262 lines (253 loc) · 10.1 KB
/
index.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
import { URL } from 'url';
export const Url = Symbol.for('Url');
export const IpAddress = Symbol.for('IpAddress');
export const Nothing = Symbol.for('Nothing');
export type IpAddressMask = `${number}.${number}.${number}.${number}`;
export interface TypeEnvyArgument {
key: string;
keyExists: boolean;
value?: string;
error?: (error: string | Error) => void;
warn?: (warning: string | Error) => void;
toString: () => string;
}
export type VariablesType<T> = {
[P in keyof T]: T[P] extends (arg: TypeEnvyArgument) => infer R
? R
: T[P] extends readonly (infer U)[]
? U extends StringConstructor
? string
: U extends BooleanConstructor
? boolean
: U extends NumberConstructor
? number
: U extends symbol
? U
: U extends typeof Nothing
? typeof Nothing
: U
: T[P] extends typeof Url
? URL
: T[P] extends typeof IpAddress
? IpAddressMask
: never;
};
/* eslint-disable @typescript-eslint/no-explicit-any */
export type VariableTemplate =
| {
[key: string]:
| ((arg: TypeEnvyArgument) => any)
| typeof Url
| typeof IpAddress
| string
| StringConstructor
| BooleanConstructor
| NumberConstructor
| readonly (
| typeof Nothing
| string
| number
| boolean
| StringConstructor
| BooleanConstructor
| NumberConstructor
| undefined
)[]
| never;
}
| never;
function toUnderscored(s: string): string {
return s.includes('_') ? s : s === s.toUpperCase() ? s : s.replace(/(.)([A-Z]+)/g, '$1_$2').toUpperCase();
}
function Requires<I extends Record<string, unknown>, Variable extends VariableTemplate>(
input: I,
variable: Variable,
validator?: (variable: VariablesType<Variable>) => boolean,
) {
const output = Object.keys(variable).reduce(
(a, c) => ({ ...a, [c]: input[c] || input[toUnderscored(c)] }),
{},
) as VariablesType<Variable>;
if (validator) {
const valid = validator(output);
if (!valid) {
throw new Error('Invalid Environment Variables');
}
} else {
Object.keys(variable).forEach((key) => {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
const validatePrimitive = (key: string, value: any, type: any): unknown => {
if (type === String) {
const ok = value === String(value); // ?
if (!ok) {
throw new Error(
`Could not safely convert required value ${key} from ${value || '<empty>'} to String.`,
);
}
return value;
} else if (type === Boolean) {
const isTrue = ['yes', 'true', 'on', 'y', '1'].indexOf(value?.toLowerCase()) >= 0;
const isFalse = ['no', 'false', 'off', 'n', '0'].indexOf(value?.toLowerCase()) >= 0;
if (!isTrue && !isFalse) {
throw new Error(
`Could not safely convert required value ${key} from ${value || '<empty>'} to Boolean.`,
);
}
return isTrue;
} else if (type === Number) {
const ok = !isNaN(parseFloat(value?.toString()));
if (!ok) {
throw new Error(
`Could not safely convert required value ${key} from ${value || '<empty>'} to Number.`,
);
}
return parseFloat(value as string);
} else if (type === Url) {
try {
const url = new URL(value);
return url;
} catch (e) {
throw new Error(
`Could not safely convert required value ${key} from ${value || '<empty>'} to URL.`,
);
}
} else if (type === IpAddress) {
const ok = /^(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(
value,
);
if (!ok) {
throw new Error(
`Could not safely convert required value ${key} from ${value || '<empty>'} to IpAddress.`,
);
}
return value.toString();
} else if (type === Nothing) {
[type, value]; // ?
if (value) {
throw new Error(Nothing.toString());
}
return Nothing;
} else if (type === undefined) {
[type, value]; // ?
if (value) {
throw new Error('undefined');
}
return undefined;
} else if (typeof type === 'function') {
try {
const ok = (type as (x: TypeEnvyArgument) => boolean)({
key: key,
keyExists: value !== undefined,
value: value,
toString: (): string => (value ? value : 'undefined').toString(),
// TODO: error/warning callback
});
return ok;
} catch (e) {
throw new Error(e instanceof Error ? e.message : (e as { toString: () => string }).toString());
}
} else {
if (typeof type === 'string' || typeof type === 'boolean' || typeof type === 'number') {
const ok = type.toString() === value?.toString();
if (!ok) {
throw new Error(
`Could not safely convert required value ${key} from ${value || '<empty>'} to ${type}`,
);
}
return validatePrimitive(
key,
value,
{
string: String,
boolean: Boolean,
number: Number,
bigint: BigInt,
undefined: undefined,
function: Function,
object: Object,
symbol: Symbol,
}[typeof type],
);
}
}
};
const realValue = output[key];
const keyType = variable[key];
if (Array.isArray(keyType)) {
const ok = keyType.map((otherType) => {
try {
return validatePrimitive(key, realValue, otherType);
} catch (e) {
return e;
}
});
if (ok.find((e) => !(e instanceof Error))) {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(output as any)[key] = ok.find((e) => !(e instanceof Error));
} else {
const firstError = ok.find(
(e) => e instanceof Error && e.message !== Nothing.toString() && e.message !== 'undefined',
);
if (firstError) {
throw firstError;
}
}
} else {
// eslint-disable-next-line @typescript-eslint/no-explicit-any
(output as any)[key] = validatePrimitive(key, realValue, keyType);
}
});
}
return output;
}
interface TypeEnvyTypes {
IpAddress: typeof IpAddress;
Url: typeof Url;
Nothing: typeof Nothing;
}
export function TypeEnvy<R extends VariableTemplate>(types: ((types: TypeEnvyTypes) => R) | R): VariablesType<R> {
return fromAny(process.env).toType(types);
}
export function fromAny<T extends Record<string, unknown>>(
value: T,
): { toType: <R extends VariableTemplate>(types: ((types: TypeEnvyTypes) => R) | R) => VariablesType<R> } {
return {
toType: <R extends VariableTemplate>(types: ((types: TypeEnvyTypes) => R) | R): VariablesType<R> => {
return Requires(
value,
typeof types === 'function'
? types({
IpAddress,
Url,
Nothing,
})
: types,
);
},
};
}
export const Common = {
not: (f: (...args: any[]) => boolean) => (x: any) => !f(x),
StringOr: (s: string) => (x: TypeEnvyArgument) => x.value || s,
StringOrError: (err: string) => (x: TypeEnvyArgument) => {
if (x.value) {
return x.value;
} else {
throw {
name: x.key,
error: err,
};
}
},
NumberOr: (s: number) => (x: TypeEnvyArgument) => [Number(x.value), s].find(Common.not(isNaN))!,
TrueOr: (s: boolean) => (x: TypeEnvyArgument) =>
x.value ? ['1', 'yes', 'true', 'on'].includes(x.value.toLowerCase()) : s,
FalseOr: (s: boolean) => (x: TypeEnvyArgument) =>
x.value ? ['0', 'no', 'false', 'off'].includes(x.value.toLowerCase()) : s,
ConstantString: (s: string) => (x: TypeEnvyArgument) => {
if (x.value && s !== x.value) {
throw `"${x.value}" does not equal expected constant "${s}" for ${x.key}`;
}
return s;
},
};