-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathconfigent.js
209 lines (184 loc) · 8.04 KB
/
configent.js
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
const { existsSync, readdirSync, readFileSync } = require('fs')
const { resolve, dirname } = require('path')
let instances = {}
let detectedFromDefaults = {}
const _defaults = {
name: '',
cacheConfig: true,
cacheDetectedDefaults: true,
useDotEnv: true,
useEnv: true,
usePackageConfig: true,
useConfig: true,
useDetectDefaults: false,
detectDefaultsConfigPath: 'configs',
sanitizeEnvValue: str => str.replace(/[-_][a-z]/g, str => str.substr(1).toUpperCase())
}
/**
* @template {Object.<string, any>} options
* @param {options} defaults default options
* @param {Partial<options>=} input provided input
* @param {object} [configentOptions] configent options
* @param {string=} [configentOptions.name = ''] name to use for configs. If left empty, name from package.json is used
* @param {boolean=} [configentOptions.cacheConfig = true] calling configent twice with same parameters will return the same instance
* @param {boolean=} [configentOptions.cacheDetectedDefaults = true] calling configent twice from the same module will return the same defaults
* @param {boolean=} [configentOptions.useDotEnv = true] include config from .env files
* @param {boolean=} [configentOptions.useEnv = true] include config from process.env
* @param {boolean=} [configentOptions.usePackageConfig = true] include config from package.json
* @param {boolean=} [configentOptions.useConfig = true] include config from [name].config.js
* @param {boolean=} [configentOptions.useDetectDefaults = true] detect defaults from context (package.json and file stucture)
* @param {string=} [configentOptions.detectDefaultsConfigPath = 'configs'] detect defaults from context (package.json and file stucture)
* @param {function=} [configentOptions.sanitizeEnvValue = str => str.replace(/[-_][a-z]/g, str => str.substr(1).toUpperCase())] sanitize environment values. Convert snake_case to camelCase by default.
* @param {NodeModule} [configentOptions.module] required if multiple modules are using configent
* @returns {options}
*/
function configent(defaults, input = {}, configentOptions) {
configentOptions = { ..._defaults, ...configentOptions }
const getParentModuleDir = createGetParentModuleDir(configentOptions)
configentOptions.name = configentOptions.name || require(resolve(getParentModuleDir(), 'package.json')).name
const {
name,
cacheConfig,
cacheDetectedDefaults,
useDotEnv,
sanitizeEnvValue,
useConfig,
useEnv,
usePackageConfig,
useDetectDefaults,
detectDefaultsConfigPath
} = configentOptions
const upperCaseRE = new RegExp(`^${name.toUpperCase()}_`)
return buildConfig()
function buildConfig() {
delete (configentOptions.module)
const hash = JSON.stringify({ name, defaults, input, configentOptions })
if (!instances[hash] || !cacheConfig) {
instances[hash] = {
...defaults,
...useDetectDefaults && getDetectDefaults(),
...usePackageConfig && getPackageConfig(),
...useConfig && getUserConfig(),
...useEnv && getEnvConfig(),
...input
}
}
return instances[hash]
}
function getEnvConfig() {
let env = process.env
if (useDotEnv) {
try {
const envPath = resolve(process.cwd(), '.env')
const envContents = readFileSync(envPath, 'utf8')
env = {
...require('dotenv').parse(envContents),
...env
}
} catch (e) {
// ignore
}
}
const entries = Object.entries(env)
.filter(([key]) => key.match(upperCaseRE))
.map(parseField)
if (entries.length)
return entries.reduce((prev, { key, value }) => ({ ...prev, [key]: value }), {})
function parseField([key, value]) {
const shouldParseValue = k => typeof defaults[k] === 'object'
key = sanitizeEnvValue(key.replace(upperCaseRE, ''))
value = shouldParseValue(key) ? JSON.parse(value) : value
return { key, value }
}
}
function getUserConfig() {
const path_js = resolve(process.cwd(), `${name}.config.js`)
const path_cjs = resolve(process.cwd(), `${name}.config.cjs`)
if (existsSync(path_js)) {
return require(path_js);
} else if (existsSync(path_cjs)) {
return require(path_cjs);
} else {
return {};
}
}
function getPackageConfig() {
const path = resolve(process.cwd(), 'package.json')
return existsSync(path) && require(path)[name]
}
function getDetectDefaults() {
const hash = JSON.stringify({ name, path: module['parent'].path })
// we only want to detect the defaults for any given module once
if (!detectedFromDefaults[hash] || !cacheDetectedDefaults) {
const pkgjson = { dependencies: {}, devDependencies: {} };
if (existsSync('package.json')) {
Object.assign(pkgjson, require(resolve(process.cwd(), 'package.json')));
}
Object.assign(pkgjson.dependencies, pkgjson.devDependencies)
const unsortedConfigTemplates = readdirSync(resolve(getParentModuleDir(), detectDefaultsConfigPath))
.map(file => ({
file,
...require(resolve(getParentModuleDir(), detectDefaultsConfigPath, file))
}))
const configTemplates = sortBySupersedings(unsortedConfigTemplates)
.filter(configTemplate => configTemplate.condition({ pkgjson }))
.reverse()
if (configTemplates) {
if (configTemplates.length > 1) // we don't care about the default template
console.log(`[%s] detected defaults from %s`, name, configTemplates.filter(template => template.file !== 'default.config.js').map(template => template.name).join(', '))
detectedFromDefaults[hash] = Object.assign({}, ...configTemplates.map(template => template.config({ pkgjson })))
}
}
return detectedFromDefaults[hash]
}
}
module.exports = { configent }
function sortBySupersedings(arr) {
// clone the array
arr = [...arr]
const sorted = []
while (arr.length) {
let foundMatch = false
const supersedings = [].concat(...arr.map(entry => entry.supersedes || []))
for (const [index, entry] of arr.entries()) {
const file = entry.file.replace(/\.config\.js/, '')
if (!supersedings.includes(file)) {
sorted.push(...arr.splice(index, 1))
foundMatch = true
break
}
}
// each iteration should find and pluck one match
if (!foundMatch) throw Error('Looks like you have circular supersedings \n' + arr.map(f => `${f.file} supersedes ${f.supersedes}`).join('\n'))
}
return sorted
}
function createGetParentModuleDir(options) {
const { module } = options
let parentModuleDir
return () => {
parentModuleDir = parentModuleDir || _getParentModuleDir(module && module.path)
return parentModuleDir
}
}
// walk through parents till we find a package.json
function _getParentModuleDir(path) {
if (!path) {
const modules = Object.values(require.cache)
/** @ts-ignore */
.filter((m) => m.children.includes(module))
if (modules.length >= 2) missingModuleError(modules)
else path = modules[0].path
}
return (existsSync(resolve(path, 'package.json'))) ?
path : _getParentModuleDir(dirname(path))
}
function missingModuleError(modules) {
const paths = modules.map(m => _getParentModuleDir(m.path))
throw new Error([
`if multiple packages are using configent, they all need to provide the module.`,
`Packages using configent: `,
...paths.map(p => '- ' + p),
`Updating the packages may fix the problem.`, ''
].join('\n'))
}