1 | const URL = require('url-parse');
|
2 | const urlRegex = require('url-regex');
|
3 | const isString = require('is-string');
|
4 | const isReachable = require('is-reachable');
|
5 |
|
6 | module.exports = string => {
|
7 | if (!isString(string)) {
|
8 | return Promise.resolve({});
|
9 | }
|
10 |
|
11 | const matches = string.match(urlRegex()) || [];
|
12 | const urls = matches.map(url => {
|
13 | const u = new URL(url);
|
14 | const suffix = /[^a-zA-Z0-9/+?#=].*$/;
|
15 |
|
16 | u.set('pathname', u.pathname.replace(suffix, ''));
|
17 | u.set('query', u.query.replace(suffix, ''));
|
18 | u.set('hash', u.hash.replace(suffix, ''));
|
19 |
|
20 | if (!u.protocol) {
|
21 | u.set('protocol', 'http:');
|
22 | }
|
23 |
|
24 | return u.toString();
|
25 | });
|
26 |
|
27 | if (urls.length === 0) {
|
28 | return Promise.resolve({});
|
29 | }
|
30 |
|
31 | const object = {};
|
32 | return urls.reduce((previous, current, index) => {
|
33 | return previous.then(result => {
|
34 | object[urls[index]] = result;
|
35 |
|
36 | if (urls.length - 1 === index) {
|
37 | return Promise.resolve(object);
|
38 | }
|
39 |
|
40 | return isReachable(urls[index + 1]);
|
41 | });
|
42 | }, isReachable(urls[0]));
|
43 | };
|