import { isBrowser } from '@unly/utils' ; import I18next from 'i18next' ; import I18nextBrowserLanguageDetector from 'i18next-browser-languagedetector' ; import includes from 'lodash.includes' ; import get from 'lodash.get' ; import AcceptLanguageDetector from './serverDetectors/acceptLanguage' ; import ServerCookieDetector from './serverDetectors/serverCookie' ; import FallbackDetector from './universalDetectors/fallback' ; import { ErrorHandler } from './utils/error' ; see https type { string } export const COOKIE_LOOKUP_KEY_LANG = 'i18next' ; param props return { string } export const universalLanguageDetect = ( props ) : string => { const { supportedLanguages , fallbackLanguage , acceptLanguageHeader = undefined , serverCookies = undefined , errorHandler = undefined , } = props ; if ( ! get ( supportedLanguages , 'length' ) ) { throw new Error ( `universal-language-detector is misconfigured. Your "supportedLanguages" should be an array containing at least one language (eg: ['en']).` ) ; } if ( ! includes ( supportedLanguages , fallbackLanguage ) ) { throw new Error ( `universal-language-detector is misconfigured. Your "fallbackLanguage" (value: "${ fallbackLanguage }") should be within your "supportedLanguages" array.` ) ; } I18next . init ( { whitelist : supportedLanguages , nonExplicitWhitelist : true , } ) ; const i18nextServices = I18next . services ; const i18nextUniversalLanguageDetector = new I18nextBrowserLanguageDetector ( ) ; const fallbackDetector = FallbackDetector ( fallbackLanguage ) ; i18nextUniversalLanguageDetector . addDetector ( fallbackDetector ) ; if ( isBrowser ( ) ) { i18nextUniversalLanguageDetector . init ( i18nextServices , { order : [ 'cookie' , 'navigator' , fallbackDetector . name ] , lookupCookie : COOKIE_LOOKUP_KEY_LANG , } ) ; } else { const serverCookieDetector = ServerCookieDetector ( serverCookies ) ; const acceptLanguageDetector = AcceptLanguageDetector ( supportedLanguages , acceptLanguageHeader , errorHandler ) ; i18nextUniversalLanguageDetector . addDetector ( serverCookieDetector ) ; i18nextUniversalLanguageDetector . addDetector ( acceptLanguageDetector ) ; i18nextUniversalLanguageDetector . init ( i18nextServices , { order : [ serverCookieDetector . name , acceptLanguageDetector . name , fallbackDetector . name ] , lookupCookie : COOKIE_LOOKUP_KEY_LANG , } ) ; } return ( i18nextUniversalLanguageDetector . detect ( ) as string ) . split ( '-' ) [ 0 ] ; } ; export default universalLanguageDetect ;