npmtest-is-reachable (v0.0.1)

Code coverage report for node-npmtest-is-reachable/node_modules/is-reachable/index.js

Statements: 37.84% (14 / 37)      Branches: 0% (0 / 22)      Functions: 0% (0 / 1)      Lines: 38.89% (14 / 36)      Ignored: none     

All files » node-npmtest-is-reachable/node_modules/is-reachable/ » 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  1 1 1 1 1 1 1 1 1 1 1   1           1                                                     1                
'use strict';
const dns = require('dns');
const arrify = require('arrify');
const got = require('got');
const isPortReachable = require('is-port-reachable');
const pAny = require('p-any');
const pify = require('pify');
const pn = require('port-numbers');
const pTimeout = require('p-timeout');
const prependHttp = require('prepend-http');
const routerIps = require('router-ips');
const URL = require('url-parse');
 
const checkRedirection = url => {
	return got(url).then(res => {
		return !routerIps.has((new URL(res.headers.location || '')).hostname);
	}).catch(() => false);
};
 
function isTargetReachable(url) {
	const uri = new URL(prependHttp(url));
	const hostname = uri.hostname;
	let protocol = uri.protocol;
	const port = Number(uri.port) || pn.getPort(protocol.slice(0, -1)).port || 80;
 
	if (!/^[a-z]+:\/\//.test(url) && port !== 80 && port !== 443) {
		protocol = pn.getService(port).name + ':';
	}
 
	return pify(dns.lookup)(hostname).then(address => {
		if (!address) {
			return false;
		}
 
		if (routerIps.has(address)) {
			return false;
		}
 
		if (protocol === 'http:' || protocol === 'https:') {
			return checkRedirection(url);
		}
 
		return isPortReachable(port, {host: address});
	}).catch(() => false);
}
 
module.exports = (dests, opts) => {
	opts = opts || {};
	opts.timeout = typeof opts.timeout === 'number' ? opts.timeout : 5000;
 
	const p = pAny(arrify(dests).map(isTargetReachable));
	return pTimeout(p, opts.timeout).catch(() => false);
};