This repository has been archived by the owner on Feb 17, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 9
/
mod.ts
180 lines (150 loc) · 4.35 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
import { difference, removeEmptyValues } from "./util.ts";
export interface DotenvConfig {
[key: string]: string;
}
export interface ConfigOptions {
path?: string;
export?: boolean;
safe?: boolean;
example?: string;
allowEmptyValues?: boolean;
defaults?: string;
}
export function parse(rawDotenv: string): DotenvConfig {
const env: DotenvConfig = {};
for (const line of rawDotenv.split("\n")) {
if (!isVariableStart(line)) continue;
const key = line.slice(0, line.indexOf("=")).trim();
let value = line.slice(line.indexOf("=") + 1).trim();
if (hasSingleQuotes(value)) {
value = value.slice(1, -1);
} else if (hasDoubleQuotes(value)) {
value = value.slice(1, -1);
value = expandNewlines(value);
} else value = value.trim();
env[key] = value;
}
return env;
}
const defaultConfigOptions = {
path: `.env`,
export: false,
safe: false,
example: `.env.example`,
allowEmptyValues: false,
defaults: `.env.defaults`,
};
export function config(options: ConfigOptions = {}): DotenvConfig {
const o: Required<ConfigOptions> = { ...defaultConfigOptions, ...options };
const conf = parseFile(o.path);
if (o.defaults) {
const confDefaults = parseFile(o.defaults);
for (const key in confDefaults) {
if (!(key in conf)) {
conf[key] = confDefaults[key];
}
}
}
if (o.safe) {
const confExample = parseFile(o.example);
assertSafe(conf, confExample, o.allowEmptyValues);
}
if (o.export) {
for (const key in conf) {
if (Deno.env.get(key) !== undefined) continue;
Deno.env.set(key, conf[key]);
}
}
return conf;
}
export async function configAsync(
options: ConfigOptions = {},
): Promise<DotenvConfig> {
const o: Required<ConfigOptions> = { ...defaultConfigOptions, ...options };
const conf = await parseFileAsync(o.path);
if (o.defaults) {
const confDefaults = await parseFileAsync(o.defaults);
for (const key in confDefaults) {
if (!(key in conf)) {
conf[key] = confDefaults[key];
}
}
}
if (o.safe) {
const confExample = await parseFileAsync(o.example);
assertSafe(conf, confExample, o.allowEmptyValues);
}
if (o.export) {
for (const key in conf) {
if (Deno.env.get(key) !== undefined) continue;
Deno.env.set(key, conf[key]);
}
}
return conf;
}
function parseFile(filepath: string) {
try {
return parse(new TextDecoder("utf-8").decode(Deno.readFileSync(filepath)));
} catch (e) {
if (e instanceof Deno.errors.NotFound) return {};
throw e;
}
}
async function parseFileAsync(filepath: string) {
try {
return parse(
new TextDecoder("utf-8").decode(await Deno.readFile(filepath)),
);
} catch (e) {
if (e instanceof Deno.errors.NotFound) return {};
throw e;
}
}
function isVariableStart(str: string): boolean {
return /^\s*[a-zA-Z_][a-zA-Z_0-9 ]*\s*=/.test(str);
}
function hasSingleQuotes(str: string): boolean {
return /^'([\s\S]*)'$/.test(str);
}
function hasDoubleQuotes(str: string): boolean {
return /^"([\s\S]*)"$/.test(str);
}
function expandNewlines(str: string): string {
return str.replaceAll("\\n", "\n");
}
function assertSafe(
conf: DotenvConfig,
confExample: DotenvConfig,
allowEmptyValues: boolean,
) {
const currentEnv = Deno.env.toObject();
// Not all the variables have to be defined in .env, they can be supplied externally
const confWithEnv = Object.assign({}, currentEnv, conf);
const missing = difference(
Object.keys(confExample),
// If allowEmptyValues is false, filter out empty values from configuration
Object.keys(
allowEmptyValues ? confWithEnv : removeEmptyValues(confWithEnv),
),
);
if (missing.length > 0) {
const errorMessages = [
`The following variables were defined in the example file but are not present in the environment:\n ${
missing.join(
", ",
)
}`,
`Make sure to add them to your env file.`,
!allowEmptyValues &&
`If you expect any of these variables to be empty, you can set the allowEmptyValues option to true.`,
];
throw new MissingEnvVarsError(errorMessages.filter(Boolean).join("\n\n"));
}
}
export class MissingEnvVarsError extends Error {
constructor(message?: string) {
super(message);
this.name = "MissingEnvVarsError";
Object.setPrototypeOf(this, new.target.prototype);
}
}