-
Notifications
You must be signed in to change notification settings - Fork 13
/
Copy pathinstall.js
78 lines (64 loc) · 1.94 KB
/
install.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
const AdaptiveFS = require('arc-fs');
const Module = require('module');
const resolve = require('resolve');
const path = require('path');
const AdaptiveProxy = require('./proxy');
const afs = new AdaptiveFS();
const proxyCache = Object.create(null);
Module.prototype._originalRequire = Module.prototype.require;
Module.prototype.require = function(request) {
let resolvedPath;
if (isCoreModule(request)) {
return this._originalRequire(request);
}
try {
resolvedPath = resolveCached(request, this);
} catch(e) {
return this._originalRequire(request);
}
const isAdaptive = afs.isAdaptiveSync(resolvedPath);
if (isAdaptive) {
return proxyCache[resolvedPath] = proxyCache[resolvedPath] || new AdaptiveProxy(
afs.getMatchesSync(resolvedPath).map(path => this._originalRequire(path))
);
}
return this._originalRequire(request);
};
let coreModules;
const isCoreModule = Module.isBuiltin || (moduleName => {
if (moduleName.startsWith('node:')) {
return true;
}
if (!coreModules) {
let coreModulesNames = Object.keys(process.binding('natives'));
coreModules = coreModulesNames.reduce(
(object, name) => ((object[name] = true), object),
{}
);
}
return coreModules[moduleName];
});
let resolveCache = Object.create(null);
function resolveCached(request, module) {
const basedir = module.filename
? path.dirname(module.filename)
: /* istanbul ignore next: fallback for node repl */ process.cwd();
const extensions = Object.keys(require.extensions);
const cacheKey = request + '|' + basedir;
let resolvedPath;
if (!(resolvedPath = resolveCache[cacheKey])) {
resolvedPath = resolveCache[cacheKey] = resolve.sync(request, {
basedir,
extensions,
readFileSync: afs.readFileSync,
isFile: file => {
try {
return afs.statSync(file).isFile();
} catch (e) {
return false;
}
}
});
}
return resolvedPath;
}