-
Notifications
You must be signed in to change notification settings - Fork 3
/
mod.ts
270 lines (245 loc) · 9.21 KB
/
mod.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
/**
* @fileoverview A cross-runtime environment variable management library.
* Provides functions for getting, setting, validating, and
* retrieving environment variables across Deno, Bun and Node.js
*/
import { UndefinedEnvironmentError, UnsupportedEnvironmentError, ValidationError } from "./lib/helpers.ts";
import type { EnvOptions, ValidatorFunction } from "./lib/helpers.ts";
import { simpleMerge } from "@cross/deepmerge";
import { getCurrentRuntime } from "@cross/runtime";
import { loadEnvFile } from "./lib/filehandler.ts";
export type { EnvOptions, ValidatorFunction } from "./lib/helpers.ts";
/**
* Various shims/type-stubs, declared for development/IDE purposes
*/
//shims the Bun runtime
declare const Bun: { env: Record<string, string> };
//shims Node.js process object
declare const process: {
env: Record<string, string>;
};
const defaultOptions: EnvOptions = {
throwErrors: false, // Errors are not thrown by default
logWarnings: true, // Warnings are logged to the console by default
dotEnv: {
enabled: false, // .env file loading disabled by default
path: ".env", // Standard .env file location
allowQuotes: true, // Allow quotes by default
enableExpansion: true, // Enable variable expansion by default
},
};
// Flags to control lib behavior (initialized with defaults)
let throwErrors = defaultOptions.throwErrors;
let logWarnings = defaultOptions.logWarnings;
/**
* Configures the behavior of the environment variable library.
*
* @param {EnvOptions} options - setup options.
*/
export async function setupEnv(options?: EnvOptions) {
const mergedOptions = simpleMerge(defaultOptions, options || {});
throwErrors = mergedOptions?.throwErrors || defaultOptions.throwErrors;
logWarnings = mergedOptions?.logWarnings || defaultOptions.logWarnings;
if (mergedOptions?.dotEnv?.enabled) {
const currentRuntime = getCurrentRuntime();
const envVars = await loadEnvFile(currentRuntime, mergedOptions);
switch (currentRuntime) {
case "deno":
Object.entries(envVars).forEach(([key, value]) => Deno.env.set(key, value));
break;
case "bun":
Object.entries(envVars).forEach(([key, value]) => Bun.env[key] = value);
break;
case "node":
Object.entries(envVars).forEach(([key, value]) => process.env[key] = value);
break;
}
}
}
/**
* Gets an environment variable across different supported runtimes.
*
* @param {string} key - The name of the environment variable.
* @returns {string | undefined} The value of the environment variable, or undefined if not found.
* @throws {UnsupportedEnvironmentError} if the current runtime is unsupported
* and the 'throwErrors' flag is set.
*/
export function getEnv(key: string): string | undefined {
const currentRuntime = getCurrentRuntime();
switch (currentRuntime) {
case "deno":
return Deno.env.get(key);
case "bun":
return Bun.env[key];
case "node":
return process.env[key];
default:
if (throwErrors) {
throw new UnsupportedEnvironmentError();
}
if (logWarnings) {
console.warn("Unsupported runtime");
}
return undefined;
}
}
/**
* Gets an environment variable across different supported runtimes and throws
* an error if the environment variable is not defined.
*
* @param {string} key - The name of the environment variable.
* @returns {string} The value of the environment variable, or undefined if not found.
* @throws {UndefinedEnvironmentError} if the current runtime is unsupported
* and the 'throwErrors' flag is set.
* @throws {UnsupportedEnvironmentError} if the current runtime is unsupported
* and the 'throwErrors' flag is set.
*/
export function requireEnv(key: string): string {
const value = getEnv(key);
if (!value) {
throw new UndefinedEnvironmentError(key);
}
return value;
}
/**
* Set an environment variable in supported runtimes.
*
* @param {string} key - The name of the environment variable.
* @param {string} value - The value to set for the environment variable.
* @throws {UnsupportedEnvironmentError} if the current runtime is unsupported
* and the 'throwErrors' flag is set.
*/
export function setEnv(key: string, value: string): void {
const currentRuntime = getCurrentRuntime();
switch (currentRuntime) {
case "deno":
Deno.env.set(key, value);
break;
case "bun":
Bun.env[key] = value;
break;
case "node":
process.env[key] = value;
break;
default:
if (throwErrors) {
throw new UnsupportedEnvironmentError();
}
if (logWarnings) {
console.warn("Unsupported runtime");
}
}
}
/**
* Checks if an environment variable with the given key exists in the
* current runtime
*
* @param {string} key - The name of the environment variable.
* @returns {boolean} True if the environment variable exists, false otherwise.
* @throws {UnsupportedEnvironmentError} if the current runtime is unsupported
* and the 'throwErrors' flag is set.
*/
export function hasEnv(key: string): boolean {
const currentRuntime = getCurrentRuntime();
switch (currentRuntime) {
case "deno":
return Deno.env.get(key) !== undefined;
case "bun":
return key in Bun.env;
case "node":
return process.env[key] !== undefined;
default:
if (throwErrors) {
throw new UnsupportedEnvironmentError();
}
if (logWarnings) {
console.warn("Unsupported runtime");
}
return false; // Unsupported runtime
}
}
/**
* Returns an object containing the accessible environment variables in the
* current runtime, optionally filtered by a prefix.
*
* @param {string} prefix - Optional prefix to filter environment variables by.
* @returns {Record<string, string | undefined>} An object where keys are environment variable names and values
* are their corresponding values (or undefined if not found).
* @throws {UnsupportedEnvironmentError} if the current runtime is unsupported
* and the 'throwErrors' flag is set.
*/
export function getAllEnv(prefix?: string): Record<string, string | undefined> {
const currentRuntime = getCurrentRuntime();
const envVars: Record<string, string | undefined> = {};
switch (currentRuntime) {
case "deno":
for (const key of Object.keys(Deno.env.toObject())) {
if (!key.startsWith("=") && (!prefix || key.startsWith(prefix))) {
envVars[key] = Deno.env.get(key);
}
}
break;
case "bun":
for (const key in Bun.env) {
if (!prefix || key.startsWith(prefix)) {
envVars[key] = Bun.env[key];
}
}
break;
case "node":
for (const key in process.env) {
if (!prefix || key.startsWith(prefix)) {
envVars[key] = process.env[key];
}
}
break;
default:
if (throwErrors) {
throw new UnsupportedEnvironmentError();
}
if (logWarnings) {
console.warn("Unsupported runtime");
}
}
return envVars;
}
/**
* Checks if an environment variable exists and validates it against a
* provided validation function.
*
* @param {string} key - The name of the environment variable.
* @param {ValidatorFunction} validator - A function that takes a string value and returns a boolean
* indicating whether the value is valid.
* @returns {boolean} True if the environment variable exists and passes validation, false otherwise.
*/
export function validateEnv(key: string, validator: ValidatorFunction): boolean {
const value = getEnv(key);
if (value !== undefined && validator(value)) {
return true;
} else {
return false;
}
}
/**
* Gets an environment variable across different supported runtimes,
* validating it against a provided validation function.
*
* @param {string} key - The name of the environment variable.
* @param {ValidatorFunction} validator - A function that takes a string value and returns a boolean
* indicating whether the value is valid.
* @returns The value of the environment variable if it exists and is valid.
* @throws ValidationError if the environment variable is found but fails validation.
*/
export function validateAndGetEnv(key: string, validator: ValidatorFunction): string | undefined {
const value = getEnv(key) || undefined;
if (value && !validator(value)) {
if (throwErrors) {
throw new ValidationError(`Environment variable '${key}' is invalid.`);
}
if (logWarnings) {
console.warn(`Environment variable '${key}' is invalid.`);
}
return undefined;
}
return value;
}