ContextDependencyHelpers.js
2.7 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
/*
MIT License http://www.opensource.org/licenses/mit-license.php
Author Tobias Koppers @sokra
*/
"use strict";
const ContextDependencyHelpers = exports;
/**
* Escapes regular expression metacharacters
* @param {string} str String to quote
* @return {string} Escaped string
*/
function quotemeta(str) {
return str.replace(/[-[\]\\/{}()*+?.^$|]/g, "\\$&");
}
ContextDependencyHelpers.create = function(Dep, range, param, expr, options, chunkName) {
let dep;
let prefix;
let postfix;
let prefixRange;
let valueRange;
let idx;
let context;
let regExp;
if(param.isTemplateString()) {
prefix = param.quasis[0].string;
postfix = param.quasis.length > 1 ? param.quasis[param.quasis.length - 1].string : "";
prefixRange = [param.quasis[0].range[0], param.quasis[0].range[1]];
valueRange = param.range;
idx = prefix.lastIndexOf("/");
context = ".";
if(idx >= 0) {
context = prefix.substr(0, idx);
prefix = `.${prefix.substr(idx)}`;
}
// If there are more than two quasis, maybe the generated RegExp can be more precise?
regExp = new RegExp(`^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta(postfix)}$`);
dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange, chunkName);
dep.loc = expr.loc;
dep.replaces = [{
range: prefixRange,
value: prefix
}];
dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression";
return dep;
} else if(param.isWrapped() && (param.prefix && param.prefix.isString() || param.postfix && param.postfix.isString())) {
prefix = param.prefix && param.prefix.isString() ? param.prefix.string : "";
postfix = param.postfix && param.postfix.isString() ? param.postfix.string : "";
prefixRange = param.prefix && param.prefix.isString() ? param.prefix.range : null;
valueRange = [prefixRange ? prefixRange[1] : param.range[0], param.range[1]];
idx = prefix.lastIndexOf("/");
context = ".";
if(idx >= 0) {
context = prefix.substr(0, idx);
prefix = `.${prefix.substr(idx)}`;
}
regExp = new RegExp(`^${quotemeta(prefix)}${options.wrappedContextRegExp.source}${quotemeta(postfix)}$`);
dep = new Dep(context, options.wrappedContextRecursive, regExp, range, valueRange, chunkName);
dep.loc = expr.loc;
dep.prepend = param.prefix && param.prefix.isString() ? prefix : null;
dep.critical = options.wrappedContextCritical && "a part of the request of a dependency is an expression";
return dep;
} else {
dep = new Dep(options.exprContextRequest, options.exprContextRecursive, options.exprContextRegExp, range, param.range, chunkName);
dep.loc = expr.loc;
dep.critical = options.exprContextCritical && "the request of a dependency is an expression";
return dep;
}
};