normalize-domain.ts 671 B

1234567891011121314151617181920212223242526
  1. import * as tldts from './cached-tld-parse';
  2. import { isProbablyIpv4 } from './is-fast-ip';
  3. export const normalizeDomain = (domain: string) => {
  4. if (!domain) return null;
  5. if (isProbablyIpv4(domain)) return null;
  6. const parsed = tldts.parse2(domain);
  7. // if (parsed.isIp) return null;
  8. if (!parsed.hostname) return null;
  9. if (!parsed.isIcann && !parsed.isPrivate) return null;
  10. let h = parsed.hostname;
  11. let sliceStart = 0;
  12. let sliceEnd = h.length;
  13. if (h[0] === '.') sliceStart = 1;
  14. if (h.endsWith('.')) sliceEnd = -1;
  15. if (sliceStart !== 0 || sliceEnd !== h.length) {
  16. h = h.slice(sliceStart, sliceEnd);
  17. }
  18. if (h) return h;
  19. return null;
  20. };