-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
NodePackageManager.js
582 lines (517 loc) Β· 17 KB
/
NodePackageManager.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
// @flow
import type {FilePath, DependencySpecifier, SemverRange} from '@parcel/types';
import type {FileSystem} from '@parcel/fs';
import type {
ModuleRequest,
PackageManager,
PackageInstaller,
InstallOptions,
Invalidations,
} from './types';
import type {ResolveResult} from './types';
import {registerSerializableClass} from '@parcel/core';
import ThrowableDiagnostic, {
encodeJSONKeyComponent,
escapeMarkdown,
generateJSONCodeHighlights,
md,
} from '@parcel/diagnostic';
import {NodeFS} from '@parcel/fs';
import nativeFS from 'fs';
import Module from 'module';
import path from 'path';
import semver from 'semver';
import logger from '@parcel/logger';
import nullthrows from 'nullthrows';
import {getModuleParts} from '@parcel/utils';
import {getConflictingLocalDependencies} from './utils';
import {installPackage} from './installPackage';
import pkg from '../package.json';
import {ResolverBase} from '@parcel/node-resolver-core';
import {pathToFileURL} from 'url';
// Package.json fields. Must match package_json.rs.
const MAIN = 1 << 0;
const SOURCE = 1 << 2;
const ENTRIES =
MAIN |
(process.env.PARCEL_BUILD_ENV !== 'production' ||
process.env.PARCEL_SELF_BUILD
? SOURCE
: 0);
// There can be more than one instance of NodePackageManager, but node has only a single module cache.
// Therefore, the resolution cache and the map of parent to child modules should also be global.
const cache = new Map<DependencySpecifier, ResolveResult>();
const children = new Map<FilePath, Set<DependencySpecifier>>();
const invalidationsCache = new Map<string, Invalidations>();
// This implements a package manager for Node by monkey patching the Node require
// algorithm so that it uses the specified FileSystem instead of the native one.
// It also handles installing packages when they are required if not already installed.
// See https://github.com/nodejs/node/blob/master/lib/internal/modules/cjs/loader.js
// for reference to Node internals.
export class NodePackageManager implements PackageManager {
fs: FileSystem;
projectRoot: FilePath;
installer: ?PackageInstaller;
resolver: ResolverBase;
constructor(
fs: FileSystem,
projectRoot: FilePath,
installer?: ?PackageInstaller,
) {
this.fs = fs;
this.projectRoot = projectRoot;
this.installer = installer;
}
_createResolver(): ResolverBase {
return new ResolverBase(this.projectRoot, {
fs:
this.fs instanceof NodeFS && process.versions.pnp == null
? undefined
: {
canonicalize: path => this.fs.realpathSync(path),
read: path => this.fs.readFileSync(path),
isFile: path => this.fs.statSync(path).isFile(),
isDir: path => this.fs.statSync(path).isDirectory(),
},
mode: 2,
entries: ENTRIES,
moduleDirResolver:
process.versions.pnp != null
? (module, from) => {
// $FlowFixMe[prop-missing]
let pnp = Module.findPnpApi(path.dirname(from));
return pnp.resolveToUnqualified(
// append slash to force loading builtins from npm
module + '/',
from,
);
}
: undefined,
});
}
static deserialize(opts: any): NodePackageManager {
return new NodePackageManager(opts.fs, opts.projectRoot, opts.installer);
}
serialize(): {|
$$raw: boolean,
fs: FileSystem,
projectRoot: FilePath,
installer: ?PackageInstaller,
|} {
return {
$$raw: false,
fs: this.fs,
projectRoot: this.projectRoot,
installer: this.installer,
};
}
async require(
name: DependencySpecifier,
from: FilePath,
opts: ?{|
range?: ?SemverRange,
shouldAutoInstall?: boolean,
saveDev?: boolean,
|},
): Promise<any> {
let {resolved, type} = await this.resolve(name, from, opts);
if (type === 2) {
logger.warn({
message: 'ES module dependencies are experimental.',
origin: '@parcel/package-manager',
codeFrames: [
{
filePath: resolved,
codeHighlights: [],
},
],
});
// On Windows, Node requires absolute paths to be file URLs.
if (process.platform === 'win32' && path.isAbsolute(resolved)) {
resolved = pathToFileURL(resolved);
}
// $FlowFixMe
return import(resolved);
}
return this.load(resolved, from);
}
requireSync(name: DependencySpecifier, from: FilePath): any {
let {resolved} = this.resolveSync(name, from);
return this.load(resolved, from);
}
load(filePath: FilePath, from: FilePath): any {
if (!path.isAbsolute(filePath)) {
// Node builtin module
// $FlowFixMe
return require(filePath);
}
// $FlowFixMe[prop-missing]
const cachedModule = Module._cache[filePath];
if (cachedModule !== undefined) {
return cachedModule.exports;
}
// $FlowFixMe
let m = new Module(filePath, Module._cache[from] || module.parent);
// $FlowFixMe[prop-missing]
Module._cache[filePath] = m;
// Patch require within this module so it goes through our require
m.require = id => {
return this.requireSync(id, filePath);
};
// Patch `fs.readFileSync` temporarily so that it goes through our file system
let {readFileSync, statSync} = nativeFS;
// $FlowFixMe
nativeFS.readFileSync = (filename, encoding) => {
return this.fs.readFileSync(filename, encoding);
};
// $FlowFixMe
nativeFS.statSync = filename => {
return this.fs.statSync(filename);
};
try {
m.load(filePath);
} catch (err) {
// $FlowFixMe[prop-missing]
delete Module._cache[filePath];
throw err;
} finally {
// $FlowFixMe
nativeFS.readFileSync = readFileSync;
// $FlowFixMe
nativeFS.statSync = statSync;
}
return m.exports;
}
async resolve(
id: DependencySpecifier,
from: FilePath,
options?: ?{|
range?: ?SemverRange,
shouldAutoInstall?: boolean,
saveDev?: boolean,
|},
): Promise<ResolveResult> {
let basedir = path.dirname(from);
let key = basedir + ':' + id;
let resolved = cache.get(key);
if (!resolved) {
let [name] = getModuleParts(id);
try {
resolved = this.resolveInternal(id, from);
} catch (e) {
if (
e.code !== 'MODULE_NOT_FOUND' ||
options?.shouldAutoInstall !== true
) {
if (
e.code === 'MODULE_NOT_FOUND' &&
options?.shouldAutoInstall !== true
) {
let err = new ThrowableDiagnostic({
diagnostic: {
message: escapeMarkdown(e.message),
hints: [
'Autoinstall is disabled, please install this package manually and restart Parcel.',
],
},
});
// $FlowFixMe - needed for loadParcelPlugin
err.code = 'MODULE_NOT_FOUND';
throw err;
} else {
throw e;
}
}
let conflicts = await getConflictingLocalDependencies(
this.fs,
name,
from,
this.projectRoot,
);
if (conflicts == null) {
this.invalidate(id, from);
await this.install([{name, range: options?.range}], from, {
saveDev: options?.saveDev ?? true,
});
return this.resolve(id, from, {
...options,
shouldAutoInstall: false,
});
}
throw new ThrowableDiagnostic({
diagnostic: conflicts.fields.map(field => ({
message: md`Could not find module "${name}", but it was listed in package.json. Run your package manager first.`,
origin: '@parcel/package-manager',
codeFrames: [
{
filePath: conflicts.filePath,
language: 'json',
code: conflicts.json,
codeHighlights: generateJSONCodeHighlights(conflicts.json, [
{
key: `/${field}/${encodeJSONKeyComponent(name)}`,
type: 'key',
message: 'Defined here, but not installed',
},
]),
},
],
})),
});
}
let range = options?.range;
if (range != null) {
let pkg = resolved.pkg;
if (pkg == null || !semver.satisfies(pkg.version, range)) {
let conflicts = await getConflictingLocalDependencies(
this.fs,
name,
from,
this.projectRoot,
);
if (conflicts == null && options?.shouldAutoInstall === true) {
this.invalidate(id, from);
await this.install([{name, range}], from);
return this.resolve(id, from, {
...options,
shouldAutoInstall: false,
});
} else if (conflicts != null) {
throw new ThrowableDiagnostic({
diagnostic: {
message: md`Could not find module "${name}" satisfying ${range}.`,
origin: '@parcel/package-manager',
codeFrames: [
{
filePath: conflicts.filePath,
language: 'json',
code: conflicts.json,
codeHighlights: generateJSONCodeHighlights(
conflicts.json,
conflicts.fields.map(field => ({
key: `/${field}/${encodeJSONKeyComponent(name)}`,
type: 'key',
message: 'Found this conflicting local requirement.',
})),
),
},
],
},
});
}
let version = pkg?.version;
let message = md`Could not resolve package "${name}" that satisfies ${range}.`;
if (version != null) {
message += md` Found ${version}.`;
}
throw new ThrowableDiagnostic({
diagnostic: {
message,
hints: [
'Looks like the incompatible version was installed transitively. Add this package as a direct dependency with a compatible version range.',
],
},
});
}
}
cache.set(key, resolved);
invalidationsCache.clear();
// Add the specifier as a child to the parent module.
// Don't do this if the specifier was an absolute path, as this was likely a dynamically resolved path
// (e.g. babel uses require() to load .babelrc.js configs and we don't want them to be added as children of babel itself).
if (!path.isAbsolute(name)) {
let moduleChildren = children.get(from);
if (!moduleChildren) {
moduleChildren = new Set();
children.set(from, moduleChildren);
}
moduleChildren.add(name);
}
}
return resolved;
}
resolveSync(name: DependencySpecifier, from: FilePath): ResolveResult {
let basedir = path.dirname(from);
let key = basedir + ':' + name;
let resolved = cache.get(key);
if (!resolved) {
resolved = this.resolveInternal(name, from);
cache.set(key, resolved);
invalidationsCache.clear();
if (!path.isAbsolute(name)) {
let moduleChildren = children.get(from);
if (!moduleChildren) {
moduleChildren = new Set();
children.set(from, moduleChildren);
}
moduleChildren.add(name);
}
}
return resolved;
}
async install(
modules: Array<ModuleRequest>,
from: FilePath,
opts?: InstallOptions,
) {
await installPackage(this.fs, this, modules, from, this.projectRoot, {
packageInstaller: this.installer,
...opts,
});
}
getInvalidations(name: DependencySpecifier, from: FilePath): Invalidations {
let basedir = path.dirname(from);
let cacheKey = basedir + ':' + name;
let resolved = cache.get(cacheKey);
if (resolved && path.isAbsolute(resolved.resolved)) {
let cached = invalidationsCache.get(resolved.resolved);
if (cached != null) {
return cached;
}
let res = {
invalidateOnFileCreate: [],
invalidateOnFileChange: new Set(),
invalidateOnStartup: false,
};
let seen = new Set();
let addKey = (name, from) => {
let basedir = path.dirname(from);
let key = basedir + ':' + name;
if (seen.has(key)) {
return;
}
seen.add(key);
let resolved = cache.get(key);
if (!resolved || !path.isAbsolute(resolved.resolved)) {
return;
}
res.invalidateOnFileCreate.push(...resolved.invalidateOnFileCreate);
res.invalidateOnFileChange.add(resolved.resolved);
for (let file of resolved.invalidateOnFileChange) {
res.invalidateOnFileChange.add(file);
}
let moduleChildren = children.get(resolved.resolved);
if (moduleChildren) {
for (let specifier of moduleChildren) {
addKey(specifier, resolved.resolved);
}
}
};
addKey(name, from);
// If this is an ES module, we won't have any of the dependencies because import statements
// cannot be intercepted. Instead, ask the resolver to parse the file and recursively analyze the deps.
if (resolved.type === 2) {
let invalidations = this.resolver.getInvalidations(resolved.resolved);
invalidations.invalidateOnFileChange.forEach(i =>
res.invalidateOnFileChange.add(i),
);
invalidations.invalidateOnFileCreate.forEach(i =>
res.invalidateOnFileCreate.push(i),
);
res.invalidateOnStartup ||= invalidations.invalidateOnStartup;
if (res.invalidateOnStartup) {
logger.warn({
message: md`${path.relative(
this.projectRoot,
resolved.resolved,
)} contains non-statically analyzable dependencies in its module graph. This causes Parcel to invalidate the cache on startup.`,
origin: '@parcel/package-manager',
});
}
}
invalidationsCache.set(resolved.resolved, res);
return res;
}
return {
invalidateOnFileCreate: [],
invalidateOnFileChange: new Set(),
invalidateOnStartup: false,
};
}
invalidate(name: DependencySpecifier, from: FilePath) {
let seen = new Set();
let invalidate = (name, from) => {
let basedir = path.dirname(from);
let key = basedir + ':' + name;
if (seen.has(key)) {
return;
}
seen.add(key);
let resolved = cache.get(key);
if (!resolved || !path.isAbsolute(resolved.resolved)) {
return;
}
invalidationsCache.delete(resolved.resolved);
// $FlowFixMe
let module = Module._cache[resolved.resolved];
if (module) {
// $FlowFixMe
delete Module._cache[resolved.resolved];
}
let moduleChildren = children.get(resolved.resolved);
if (moduleChildren) {
for (let specifier of moduleChildren) {
invalidate(specifier, resolved.resolved);
}
}
children.delete(resolved.resolved);
cache.delete(key);
};
invalidate(name, from);
this.resolver = this._createResolver();
}
resolveInternal(name: string, from: string): ResolveResult {
if (this.resolver == null) {
this.resolver = this._createResolver();
}
let res = this.resolver.resolve({
filename: name,
specifierType: 'commonjs',
parent: from,
});
// Invalidate whenever the .pnp.js file changes.
// TODO: only when we actually resolve a node_modules package?
if (process.versions.pnp != null && res.invalidateOnFileChange) {
// $FlowFixMe[prop-missing]
let pnp = Module.findPnpApi(path.dirname(from));
res.invalidateOnFileChange.push(pnp.resolveToUnqualified('pnpapi', null));
}
if (res.error) {
let e = new Error(`Could not resolve module "${name}" from "${from}"`);
// $FlowFixMe
e.code = 'MODULE_NOT_FOUND';
throw e;
}
let getPkg;
switch (res.resolution.type) {
case 'Path':
getPkg = () => {
let pkgPath = this.fs.findAncestorFile(
['package.json'],
nullthrows(res.resolution.value),
this.projectRoot,
);
return pkgPath
? JSON.parse(this.fs.readFileSync(pkgPath, 'utf8'))
: null;
};
// fallthrough
case 'Builtin':
return {
resolved: res.resolution.value,
invalidateOnFileChange: new Set(res.invalidateOnFileChange),
invalidateOnFileCreate: res.invalidateOnFileCreate,
type: res.moduleType,
get pkg() {
return getPkg();
},
};
default:
throw new Error('Unknown resolution type');
}
}
}
registerSerializableClass(
`${pkg.version}:NodePackageManager`,
NodePackageManager,
);