-
Notifications
You must be signed in to change notification settings - Fork 56
/
clean-host.js
107 lines (85 loc) · 2.06 KB
/
clean-host.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
var URL = require('url');
var isValid = require('./is-valid.js');
/**
* Utility to cleanup the base host value. Also removes url fragments.
*
* Works for:
* - hostname
* - //hostname
* - scheme://hostname
* - scheme+scheme://hostname
*
* @param {string} value
* @return {String}
*/
// scheme = ALPHA *( ALPHA / DIGIT / "+" / "-" / "." )
var hasPrefixRE = /^(([a-z][a-z0-9+.-]*)?:)?\/\//;
/**
* @see https://github.com/oncletom/tld.js/issues/95
*
* @param {string} value
*/
function trimTrailingDots(value) {
if (value[value.length - 1] === '.') {
return value.substr(0, value.length - 1);
}
return value;
}
/**
* Fast check to avoid calling `trim` when not needed.
*
* @param {string} value
*/
function checkTrimmingNeeded(value) {
return (
value.length > 0 && (
value.charCodeAt(0) <= 32 ||
value.charCodeAt(value.length - 1) <= 32
)
);
}
/**
* Fast check to avoid calling `toLowerCase` when not needed.
*
* @param {string} value
*/
function checkLowerCaseNeeded(value) {
for (var i = 0; i < value.length; i += 1) {
var code = value.charCodeAt(i);
if (code >= 65 && code <= 90) { // [A-Z]
return true;
}
}
return false;
}
module.exports = function extractHostname(value) {
// First check if `value` is already a valid hostname.
if (isValid(value)) {
return trimTrailingDots(value);
}
var url = value;
if (typeof url !== 'string') {
url = '' + url;
}
var needsTrimming = checkTrimmingNeeded(url);
if (needsTrimming) {
url = url.trim();
}
var needsLowerCase = checkLowerCaseNeeded(url);
if (needsLowerCase) {
url = url.toLowerCase();
}
// Try again after `url` has been transformed to lowercase and trimmed.
if ((needsLowerCase || needsTrimming) && isValid(url)) {
return trimTrailingDots(url);
}
// Proceed with heavier url parsing to extract the hostname.
if (!hasPrefixRE.test(url)) {
url = '//' + url;
}
var parts = URL.parse(url, null, true);
if (parts.hostname) {
return trimTrailingDots(parts.hostname);
}
return null;
};