-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathindex.js
106 lines (91 loc) · 2.44 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
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
'use strict';
/**
Overly tolerant url parser
*/
var Url = module.exports = {
PROTOCOL: '://',
COLON: ':',
AT: '@',
SLASH: '/',
parse: function (url) {
// first parse auth/host/port
var parsed = this._parse(url);
// then handle path (quick & dirty way)
['host', 'hostname', 'port'].forEach(function (part) {
if (strCount(parsed[part], this.SLASH) > 0) {
var pair = parsed[part].split(this.SLASH);
parsed[part] = pair.shift();
parsed.path = this.SLASH + pair.join(this.SLASH);
}
}, this);
return parsed;
},
_parse: function (url) {
var parsed = {
protocol: null, // string
auth: null, // string
hostname: null, // string
host: null, // string
port: null, // string
href: url, // string
path: null
};
// check protocol
var protocolIdx = url.indexOf(this.PROTOCOL);
if (protocolIdx !== -1) {
parsed.protocol = url.substring(0, protocolIdx + 1);
protocolIdx += this.PROTOCOL.length;
// remove the protocol part from the url
url = url.substring(protocolIdx);
}
var atCount = strCount(url, this.AT);
var colonCount = strCount(url, this.COLON);
var atIsPresent = atCount > 0;
var colonIsPresent = colonCount > 0;
if (!atIsPresent && !colonIsPresent) {
parsed.host = url;
parsed.hostname = url;
// parse is done, there are no port and auth
return parsed;
}
if (colonCount === 1 && !atIsPresent) { // it can only be the port number
extractPortAndHostnameFromHost(parsed, url);
return parsed;
}
var parts = url.split(this.AT);
var host = parts.pop();
extractPortAndHostnameFromHost(parsed, host);
parsed.auth = parts.join(this.AT);
return parsed;
}
};
function strCount(str, substr) {
if (str === null || substr === null) {
return 0;
}
str = String(str);
substr = String(substr);
var count = 0,
pos = 0,
length = substr.length;
while (true) {
pos = str.indexOf(substr, pos);
if (pos === -1) {
break;
}
count++;
pos += length;
}
return count;
}
function extractPortAndHostnameFromHost(parsed, host) {
var portIdx = host.indexOf(Url.COLON);
parsed.host = host;
if (portIdx === -1) {
parsed.hostname = host;
// no colon is present inside host
return;
}
parsed.port = host.substring(portIdx + Url.COLON.length);
parsed.hostname = host.substring(0, portIdx);
}