UNPKG

resolve-accept-language

Version:

Resolve the preferred locale based on the value of an `Accept-Language` HTTP header.

45 lines (44 loc) 2.3 kB
/** The type of matches. */ export type MatchType = 'locale' | 'languageSpecificLocale' | 'language' | 'relatedLocale' | 'languageCountry' | 'country' | 'defaultLocale'; /** The type of matches enumeration. */ export declare const MATCH_TYPES: { readonly [K in MatchType]: K; }; /** Type to normalize the locale format. */ export type NormalizeLocale<Remainder extends string> = Remainder extends `${infer LanguageCode}-${infer CountryCode}` ? `${Lowercase<LanguageCode>}-${Uppercase<CountryCode>}` : Remainder; /** Additional options to apply. */ type Options<WithMatchType extends boolean | undefined> = { /** Should the match type be returned? */ returnMatchType?: WithMatchType; /** Should the country of the locale be used for matching? */ matchCountry?: boolean; }; type Result<Locales extends readonly string[], WithMatchType extends boolean | undefined> = WithMatchType extends true ? { /** The best locale match. */ match: NormalizeLocale<Locales[number]>; /** The type of match. */ matchType: MatchType; } : NormalizeLocale<Locales[number]>; /** * Resolve the preferred locale from an HTTP `Accept-Language` header. * * All locale identifiers provided as parameters must following the BCP 47 `language`-`country` (case insensitive). * * @param acceptLanguageHeader - The value of an HTTP request `Accept-Language` header (also known as a "language priority list"). * @param locales - An array of locale identifiers that must include the default locale. The order will be used for matching where * the first identifier will be more likely to be matched than the last identifier. * @param defaultLocale - The default locale identifier when no match is found. * @param options - Additional options to apply. * * @returns Either the best locale match or a match object, depending on options. * * @example * // returns 'fr-CA' * resolveAcceptLanguage( * 'fr-CA;q=0.01,en-CA;q=0.1,en-US;q=0.001', * ['en-US', 'fr-CA'], * 'en-US' * ) */ export declare const resolveAcceptLanguage: <Locales extends readonly string[], WithMatchType extends boolean | undefined = undefined>(acceptLanguageHeader: string, locales: Locales, defaultLocale: Locales[number], options?: Options<WithMatchType>) => Result<Locales, WithMatchType>; export {};