UNPKG

1.98 kBtext/coffeescriptView Raw
1Container = require './container'
2normalize = require('path').normalize
3
4isRelative = (path) -> path.indexOf('.') == 0
5
6joinPaths = (arr) -> arr.join '/'
7
8getFullPath = (path, basePath) ->
9 if window?
10 if isRelative(path) && basePath != ''
11 normalize(joinPaths([ basePath, path]))
12 else
13 path
14 else if isRelative path
15 joinPaths [ basePath, path ]
16 else
17 joinPaths [ basePath, 'node_modules', path ]
18
19evaluateType = (moduleConfig, module) ->
20 return moduleConfig.type if moduleConfig.type?
21 path = moduleConfig.require || moduleConfig
22 if typeof module == 'function' && isRelative path
23 return 'factory'
24 else
25 return 'value'
26
27getPath = (moduleConfig) ->
28 if typeof moduleConfig == 'string'
29 return moduleConfig
30 else
31 return moduleConfig.require
32
33clearCache = (modules, basePath) ->
34 Object.keys(modules).forEach (key) ->
35 moduleConfig = modules[key]
36 path = getPath moduleConfig
37 fullPath = getFullPath path, basePath
38 delete require.cache[require.resolve(fullPath)]
39
40populateContainer = (di, modules, basePath) ->
41
42 Object.keys(modules).forEach (key) ->
43 moduleConfig = modules[key]
44 path = getPath moduleConfig
45 fullPath = getFullPath path, basePath
46 try
47 module = require fullPath
48 catch e
49 module = require path
50 type = evaluateType moduleConfig, module
51 if type == 'spread'
52 di.spread module
53 else
54 di[type] key, module
55
56module.exports = (options) ->
57 { config, basePath, opts, parents } = options
58 throw new TypeError('No configuration was provided for loadConfig') unless config?
59 clearCache(modules, basePath) if options?.clearCache == true
60 di = new Container opts, parents
61 modules = config.modules || {}
62 configParents = config.parents || []
63 configParents.forEach (p) ->
64 parentModules = require joinPaths [ p.nodeModule, p.configFile ]
65 populateContainer(di, parentModules.modules, p.nodeModule)
66 populateContainer(di, modules, basePath)
67
68 return di