-
-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathindex.js
52 lines (40 loc) · 1.19 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
import {Buffer} from 'node:buffer';
import urlRegex from 'url-regex';
import isString from 'is-string';
import isReachable from 'is-reachable';
const stringify = object => {
if (isString(object)) {
return object;
}
if (Buffer.isBuffer(object)) {
return object.toString();
}
return '';
};
export default function reachableUrls(url) {
const matches = stringify(url).match(urlRegex()) || [];
const urls = matches.map(url => {
const u = new URL(url);
u.protocol ||= 'https:';
return u;
}).filter(url => /https?/.test(url.protocol)).map(url => {
const suffix = /[^\w/+\-?#=:.].*$/;
url.pathname = url.pathname?.replace(suffix, '');
url.query = url.query?.replace(suffix, '');
url.hash = url.hash?.replace(suffix, '');
return url.toString();
});
if (urls.length === 0) {
return Promise.resolve({});
}
const object = {};
/* eslint-disable-next-line unicorn/no-array-reduce */
return urls.reduce(async (previous, current, index) => {
const result = await previous;
object[urls[index]] = result;
if (urls.length - 1 === index) {
return object;
}
return isReachable(urls[index + 1]);
}, isReachable(urls[0]));
}