index.ts 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. import {
  2. FLAG,
  3. getEmptyResult,
  4. IOptions,
  5. IResult,
  6. parseImpl,
  7. resetResult,
  8. } from 'tldts-core';
  9. import suffixLookup from './src/suffix-trie';
  10. // For all methods but 'parse', it does not make sense to allocate an object
  11. // every single time to only return the value of a specific attribute. To avoid
  12. // this un-necessary allocation, we use a global object which is re-used.
  13. const RESULT: IResult = getEmptyResult();
  14. export function parse(url: string, options?: Partial<IOptions>): IResult {
  15. return parseImpl(url, FLAG.ALL, suffixLookup, options, getEmptyResult());
  16. }
  17. export function getHostname(
  18. url: string,
  19. options?: Partial<IOptions>,
  20. ): string | null {
  21. /*@__INLINE__*/ resetResult(RESULT);
  22. return parseImpl(url, FLAG.HOSTNAME, suffixLookup, options, RESULT).hostname;
  23. }
  24. export function getPublicSuffix(
  25. url: string,
  26. options?: Partial<IOptions>,
  27. ): string | null {
  28. /*@__INLINE__*/ resetResult(RESULT);
  29. return parseImpl(url, FLAG.PUBLIC_SUFFIX, suffixLookup, options, RESULT)
  30. .publicSuffix;
  31. }
  32. export function getDomain(
  33. url: string,
  34. options?: Partial<IOptions>,
  35. ): string | null {
  36. /*@__INLINE__*/ resetResult(RESULT);
  37. return parseImpl(url, FLAG.DOMAIN, suffixLookup, options, RESULT).domain;
  38. }
  39. export function getFullDomain(
  40. url: string,
  41. options?: Partial<IOptions>,
  42. ): string | null {
  43. /*@__INLINE__*/ resetResult(RESULT);
  44. const result = parseImpl(url, FLAG.DOMAIN, suffixLookup, options, RESULT);
  45. // The hostname *is* the full domain (subdomain + domain) whenever a
  46. // registrable domain exists; gate on `domain` so non-registrable inputs
  47. // (IPs, suffix-less or invalid hostnames) return `null` like `getDomain`.
  48. return result.domain === null ? null : result.hostname;
  49. }
  50. export function getSubdomain(
  51. url: string,
  52. options?: Partial<IOptions>,
  53. ): string | null {
  54. /*@__INLINE__*/ resetResult(RESULT);
  55. return parseImpl(url, FLAG.SUB_DOMAIN, suffixLookup, options, RESULT)
  56. .subdomain;
  57. }
  58. export function getDomainWithoutSuffix(
  59. url: string,
  60. options?: Partial<IOptions>,
  61. ): string | null {
  62. /*@__INLINE__*/ resetResult(RESULT);
  63. return parseImpl(url, FLAG.ALL, suffixLookup, options, RESULT)
  64. .domainWithoutSuffix;
  65. }