-
Notifications
You must be signed in to change notification settings - Fork 754
Expand file tree
/
Copy pathinline_env_vars.ts
More file actions
66 lines (61 loc) · 2.11 KB
/
Copy pathinline_env_vars.ts
File metadata and controls
66 lines (61 loc) · 2.11 KB
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
import type { NodePath, types } from "@babel/core";
export function inlineEnvVarsPlugin(mode: string) {
const allowed = new Map<string, string>();
for (const [name, value] of Object.entries(Deno.env.toObject())) {
if (name.startsWith("FRESH_PUBLIC_")) {
allowed.set(name, value);
}
}
allowed.set("NODE_ENV", Deno.env.get("NODE_ENV") ?? mode);
return (
{ types: t }: { types: typeof types },
): babel.PluginObj => {
function replace(path: NodePath, name: string) {
if (allowed.has(name)) {
const value = allowed.get(name);
if (value !== undefined) {
path.replaceWith(t.stringLiteral(value));
} else {
path.replaceWith(t.identifier("undefined"));
}
}
}
return {
name: "fresh-env-var",
visitor: {
MemberExpression(path) {
// Check: process.env.*
if (
t.isMemberExpression(path.node.object) &&
t.isIdentifier(path.node.object.object) &&
path.node.object.object.name === "process" &&
t.isIdentifier(path.node.object.property) &&
path.node.object.property.name === "env" &&
t.isIdentifier(path.node.property)
) {
const name = path.node.property.name;
replace(path, name);
}
},
CallExpression(path) {
// Check: Deno.env.get("<string>")
if (
t.isMemberExpression(path.node.callee) &&
t.isMemberExpression(path.node.callee.object) &&
t.isIdentifier(path.node.callee.object.object) &&
path.node.callee.object.object.name === "Deno" &&
t.isIdentifier(path.node.callee.object.property) &&
path.node.callee.object.property.name === "env" &&
t.isIdentifier(path.node.callee.property) &&
path.node.callee.property.name === "get" &&
path.node.arguments.length > 0 &&
t.isStringLiteral(path.node.arguments[0])
) {
const name = path.node.arguments[0].value;
replace(path, name);
}
},
},
};
};
}