/
ModuleResolution.js
377 lines (347 loc) Β· 10.5 KB
/
ModuleResolution.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
/**
* 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
*/
'use strict';
import type {
CustomResolver,
DoesFileExist,
FileCandidates,
IsAssetFile,
RealPath,
Resolution,
ResolveAsset,
} from 'metro-resolver';
import type {ResolverInputOptions} from '../../shared/types.flow';
import type {PackageInfo, PackageJson} from 'metro-resolver/src/types';
const {codeFrameColumns} = require('@babel/code-frame');
const fs = require('fs');
const invariant = require('invariant');
const Resolver = require('metro-resolver');
const createDefaultContext = require('metro-resolver/src/createDefaultContext');
const path = require('path');
const util = require('util');
import type {BundlerResolution} from '../../DeltaBundler/types.flow';
export type DirExistsFn = (filePath: string) => boolean;
export type Packageish = interface {
path: string,
read(): PackageJson,
};
export type Moduleish = interface {
+path: string,
getPackage(): ?Packageish,
};
export type ModuleishCache<TPackage> = interface {
getPackage(
name: string,
platform?: string,
supportsNativePlatform?: boolean,
): TPackage,
getPackageOf(modulePath: string): ?TPackage,
};
type Options<TPackage> = $ReadOnly<{
dirExists: DirExistsFn,
disableHierarchicalLookup: boolean,
doesFileExist: DoesFileExist,
emptyModulePath: string,
extraNodeModules: ?Object,
getHasteModulePath: (name: string, platform: ?string) => ?string,
getHastePackagePath: (name: string, platform: ?string) => ?string,
isAssetFile: IsAssetFile,
mainFields: $ReadOnlyArray<string>,
moduleCache: ModuleishCache<TPackage>,
nodeModulesPaths: $ReadOnlyArray<string>,
preferNativePlatform: boolean,
projectRoot: string,
resolveAsset: ResolveAsset,
resolveRequest: ?CustomResolver,
sourceExts: $ReadOnlyArray<string>,
unstable_conditionNames: $ReadOnlyArray<string>,
unstable_conditionsByPlatform: $ReadOnly<{
[platform: string]: $ReadOnlyArray<string>,
}>,
unstable_enablePackageExports: boolean,
unstable_realPath: ?RealPath,
}>;
class ModuleResolver<TPackage: Packageish> {
_options: Options<TPackage>;
// A module representing the project root, used as the origin when resolving `emptyModulePath`.
_projectRootFakeModule: Moduleish;
// An empty module, the result of resolving `emptyModulePath` from the project root.
_cachedEmptyModule: ?BundlerResolution;
// $FlowFixMe[missing-local-annot]
constructor(options: Options<TPackage>) {
this._options = options;
const {projectRoot, moduleCache} = this._options;
this._projectRootFakeModule = {
path: path.join(projectRoot, '_'),
getPackage: () =>
moduleCache.getPackageOf(this._projectRootFakeModule.path),
isHaste() {
throw new Error('not implemented');
},
getName() {
throw new Error('not implemented');
},
};
}
_getEmptyModule(): BundlerResolution {
let emptyModule = this._cachedEmptyModule;
if (!emptyModule) {
emptyModule = this.resolveDependency(
this._projectRootFakeModule,
this._options.emptyModulePath,
false,
null,
/* resolverOptions */ {},
);
this._cachedEmptyModule = emptyModule;
}
return emptyModule;
}
resolveDependency(
fromModule: Moduleish,
moduleName: string,
allowHaste: boolean,
platform: string | null,
resolverOptions: ResolverInputOptions,
): BundlerResolution {
const {
disableHierarchicalLookup,
doesFileExist,
extraNodeModules,
isAssetFile,
mainFields,
nodeModulesPaths,
preferNativePlatform,
resolveAsset,
resolveRequest,
sourceExts,
unstable_conditionNames,
unstable_conditionsByPlatform,
unstable_enablePackageExports,
unstable_realPath,
} = this._options;
try {
const result = Resolver.resolve(
createDefaultContext({
allowHaste,
disableHierarchicalLookup,
doesFileExist,
extraNodeModules,
isAssetFile,
mainFields,
nodeModulesPaths,
preferNativePlatform,
resolveAsset,
resolveRequest,
sourceExts,
unstable_conditionNames,
unstable_conditionsByPlatform,
unstable_enablePackageExports,
unstable_realPath,
customResolverOptions: resolverOptions.customResolverOptions ?? {},
originModulePath: fromModule.path,
resolveHasteModule: (name: string) =>
this._options.getHasteModulePath(name, platform),
resolveHastePackage: (name: string) =>
this._options.getHastePackagePath(name, platform),
getPackage: this._getPackage,
getPackageForModule: (modulePath: string) =>
this._getPackageForModule(fromModule, modulePath),
}),
moduleName,
platform,
);
return this._getFileResolvedModule(result);
} catch (error) {
if (error instanceof Resolver.FailedToResolvePathError) {
const {candidates} = error;
throw new UnableToResolveError(
fromModule.path,
moduleName,
[
'\n\nNone of these files exist:',
` * ${Resolver.formatFileCandidates(
this._removeRoot(candidates.file),
)}`,
` * ${Resolver.formatFileCandidates(
this._removeRoot(candidates.dir),
)}`,
].join('\n'),
{
cause: error,
},
);
}
if (error instanceof Resolver.FailedToResolveNameError) {
const dirPaths = error.dirPaths;
const extraPaths = error.extraPaths;
const displayDirPaths = dirPaths
.filter((dirPath: string) => this._options.dirExists(dirPath))
.map(dirPath => path.relative(this._options.projectRoot, dirPath))
.concat(extraPaths);
const hint = displayDirPaths.length ? ' or in these directories:' : '';
throw new UnableToResolveError(
fromModule.path,
moduleName,
[
`${moduleName} could not be found within the project${hint || '.'}`,
...displayDirPaths.map((dirPath: string) => ` ${dirPath}`),
].join('\n'),
{
cause: error,
},
);
}
throw error;
}
}
_getPackage = (packageJsonPath: string): ?PackageJson => {
try {
return this._options.moduleCache.getPackage(packageJsonPath).read();
} catch (e) {
// Do nothing. The standard module cache does not trigger any error, but
// the ModuleGraph one does, if the module does not exist.
}
return null;
};
_getPackageForModule = (
fromModule: Moduleish,
modulePath: string,
): ?PackageInfo => {
let pkg;
try {
pkg = this._options.moduleCache.getPackageOf(modulePath);
} catch (e) {
// Do nothing. The standard module cache does not trigger any error, but
// the ModuleGraph one does, if the module does not exist.
}
return pkg != null
? {
rootPath: path.dirname(pkg.path),
packageJson: pkg.read(),
}
: null;
};
/**
* TODO: Return Resolution instead of coercing to BundlerResolution here
*/
_getFileResolvedModule(resolution: Resolution): BundlerResolution {
switch (resolution.type) {
case 'sourceFile':
return resolution;
case 'assetFiles':
// FIXME: we should forward ALL the paths/metadata,
// not just an arbitrary item!
const arbitrary = getArrayLowestItem(resolution.filePaths);
invariant(arbitrary != null, 'invalid asset resolution');
return {type: 'sourceFile', filePath: arbitrary};
case 'empty':
return this._getEmptyModule();
default:
(resolution.type: empty);
throw new Error('invalid type');
}
}
_removeRoot(candidates: FileCandidates): FileCandidates {
if (candidates.filePathPrefix) {
candidates.filePathPrefix = path.relative(
this._options.projectRoot,
candidates.filePathPrefix,
);
}
return candidates;
}
}
function getArrayLowestItem(a: $ReadOnlyArray<string>): string | void {
if (a.length === 0) {
return undefined;
}
let lowest = a[0];
for (let i = 1; i < a.length; ++i) {
if (a[i] < lowest) {
lowest = a[i];
}
}
return lowest;
}
class UnableToResolveError extends Error {
/**
* File path of the module that tried to require a module, ex. `/js/foo.js`.
*/
originModulePath: string;
/**
* The name of the module that was required, no necessarily a path,
* ex. `./bar`, or `invariant`.
*/
targetModuleName: string;
/**
* Original error that causes this error
*/
cause: ?Error;
constructor(
originModulePath: string,
targetModuleName: string,
message: string,
options?: $ReadOnly<{
cause?: Error,
}>,
) {
super();
this.originModulePath = originModulePath;
this.targetModuleName = targetModuleName;
const codeFrameMessage = this.buildCodeFrameMessage();
this.message =
util.format(
'Unable to resolve module %s from %s: %s',
targetModuleName,
originModulePath,
message,
) + (codeFrameMessage ? '\n' + codeFrameMessage : '');
this.cause = options?.cause;
}
buildCodeFrameMessage(): ?string {
let file;
try {
file = fs.readFileSync(this.originModulePath, 'utf8');
} catch (error) {
if (error.code === 'ENOENT' || error.code === 'EISDIR') {
// We're probably dealing with a virtualised file system where
// `this.originModulePath` doesn't actually exist on disk.
// We can't show a code frame, but there's no need to let this I/O
// error shadow the original module resolution error.
return null;
}
throw error;
}
const lines = file.split('\n');
let lineNumber = 0;
let column = -1;
for (let line = 0; line < lines.length; line++) {
const columnLocation = lines[line].lastIndexOf(this.targetModuleName);
if (columnLocation >= 0) {
lineNumber = line;
column = columnLocation;
break;
}
}
return codeFrameColumns(
fs.readFileSync(this.originModulePath, 'utf8'),
{
start: {column: column + 1, line: lineNumber + 1},
},
{forceColor: process.env.NODE_ENV !== 'test'},
);
}
}
module.exports = {
ModuleResolver,
UnableToResolveError,
};