/
link.ts
481 lines (453 loc) · 16 KB
/
link.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
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
import { promises as fs } from 'fs'
import path from 'path'
import { calcDepState, DepsStateCache } from '@pnpm/calc-dep-state'
import {
progressLogger,
rootLogger,
stageLogger,
statsLogger,
} from '@pnpm/core-loggers'
import {
filterLockfileByImporters,
} from '@pnpm/filter-lockfile'
import hoist from '@pnpm/hoist'
import { Lockfile } from '@pnpm/lockfile-file'
import logger from '@pnpm/logger'
import { prune } from '@pnpm/modules-cleaner'
import { IncludedDependencies } from '@pnpm/modules-yaml'
import {
DependenciesGraph,
DependenciesGraphNode,
LinkedDependency,
} from '@pnpm/resolve-dependencies'
import { StoreController } from '@pnpm/store-controller-types'
import symlinkDependency, { symlinkDirectRootDependency } from '@pnpm/symlink-dependency'
import {
HoistedDependencies,
Registries,
} from '@pnpm/types'
import pLimit from 'p-limit'
import pathExists from 'path-exists'
import fromPairs from 'ramda/src/fromPairs.js'
import equals from 'ramda/src/equals.js'
import isEmpty from 'ramda/src/isEmpty.js'
import difference from 'ramda/src/difference.js'
import omit from 'ramda/src/omit.js'
import props from 'ramda/src/props.js'
import { ImporterToUpdate } from './index'
const brokenModulesLogger = logger('_broken_node_modules')
export default async function linkPackages (
projects: ImporterToUpdate[],
depGraph: DependenciesGraph,
opts: {
currentLockfile: Lockfile
dependenciesByProjectId: {
[id: string]: {[alias: string]: string}
}
force: boolean
depsStateCache: DepsStateCache
extraNodePaths: string[]
hoistedDependencies: HoistedDependencies
hoistedModulesDir: string
hoistPattern?: string[]
ignoreScripts: boolean
publicHoistPattern?: string[]
include: IncludedDependencies
linkedDependenciesByProjectId: Record<string, LinkedDependency[]>
lockfileDir: string
makePartialCurrentLockfile: boolean
outdatedDependencies: {[pkgId: string]: string}
pruneStore: boolean
pruneVirtualStore: boolean
registries: Registries
rootModulesDir: string
sideEffectsCacheRead: boolean
symlink: boolean
skipped: Set<string>
storeController: StoreController
virtualStoreDir: string
wantedLockfile: Lockfile
wantedToBeSkippedPackageIds: Set<string>
}
): Promise<{
currentLockfile: Lockfile
newDepPaths: string[]
newHoistedDependencies: HoistedDependencies
removedDepPaths: Set<string>
}> {
let depNodes = Object.values(depGraph).filter(({ depPath, id }) => {
if (((opts.wantedLockfile.packages?.[depPath]) != null) && !opts.wantedLockfile.packages[depPath].optional) {
opts.skipped.delete(depPath)
return true
}
if (opts.wantedToBeSkippedPackageIds.has(id)) {
opts.skipped.add(depPath)
return false
}
opts.skipped.delete(depPath)
return true
})
if (!opts.include.dependencies) {
depNodes = depNodes.filter(({ dev, optional }) => dev || optional)
}
if (!opts.include.devDependencies) {
depNodes = depNodes.filter(({ optional, prod }) => prod || optional)
}
if (!opts.include.optionalDependencies) {
depNodes = depNodes.filter(({ optional }) => !optional)
}
depGraph = fromPairs(depNodes.map((depNode) => [depNode.depPath, depNode]))
const removedDepPaths = await prune(projects, {
currentLockfile: opts.currentLockfile,
hoistedDependencies: opts.hoistedDependencies,
hoistedModulesDir: (opts.hoistPattern != null) ? opts.hoistedModulesDir : undefined,
include: opts.include,
lockfileDir: opts.lockfileDir,
pruneStore: opts.pruneStore,
pruneVirtualStore: opts.pruneVirtualStore,
publicHoistedModulesDir: (opts.publicHoistPattern != null) ? opts.rootModulesDir : undefined,
registries: opts.registries,
skipped: opts.skipped,
storeController: opts.storeController,
virtualStoreDir: opts.virtualStoreDir,
wantedLockfile: opts.wantedLockfile,
})
stageLogger.debug({
prefix: opts.lockfileDir,
stage: 'importing_started',
})
const projectIds = projects.map(({ id }) => id)
const filterOpts = {
include: opts.include,
registries: opts.registries,
skipped: opts.skipped,
}
const newCurrentLockfile = filterLockfileByImporters(opts.wantedLockfile, projectIds, {
...filterOpts,
failOnMissingDependencies: true,
skipped: new Set(),
})
const newDepPaths = await linkNewPackages(
filterLockfileByImporters(opts.currentLockfile, projectIds, {
...filterOpts,
failOnMissingDependencies: false,
}),
newCurrentLockfile,
depGraph,
{
force: opts.force,
depsStateCache: opts.depsStateCache,
ignoreScripts: opts.ignoreScripts,
lockfileDir: opts.lockfileDir,
optional: opts.include.optionalDependencies,
sideEffectsCacheRead: opts.sideEffectsCacheRead,
symlink: opts.symlink,
skipped: opts.skipped,
storeController: opts.storeController,
virtualStoreDir: opts.virtualStoreDir,
}
)
stageLogger.debug({
prefix: opts.lockfileDir,
stage: 'importing_done',
})
if (opts.symlink) {
await Promise.all(projects.map(async ({ id, manifest, modulesDir, rootDir }) => {
const deps = opts.dependenciesByProjectId[id]
const importerFromLockfile = newCurrentLockfile.importers[id]
await Promise.all([
...Object.entries(deps)
.filter(([rootAlias]) => importerFromLockfile.specifiers[rootAlias])
.map(([rootAlias, depPath]) => ({ rootAlias, depGraphNode: depGraph[depPath] }))
.filter(({ depGraphNode }) => depGraphNode)
.map(async ({ rootAlias, depGraphNode }) => {
if (
(await symlinkDependency(depGraphNode.dir, modulesDir, rootAlias)).reused
) return
const isDev = Boolean(manifest.devDependencies?.[depGraphNode.name])
const isOptional = Boolean(manifest.optionalDependencies?.[depGraphNode.name])
rootLogger.debug({
added: {
dependencyType: isDev && 'dev' || isOptional && 'optional' || 'prod',
id: depGraphNode.id,
latest: opts.outdatedDependencies[depGraphNode.id],
name: rootAlias,
realName: depGraphNode.name,
version: depGraphNode.version,
},
prefix: rootDir,
})
}),
...opts.linkedDependenciesByProjectId[id].map(async (linkedDependency) => {
const depLocation = resolvePath(rootDir, linkedDependency.resolution.directory)
return symlinkDirectRootDependency(depLocation, modulesDir, linkedDependency.alias, {
fromDependenciesField: linkedDependency.dev && 'devDependencies' || linkedDependency.optional && 'optionalDependencies' || 'dependencies',
linkedPackage: linkedDependency,
prefix: rootDir,
})
}),
])
}))
}
let currentLockfile: Lockfile
const allImportersIncluded = equals(projectIds.sort(), Object.keys(opts.wantedLockfile.importers).sort())
if (
opts.makePartialCurrentLockfile ||
!allImportersIncluded
) {
const packages = opts.currentLockfile.packages ?? {}
if (opts.wantedLockfile.packages != null) {
for (const depPath in opts.wantedLockfile.packages) { // eslint-disable-line:forin
if (depGraph[depPath]) {
packages[depPath] = opts.wantedLockfile.packages[depPath]
}
}
}
const projects = projectIds.reduce((acc, projectId) => {
acc[projectId] = opts.wantedLockfile.importers[projectId]
return acc
}, opts.currentLockfile.importers)
currentLockfile = filterLockfileByImporters(
{
...opts.wantedLockfile,
importers: projects,
packages,
},
Object.keys(projects), {
...filterOpts,
failOnMissingDependencies: false,
skipped: new Set(),
}
)
} else if (
opts.include.dependencies &&
opts.include.devDependencies &&
opts.include.optionalDependencies &&
opts.skipped.size === 0
) {
currentLockfile = opts.wantedLockfile
} else {
currentLockfile = newCurrentLockfile
}
let newHoistedDependencies!: HoistedDependencies
if ((opts.hoistPattern != null || opts.publicHoistPattern != null) && (newDepPaths.length > 0 || removedDepPaths.size > 0)) {
// It is important to keep the skipped packages in the lockfile which will be saved as the "current lockfile".
// pnpm is comparing the current lockfile to the wanted one and they should much.
// But for hoisting, we need a version of the lockfile w/o the skipped packages, so we're making a copy.
const hoistLockfile = {
...currentLockfile,
packages: omit(Array.from(opts.skipped), currentLockfile.packages),
}
newHoistedDependencies = await hoist({
extraNodePath: opts.extraNodePaths,
lockfile: hoistLockfile,
importerIds: projectIds,
privateHoistedModulesDir: opts.hoistedModulesDir,
privateHoistPattern: opts.hoistPattern ?? [],
publicHoistedModulesDir: opts.rootModulesDir,
publicHoistPattern: opts.publicHoistPattern ?? [],
virtualStoreDir: opts.virtualStoreDir,
})
} else {
newHoistedDependencies = {}
}
return {
currentLockfile,
newDepPaths,
newHoistedDependencies,
removedDepPaths,
}
}
const isAbsolutePath = /^[/]|^[A-Za-z]:/
// This function is copied from @pnpm/local-resolver
function resolvePath (where: string, spec: string) {
if (isAbsolutePath.test(spec)) return spec
return path.resolve(where, spec)
}
async function linkNewPackages (
currentLockfile: Lockfile,
wantedLockfile: Lockfile,
depGraph: DependenciesGraph,
opts: {
depsStateCache: DepsStateCache
force: boolean
optional: boolean
ignoreScripts: boolean
lockfileDir: string
sideEffectsCacheRead: boolean
symlink: boolean
skipped: Set<string>
storeController: StoreController
virtualStoreDir: string
}
): Promise<string[]> {
const wantedRelDepPaths = difference(Object.keys(wantedLockfile.packages ?? {}), Array.from(opts.skipped))
let newDepPathsSet: Set<string>
if (opts.force) {
newDepPathsSet = new Set(
wantedRelDepPaths
// when installing a new package, not all the nodes are analyzed
// just skip the ones that are in the lockfile but were not analyzed
.filter((depPath) => depGraph[depPath])
)
} else {
newDepPathsSet = await selectNewFromWantedDeps(wantedRelDepPaths, currentLockfile, depGraph)
}
statsLogger.debug({
added: newDepPathsSet.size,
prefix: opts.lockfileDir,
})
const existingWithUpdatedDeps = []
if (!opts.force && (currentLockfile.packages != null) && (wantedLockfile.packages != null)) {
// add subdependencies that have been updated
// TODO: no need to relink everything. Can be relinked only what was changed
for (const depPath of wantedRelDepPaths) {
if (currentLockfile.packages[depPath] &&
(!equals(currentLockfile.packages[depPath].dependencies, wantedLockfile.packages[depPath].dependencies) ||
!equals(currentLockfile.packages[depPath].optionalDependencies, wantedLockfile.packages[depPath].optionalDependencies))) {
// TODO: come up with a test that triggers the usecase of depGraph[depPath] undefined
// see related issue: https://github.com/pnpm/pnpm/issues/870
if (depGraph[depPath] && !newDepPathsSet.has(depPath)) {
existingWithUpdatedDeps.push(depGraph[depPath])
}
}
}
}
if (!newDepPathsSet.size && (existingWithUpdatedDeps.length === 0)) return []
const newDepPaths = Array.from(newDepPathsSet)
const newPkgs = props<string, DependenciesGraphNode>(newDepPaths, depGraph)
await Promise.all(newPkgs.map(async (depNode) => fs.mkdir(depNode.modules, { recursive: true })))
await Promise.all([
!opts.symlink
? Promise.resolve()
: linkAllModules([...newPkgs, ...existingWithUpdatedDeps], depGraph, {
lockfileDir: opts.lockfileDir,
optional: opts.optional,
}),
linkAllPkgs(opts.storeController, newPkgs, {
depGraph,
depsStateCache: opts.depsStateCache,
force: opts.force,
ignoreScripts: opts.ignoreScripts,
lockfileDir: opts.lockfileDir,
sideEffectsCacheRead: opts.sideEffectsCacheRead,
}),
])
return newDepPaths
}
async function selectNewFromWantedDeps (
wantedRelDepPaths: string[],
currentLockfile: Lockfile,
depGraph: DependenciesGraph
) {
const newDeps = new Set<string>()
const prevDeps = currentLockfile.packages ?? {}
await Promise.all(
wantedRelDepPaths.map(
async (depPath: string) => {
const depNode = depGraph[depPath]
if (!depNode) return
const prevDep = prevDeps[depPath]
if (
prevDep &&
depNode.resolution['integrity'] === prevDep.resolution['integrity']
) {
if (await pathExists(depNode.dir)) {
return
}
brokenModulesLogger.debug({
missing: depNode.dir,
})
}
newDeps.add(depPath)
}
)
)
return newDeps
}
const limitLinking = pLimit(16)
async function linkAllPkgs (
storeController: StoreController,
depNodes: DependenciesGraphNode[],
opts: {
depGraph: DependenciesGraph
depsStateCache: DepsStateCache
force: boolean
ignoreScripts: boolean
lockfileDir: string
sideEffectsCacheRead: boolean
}
) {
return Promise.all(
depNodes.map(async (depNode) => {
const filesResponse = await depNode.fetchingFiles()
if (typeof depNode.requiresBuild === 'function') {
depNode.requiresBuild = await depNode.requiresBuild()
}
let sideEffectsCacheKey: string | undefined
if (opts.sideEffectsCacheRead && filesResponse.sideEffects && !isEmpty(filesResponse.sideEffects)) {
sideEffectsCacheKey = calcDepState(opts.depGraph, opts.depsStateCache, depNode.depPath, {
isBuilt: !opts.ignoreScripts && depNode.requiresBuild,
patchFileHash: depNode.patchFile?.hash,
})
}
const { importMethod, isBuilt } = await storeController.importPackage(depNode.dir, {
filesResponse,
force: opts.force,
sideEffectsCacheKey,
requiresBuild: depNode.requiresBuild || depNode.patchFile != null,
})
if (importMethod) {
progressLogger.debug({
method: importMethod,
requester: opts.lockfileDir,
status: 'imported',
to: depNode.dir,
})
}
depNode.isBuilt = isBuilt
const selfDep = depNode.children[depNode.name]
if (selfDep) {
const pkg = opts.depGraph[selfDep]
if (!pkg || !pkg.installable && pkg.optional) return
const targetModulesDir = path.join(depNode.modules, depNode.name, 'node_modules')
await limitLinking(async () => symlinkDependency(pkg.dir, targetModulesDir, depNode.name))
}
})
)
}
async function linkAllModules (
depNodes: DependenciesGraphNode[],
depGraph: DependenciesGraph,
opts: {
lockfileDir: string
optional: boolean
}
) {
await Promise.all(
depNodes
.map(async ({ children, optionalDependencies, name, modules }) => {
const childrenToLink = opts.optional
? children
: Object.keys(children)
.reduce((nonOptionalChildren, childAlias) => {
if (!optionalDependencies.has(childAlias)) {
nonOptionalChildren[childAlias] = children[childAlias]
}
return nonOptionalChildren
}, {})
await Promise.all(
Object.entries(childrenToLink)
.map(async ([childAlias, childDepPath]) => {
if (childDepPath.startsWith('link:')) {
await limitLinking(async () => symlinkDependency(path.resolve(opts.lockfileDir, childDepPath.slice(5)), modules, childAlias))
return
}
const pkg = depGraph[childDepPath]
if (!pkg || !pkg.installable && pkg.optional || childAlias === name) return
await limitLinking(async () => symlinkDependency(pkg.dir, modules, childAlias))
})
)
})
)
}