-
Notifications
You must be signed in to change notification settings - Fork 16
/
index.js
60 lines (39 loc) · 1.43 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
"use strict";
var url = require('url');
var parse_url = function(remote_url, options) {
if(typeof remote_url == "string")
remote_url = url.parse(remote_url);
return parse_host(remote_url.hostname, options);
};
var tlds = null;
var parse_host = function(host, options) {
let allowPrivateTLD = options && options.allowPrivateTLD || false;
let allowUnknownTLD = options && options.allowUnknownTLD || false;
let allowDotlessTLD = options && options.allowDotlessTLD || false;
if(!tlds) {
tlds = require('./effective_tld_names.json');
tlds.combined = Object.assign({}, tlds.icann, tlds.private);
}
var parts = host.split(".");
var stack = "", tld_level = -1;
var roots = allowPrivateTLD ? tlds.combined : tlds.icann;
for(var i = parts.length - 1, part; i >= 0; i--) {
part = parts[i];
stack = stack ? part + "." + stack : part;
if(roots[stack])
tld_level = roots[stack];
}
if(tld_level == -1 && allowUnknownTLD)
tld_level = 1;
if(parts.length <= tld_level || tld_level == -1) {
if(!(parts.length == tld_level && allowDotlessTLD))
throw new Error("Invalid TLD " + JSON.stringify({parts, tld_level, allowUnknownTLD}));
}
return {
tld : parts.slice(-tld_level).join('.'),
domain : parts.slice(-tld_level - 1).join('.'),
sub : parts.slice(0, (-tld_level - 1)).join('.'),
};
};
module.exports = parse_url;
module.exports.parse_host = parse_host;