-
Notifications
You must be signed in to change notification settings - Fork 0
/
plugins.js
98 lines (87 loc) · 2.31 KB
/
plugins.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
import importFile from 'import-file';
import { resolve } from 'path';
import { isObject, isFunction } from 'lodash';
import { createLogger } from 'pot-logger';
let plugins = [];
const logger = createLogger('plugin', 'cyan');
function init(config) {
const traceNewPlugin = (PluginModule) => {
logger.trace(`"${PluginModule.name}" found`);
};
plugins = config.plugins
.map((plugin) => {
if (!plugin) {
return { enable: false };
}
if (Array.isArray(plugin) && plugin[0]) {
return {
module: plugin[0],
options: plugin[1],
};
}
if (plugin.constructor === Object && plugin.module) {
return plugin;
}
return { module: plugin };
})
.filter(({ enable = true }) => enable)
.map((plugin) => {
const { module, options = {} } = plugin;
if (isFunction(module)) {
const PluginModule = module;
traceNewPlugin(PluginModule);
return new PluginModule(options);
}
if (isObject(module)) {
traceNewPlugin(module.constructor);
return plugin;
}
try {
const PluginModule = importFile(module, {
cwd: config.baseDir,
resolvers: [resolve(__dirname, '../plugins')],
useLoader: false,
});
traceNewPlugin(PluginModule);
return new PluginModule(options, config);
}
catch (err) {
err.message += ` in "${module}" plugin`;
logger.error(err.message);
logger.error(err.stack);
}
})
.filter(Boolean);
}
const findCurrentPlugins = (phase) => plugins.filter((plugin) => plugin[phase]);
const deprecatedPhases = ['initServer', 'registerDatabase'];
const traceApplied = (plugin, phase) => {
const pluginName = plugin.constructor.name;
if (deprecatedPhases.includes(phase)) {
logger.warn(`Phase "${phase}" in "${pluginName}" has been deprecated.`);
}
logger.trace(`"${pluginName}" phase "${phase}" applied.`);
};
export default {
init,
sync(phase, ...args) {
findCurrentPlugins(phase).forEach((plugin) => {
plugin[phase](...args);
traceApplied(plugin, phase);
});
},
async sequence(phase, ...args) {
for (const plugin of findCurrentPlugins(phase)) {
await plugin[phase](...args);
traceApplied(plugin, phase);
}
},
async parallel(phase, ...args) {
return Promise.all(
findCurrentPlugins(phase).map(async (plugin) => {
await plugin[phase](...args);
traceApplied(plugin, phase);
}),
);
},
};