UNPKG

1.54 kBJavaScriptView Raw
1const resolveFrom = require('resolve-from')
2const defaultAddPrefix = require('./add-prefix')
3
4function resolve(name, prefix, addPrefix, cwd) {
5 if (typeof name !== 'string') {
6 return name
7 }
8
9 const prefixed = addPrefix(name, prefix)
10 if (prefixed === true) {
11 name = defaultAddPrefix(name, prefix)
12 } else if (typeof prefixed === 'string') {
13 name = prefixed
14 }
15
16 return require(resolveFrom(cwd, name))
17}
18
19function defaultCaller(resolved, options) {
20 return typeof resolved === 'object'
21 ? resolve.apply(options)
22 : resolved(options)
23}
24
25module.exports = function(
26 config,
27 {
28 caller = defaultCaller,
29 cwd = process.cwd(),
30 isResolved = original => original && typeof original !== 'string',
31 isCalled = isResolved,
32 prefix,
33 addPrefix = () => true
34 } = {}
35) {
36 if (!config || typeof config !== 'object') {
37 return null
38 }
39
40 if (!Array.isArray(config)) {
41 config = Object.keys(config).reduce((res, name) => {
42 res.push([name, config[name]])
43 return res
44 }, [])
45 }
46
47 return config.map(item => {
48 // Ensure it's an array
49 if (!Array.isArray(item)) item = [item]
50
51 // If it's function we consider it as already executed
52 // Since if you can provide it as a function for example
53 // You can directly call it with the options
54 // Instead of using `[resolved, options]`
55 const resolved = isResolved(item[0])
56 ? item[0]
57 : resolve(item[0], prefix, addPrefix, cwd)
58 return isCalled(item[0], resolved) ? resolved : caller(resolved, item[1])
59 })
60}