/
ModuleFinder.js
228 lines (210 loc) · 6.72 KB
/
ModuleFinder.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
import path from 'path';
import logLevel from 'loglevel';
import ExportsStorage from './ExportsStorage';
import Watcher from './Watcher';
import findExports from './findExports';
import findPackageDependencies from './findPackageDependencies';
import readFile from './readFile';
import requireResolve from './requireResolve';
function assumedLocalPath(pathToResolvedPackageFile, packageName) {
const i = pathToResolvedPackageFile.indexOf(`/${packageName}/`);
return `./node_modules/${pathToResolvedPackageFile.slice(i + 1)}`;
}
/**
* Checks for package.json or npm-shrinkwrap.json inside a list of files and
* expands the list of files to include package dependencies if so.
*/
function expandFiles(files, workingDirectory) {
return new Promise((resolve) => {
const result = new Set([]);
files.forEach((file) => {
if (file.path !== './package.json' &&
file.path !== './npm-shrinkwrap.json') {
result.add(file);
return;
}
findPackageDependencies(workingDirectory, true).forEach((dep) => {
const pathToResolve = path.join(
workingDirectory,
'node_modules',
dep
);
const resolvedPath = requireResolve(pathToResolve);
if (resolvedPath === pathToResolve) {
// Ignore
return;
}
result.add({
path: assumedLocalPath(resolvedPath, dep),
mtime: file.mtime,
alias: dep,
});
});
});
resolve([...result]);
});
}
function aliasedExportNames(alias, ignorePackagePrefixes) {
const result = [alias];
ignorePackagePrefixes.forEach((prefix) => {
if (alias.startsWith(prefix)) {
result.push(alias.slice(prefix.length));
}
});
return result;
}
function defaultExportNames(pathToFile) {
const parsed = path.parse(pathToFile);
let fileName = parsed.name;
let dirName = path.basename(parsed.dir);
if (/package\.json|index\.jsx?/.test(parsed.base)) {
fileName = dirName;
dirName = path.basename(path.dirname(parsed.dir));
}
if (dirName === '.') {
return [fileName];
}
const result = [
`${dirName}-${fileName}`,
fileName,
];
if (/e?s$/.test(dirName)) {
// When the directory has an "s" (or "es") at the end, we assume it's a
// plural form of something. We then add a third name to the list. As an
// example, if we have './mocks/ModuleFinder.js' as the pathToFile, we add
// 'mock-ModuleFinder' here, which will allow the user to find the module
// with `MockModuleFinder` as the variable name.
result.push(`${dirName.replace(/e?s$/, '')}-${fileName}`);
}
return result;
}
const instances = {};
export default class ModuleFinder {
/**
* Factory method to get an instance for a specific working directory.
*/
static getForWorkingDirectory(workingDirectory, { excludes, ignorePackagePrefixes }) {
let instance = instances[workingDirectory];
if (!instance) {
instance = new ModuleFinder(workingDirectory, {
excludes,
ignorePackagePrefixes,
});
instances[workingDirectory] = instance;
}
return instance;
}
constructor(workingDirectory, { excludes, ignorePackagePrefixes }) {
this.excludes = excludes;
this.ignorePackagePrefixes = ignorePackagePrefixes;
this.workingDirectory = workingDirectory;
this.storage = new ExportsStorage();
this.watcher = new Watcher({
workingDirectory,
excludes,
onFilesAdded: this.handleFilesAdded.bind(this),
onFilesRemoved: this.handleFilesRemoved.bind(this),
storage: this.storage,
});
this.queue = [];
this.processingQueue = false;
}
initializeStorage(dbFilename) {
return this.storage.init(dbFilename)
.then(() => Promise.all(this.excludes.map((globPattern) =>
this.storage.removeAll(globPattern))))
.then(() => this.storage.purgeDeadNodeModules(this.workingDirectory));
}
startWatcher() {
return this.watcher.initialize();
}
processQueue(done) {
const file = this.queue.pop();
if (!file) {
this.processingQueue = false;
logLevel.debug('Queue empty');
done();
return;
}
const { path: pathToFile, mtime, alias } = file;
this.processingQueue = true;
logLevel.debug(`Processing ${pathToFile}`);
const fullPath = path.join(this.workingDirectory, pathToFile);
readFile(fullPath).then((data) => {
let exports = { named: [], hasDefault: true };
try {
exports = findExports(data, fullPath);
} catch (e) {
logLevel.error(`Failed to parse ${pathToFile}`, e.message, e.stack);
}
if (exports.named.length || exports.hasDefault) {
const all = exports.named.slice(0);
if (exports.hasDefault) {
all.push('default');
}
logLevel.debug(
`Found exports for ${pathToFile}:\n${all.join(', ')}`);
} else {
logLevel.debug(`No exports found for ${pathToFile}`);
}
const defaultNames = [];
if (exports.hasDefault) {
if (alias) {
defaultNames.push(...aliasedExportNames(alias, this.ignorePackagePrefixes));
} else {
defaultNames.push(...defaultExportNames(pathToFile));
}
}
this.storage.update({
names: exports.named,
defaultNames,
pathToFile,
mtime,
}).then(() => {
this.processQueue(done);
}).catch((error) => {
logLevel.error(
`Failed to update ${pathToFile} in storage. Reason: ${error.message}`);
this.processQueue(done);
});
}).catch((err) => {
logLevel.error(err.message);
this.processQueue(done);
});
}
handleFilesAdded(unexpandedFiles) {
return new Promise((resolve) => {
expandFiles(unexpandedFiles, this.workingDirectory).then((files) => {
logLevel.debug(`Checking ${files.length} files for potential updates`);
this.storage.needsUpdate(files).then((filesToUpdate) => {
logLevel.debug(`Got ${filesToUpdate.length} files to update`);
if (!filesToUpdate.length) {
resolve();
return;
}
filesToUpdate.forEach((file) => {
this.queue.unshift(file);
if (!this.processingQueue) {
logLevel.debug('Kicking off queue');
this.processQueue(resolve);
}
});
});
});
});
}
handleFilesRemoved(files) {
if (!files.length) {
return Promise.resolve();
}
logLevel.debug(`Removing ${files.length} files`);
const promises = files.map(({ path: pathToFile }) => {
logLevel.debug(`Removing ${pathToFile}`);
return this.storage.remove(pathToFile);
});
return Promise.all(promises);
}
find(variableName) {
return this.storage.get(variableName);
}
}