/
plugins-loader.ts
80 lines (73 loc) 路 2.62 KB
/
plugins-loader.ts
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
import { join } from 'path';
import * as ts from 'typescript';
import { CLI_ERRORS } from '../ui';
const PLUGIN_ENTRY_FILENAME = 'plugin';
type Transformer = ts.TransformerFactory<any> | ts.CustomTransformerFactory;
type PluginEntry = string | PluginAndOptions;
interface PluginAndOptions {
name: 'string';
options: Record<string, any>;
}
export interface NestCompilerPlugin {
before?: (options?: Record<string, any>, program?: ts.Program) => Transformer;
after?: (options?: Record<string, any>, program?: ts.Program) => Transformer;
afterDeclarations?: (
options?: Record<string, any>,
program?: ts.Program,
) => Transformer;
}
export interface MultiNestCompilerPlugins {
beforeHooks: Array<(program?: ts.Program) => Transformer>;
afterHooks: Array<(program?: ts.Program) => Transformer>;
afterDeclarationsHooks: Array<(program?: ts.Program) => Transformer>;
}
export class PluginsLoader {
public load(plugins: PluginEntry[] = []): MultiNestCompilerPlugins {
const pluginNames = plugins.map((entry) =>
entry ? (entry as PluginAndOptions)?.name : (entry as string)
);
const nodeModulePaths = [
join(process.cwd(), 'node_modules'),
...module.paths,
];
const pluginRefs: NestCompilerPlugin[] = pluginNames.map((item) => {
try {
try {
const binaryPath = require.resolve(
join(item, PLUGIN_ENTRY_FILENAME),
{
paths: nodeModulePaths,
},
);
return require(binaryPath);
} catch {}
const binaryPath = require.resolve(item, { paths: nodeModulePaths });
return require(binaryPath);
} catch (e) {
throw new Error(`"${item}" plugin could not be found!`);
}
});
const beforeHooks: MultiNestCompilerPlugins['afterHooks'] = [];
const afterHooks: MultiNestCompilerPlugins['beforeHooks'] = [];
const afterDeclarationsHooks: MultiNestCompilerPlugins['afterDeclarationsHooks'] =
[];
pluginRefs.forEach((plugin, index) => {
if (!plugin.before && !plugin.after && !plugin.afterDeclarations) {
throw new Error(CLI_ERRORS.WRONG_PLUGIN(pluginNames[index]));
}
const options = plugins[index]?.options || {};
plugin.before &&
beforeHooks.push(plugin.before.bind(plugin.before, options));
plugin.after && afterHooks.push(plugin.after.bind(plugin.after, options));
plugin.afterDeclarations &&
afterDeclarationsHooks.push(
plugin.afterDeclarations.bind(plugin.afterDeclarations, options),
);
});
return {
beforeHooks,
afterHooks,
afterDeclarationsHooks,
};
}
}