-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathenv.ts
168 lines (146 loc) · 4.07 KB
/
env.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
import { z } from "./z.ts";
import { colors } from "./fmt.ts";
import { table } from "./lib/simple-table.ts";
import { Prettify } from "./lib/types.ts";
import { textEncoder } from "./lib/text-encoder.ts";
/**
* Add type-safe environment variables to your CLI context.
*
* @param env - The environment variables schema.
*/
export function env<EnvSchema extends z.ZodRawShape>(
env?: EnvSchema,
): Prettify<Env<EnvSchema>> {
const envSchema = env ? z.object(env) : undefined;
function toObject() {
if (envSchema) {
try {
return envSchema.parse(Deno.env.toObject());
} catch (err) {
if (err instanceof z.ZodError) {
const envErr = new EnvError(err);
Deno.stderr.write(textEncoder.encode(envErr.message))
.then(
() => {
Deno.exit(1);
},
);
}
throw err;
}
}
return Deno.env.toObject();
}
toObject();
return {
get(key) {
const schema = envSchema?.shape[key];
if (!schema) {
return Deno.env.get(key);
}
try {
return schema.parse(Deno.env.get(key));
} catch (err) {
if (err instanceof z.ZodError) {
throw new EnvError(err);
}
throw err;
}
},
set(key, value) {
Deno.env.set(key, value);
},
delete(key) {
Deno.env.delete(key);
},
// @ts-expect-error: it's fine
toObject,
};
}
env.string = function string(message?: string) {
return z.string({ invalid_type_error: message, required_error: message });
};
env.bool = function boolean(message?: string) {
return z
.union([
z.string({ invalid_type_error: message, required_error: message }),
z.number({ invalid_type_error: message, required_error: message }),
])
.transform((s, ctx) => {
if (s === "true" || s == 1) return true;
if (s === "false" || s == 0) return false;
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: message || "Invalid boolean.",
});
});
};
env.number = function number(message = "Must be a number.") {
return z
.string({ invalid_type_error: message, required_error: message })
.transform((value) => {
return Number(value);
})
.refine((value) => {
return !isNaN(value);
}, message);
};
env.int = function int(message = "Must be an integer.") {
return z
.string({ invalid_type_error: message, required_error: message })
.transform((value) => {
return Number(value);
})
.refine((value) => {
return Number.isInteger(value);
}, message);
};
env.port = function port(
message = "Invalid port. Must be an integer between 0 and 65536.",
) {
return env.int().refine((value) => {
return value >= 0 && value <= 65536;
}, message);
};
env.url = function url(message?: string) {
return z.string().url(message);
};
env.json = function json<Schema extends z.ZodTypeAny>(
schema: Schema,
message?: string,
) {
return z.string().transform((s, ctx): z.infer<Schema> => {
try {
return schema.parse(JSON.parse(s));
} catch (_err) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: message || "Invalid JSON.",
});
}
});
};
export class EnvError extends Error {
constructor(zodError: z.ZodError) {
const issues: string[][] = zodError.issues.flatMap((issue) => {
return [["•", colors.bold(issue.path.join(".")), issue.message]];
});
let issuesTable = "";
for (const line of table(issues, { indent: 0, cellPadding: 1 })) {
issuesTable += line + "\n";
}
super(`Invalid environment variables:\n${issuesTable}`);
this.name = "EnvError";
}
}
export type Env<EnvSchema extends z.ZodRawShape> = {
get<Key extends Extract<keyof z.infer<z.ZodObject<EnvSchema>>, string>>(
key: Key,
): z.infer<z.ZodObject<EnvSchema>>[Key];
set(
key: Extract<keyof z.infer<z.ZodObject<EnvSchema>>, string>,
value: string,
): void;
delete(key: Extract<keyof z.infer<z.ZodObject<EnvSchema>>, string>): void;
toObject(): z.infer<z.ZodObject<EnvSchema>>;
};