import acceptLanguageParser from 'accept-language-parser' ; import { CustomDetector , DetectorOptions } from 'i18next-browser-languagedetector' ; import iso3166 from '@unly/iso3166-1' ; import { _defaultErrorHandler , ERROR_LEVELS , ErrorHandler } from '../utils/error' ; param supportedLanguages param acceptLanguageHeader param errorHandler private export const _resolveAcceptLanguage = ( supportedLanguages , acceptLanguageHeader , errorHandler = _defaultErrorHandler ) : string | undefined => { let bestSupportedLanguage ; try { bestSupportedLanguage = acceptLanguageParser . pick ( supportedLanguages , acceptLanguageHeader , { loose : true , } ) ; } catch ( e ) { errorHandler ( e , ERROR_LEVELS . ERROR , '_resolveAcceptLanguage' , { inputs : { supportedLanguages , acceptLanguageHeader , } , } ) ; } if ( bestSupportedLanguage ) { try { return iso3166 . to2 ( iso3166 . fromLocale ( bestSupportedLanguage ) ) . toLowerCase ( ) ; } catch ( e ) { errorHandler ( e , ERROR_LEVELS . ERROR , '_resolveAcceptLanguage' , { inputs : { supportedLanguages , acceptLanguageHeader , } , bestSupportedLanguage , } ) ; } } } ; export const acceptLanguage = ( supportedLanguages , acceptLanguageHeader , errorHandler ? ) : CustomDetector => { return { name : 'acceptLanguage' , lookup : ( options ) : string | undefined => { return _resolveAcceptLanguage ( supportedLanguages , acceptLanguageHeader , errorHandler ) ; } , cacheUserLanguage : ( ) : void => { } , } ; } ; export default acceptLanguage ;