/
index.js
294 lines (250 loc) · 9.09 KB
/
index.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
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
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
"use strict";
const npa = require("npm-package-arg");
const semver = require("semver");
const log = require("npmlog");
const ValidationError = require("@lerna/validation-error");
const prereleaseIdFromVersion = require("@lerna/prerelease-id-from-version");
/**
* Represents a node in a PackageGraph.
* @constructor
* @param {!<Package>} pkg - A Package object to build the node from.
*/
class PackageGraphNode {
constructor(pkg) {
Object.defineProperties(this, {
// immutable properties
name: {
enumerable: true,
value: pkg.name,
},
location: {
value: pkg.location,
},
prereleaseId: {
// an existing prerelease ID only matters at the beginning
value: prereleaseIdFromVersion(pkg.version),
},
// properties that might change over time
version: {
get() {
return pkg.version;
},
},
pkg: {
get() {
return pkg;
},
},
});
this.externalDependencies = new Map();
this.localDependencies = new Map();
this.localDependents = new Map();
}
/**
* Determine if the Node satisfies a resolved semver range.
* @see https://github.com/npm/npm-package-arg#result-object
*
* @param {!Result} resolved npm-package-arg Result object
* @returns {Boolean}
*/
satisfies({ gitCommittish, gitRange, fetchSpec }) {
return semver.satisfies(this.version, gitCommittish || gitRange || fetchSpec);
}
}
/**
* A PackageGraph.
* @constructor
* @param {!Array.<Package>} packages An array of Packages to build the graph out of.
* @param {String} graphType ("allDependencies" or "dependencies")
* Pass "dependencies" to create a graph of only dependencies,
* excluding the devDependencies that would normally be included.
* @param {Boolean} forceLocal Force all local dependencies to be linked.
*/
class PackageGraph extends Map {
constructor(packages, graphType = "allDependencies", forceLocal) {
super(packages.map(pkg => [pkg.name, new PackageGraphNode(pkg)]));
if (packages.length !== this.size) {
// weed out the duplicates
const seen = new Map();
for (const { name, location } of packages) {
if (seen.has(name)) {
seen.get(name).push(location);
} else {
seen.set(name, [location]);
}
}
for (const [name, locations] of seen) {
if (locations.length > 1) {
throw new ValidationError(
"ENAME",
[`Package name "${name}" used in multiple packages:`, ...locations].join("\n\t")
);
}
}
}
this.forEach((currentNode, currentName) => {
const graphDependencies =
graphType === "dependencies"
? Object.assign({}, currentNode.pkg.optionalDependencies, currentNode.pkg.dependencies)
: Object.assign(
{},
currentNode.pkg.devDependencies,
currentNode.pkg.optionalDependencies,
currentNode.pkg.dependencies
);
Object.keys(graphDependencies).forEach(depName => {
const depNode = this.get(depName);
// Yarn decided to ignore https://github.com/npm/npm/pull/15900 and implemented "link:"
// As they apparently have no intention of being compatible, we have to do it for them.
// @see https://github.com/yarnpkg/yarn/issues/4212
const spec = graphDependencies[depName].replace(/^link:/, "file:");
const resolved = npa.resolve(depName, spec, currentNode.location);
if (!depNode) {
// it's an external dependency, store the resolution and bail
return currentNode.externalDependencies.set(depName, resolved);
}
if (forceLocal || resolved.fetchSpec === depNode.location || depNode.satisfies(resolved)) {
// a local file: specifier OR a matching semver
currentNode.localDependencies.set(depName, resolved);
depNode.localDependents.set(currentName, currentNode);
} else {
// non-matching semver of a local dependency
currentNode.externalDependencies.set(depName, resolved);
}
});
});
}
get rawPackageList() {
return Array.from(this.values()).map(node => node.pkg);
}
/**
* Takes a list of Packages and returns a list of those same Packages with any Packages
* they depend on. i.e if packageA depended on packageB `graph.addDependencies([packageA])`
* would return [packageA, packageB].
*
* @param {!Array.<Package>} filteredPackages The packages to include dependencies for.
* @return {Array.<Package>} The packages with any dependencies that weren't already included.
*/
addDependencies(filteredPackages) {
return this.extendList(filteredPackages, "localDependencies");
}
/**
* Takes a list of Packages and returns a list of those same Packages with any Packages
* that depend on them. i.e if packageC depended on packageD `graph.addDependents([packageD])`
* would return [packageD, packageC].
*
* @param {!Array.<Package>} filteredPackages The packages to include dependents for.
* @return {Array.<Package>} The packages with any dependents that weren't already included.
*/
addDependents(filteredPackages) {
return this.extendList(filteredPackages, "localDependents");
}
/**
* Extends a list of packages by traversing on a given property, which must refer to a
* `PackageGraphNode` property that is a collection of `PackageGraphNode`s
*
* @param {!Array.<Package>} packageList The list of packages to extend
* @param {!String} nodeProp The property on `PackageGraphNode` used to traverse
* @return {Array.<Package>} The packages with any additional packages found by traversing
* nodeProp
*/
extendList(packageList, nodeProp) {
// the current list of packages we are expanding using breadth-first-search
const search = new Set(packageList.map(({ name }) => this.get(name)));
// an intermediate list of matched PackageGraphNodes
const result = [];
search.forEach(currentNode => {
// anything searched for is always a result
result.push(currentNode);
currentNode[nodeProp].forEach((meta, depName) => {
const depNode = this.get(depName);
if (depNode !== currentNode && !search.has(depNode)) {
search.add(depNode);
}
});
});
// actual Package instances, not PackageGraphNodes
return result.map(node => node.pkg);
}
/**
* Return a tuple of cycle paths and nodes, which have been removed from the graph.
* @param {!boolean} rejectCycles Whether or not to reject cycles
* @returns [Set<String[]>, Set<PackageGraphNode>]
*/
partitionCycles(rejectCycles) {
const cyclePaths = new Set();
const cycleNodes = new Set();
this.forEach((currentNode, currentName) => {
const seen = new Set();
const visits = walk => (dependentNode, dependentName, siblingDependents) => {
const step = walk.concat(dependentName);
if (seen.has(dependentNode)) {
return;
}
seen.add(dependentNode);
if (dependentNode === currentNode) {
// a direct cycle
cycleNodes.add(currentNode);
cyclePaths.add(step);
return;
}
if (siblingDependents.has(currentName)) {
// a transitive cycle
const cycleDependentName = Array.from(dependentNode.localDependencies.keys()).find(key =>
currentNode.localDependents.has(key)
);
const pathToCycle = step
.slice()
.reverse()
.concat(cycleDependentName);
cycleNodes.add(dependentNode);
cyclePaths.add(pathToCycle);
}
dependentNode.localDependents.forEach(visits(step));
};
currentNode.localDependents.forEach(visits([currentName]));
});
if (cyclePaths.size) {
const cycleMessage = ["Dependency cycles detected, you should fix these!"]
.concat(Array.from(cyclePaths).map(cycle => cycle.join(" -> ")))
.join("\n");
if (rejectCycles) {
throw new ValidationError("ECYCLE", cycleMessage);
}
log.warn("ECYCLE", cycleMessage);
}
return [cyclePaths, cycleNodes];
}
/**
* Remove cycle nodes.
* @param {Set<PackageGraphNode>} cycleNodes
*/
pruneCycleNodes(cycleNodes) {
return this.prune(...cycleNodes);
}
/**
* Remove all candidate nodes.
* @param {PackageGraphNode[]} candidates
*/
prune(...candidates) {
if (candidates.length === this.size) {
return this.clear();
}
candidates.forEach(node => this.remove(node));
}
/**
* Delete by value (instead of key), as well as removing pointers
* to itself in the other node's internal collections.
* @param {PackageGraphNode} candidateNode instance to remove
*/
remove(candidateNode) {
this.delete(candidateNode.name);
this.forEach(node => {
// remove incoming edges ("indegree")
node.localDependencies.delete(candidateNode.name);
// remove outgoing edges ("outdegree")
node.localDependents.delete(candidateNode.name);
});
}
}
module.exports = PackageGraph;