This repository has been archived by the owner on Oct 19, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 3
/
index.js
96 lines (76 loc) · 2.33 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
'use strict';
const Url = require('url');
const Http = require('http');
const Https = require('https');
const defaults = {
maxRedirects: 50
};
module.exports = (options = {}) => {
const config = getConfig();
return {
urls,
domains,
destination
};
async function urls (url) {
if (!url) {
throw new Error('Url must be defined');
}
if (typeof url !== 'string') {
throw new Error('Url must be a string');
}
let _urls = [url];
for (let i = 0; i < config.maxRedirects; i++) {
const _url = _urls[i];
const redirect = await getRedirect(_url);
if (!redirect) {
return _urls;
}
if (_urls.indexOf(redirect) !== -1) {
throw new Error(`Redirect loop: ${url}`);
}
_urls.push(redirect);
}
return _urls;
}
async function domains (url) {
return (await urls(url)).map((_url) => {
return Url.parse(_url).host;
}).filter((value, index, self) => self.indexOf(value) === index);
}
async function destination (url) {
return (await urls(url)).pop();
}
async function getRedirect (url) {
const requestOptions = Url.parse(url);
const client = requestOptions.protocol === 'https:'
? Https
: Http;
requestOptions.method = 'HEAD';
return new Promise((resolve, reject) => {
const req = client.request(requestOptions, (res) => {
if (!res.headers.location || res.statusCode >= 400) {
resolve(null);
return;
}
const redirect = Url.resolve(url, res.headers.location);
resolve(redirect);
});
req.on('error', reject);
req.end();
})
}
function getConfig () {
const config = {};
if (options.maxRedirects) {
if (typeof options.maxRedirects !== 'number') {
throw new Error('options.maxRedirects must be a number');
}
config.maxRedirects = options.maxRedirects;
}
else {
config.maxRedirects = defaults.maxRedirects;
}
return config;
}
};