All files / lib/i18n locales.ts

100% Statements 23/23
94.44% Branches 17/18
100% Functions 9/9
100% Lines 21/21

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 575x       5x   5x   5x           5x             15x       19x       10x 5x   5x     8x 8x 8x   8x 4x 5x 6x 6x 4x     1x             7x    
export const locales = ["fr", "en", "es"] as const;
 
export type Locale = (typeof locales)[number];
 
export const defaultLocale: Locale = "fr";
 
export const LOCALE_COOKIE = "codetics-locale";
 
export const localeNames: Record<Locale, string> = {
  fr: "Français",
  en: "English",
  es: "Español",
};
 
const intlLocales: Record<Locale, string> = {
  fr: "fr-FR",
  en: "en-GB",
  es: "es-ES",
};
 
export function isLocale(value: unknown): value is Locale {
  return typeof value === "string" && (locales as readonly string[]).includes(value);
}
 
export function intlLocale(locale: Locale): string {
  return intlLocales[locale];
}
 
export function matchLocale(header: string | null | undefined): Locale | null {
  if (!header) {
    return null;
  }
  const ranked = header
    .split(",")
    .map((part, index) => {
      const [tag, ...params] = part.trim().split(";");
      const quality = params.map((param) => param.trim()).find((param) => param.startsWith("q="));
      return { tag: tag.toLowerCase(), q: quality ? Number(quality.slice(2)) || 0 : 1, index };
    })
    .filter((entry) => entry.tag && entry.q > 0)
    .sort((a, b) => b.q - a.q || a.index - b.index);
  for (const entry of ranked) {
    const base = entry.tag.split("-")[0];
    if (isLocale(base)) {
      return base;
    }
  }
  return null;
}
 
export function resolveLocale(
  cookie: string | null | undefined,
  header: string | null | undefined,
) {
  return isLocale(cookie) ? cookie : (matchLocale(header) ?? defaultLocale);
}