All files / src/lib hostname.js

100% Statements 20/20
100% Branches 11/11
100% Functions 3/3
100% Lines 19/19
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                          34x     34x 2x       30156x 32x   5x 5x       27x         56x     56x 56x 56x 56x   55x 2x       53x 53x 4x       49x        
/*!
 * SuperGenPass library
 * https://github.com/chriszarate/supergenpass-lib
 * https://chriszarate.github.com/supergenpass/
 * License: GPLv2
 */
 
import tldList from './tld-list';
import endsWith from 'babel-runtime/core-js/string/ends-with';
import find from 'babel-runtime/core-js/array/find';
 
// Remove subdomains while respecting a number of secondary ccTLDs.
function removeSubdomains(hostname) {
  const hostnameParts = hostname.split('.');
 
  // A hostname with less than three parts is as short as it will get.
  if (hostnameParts.length < 2) {
    return hostname;
  }
 
  // Try to find a match in the list of ccTLDs.
  const ccTld = find(tldList, part => endsWith(hostname, part));
  if (ccTld) {
    // Get one extra part from the hostname.
    const partCount = ccTld.split('.').length + 1;
    return hostnameParts.slice(0 - partCount).join('.');
  }
 
  // If no ccTLDs were matched, return the final two parts of the hostname.
  return hostnameParts.slice(-2).join('.');
}
 
// Isolate the domain name of a URL.
function getHostname(url, userOptions = {}) {
  const defaults = {
    removeSubdomains: true,
  };
  const options = Object.assign({}, defaults, userOptions);
  const domainRegExp = /^(?:[a-z]+:\/\/)?(?:[^/@]+@)?([^/:]+)/i;
  const ipAddressRegExp = /^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/;
  const domainMatch = url.match(domainRegExp);
 
  if (domainMatch === null) {
    throw new Error(`URL is invalid: ${url}`);
  }
 
  // If the hostname is an IP address, no further processing can be done.
  const hostname = domainMatch[1];
  if (ipAddressRegExp.test(hostname)) {
    return hostname;
  }
 
  // Return the hostname with subdomains removed, if requested.
  return (options.removeSubdomains) ? removeSubdomains(hostname) : hostname;
}
 
export default getHostname;