forked from goatandsheep/react-native-dotenv
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathindex.js
More file actions
214 lines (188 loc) · 7.14 KB
/
index.js
File metadata and controls
214 lines (188 loc) · 7.14 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
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
const {readFileSync, statSync} = require('fs')
const dotenv = require('dotenv')
function parseDotenvFile(path, verbose = false) {
let content
try {
content = readFileSync(path)
} catch (error) {
// The env file does not exist.
if (verbose) {
console.error('react-native-dotenv', error)
}
return {}
}
return dotenv.parse(content)
}
function safeObjectAssign(targetObject, sourceObject, exceptions = []) {
const keys = Object.keys(targetObject)
for (let i = 0, length = keys.length; i < length; i++) {
if (targetObject[keys[i]] && sourceObject[keys[i]]) {
targetObject[keys[i]] = sourceObject[keys[i]]
}
}
for (let j = 0, length = exceptions.length; j < length; j++) {
if (sourceObject[exceptions[j]]) {
targetObject[exceptions[j]] = sourceObject[exceptions[j]]
}
}
return targetObject
}
function mtime(filePath) {
try {
return statSync(filePath).mtimeMs
} catch {
return null
}
}
module.exports = (api, options) => {
const t = api.types
this.env = {}
options = {
envName: 'APP_ENV',
moduleName: '@env',
path: '.env',
whitelist: null,
blacklist: null,
allowlist: null,
blocklist: null,
safe: false,
allowUndefined: true,
verbose: false,
...options,
}
const babelMode = process.env[options.envName] || (process.env.BABEL_ENV && process.env.BABEL_ENV !== 'undefined' && process.env.BABEL_ENV !== 'development' && process.env.BABEL_ENV) || process.env.NODE_ENV || 'development'
const localFilePath = options.path + '.local'
const modeFilePath = options.path + '.' + babelMode
const modeLocalFilePath = options.path + '.' + babelMode + '.local'
if (options.verbose) {
console.log('dotenvMode', babelMode)
}
api.cache.using(() => mtime(options.path))
api.cache.using(() => mtime(localFilePath))
api.cache.using(() => mtime(modeFilePath))
api.cache.using(() => mtime(modeLocalFilePath))
const dotenvTemporary = Object.assign({}, process.env)
if (options.safe) {
const parsed = parseDotenvFile(options.path, options.verbose)
const localParsed = parseDotenvFile(localFilePath, options.verbose)
const modeParsed = parseDotenvFile(modeFilePath, options.verbose)
const modeLocalParsed = parseDotenvFile(modeLocalFilePath, options.verbose)
this.env = safeObjectAssign(Object.assign(Object.assign(Object.assign(parsed, modeParsed), localParsed), modeLocalParsed), dotenvTemporary, ['NODE_ENV', 'BABEL_ENV', options.envName])
this.env.NODE_ENV = process.env.NODE_ENV || babelMode
} else {
dotenv.config({
path: modeLocalFilePath,
silent: true,
})
dotenv.config({
path: modeFilePath,
silent: true,
})
dotenv.config({
path: localFilePath,
silent: true,
})
dotenv.config({
path: options.path,
})
this.env = process.env
this.env = Object.assign(this.env, dotenvTemporary)
}
api.addExternalDependency(options.path)
api.addExternalDependency(localFilePath)
api.addExternalDependency(modeFilePath)
api.addExternalDependency(modeLocalFilePath)
return ({
name: 'dotenv-import',
pre() {
this.opts = {
envName: 'APP_ENV',
moduleName: '@env',
path: '.env',
whitelist: null,
blacklist: null,
allowlist: null,
blocklist: null,
safe: false,
allowUndefined: true,
verbose: false,
...this.opts,
}
const dotenvTemporary = Object.assign({}, process.env)
if (this.opts.safe) {
const parsed = parseDotenvFile(this.opts.path, this.opts.verbose)
const localParsed = parseDotenvFile(localFilePath)
const modeParsed = parseDotenvFile(modeFilePath)
const modeLocalParsed = parseDotenvFile(modeLocalFilePath)
this.env = safeObjectAssign(Object.assign(Object.assign(Object.assign(parsed, modeParsed), localParsed), modeLocalParsed), dotenvTemporary, ['NODE_ENV', 'BABEL_ENV', options.envName])
this.env.NODE_ENV = process.env.NODE_ENV || babelMode
} else {
dotenv.config({
path: modeLocalFilePath,
silent: true,
})
dotenv.config({
path: modeFilePath,
silent: true,
})
dotenv.config({
path: localFilePath,
silent: true,
})
dotenv.config({
path: options.path,
})
this.env = process.env
this.env = Object.assign(this.env, dotenvTemporary)
}
},
visitor: {
ImportDeclaration(path, {opts}) {
if (path.node.source.value === opts.moduleName) {
for (const [idx, specifier] of path.node.specifiers.entries()) {
if (specifier.type === 'ImportDefaultSpecifier') {
throw path.get('specifiers')[idx].buildCodeFrameError('Default import is not supported')
}
if (specifier.type === 'ImportNamespaceSpecifier') {
throw path.get('specifiers')[idx].buildCodeFrameError('Wildcard import is not supported')
}
if (specifier.imported && specifier.local) {
const importedId = specifier.imported.name
const localId = specifier.local.name
if (Array.isArray(opts.allowlist) && !opts.allowlist.includes(importedId)) {
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" was not present in allowlist`)
} else if (Array.isArray(opts.whitelist) && !opts.whitelist.includes(importedId)) {
console.warn('[DEPRECATION WARNING] This option is will be deprecated soon. Use allowlist instead')
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" was not whitelisted`)
}
if (Array.isArray(opts.blocklist) && opts.blocklist.includes(importedId)) {
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" was not present in blocklist`)
} else if (Array.isArray(opts.blacklist) && opts.blacklist.includes(importedId)) {
console.warn('[DEPRECATION WARNING] This option is will be deprecated soon. Use blocklist instead')
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" was blacklisted`)
}
if (!opts.allowUndefined && !Object.prototype.hasOwnProperty.call(this.env, importedId)) {
throw path.get('specifiers')[idx].buildCodeFrameError(`"${importedId}" is not defined in ${opts.path}`)
}
const binding = path.scope.getBinding(localId)
for (const refPath of binding.referencePaths) {
refPath.replaceWith(t.valueToNode(this.env[importedId]))
}
}
}
path.remove()
}
},
MemberExpression(path, {opts}) {
if (path.get('object').matchesPattern('process.env')) {
const key = path.toComputedKey()
if (t.isStringLiteral(key)) {
const importedId = key.value
const value = (opts.env && importedId in opts.env) ? opts.env[importedId] : process.env[importedId]
path.replaceWith(t.valueToNode(value))
}
}
},
},
})
}