/
NodePackageManager.js
423 lines (373 loc) Β· 12.2 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
// @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 nativeFS from 'fs';
import Module from 'module';
import path from 'path';
import semver from 'semver';
import {getModuleParts} from '@parcel/utils';
import {getConflictingLocalDependencies} from './utils';
import {installPackage} from './installPackage';
import pkg from '../package.json';
import {NodeResolver} from './NodeResolver';
import {NodeResolverSync} from './NodeResolverSync';
// 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>>();
// 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: NodeResolver;
syncResolver: NodeResolverSync;
invalidationsCache: Map<string, Invalidations> = new Map();
constructor(
fs: FileSystem,
projectRoot: FilePath,
installer?: ?PackageInstaller,
) {
this.fs = fs;
this.projectRoot = projectRoot;
this.installer = installer;
this.resolver = new NodeResolver(this.fs, projectRoot);
this.syncResolver = new NodeResolverSync(this.fs, projectRoot);
}
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} = await this.resolve(name, from, opts);
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 = nativeFS.readFileSync;
// $FlowFixMe
nativeFS.readFileSync = (filename, encoding) => {
// $FlowFixMe
nativeFS.readFileSync = readFileSync;
return this.fs.readFileSync(filename, encoding);
};
try {
m.load(filePath);
} catch (err) {
// $FlowFixMe[prop-missing]
delete Module._cache[filePath];
throw err;
}
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 = await this.resolver.resolve(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) {
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) {
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);
this.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.syncResolver.resolve(name, from);
cache.set(key, resolved);
this.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 key = name + ':' + from;
let cached = this.invalidationsCache.get(key);
if (cached != null) {
return cached;
}
let res = {
invalidateOnFileCreate: [],
invalidateOnFileChange: new Set(),
};
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);
this.invalidationsCache.set(key, res);
return res;
}
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;
}
// $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);
this.resolver.invalidate(resolved.resolved);
this.syncResolver.invalidate(resolved.resolved);
};
invalidate(name, from);
}
}
registerSerializableClass(
`${pkg.version}:NodePackageManager`,
NodePackageManager,
);