test(i18n): add unit tests for locale detection + extract to module
Extract detectLocale() from hooks.server.ts into src/lib/server/locale.ts so it can be tested in isolation. Add 7 unit tests covering: - German, English, Spanish browser preferences - Fallback when primary language is unsupported - Quality value (q=) ordering - Fully unsupported language → null - Empty Accept-Language header → null Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>
This commit is contained in:
20
frontend/src/lib/server/locale.ts
Normal file
20
frontend/src/lib/server/locale.ts
Normal file
@@ -0,0 +1,20 @@
|
||||
import { locales } from '$lib/paraglide/runtime';
|
||||
|
||||
/**
|
||||
* Picks the best supported locale from an Accept-Language header value.
|
||||
* Returns null when no supported locale is found.
|
||||
*/
|
||||
export function detectLocale(acceptLanguage: string): string | null {
|
||||
const preferred = acceptLanguage
|
||||
.split(',')
|
||||
.map((part) => {
|
||||
const [lang, q] = part.trim().split(';q=');
|
||||
return { lang: lang.trim().split('-')[0].toLowerCase(), q: q ? parseFloat(q) : 1 };
|
||||
})
|
||||
.sort((a, b) => b.q - a.q);
|
||||
|
||||
for (const { lang } of preferred) {
|
||||
if ((locales as readonly string[]).includes(lang)) return lang;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
Reference in New Issue
Block a user