/
nx-plugin.ts
228 lines (212 loc) · 6.81 KB
/
nx-plugin.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
import { sync } from 'fast-glob';
import { existsSync } from 'fs';
import * as path from 'path';
import { appRootPath } from '../utils/app-root';
import { readJsonFile } from '../utils/fileutils';
import { registerTsProject } from '../utils/register';
import { PackageJson } from './package-json';
import { ProjectGraphProcessor } from './project-graph';
import { Workspaces } from './workspace';
import {
ProjectConfiguration,
TargetConfiguration,
WorkspaceJsonConfiguration,
} from './workspace.model';
export type ProjectTargetConfigurator = (
file: string
) => Record<string, TargetConfiguration>;
/**
* A plugin for Nx
*/
export interface NxPlugin {
name: string;
processProjectGraph?: ProjectGraphProcessor;
registerProjectTargets?: ProjectTargetConfigurator;
/**
* A glob pattern to search for non-standard project files.
* @example: ["*.csproj", "pom.xml"]
*/
projectFilePatterns?: string[];
}
// Short lived cache (cleared between cmd runs)
// holding resolved nx plugin objects.
// Allows loadNxPlugins to be called multiple times w/o
// executing resolution mulitple times.
let nxPluginCache: NxPlugin[] = null;
export function loadNxPlugins(
plugins?: string[],
paths = [appRootPath]
): NxPlugin[] {
return plugins?.length
? nxPluginCache ||
(nxPluginCache = plugins.map((moduleName) => {
let pluginPath: string;
try {
pluginPath = require.resolve(moduleName, {
paths,
});
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
const plugin = resolveLocalNxPlugin(moduleName);
const { main } = Object.values(plugin.projectConfig.targets).find(
(x) =>
[
'@nrwl/js:tsc',
'@nrwl/js:swc',
'@nrwl/node:package',
].includes(x.executor)
)?.options;
pluginPath = main ? path.join(appRootPath, main) : plugin.path;
} else {
throw e;
}
}
const packageJsonPath = path.join(pluginPath, 'package.json');
const { name } =
!['.ts', '.js'].some((x) => x === path.extname(pluginPath)) && // Not trying to point to a ts or js file
existsSync(packageJsonPath) // plugin has a package.json
? readJsonFile(packageJsonPath) // read name from package.json
: { name: path.basename(pluginPath) }; // use the name of the file we point to
const plugin = require(pluginPath) as NxPlugin;
plugin.name = name;
return plugin;
}))
: [];
}
export function mergePluginTargetsWithNxTargets(
projectRoot: string,
targets: Record<string, TargetConfiguration>,
plugins: NxPlugin[]
): Record<string, TargetConfiguration> {
let newTargets: Record<string, TargetConfiguration> = {};
for (const plugin of plugins) {
if (!plugin.projectFilePatterns?.length || !plugin.registerProjectTargets) {
continue;
}
const projectFiles = sync(`+(${plugin.projectFilePatterns.join('|')})`, {
cwd: path.join(appRootPath, projectRoot),
});
for (const projectFile of projectFiles) {
newTargets = {
...newTargets,
...plugin.registerProjectTargets(path.join(projectRoot, projectFile)),
};
}
}
return { ...newTargets, ...targets };
}
export function readPluginPackageJson(
pluginName: string,
paths = [appRootPath]
): {
path: string;
json: PackageJson;
} {
let packageJsonPath: string;
try {
packageJsonPath = require.resolve(`${pluginName}/package.json`, {
paths,
});
} catch (e) {
if (e.code === 'MODULE_NOT_FOUND') {
const localPluginPath = resolveLocalNxPlugin(pluginName);
if (localPluginPath) {
const localPluginPackageJson = path.join(
localPluginPath.path,
'package.json'
);
return {
path: localPluginPackageJson,
json: readJsonFile(localPluginPackageJson),
};
}
}
throw e;
}
return { json: readJsonFile(packageJsonPath), path: packageJsonPath };
}
/**
* Builds a plugin package and returns the path to output
* @param importPath What is the import path that refers to a potential plugin?
* @returns The path to the built plugin, or null if it doesn't exist
*/
const localPluginCache: Record<
string,
{ path: string; projectConfig: ProjectConfiguration }
> = {};
export function resolveLocalNxPlugin(
importPath: string,
root = appRootPath
): { path: string; projectConfig: ProjectConfiguration } | null {
localPluginCache[importPath] ??= lookupLocalPlugin(importPath, root);
return localPluginCache[importPath];
}
let tsNodeAndPathsRegistered = false;
function registerTSTranspiler() {
if (!tsNodeAndPathsRegistered) {
registerTsProject(appRootPath, 'tsconfig.base.json');
}
tsNodeAndPathsRegistered = true;
}
function lookupLocalPlugin(importPath: string, root = appRootPath) {
const workspace = new Workspaces(root).readWorkspaceConfiguration({
ignorePluginInference: true,
});
const plugin = findNxProjectForImportPath(importPath, workspace, root);
if (!plugin) {
return null;
}
if (!tsNodeAndPathsRegistered) {
registerTSTranspiler();
}
const projectConfig = workspace.projects[plugin];
return { path: path.join(root, projectConfig.root), projectConfig };
}
function findNxProjectForImportPath(
importPath: string,
workspace: WorkspaceJsonConfiguration,
root = appRootPath
): string | null {
const tsConfigPaths: Record<string, string[]> = readTsConfigPaths(root);
const possiblePaths = tsConfigPaths[importPath]?.map((p) =>
path.resolve(root, p)
);
if (tsConfigPaths[importPath]) {
const projectRootMappings = Object.entries(workspace.projects).reduce(
(m, [project, config]) => {
m[path.resolve(root, config.root)] = project;
return m;
},
{}
);
for (const root of Object.keys(projectRootMappings)) {
if (possiblePaths.some((p) => p.startsWith(root))) {
return projectRootMappings[root];
}
}
if (process.env.NX_VERBOSE_LOGGING) {
console.log(
'Unable to find local plugin',
possiblePaths,
projectRootMappings
);
}
throw new Error(
'Unable to resolve local plugin with import path ' + importPath
);
}
}
let tsconfigPaths: Record<string, string[]>;
function readTsConfigPaths(root: string = appRootPath) {
if (!tsconfigPaths) {
const tsconfigPath: string | null = ['tsconfig.base.json', 'tsconfig.json']
.map((x) => path.join(root, x))
.filter((x) => existsSync(x))[0];
if (!tsconfigPath) {
throw new Error('unable to find tsconfig.base.json or tsconfig.json');
}
const { compilerOptions } = readJsonFile(tsconfigPath);
tsconfigPaths = compilerOptions?.paths;
}
return tsconfigPaths;
}