tld-detector.js
1 /** 2 * TLD-based Country Detection 3 * Detects country from domain TLD (country-code top-level domains) 4 */ 5 6 // Map of ccTLDs to country codes 7 const ccTLD_MAP = { 8 '.com.au': 'AU', 9 '.au': 'AU', 10 '.co.uk': 'UK', 11 '.uk': 'UK', 12 '.co.nz': 'NZ', 13 '.nz': 'NZ', 14 '.ca': 'CA', 15 '.de': 'DE', 16 '.fr': 'FR', 17 '.it': 'IT', 18 '.es': 'ES', 19 '.pt': 'PT', 20 '.nl': 'NL', 21 '.be': 'BE', 22 '.ch': 'CH', 23 '.at': 'AT', 24 '.se': 'SE', 25 '.no': 'NO', 26 '.dk': 'DK', 27 '.fi': 'FI', 28 '.ie': 'IE', 29 '.pl': 'PL', 30 '.jp': 'JP', 31 '.kr': 'KR', 32 '.cn': 'CN', 33 '.in': 'IN', 34 '.mx': 'MX', 35 }; 36 37 /** 38 * Detect country from domain TLD 39 * @param {string} domain - Domain name (e.g., "example.com.au") 40 * @returns {{countryCode: string|null, confidence: 'high'|'low', source: 'cctld'|'unknown'}} 41 */ 42 export function detectCountryFromTLD(domain) { 43 if (!domain) { 44 return { countryCode: null, confidence: 'low', source: 'unknown' }; 45 } 46 47 // Check for country-code TLD match 48 for (const [tld, code] of Object.entries(ccTLD_MAP)) { 49 if (domain.endsWith(tld)) { 50 return { countryCode: code, confidence: 'high', source: 'cctld' }; 51 } 52 } 53 54 // Generic TLD (.com, .net, .org, .io, etc.) - can't determine country 55 return { countryCode: null, confidence: 'low', source: 'unknown' }; 56 } 57 58 /** 59 * Parse country code from google_domain 60 * @param {string} googleDomain - Google domain (e.g., "google.com.au") 61 * @returns {string} - Country code (e.g., "AU") 62 */ 63 export function parseCountryFromGoogleDomain(googleDomain) { 64 const domainMap = { 65 'google.com.au': 'AU', 66 'google.co.uk': 'UK', 67 'google.co.nz': 'NZ', 68 'google.ca': 'CA', 69 'google.de': 'DE', 70 'google.fr': 'FR', 71 'google.it': 'IT', 72 'google.es': 'ES', 73 'google.pt': 'PT', 74 'google.nl': 'NL', 75 'google.be': 'BE', 76 'google.ch': 'CH', 77 'google.at': 'AT', 78 'google.se': 'SE', 79 'google.no': 'NO', 80 'google.dk': 'DK', 81 'google.fi': 'FI', 82 'google.ie': 'IE', 83 'google.pl': 'PL', 84 'google.co.jp': 'JP', 85 'google.jp': 'JP', 86 'google.co.kr': 'KR', 87 'google.kr': 'KR', 88 'google.cn': 'CN', 89 'google.co.in': 'IN', 90 'google.in': 'IN', 91 'google.com.mx': 'MX', 92 'google.com': 'US', // Default 93 }; 94 95 // eslint-disable-next-line security/detect-object-injection -- googleDomain is validated parameter 96 return domainMap[googleDomain] || 'US'; 97 }