forked from DevExpress/match-url-wildcard
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
68 lines (48 loc) · 1.88 KB
/
index.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
var escapeRegExp = require('escape-string-regexp');
var startsWithWildcardRegExp = /^\*\./;
var endsWithWildcardRegExp = /\.\*$/;
var trailingSlashesRegExp = /\/.{0,10000}$/;
var portRegExp = /:(\d+)$/;
var protocolRegExp = /^(\w+):\/\//;
var wildcardRegExp = /\\\.\\\*/g;
function parseUrl (url) {
if (!url || typeof url !== 'string')
return null;
var protocol = url.match(protocolRegExp);
protocol = protocol ? protocol[1] : null;
url = url.replace(protocolRegExp, '');
url = url.replace(trailingSlashesRegExp, '');
var port = url.match(portRegExp);
port = port ? parseInt(port[1], 10) : null;
url = url.replace(portRegExp, '');
return { protocol, url, port };
}
function prepareRule (url) {
var rule = parseUrl(url);
if (rule) {
rule.url = rule.url.replace(startsWithWildcardRegExp, '.');
rule.url = rule.url.replace(endsWithWildcardRegExp, '.');
}
return rule;
}
function urlMatchRule (sourceUrl, rule) {
if (!sourceUrl || !rule)
return false;
var matchByProtocols = !rule.protocol || !sourceUrl.protocol || rule.protocol === sourceUrl.protocol;
var matchByPorts = !rule.port || sourceUrl.port === rule.port;
var domainRequiredBeforeRule = rule.url.startsWith('.');
var domainRequiredAfterRule = rule.url.endsWith('.');
var regExStr = '^';
if (domainRequiredBeforeRule)
regExStr += '.+';
regExStr += escapeRegExp(rule.url).replace(wildcardRegExp, '\\..*');
if (domainRequiredAfterRule)
regExStr += '.+';
regExStr += '$';
return new RegExp(regExStr).test(sourceUrl.url) && matchByProtocols && matchByPorts;
}
module.exports = function (url, rules) {
if (!Array.isArray(rules))
rules = [rules];
return rules.some(rule => urlMatchRule(parseUrl(url), prepareRule(rule)));
}