-
-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
Copy pathResolver.js
439 lines (366 loc) Β· 12.2 KB
/
Resolver.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
const builtins = require('./builtins');
const path = require('path');
const glob = require('glob');
const fs = require('./utils/fs');
const micromatch = require('micromatch');
const EMPTY_SHIM = require.resolve('./builtins/_empty');
const GLOB_RE = /[*+{}]/;
/**
* This resolver implements a modified version of the node_modules resolution algorithm:
* https://nodejs.org/api/modules.html#modules_all_together
*
* In addition to the standard algorithm, Parcel supports:
* - All file extensions supported by Parcel.
* - Glob file paths
* - Absolute paths (e.g. /foo) resolved relative to the project root.
* - Tilde paths (e.g. ~/foo) resolved relative to the nearest module root in node_modules.
* - The package.json module, jsnext:main, and browser field as replacements for package.main.
* - The package.json browser and alias fields as an alias map within a local module.
* - The package.json alias field in the root package for global aliases across all modules.
*/
class Resolver {
constructor(options = {}) {
this.options = options;
this.cache = new Map();
this.packageCache = new Map();
this.rootPackage = null;
}
async resolve(input, parent) {
let filename = input;
// Check the cache first
let key = this.getCacheKey(filename, parent);
if (this.cache.has(key)) {
return this.cache.get(key);
}
// Check if this is a glob
if (GLOB_RE.test(filename) && glob.hasMagic(filename)) {
return {path: path.resolve(path.dirname(parent), filename)};
}
// Get file extensions to search
let extensions = Array.isArray(this.options.extensions)
? this.options.extensions.slice()
: Object.keys(this.options.extensions);
if (parent) {
// parent's extension given high priority
const parentExt = path.extname(parent);
extensions = [parentExt, ...extensions.filter(ext => ext !== parentExt)];
}
extensions.unshift('');
// Resolve the module directory or local file path
let module = await this.resolveModule(filename, parent);
let resolved;
if (module.moduleDir) {
resolved = await this.loadNodeModules(module, extensions);
} else if (module.filePath) {
resolved = await this.loadRelative(module.filePath, extensions);
}
if (!resolved) {
let dir = parent ? path.dirname(parent) : process.cwd();
let err = new Error(`Cannot find module '${input}' from '${dir}'`);
err.code = 'MODULE_NOT_FOUND';
throw err;
}
this.cache.set(key, resolved);
return resolved;
}
async resolveModule(filename, parent) {
let dir = parent ? path.dirname(parent) : process.cwd();
// If this isn't the entrypoint, resolve the input file to an absolute path
if (parent) {
filename = this.resolveFilename(filename, dir);
}
// Resolve aliases in the parent module for this file.
filename = await this.loadAlias(filename, dir);
// Return just the file path if this is a file, not in node_modules
if (path.isAbsolute(filename)) {
return {
filePath: filename
};
}
// Resolve the module in node_modules
let resolved;
try {
resolved = await this.findNodeModulePath(filename, dir);
} catch (err) {
// ignore
}
// If we couldn't resolve the node_modules path, just return the module name info
if (!resolved) {
let parts = this.getModuleParts(filename);
resolved = {
moduleName: parts[0],
subPath: parts[1]
};
}
return resolved;
}
getCacheKey(filename, parent) {
return (parent ? path.dirname(parent) : '') + ':' + filename;
}
resolveFilename(filename, dir) {
switch (filename[0]) {
case '/':
// Absolute path. Resolve relative to project root.
return path.resolve(this.options.rootDir, filename.slice(1));
case '~':
// Tilde path. Resolve relative to nearest node_modules directory,
// or the project root - whichever comes first.
while (
dir !== this.options.rootDir &&
path.basename(path.dirname(dir)) !== 'node_modules'
) {
dir = path.dirname(dir);
}
return path.join(dir, filename.slice(1));
case '.':
// Relative path.
return path.resolve(dir, filename);
default:
// Module
return path.normalize(filename);
}
}
async loadRelative(filename, extensions) {
// Find a package.json file in the current package.
let pkg = await this.findPackage(path.dirname(filename));
// First try as a file, then as a directory.
return (
(await this.loadAsFile(filename, extensions, pkg)) ||
(await this.loadDirectory(filename, extensions, pkg))
);
}
async findNodeModulePath(filename, dir) {
if (builtins[filename]) {
return {filePath: builtins[filename]};
}
let parts = this.getModuleParts(filename);
let root = path.parse(dir).root;
while (dir !== root) {
// Skip node_modules directories
if (path.basename(dir) === 'node_modules') {
dir = path.dirname(dir);
}
try {
// First, check if the module directory exists. This prevents a lot of unnecessary checks later.
let moduleDir = path.join(dir, 'node_modules', parts[0]);
let stats = await fs.stat(moduleDir);
if (stats.isDirectory()) {
return {
moduleName: parts[0],
subPath: parts[1],
moduleDir: moduleDir,
filePath: path.join(dir, 'node_modules', filename)
};
}
} catch (err) {
// ignore
}
// Move up a directory
dir = path.dirname(dir);
}
}
async loadNodeModules(module, extensions) {
try {
// If a module was specified as a module sub-path (e.g. some-module/some/path),
// it is likely a file. Try loading it as a file first.
if (module.subPath) {
let pkg = await this.readPackage(module.moduleDir);
let res = await this.loadAsFile(module.filePath, extensions, pkg);
if (res) {
return res;
}
}
// Otherwise, load as a directory.
return await this.loadDirectory(module.filePath, extensions);
} catch (e) {
// ignore
}
}
async isFile(file) {
try {
let stat = await fs.stat(file);
return stat.isFile() || stat.isFIFO();
} catch (err) {
return false;
}
}
async loadDirectory(dir, extensions, pkg) {
try {
pkg = await this.readPackage(dir);
// First try loading package.main as a file, then try as a directory.
let main = this.getPackageMain(pkg);
let res =
(await this.loadAsFile(main, extensions, pkg)) ||
(await this.loadDirectory(main, extensions, pkg));
if (res) {
return res;
}
} catch (err) {
// ignore
}
// Fall back to an index file inside the directory.
return await this.loadAsFile(path.join(dir, 'index'), extensions, pkg);
}
async readPackage(dir) {
let file = path.join(dir, 'package.json');
if (this.packageCache.has(file)) {
return this.packageCache.get(file);
}
let json = await fs.readFile(file, 'utf8');
let pkg = JSON.parse(json);
pkg.pkgfile = file;
pkg.pkgdir = dir;
// If the package has a `source` field, check if it is behind a symlink.
// If so, we treat the module as source code rather than a pre-compiled module.
if (pkg.source) {
let realpath = await fs.realpath(file);
if (realpath === file) {
delete pkg.source;
}
}
this.packageCache.set(file, pkg);
return pkg;
}
getPackageMain(pkg) {
let {browser} = pkg;
if (typeof browser === 'object' && browser[pkg.name]) {
browser = browser[pkg.name];
}
// libraries like d3.js specifies node.js specific files in the "main" which breaks the build
// we use the "module" or "browser" field to get the full dependency tree if available.
// If this is a linked module with a `source` field, use that as the entry point.
let main = [pkg.source, pkg.module, browser, pkg.main].find(
entry => typeof entry === 'string'
);
// Default to index file if no main field find
if (!main || main === '.' || main === './') {
main = 'index';
}
return path.resolve(pkg.pkgdir, main);
}
async loadAsFile(file, extensions, pkg) {
// Try all supported extensions
for (let f of this.expandFile(file, extensions, pkg)) {
if (await this.isFile(f)) {
return {path: f, pkg};
}
}
}
expandFile(file, extensions, pkg, expandAliases = true) {
// Expand extensions and aliases
let res = [];
for (let ext of extensions) {
let f = file + ext;
if (expandAliases) {
let alias = this.resolveAliases(file + ext, pkg);
if (alias !== f) {
res = res.concat(this.expandFile(alias, extensions, pkg, false));
}
}
res.push(f);
}
return res;
}
resolveAliases(filename, pkg) {
// First resolve local package aliases, then project global ones.
return this.resolvePackageAliases(
this.resolvePackageAliases(filename, pkg),
this.rootPackage
);
}
resolvePackageAliases(filename, pkg) {
if (!pkg) {
return filename;
}
// Resolve aliases in the package.source, package.alias, and package.browser fields.
return (
this.getAlias(filename, pkg.pkgdir, pkg.source) ||
this.getAlias(filename, pkg.pkgdir, pkg.alias) ||
this.getAlias(filename, pkg.pkgdir, pkg.browser) ||
filename
);
}
getAlias(filename, dir, aliases) {
if (!filename || !aliases || typeof aliases !== 'object') {
return null;
}
let alias;
// If filename is an absolute path, get one relative to the package.json directory.
if (path.isAbsolute(filename)) {
filename = path.relative(dir, filename);
if (filename[0] !== '.') {
filename = './' + filename;
}
alias = this.lookupAlias(aliases, filename);
} else {
// It is a node_module. First try the entire filename as a key.
alias = aliases[filename];
if (alias == null) {
// If it didn't match, try only the module name.
let parts = this.getModuleParts(filename);
alias = aliases[parts[0]];
if (typeof alias === 'string') {
// Append the filename back onto the aliased module.
alias = path.join(alias, ...parts.slice(1));
}
}
}
// If the alias is set to `false`, return an empty file.
if (alias === false) {
return EMPTY_SHIM;
}
// If the alias is a relative path, then resolve
// relative to the package.json directory.
if (alias && alias[0] === '.') {
return path.resolve(dir, alias);
}
// Otherwise, assume the alias is a module
return alias;
}
lookupAlias(aliases, filename) {
// First, try looking up the exact filename
let alias = aliases[filename];
if (alias != null) {
return alias;
}
// Otherwise, try replacing glob keys
for (let key in aliases) {
if (GLOB_RE.test(key)) {
let re = micromatch.makeRe(key, {capture: true});
if (re.test(filename)) {
return filename.replace(re, aliases[key]);
}
}
}
}
async findPackage(dir) {
// Find the nearest package.json file within the current node_modules folder
let root = path.parse(dir).root;
while (dir !== root && path.basename(dir) !== 'node_modules') {
try {
return await this.readPackage(dir);
} catch (err) {
// ignore
}
dir = path.dirname(dir);
}
}
async loadAlias(filename, dir) {
// Load the root project's package.json file if we haven't already
if (!this.rootPackage) {
this.rootPackage = await this.findPackage(this.options.rootDir);
}
// Load the local package, and resolve aliases
let pkg = await this.findPackage(dir);
return this.resolveAliases(filename, pkg);
}
getModuleParts(name) {
let parts = path.normalize(name).split(path.sep);
if (parts[0].charAt(0) === '@') {
// Scoped module (e.g. @scope/module). Merge the first two parts back together.
parts.splice(0, 2, `${parts[0]}/${parts[1]}`);
}
return parts;
}
}
module.exports = Resolver;