UNPKG

2.9 kBJavaScriptView Raw
1import glob from 'glob'
2import fs from 'fs'
3import path from 'path'
4import gm from 'global-modules'
5
6process.env.NODE_ENV = process.env.NODE_ENV || 'development'
7
8const environment = (module.exports.environment = process.env.NODE_ENV)
9const packageJSON = path.resolve(process.cwd(), 'package.json')
10const json = fs.existsSync(packageJSON)
11 ? JSON.parse(fs.readFileSync(packageJSON, 'utf8')).mhy || {}
12 : {}
13export const moduleHome = path.resolve(__dirname)
14const indexTemplatePath = 'src/index.html'
15const indexTemplatePathProject = path.resolve(process.cwd(), indexTemplatePath)
16
17let indexTemplatePathMhy
18try {
19 indexTemplatePathMhy = path.resolve(gm, `@mhy/mhy/${indexTemplatePath}`)
20} catch (e) {
21 indexTemplatePathMhy = path.resolve(
22 `${
23 process.env.NPM_CONFIG_PREFIX
24 }/lib/node_modules/@mhy/mhy/${indexTemplatePath}`
25 )
26}
27
28export const indexTemplate = fs.existsSync(indexTemplatePathProject)
29 ? indexTemplatePathProject
30 : indexTemplatePathMhy
31
32export const load = (module, defaults = {}) => {
33 applyEntries(module, 'root', defaults)
34 applyEntries(module, environment, defaults)
35 applyJSON(module, 'root', defaults)
36 applyJSON(module, environment, defaults)
37 return defaults
38}
39
40export const loadProcess = module => {
41 const d = {}
42 applyEntries(module, 'root', d, path.join(__dirname, 'ecosystem', 'root', `${module}.js`))
43 applyEntries(module, environment, d, path.join(__dirname, 'ecosystem', environment, `${module}.js`))
44 return d[module]
45}
46
47const applyEntries = (module, env, o, defaultEntries = path.join(__dirname, module, env, '**/*')) => {
48 let entries = glob.sync(defaultEntries, {
49 ignore: ['index.js'],
50 nodir: true
51 })
52 for (const entry of entries) {
53 const segments = entry.split(`/${env}/`)[1].split('/')
54 let tmp = o
55 segments.forEach((v, k) => {
56 if (Array.isArray(tmp)) {
57 // Value is array, no need to do anything with it
58 } else if (k < segments.length - 1) {
59 // It's not last item
60
61 tmp[v] = tmp[v] || {}
62
63 if (Array.isArray(tmp[v])) {
64 tmp[v] = tmp = require(entry).default(tmp[v])
65 } else {
66 tmp = tmp[v]
67 }
68 } else {
69 // It's last item, require and execute default
70 v = v.replace('.js', '')
71 tmp[v] = require(entry).default(tmp[v])
72 }
73 })
74 }
75}
76
77const applyJSON = (module, env, o, j) => {
78 try {
79 j = j || json[module][env] || {}
80 } catch (e) {
81 return
82 }
83
84 for (const [k, v] of Object.entries(j)) {
85 if (!Array.isArray(v) && v instanceof Object) {
86 o[k] = o[k] || v || {}
87 applyJSON(module, env, o[k] || {}, v)
88 } else {
89 o[k] = v
90 }
91 }
92}