Resolver.js
8.91 KB
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
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const util = require("util");
const Tapable = require("tapable/lib/Tapable");
const SyncHook = require("tapable/lib/SyncHook");
const AsyncSeriesBailHook = require("tapable/lib/AsyncSeriesBailHook");
const AsyncSeriesHook = require("tapable/lib/AsyncSeriesHook");
const createInnerContext = require("./createInnerContext");
const REGEXP_NOT_MODULE = /^\.$|^\.[\\/]|^\.\.$|^\.\.[\\/]|^\/|^[A-Z]:[\\/]/i;
const REGEXP_DIRECTORY = /[\\/]$/i;
const memoryFsJoin = require("memory-fs/lib/join");
const memoizedJoin = new Map();
const memoryFsNormalize = require("memory-fs/lib/normalize");
function withName(name, hook) {
hook.name = name;
return hook;
}
function toCamelCase(str) {
return str.replace(/-([a-z])/g, str => str.substr(1).toUpperCase());
}
const deprecatedPushToMissing = util.deprecate((set, item) => {
set.add(item);
}, "Resolver: 'missing' is now a Set. Use add instead of push.");
const deprecatedResolveContextInCallback = util.deprecate(x => {
return x;
}, "Resolver: The callback argument was splitted into resolveContext and callback.");
const deprecatedHookAsString = util.deprecate(x => {
return x;
}, "Resolver#doResolve: The type arguments (string) is now a hook argument (Hook). Pass a reference to the hook instead.");
class Resolver extends Tapable {
constructor(fileSystem) {
super();
this.fileSystem = fileSystem;
this.hooks = {
resolveStep: withName("resolveStep", new SyncHook(["hook", "request"])),
noResolve: withName("noResolve", new SyncHook(["request", "error"])),
resolve: withName(
"resolve",
new AsyncSeriesBailHook(["request", "resolveContext"])
),
result: new AsyncSeriesHook(["result", "resolveContext"])
};
this._pluginCompat.tap("Resolver: before/after", options => {
if (/^before-/.test(options.name)) {
options.name = options.name.substr(7);
options.stage = -10;
} else if (/^after-/.test(options.name)) {
options.name = options.name.substr(6);
options.stage = 10;
}
});
this._pluginCompat.tap("Resolver: step hooks", options => {
const name = options.name;
const stepHook = !/^resolve(-s|S)tep$|^no(-r|R)esolve$/.test(name);
if (stepHook) {
options.async = true;
this.ensureHook(name);
const fn = options.fn;
options.fn = (request, resolverContext, callback) => {
const innerCallback = (err, result) => {
if (err) return callback(err);
if (result !== undefined) return callback(null, result);
callback();
};
for (const key in resolverContext) {
innerCallback[key] = resolverContext[key];
}
fn.call(this, request, innerCallback);
};
}
});
}
ensureHook(name) {
if (typeof name !== "string") return name;
name = toCamelCase(name);
if (/^before/.test(name)) {
return this.ensureHook(
name[6].toLowerCase() + name.substr(7)
).withOptions({
stage: -10
});
}
if (/^after/.test(name)) {
return this.ensureHook(
name[5].toLowerCase() + name.substr(6)
).withOptions({
stage: 10
});
}
const hook = this.hooks[name];
if (!hook) {
return (this.hooks[name] = withName(
name,
new AsyncSeriesBailHook(["request", "resolveContext"])
));
}
return hook;
}
getHook(name) {
if (typeof name !== "string") return name;
name = toCamelCase(name);
if (/^before/.test(name)) {
return this.getHook(name[6].toLowerCase() + name.substr(7)).withOptions({
stage: -10
});
}
if (/^after/.test(name)) {
return this.getHook(name[5].toLowerCase() + name.substr(6)).withOptions({
stage: 10
});
}
const hook = this.hooks[name];
if (!hook) {
throw new Error(`Hook ${name} doesn't exist`);
}
return hook;
}
resolveSync(context, path, request) {
let err,
result,
sync = false;
this.resolve(context, path, request, {}, (e, r) => {
err = e;
result = r;
sync = true;
});
if (!sync)
throw new Error(
"Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!"
);
if (err) throw err;
return result;
}
resolve(context, path, request, resolveContext, callback) {
// TODO remove in enhanced-resolve 5
// For backward compatiblity START
if (typeof callback !== "function") {
callback = deprecatedResolveContextInCallback(resolveContext);
// resolveContext is a function containing additional properties
// It's now used for resolveContext and callback
}
// END
const obj = {
context: context,
path: path,
request: request
};
const message = "resolve '" + request + "' in '" + path + "'";
// Try to resolve assuming there is no error
// We don't log stuff in this case
return this.doResolve(
this.hooks.resolve,
obj,
message,
{
missing: resolveContext.missing,
stack: resolveContext.stack
},
(err, result) => {
if (!err && result) {
return callback(
null,
result.path === false ? false : result.path + (result.query || ""),
result
);
}
const localMissing = new Set();
// TODO remove in enhanced-resolve 5
localMissing.push = item => deprecatedPushToMissing(localMissing, item);
const log = [];
return this.doResolve(
this.hooks.resolve,
obj,
message,
{
log: msg => {
if (resolveContext.log) {
resolveContext.log(msg);
}
log.push(msg);
},
missing: localMissing,
stack: resolveContext.stack
},
(err, result) => {
if (err) return callback(err);
const error = new Error("Can't " + message);
error.details = log.join("\n");
error.missing = Array.from(localMissing);
this.hooks.noResolve.call(obj, error);
return callback(error);
}
);
}
);
}
doResolve(hook, request, message, resolveContext, callback) {
// TODO remove in enhanced-resolve 5
// For backward compatiblity START
if (typeof callback !== "function") {
callback = deprecatedResolveContextInCallback(resolveContext);
// resolveContext is a function containing additional properties
// It's now used for resolveContext and callback
}
if (typeof hook === "string") {
const name = toCamelCase(hook);
hook = deprecatedHookAsString(this.hooks[name]);
if (!hook) {
throw new Error(`Hook "${name}" doesn't exist`);
}
}
// END
if (typeof callback !== "function")
throw new Error("callback is not a function " + Array.from(arguments));
if (!resolveContext)
throw new Error(
"resolveContext is not an object " + Array.from(arguments)
);
const stackLine =
hook.name +
": (" +
request.path +
") " +
(request.request || "") +
(request.query || "") +
(request.directory ? " directory" : "") +
(request.module ? " module" : "");
let newStack;
if (resolveContext.stack) {
newStack = new Set(resolveContext.stack);
if (resolveContext.stack.has(stackLine)) {
// Prevent recursion
const recursionError = new Error(
"Recursion in resolving\nStack:\n " +
Array.from(newStack).join("\n ")
);
recursionError.recursion = true;
if (resolveContext.log)
resolveContext.log("abort resolving because of recursion");
return callback(recursionError);
}
newStack.add(stackLine);
} else {
newStack = new Set([stackLine]);
}
this.hooks.resolveStep.call(hook, request);
if (hook.isUsed()) {
const innerContext = createInnerContext(
{
log: resolveContext.log,
missing: resolveContext.missing,
stack: newStack
},
message
);
return hook.callAsync(request, innerContext, (err, result) => {
if (err) return callback(err);
if (result) return callback(null, result);
callback();
});
} else {
callback();
}
}
parse(identifier) {
if (identifier === "") return null;
const part = {
request: "",
query: "",
module: false,
directory: false,
file: false
};
const idxQuery = identifier.indexOf("?");
if (idxQuery === 0) {
part.query = identifier;
} else if (idxQuery > 0) {
part.request = identifier.slice(0, idxQuery);
part.query = identifier.slice(idxQuery);
} else {
part.request = identifier;
}
if (part.request) {
part.module = this.isModule(part.request);
part.directory = this.isDirectory(part.request);
if (part.directory) {
part.request = part.request.substr(0, part.request.length - 1);
}
}
return part;
}
isModule(path) {
return !REGEXP_NOT_MODULE.test(path);
}
isDirectory(path) {
return REGEXP_DIRECTORY.test(path);
}
join(path, request) {
let cacheEntry;
let pathCache = memoizedJoin.get(path);
if (typeof pathCache === "undefined") {
memoizedJoin.set(path, (pathCache = new Map()));
} else {
cacheEntry = pathCache.get(request);
if (typeof cacheEntry !== "undefined") return cacheEntry;
}
cacheEntry = memoryFsJoin(path, request);
pathCache.set(request, cacheEntry);
return cacheEntry;
}
normalize(path) {
return memoryFsNormalize(path);
}
}
module.exports = Resolver;