All files / service-web-theme/src locale.ts

100% Statements 34/34
96% Branches 24/25
100% Functions 12/12
100% Lines 27/27

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 57 58 59 60 61 62 63 64 65 66 67 68 69 70    45x   45x     45x     45x     62x                       22x 21x 20x 7x 7x   15x         14x 9x 10x 10x   8x         2x         145x 145x 145x         20x     26x 26x 26x   26x 6x 12x    
/** Languages shared by the service pages, and how a request picks one. */
 
export const LOCALES = ['en', 'ja'] as const;
export type Locale = (typeof LOCALES)[number];
export const DEFAULT_LOCALE: Locale = 'en';
 
/** Each language by its own name, for the language switch. */
export const LOCALE_NAMES: Readonly<Record<Locale, string>> = { en: 'English', ja: '日本語' };
 
/** Cookie holding the language the viewer picked on this host. */
export const LOCALE_COOKIE = 'be-music-lang';
 
export function isLocale(value: string | undefined | null): value is Locale {
  return value !== undefined && value !== null && (LOCALES as readonly string[]).includes(value);
}
 
/**
 * The language of a page: `?lang=` first, then the language the viewer picked, then `Accept-Language` in preference
 * order, then English. The same order as the Leaderboard.
 */
export function resolveLocale(request: {
  query?: string | undefined;
  cookie?: string | undefined;
  acceptLanguage?: string | undefined;
}): Locale {
  if (isLocale(request.query)) return request.query;
  if (isLocale(request.cookie)) return request.cookie;
  for (const tag of parseAcceptLanguage(request.acceptLanguage ?? '')) {
    const primary = tag.split('-')[0]!.toLowerCase();
    if (isLocale(primary)) return primary;
  }
  return DEFAULT_LOCALE;
}
 
/** The `be-music-lang` value from a Cookie header. */
export function localeFromCookie(header: string | null): string | undefined {
  if (header === null) return undefined;
  for (const part of header.split(';')) {
    const [name, ...rest] = part.trim().split('=');
    if (name === LOCALE_COOKIE) return decodeURIComponent(rest.join('='));
  }
  return undefined;
}
 
/** Remembers a chosen language on this host. `Secure` only on https, so a local http server can store it too. */
export function localeSetCookie(locale: Locale, secure: boolean): string {
  return `${LOCALE_COOKIE}=${locale}; Path=/; Max-Age=34560000; SameSite=Lax${secure ? '; Secure' : ''}`;
}
 
/** `?lang=` on the same path, keeping every other query parameter. */
export function withLocale(requestURL: string, locale: Locale): string {
  const url = new URL(requestURL, 'https://be-music.local');
  url.searchParams.set('lang', locale);
  return `${url.pathname}${url.search}`;
}
 
/** The language tags of an `Accept-Language` header, most wanted first (`q=0` ones dropped). */
function parseAcceptLanguage(header: string): string[] {
  return header
    .split(',')
    .map((part, index) => {
      const [tag = '', ...params] = part.trim().split(';');
      const q = params.map((param) => /^\s*q=([\d.]+)\s*$/.exec(param)?.[1]).find((value) => value !== undefined);
      return { tag: tag.trim(), q: q === undefined ? 1 : Number(q), index };
    })
    .filter((entry) => entry.tag !== '' && entry.tag !== '*' && entry.q > 0)
    .sort((a, b) => b.q - a.q || a.index - b.index)
    .map((entry) => entry.tag);
}