/
DependencyGraph.js
384 lines (337 loc) Β· 11.9 KB
/
DependencyGraph.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
/**
* Copyright (c) Meta Platforms, Inc. and affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
* @format
* @oncall react_native
*/
import type Package from './Package';
import type {ConfigT} from 'metro-config/src/configTypes.flow';
import type MetroFileMap, {
ChangeEvent,
FileSystem,
IModuleMap,
HealthCheckResult,
WatcherStatus,
} from 'metro-file-map';
import {DuplicateHasteCandidatesError} from 'metro-file-map';
const canonicalize = require('metro-core/src/canonicalize');
const createHasteMap = require('./DependencyGraph/createHasteMap');
const {ModuleResolver} = require('./DependencyGraph/ModuleResolution');
const ModuleCache = require('./ModuleCache');
const {EventEmitter} = require('events');
const fs = require('fs');
const {
AmbiguousModuleResolutionError,
Logger: {createActionStartEntry, createActionEndEntry, log},
PackageResolutionError,
} = require('metro-core');
const {InvalidPackageError} = require('metro-resolver');
const nullthrows = require('nullthrows');
const path = require('path');
import type {ResolverInputOptions} from '../shared/types.flow';
import type {BundlerResolution} from '../DeltaBundler/types.flow';
const NULL_PLATFORM = Symbol();
function getOrCreateMap<T>(
map: Map<string | symbol, Map<string | symbol, T>>,
field: string,
): Map<string | symbol, T> {
let subMap = map.get(field);
if (!subMap) {
subMap = new Map();
map.set(field, subMap);
}
return subMap;
}
class DependencyGraph extends EventEmitter {
_assetExtensions: Set<string>;
_config: ConfigT;
_haste: MetroFileMap;
_fileSystem: FileSystem;
_moduleCache: ModuleCache;
_hasteModuleMap: IModuleMap;
_moduleResolver: ModuleResolver<Package>;
_resolutionCache: Map<
// Custom resolver options
string | symbol,
Map<
// Origin folder
string | symbol,
Map<
// Dependency name
string | symbol,
Map<
// Platform
string | symbol,
BundlerResolution,
>,
>,
>,
>;
_readyPromise: Promise<void>;
constructor(
config: ConfigT,
options?: {
+hasReducedPerformance?: boolean,
+watch?: boolean,
},
) {
super();
this._config = config;
this._assetExtensions = new Set(
config.resolver.assetExts.map(asset => '.' + asset),
);
const {hasReducedPerformance, watch} = options ?? {};
const initializingMetroLogEntry = log(
createActionStartEntry('Initializing Metro'),
);
config.reporter.update({
type: 'dep_graph_loading',
hasReducedPerformance: !!hasReducedPerformance,
});
const haste = createHasteMap(config, {watch});
// We can have a lot of graphs listening to Haste for changes.
// Bump this up to silence the max listeners EventEmitter warning.
haste.setMaxListeners(1000);
this._haste = haste;
this._haste.on('status', status => this._onWatcherStatus(status));
this._readyPromise = haste.build().then(({fileSystem, hasteModuleMap}) => {
log(createActionEndEntry(initializingMetroLogEntry));
config.reporter.update({type: 'dep_graph_loaded'});
this._fileSystem = fileSystem;
this._hasteModuleMap = hasteModuleMap;
this._haste.on('change', changeEvent => this._onHasteChange(changeEvent));
this._haste.on('healthCheck', result =>
this._onWatcherHealthCheck(result),
);
this._resolutionCache = new Map();
this._moduleCache = this._createModuleCache();
this._createModuleResolver();
});
}
_onWatcherHealthCheck(result: HealthCheckResult) {
this._config.reporter.update({type: 'watcher_health_check_result', result});
}
_onWatcherStatus(status: WatcherStatus) {
this._config.reporter.update({type: 'watcher_status', status});
}
// Waits for the dependency graph to become ready after initialisation.
// Don't read anything from the graph until this resolves.
async ready(): Promise<void> {
await this._readyPromise;
}
// Creates the dependency graph and waits for it to become ready.
// @deprecated Use the constructor + ready() directly.
static async load(
config: ConfigT,
options?: {+hasReducedPerformance?: boolean, +watch?: boolean},
): Promise<DependencyGraph> {
const self = new DependencyGraph(config, options);
await self.ready();
return self;
}
_getClosestPackage(filePath: string): ?string {
const parsedPath = path.parse(filePath);
const root = parsedPath.root;
let dir = parsedPath.dir;
do {
const candidate = path.join(dir, 'package.json');
if (this._fileSystem.exists(candidate)) {
return candidate;
}
dir = path.dirname(dir);
} while (dir !== '.' && dir !== root);
return null;
}
_onHasteChange({eventsQueue}: ChangeEvent) {
this._resolutionCache = new Map();
eventsQueue.forEach(({filePath}) => this._moduleCache.invalidate(filePath));
this._createModuleResolver();
this.emit('change');
}
_createModuleResolver() {
this._moduleResolver = new ModuleResolver({
dirExists: (filePath: string) => {
try {
return fs.lstatSync(filePath).isDirectory();
} catch (e) {}
return false;
},
disableHierarchicalLookup:
this._config.resolver.disableHierarchicalLookup,
doesFileExist: this._doesFileExist,
emptyModulePath: this._config.resolver.emptyModulePath,
extraNodeModules: this._config.resolver.extraNodeModules,
getHasteModulePath: (name, platform) =>
this._hasteModuleMap.getModule(name, platform, true),
getHastePackagePath: (name, platform) =>
this._hasteModuleMap.getPackage(name, platform, true),
isAssetFile: file => this._assetExtensions.has(path.extname(file)),
mainFields: this._config.resolver.resolverMainFields,
moduleCache: this._moduleCache,
nodeModulesPaths: this._config.resolver.nodeModulesPaths,
preferNativePlatform: true,
projectRoot: this._config.projectRoot,
resolveAsset: (dirPath: string, assetName: string, extension: string) => {
const basePath = dirPath + path.sep + assetName;
let assets = [
basePath + extension,
...this._config.resolver.assetResolutions.map(
resolution => basePath + '@' + resolution + 'x' + extension,
),
];
if (this._config.resolver.unstable_enableSymlinks) {
assets = assets
.map(candidate => this._fileSystem.realPath(candidate))
.filter(Boolean);
} else {
assets = assets.filter(candidate =>
this._fileSystem.exists(candidate),
);
}
return assets.length ? assets : null;
},
resolveRequest: this._config.resolver.resolveRequest,
sourceExts: this._config.resolver.sourceExts,
unstable_conditionNames: this._config.resolver.unstable_conditionNames,
unstable_conditionsByPlatform:
this._config.resolver.unstable_conditionsByPlatform,
unstable_enablePackageExports:
this._config.resolver.unstable_enablePackageExports,
unstable_realPath: this._config.resolver.unstable_enableSymlinks
? path => this._fileSystem.realPath(path)
: null,
});
}
_createModuleCache(): ModuleCache {
return new ModuleCache({
getClosestPackage: filePath => this._getClosestPackage(filePath),
});
}
getAllFiles(): Array<string> {
return nullthrows(this._fileSystem).getAllFiles();
}
getSha1(filename: string): string {
// TODO If it looks like we're trying to get the sha1 from a file located
// within a Zip archive, then we instead compute the sha1 for what looks
// like the Zip archive itself.
const splitIndex = filename.indexOf('.zip/');
const containerName =
splitIndex !== -1 ? filename.slice(0, splitIndex + 4) : filename;
// TODO Calling realpath allows us to get a hash for a given path even when
// it's a symlink to a file, which prevents Metro from crashing in such a
// case. However, it doesn't allow Metro to track changes to the target file
// of the symlink. We should fix this by implementing a symlink map into
// Metro (or maybe by implementing those "extra transformation sources" we've
// been talking about for stuff like CSS or WASM).
const resolvedPath = fs.realpathSync(containerName);
const sha1 = this._fileSystem.getSha1(resolvedPath);
if (!sha1) {
throw new ReferenceError(
`SHA-1 for file ${filename} (${resolvedPath}) is not computed.
Potential causes:
1) You have symlinks in your project - watchman does not follow symlinks.
2) Check \`blockList\` in your metro.config.js and make sure it isn't excluding the file path.`,
);
}
return sha1;
}
getWatcher(): EventEmitter {
return this._haste;
}
end() {
this._haste.end();
}
/** Given a search context, return a list of file paths matching the query. */
matchFilesWithContext(
from: string,
context: $ReadOnly<{
/* Should search for files recursively. */
recursive: boolean,
/* Filter relative paths against a pattern. */
filter: RegExp,
}>,
): string[] {
return this._fileSystem.matchFilesWithContext(from, context);
}
resolveDependency(
from: string,
to: string,
platform: string | null,
resolverOptions: ResolverInputOptions,
// TODO: Fold assumeFlatNodeModules into resolverOptions and add to graphId
{assumeFlatNodeModules}: {assumeFlatNodeModules: boolean} = {
assumeFlatNodeModules: false,
},
): BundlerResolution {
const isSensitiveToOriginFolder =
// Resolution is always relative to the origin folder unless we assume a flat node_modules
!assumeFlatNodeModules ||
// Path requests are resolved relative to the origin folder
to.includes('/') ||
to === '.' ||
to === '..' ||
// Preserve standard assumptions under node_modules
from.includes(path.sep + 'node_modules' + path.sep);
// Compound key for the resolver cache
const resolverOptionsKey =
JSON.stringify(
resolverOptions.customResolverOptions ?? {},
canonicalize,
) ?? '';
const originKey = isSensitiveToOriginFolder ? path.dirname(from) : '';
const targetKey = to;
const platformKey = platform ?? NULL_PLATFORM;
// Traverse the resolver cache, which is a tree of maps
const mapByResolverOptions = this._resolutionCache;
const mapByOrigin = getOrCreateMap(
mapByResolverOptions,
resolverOptionsKey,
);
const mapByTarget = getOrCreateMap(mapByOrigin, originKey);
const mapByPlatform = getOrCreateMap(mapByTarget, targetKey);
let resolution: ?BundlerResolution = mapByPlatform.get(platformKey);
if (!resolution) {
try {
resolution = this._moduleResolver.resolveDependency(
this._moduleCache.getModule(from),
to,
true,
platform,
resolverOptions,
);
} catch (error) {
if (error instanceof DuplicateHasteCandidatesError) {
throw new AmbiguousModuleResolutionError(from, error);
}
if (error instanceof InvalidPackageError) {
throw new PackageResolutionError({
packageError: error,
originModulePath: from,
targetModuleName: to,
});
}
throw error;
}
}
mapByPlatform.set(platformKey, resolution);
return resolution;
}
_doesFileExist = (filePath: string): boolean => {
return this._fileSystem.exists(filePath);
};
getHasteName(filePath: string): string {
const hasteName = this._fileSystem.getModuleName(filePath);
if (hasteName) {
return hasteName;
}
return path.relative(this._config.projectRoot, filePath);
}
getDependencies(filePath: string): Array<string> {
return nullthrows(this._fileSystem.getDependencies(filePath));
}
}
module.exports = DependencyGraph;