-
Notifications
You must be signed in to change notification settings - Fork 2.7k
/
Copy pathpackage-resolver.js
651 lines (515 loc) · 17.2 KB
/
package-resolver.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
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
/* @flow */
import type {Manifest, DependencyRequestPatterns, DependencyRequestPattern} from './types.js';
import type {RegistryNames} from './registries/index.js';
import type PackageReference from './package-reference.js';
import type {Reporter} from './reporters/index.js';
import {getExoticResolver} from './resolvers/index.js';
import type Config from './config.js';
import PackageRequest from './package-request.js';
import {normalizePattern} from './util/normalize-pattern.js';
import RequestManager from './util/request-manager.js';
import BlockingQueue from './util/blocking-queue.js';
import Lockfile, {type LockManifest} from './lockfile';
import map from './util/map.js';
import WorkspaceLayout from './workspace-layout.js';
import ResolutionMap, {shouldUpdateLockfile} from './resolution-map.js';
const invariant = require('invariant');
const semver = require('semver');
export type ResolverOptions = {|
isFlat?: boolean,
isFrozen?: boolean,
workspaceLayout?: WorkspaceLayout,
|};
export default class PackageResolver {
constructor(config: Config, lockfile: Lockfile, resolutionMap: ResolutionMap = new ResolutionMap(config)) {
this.patternsByPackage = map();
this.fetchingPatterns = new Set();
this.fetchingQueue = new BlockingQueue('resolver fetching');
this.patterns = map();
this.resolutionMap = resolutionMap;
this.usedRegistries = new Set();
this.flat = false;
this.reporter = config.reporter;
this.lockfile = lockfile;
this.config = config;
this.delayedResolveQueue = [];
}
// whether the dependency graph will be flattened
flat: boolean;
frozen: boolean;
workspaceLayout: ?WorkspaceLayout;
resolutionMap: ResolutionMap;
// list of registries that have been used in this resolution
usedRegistries: Set<RegistryNames>;
// activity monitor
activity: ?{
tick: (name: string) => void,
end: () => void,
};
// patterns we've already resolved or are in the process of resolving
fetchingPatterns: Set<string>;
// TODO
fetchingQueue: BlockingQueue;
// manages and throttles json api http requests
requestManager: RequestManager;
// list of patterns associated with a package
patternsByPackage: {
[packageName: string]: Array<string>,
};
// lockfile instance which we can use to retrieve version info
lockfile: Lockfile;
// a map of dependency patterns to packages
patterns: {
[packagePattern: string]: Manifest,
};
// reporter instance, abstracts out display logic
reporter: Reporter;
// environment specific config methods and options
config: Config;
// list of packages need to be resolved later (they found a matching version in the
// resolver, but better matches can still arrive later in the resolve process)
delayedResolveQueue: Array<{req: PackageRequest, info: Manifest}>;
/**
* TODO description
*/
isNewPattern(pattern: string): boolean {
return !!this.patterns[pattern].fresh;
}
updateManifest(ref: PackageReference, newPkg: Manifest): Promise<void> {
// inherit fields
const oldPkg = this.patterns[ref.patterns[0]];
newPkg._reference = ref;
newPkg._remote = ref.remote;
newPkg.name = oldPkg.name;
newPkg.fresh = oldPkg.fresh;
newPkg.prebuiltVariants = oldPkg.prebuiltVariants;
// update patterns
for (const pattern of ref.patterns) {
this.patterns[pattern] = newPkg;
}
return Promise.resolve();
}
updateManifests(newPkgs: Array<Manifest>): Promise<void> {
for (const newPkg of newPkgs) {
if (newPkg._reference) {
for (const pattern of newPkg._reference.patterns) {
const oldPkg = this.patterns[pattern];
newPkg.prebuiltVariants = oldPkg.prebuiltVariants;
this.patterns[pattern] = newPkg;
}
}
}
return Promise.resolve();
}
/**
* Given a list of patterns, dedupe them to a list of unique patterns.
*/
dedupePatterns(patterns: Iterable<string>): Array<string> {
const deduped = [];
const seen = new Set();
for (const pattern of patterns) {
const info = this.getResolvedPattern(pattern);
if (seen.has(info)) {
continue;
}
seen.add(info);
deduped.push(pattern);
}
return deduped;
}
/**
* Get a list of all manifests by topological order.
*/
getTopologicalManifests(seedPatterns: Array<string>): Iterable<Manifest> {
const pkgs: Set<Manifest> = new Set();
const skip: Set<Manifest> = new Set();
const add = (seedPatterns: Array<string>) => {
for (const pattern of seedPatterns) {
const pkg = this.getStrictResolvedPattern(pattern);
if (skip.has(pkg)) {
continue;
}
const ref = pkg._reference;
invariant(ref, 'expected reference');
skip.add(pkg);
add(ref.dependencies);
pkgs.add(pkg);
}
};
add(seedPatterns);
return pkgs;
}
/**
* Get a list of all manifests by level sort order.
*/
getLevelOrderManifests(seedPatterns: Array<string>): Iterable<Manifest> {
const pkgs: Set<Manifest> = new Set();
const skip: Set<Manifest> = new Set();
const add = (seedPatterns: Array<string>) => {
const refs = [];
for (const pattern of seedPatterns) {
const pkg = this.getStrictResolvedPattern(pattern);
if (skip.has(pkg)) {
continue;
}
const ref = pkg._reference;
invariant(ref, 'expected reference');
refs.push(ref);
skip.add(pkg);
pkgs.add(pkg);
}
for (const ref of refs) {
add(ref.dependencies);
}
};
add(seedPatterns);
return pkgs;
}
/**
* Get a list of all package names in the dependency graph.
*/
getAllDependencyNamesByLevelOrder(seedPatterns: Array<string>): Iterable<string> {
const names = new Set();
for (const {name} of this.getLevelOrderManifests(seedPatterns)) {
names.add(name);
}
return names;
}
/**
* Retrieve all the package info stored for this package name.
*/
getAllInfoForPackageName(name: string): Array<Manifest> {
const patterns = this.patternsByPackage[name] || [];
return this.getAllInfoForPatterns(patterns);
}
/**
* Retrieve all the package info stored for a list of patterns.
*/
getAllInfoForPatterns(patterns: string[]): Array<Manifest> {
const infos = [];
const seen = new Set();
for (const pattern of patterns) {
const info = this.patterns[pattern];
if (seen.has(info)) {
continue;
}
seen.add(info);
infos.push(info);
}
return infos;
}
/**
* Get a flat list of all package info.
*/
getManifests(): Array<Manifest> {
const infos = [];
const seen = new Set();
for (const pattern in this.patterns) {
const info = this.patterns[pattern];
if (seen.has(info)) {
continue;
}
infos.push(info);
seen.add(info);
}
return infos;
}
/**
* replace pattern in resolver, e.g. `name` is replaced with `name@^1.0.1`
*/
replacePattern(pattern: string, newPattern: string) {
const pkg = this.getResolvedPattern(pattern);
invariant(pkg, `missing package ${pattern}`);
const ref = pkg._reference;
invariant(ref, 'expected package reference');
ref.patterns = [newPattern];
this.addPattern(newPattern, pkg);
this.removePattern(pattern);
}
/**
* Make all versions of this package resolve to it.
*/
collapseAllVersionsOfPackage(name: string, version: string): string {
const patterns = this.dedupePatterns(this.patternsByPackage[name]);
return this.collapsePackageVersions(name, version, patterns);
}
/**
* Make all given patterns resolve to version.
*/
collapsePackageVersions(name: string, version: string, patterns: string[]): string {
const human = `${name}@${version}`;
// get manifest that matches the version we're collapsing too
let collapseToReference: ?PackageReference;
let collapseToManifest: Manifest;
let collapseToPattern: string;
for (const pattern of patterns) {
const _manifest = this.patterns[pattern];
if (_manifest.version === version) {
collapseToReference = _manifest._reference;
collapseToManifest = _manifest;
collapseToPattern = pattern;
break;
}
}
invariant(
collapseToReference && collapseToManifest && collapseToPattern,
`Couldn't find package manifest for ${human}`,
);
for (const pattern of patterns) {
// don't touch the pattern we're collapsing to
if (pattern === collapseToPattern) {
continue;
}
// remove this pattern
const ref = this.getStrictResolvedPattern(pattern)._reference;
invariant(ref, 'expected package reference');
const refPatterns = ref.patterns.slice();
ref.prune();
// add pattern to the manifest we're collapsing to
for (const pattern of refPatterns) {
collapseToReference.addPattern(pattern, collapseToManifest);
}
}
return collapseToPattern;
}
/**
* TODO description
*/
addPattern(pattern: string, info: Manifest) {
this.patterns[pattern] = info;
const byName = (this.patternsByPackage[info.name] = this.patternsByPackage[info.name] || []);
if (byName.indexOf(pattern) === -1) {
byName.push(pattern);
}
}
/**
* TODO description
*/
removePattern(pattern: string) {
const pkg = this.patterns[pattern];
if (!pkg) {
return;
}
const byName = this.patternsByPackage[pkg.name];
if (!byName) {
return;
}
byName.splice(byName.indexOf(pattern), 1);
delete this.patterns[pattern];
}
/**
* TODO description
*/
getResolvedPattern(pattern: string): ?Manifest {
return this.patterns[pattern];
}
/**
* TODO description
*/
getStrictResolvedPattern(pattern: string): Manifest {
const manifest = this.getResolvedPattern(pattern);
invariant(manifest, 'expected manifest');
return manifest;
}
/**
* TODO description
*/
getExactVersionMatch(name: string, version: string, manifest: ?Manifest): ?Manifest {
const patterns = this.patternsByPackage[name];
if (!patterns) {
return null;
}
for (const pattern of patterns) {
const info = this.getStrictResolvedPattern(pattern);
if (info.version === version) {
return info;
}
}
if (manifest && getExoticResolver(version)) {
return this.exoticRangeMatch(patterns.map(this.getStrictResolvedPattern.bind(this)), manifest);
}
return null;
}
/**
* Get the manifest of the highest known version that satisfies a package range
*/
getHighestRangeVersionMatch(name: string, range: string, manifest: ?Manifest): ?Manifest {
const patterns = this.patternsByPackage[name];
if (!patterns) {
return null;
}
const versionNumbers = [];
const resolvedPatterns = patterns.map((pattern): Manifest => {
const info = this.getStrictResolvedPattern(pattern);
versionNumbers.push(info.version);
return info;
});
const maxValidRange = semver.maxSatisfying(versionNumbers, range);
if (!maxValidRange) {
return manifest && getExoticResolver(range) ? this.exoticRangeMatch(resolvedPatterns, manifest) : null;
}
const indexOfmaxValidRange = versionNumbers.indexOf(maxValidRange);
const maxValidRangeManifest = resolvedPatterns[indexOfmaxValidRange];
return maxValidRangeManifest;
}
/**
* Get the manifest of the package that matches an exotic range
*/
exoticRangeMatch(resolvedPkgs: Array<Manifest>, manifest: Manifest): ?Manifest {
const remote = manifest._remote;
if (!(remote && remote.reference && remote.type === 'copy')) {
return null;
}
const matchedPkg = resolvedPkgs.find(
({_remote: pkgRemote}) => pkgRemote && pkgRemote.reference === remote.reference && pkgRemote.type === 'copy',
);
if (matchedPkg) {
manifest._remote = matchedPkg._remote;
}
return matchedPkg;
}
/**
* Determine if LockfileEntry is incorrect, remove it from lockfile cache and consider the pattern as new
*/
isLockfileEntryOutdated(version: string, range: string, hasVersion: boolean): boolean {
return !!(
semver.validRange(range) &&
semver.valid(version) &&
!getExoticResolver(range) &&
hasVersion &&
!semver.satisfies(version, range)
);
}
/**
* TODO description
*/
async find(initialReq: DependencyRequestPattern): Promise<void> {
const req = this.resolveToResolution(initialReq);
// we've already resolved it with a resolution
if (!req) {
return;
}
const request = new PackageRequest(req, this);
const fetchKey = `${req.registry}:${req.pattern}:${String(req.optional)}`;
const initialFetch = !this.fetchingPatterns.has(fetchKey);
let fresh = false;
if (this.activity) {
this.activity.tick(req.pattern);
}
if (initialFetch) {
this.fetchingPatterns.add(fetchKey);
const lockfileEntry = this.lockfile.getLocked(req.pattern);
if (lockfileEntry) {
const {range, hasVersion} = normalizePattern(req.pattern);
if (this.isLockfileEntryOutdated(lockfileEntry.version, range, hasVersion)) {
this.reporter.warn(this.reporter.lang('incorrectLockfileEntry', req.pattern));
this.removePattern(req.pattern);
this.lockfile.removePattern(req.pattern);
fresh = true;
}
} else {
fresh = true;
}
request.init();
}
await request.find({fresh, frozen: this.frozen});
}
/**
* TODO description
*/
async init(
deps: DependencyRequestPatterns,
{isFlat, isFrozen, workspaceLayout}: ResolverOptions = {
isFlat: false,
isFrozen: false,
workspaceLayout: undefined,
},
): Promise<void> {
this.flat = Boolean(isFlat);
this.frozen = Boolean(isFrozen);
this.workspaceLayout = workspaceLayout;
const activity = (this.activity = this.reporter.activity());
for (const req of deps) {
await this.find(req);
}
// all required package versions have been discovered, so now packages that
// resolved to existing versions can be resolved to their best available version
this.resolvePackagesWithExistingVersions();
for (const req of this.resolutionMap.delayQueue) {
this.resolveToResolution(req);
}
if (isFlat) {
for (const dep of deps) {
const name = normalizePattern(dep.pattern).name;
this.optimizeResolutions(name);
}
}
activity.end();
this.activity = null;
}
// for a given package, see if a single manifest can satisfy all ranges
optimizeResolutions(name: string) {
const patterns: Array<string> = this.dedupePatterns(this.patternsByPackage[name] || []);
// don't optimize things that already have a lockfile entry:
// https://github.com/yarnpkg/yarn/issues/79
const collapsablePatterns = patterns.filter(pattern => {
const remote = this.patterns[pattern]._remote;
return !this.lockfile.getLocked(pattern) && (!remote || remote.type !== 'workspace');
});
if (collapsablePatterns.length < 2) {
return;
}
// reverse sort, so we'll find the maximum satisfying version first
const availableVersions = this.getAllInfoForPatterns(collapsablePatterns).map(manifest => manifest.version);
availableVersions.sort(semver.rcompare);
const ranges = collapsablePatterns.map(pattern => normalizePattern(pattern).range);
// find the most recent version that satisfies all patterns (if one exists), and
// collapse to that version.
for (const version of availableVersions) {
if (ranges.every(range => semver.satisfies(version, range))) {
this.collapsePackageVersions(name, version, collapsablePatterns);
return;
}
}
}
/**
* Called by the package requester for packages that this resolver already had
* a matching version for. Delay the resolve, because better matches can still be
* discovered.
*/
reportPackageWithExistingVersion(req: PackageRequest, info: Manifest) {
this.delayedResolveQueue.push({req, info});
}
/**
* Executes the resolve to existing versions for packages after the find process,
* when all versions that are going to be used have been discovered.
*/
resolvePackagesWithExistingVersions() {
for (const {req, info} of this.delayedResolveQueue) {
req.resolveToExistingVersion(info);
}
}
resolveToResolution(req: DependencyRequestPattern): ?DependencyRequestPattern {
const {parentNames, pattern} = req;
if (!parentNames || this.flat) {
return req;
}
const resolution = this.resolutionMap.find(pattern, parentNames);
if (resolution) {
const resolutionManifest = this.getResolvedPattern(resolution);
if (resolutionManifest) {
invariant(resolutionManifest._reference, 'resolutions should have a resolved reference');
resolutionManifest._reference.patterns.push(pattern);
this.addPattern(pattern, resolutionManifest);
const lockManifest: ?LockManifest = this.lockfile.getLocked(pattern);
if (shouldUpdateLockfile(lockManifest, resolutionManifest._reference)) {
this.lockfile.removePattern(pattern);
}
} else {
this.resolutionMap.addToDelayQueue(req);
}
return null;
}
return req;
}
}