🤯 LobeHub - Super-Agents on Your Team. Add super-agents to the chats your team already uses.They take on work by themselves and get better every week.
TypeScript agentagent-collaborationagent-harnessloop-engineeringmcppersonal-assistantproactive-agentskillssuper-agenttask-management
♻️ refactor(locales): resolve request locales with @lobehub/edge-contract (#22387)
Innei9ae9852de3dd
diff --git a/packages/locales/package.json b/packages/locales/package.jsonindex c29a24f43ca..65dfe30abb9 100644--- a/packages/locales/package.json+++ b/packages/locales/package.json@@ -13,6 +13,7 @@"@lobechat/const": "workspace:*","@lobechat/env": "workspace:*","@lobechat/utils": "workspace:*",+ "@lobehub/edge-contract": "^0.2.0","i18next": "^25.10.10","i18next-browser-languagedetector": "^8.2.1","i18next-resources-to-backend": "^1.2.1",diff --git a/packages/locales/src/requestLocale.test.ts b/packages/locales/src/requestLocale.test.tsindex 43cfe685c1f..5309d94ccaa 100644--- a/packages/locales/src/requestLocale.test.ts+++ b/packages/locales/src/requestLocale.test.ts@@ -90,3 +90,11 @@ describe('resolveRequestLocale', () => {expect(resolveRequestLocale(request({ language: '' }))).toBe('en-US');});});++describe('shared vocabulary', () => {+ it('falls back to the default the gateway and the KV config use', async () => {+ const { DEFAULT_APP_LOCALE } = await import('@lobehub/edge-contract/request-locale');+ const { DEFAULT_LANG } = await import('@/const/locale');+ expect(DEFAULT_LANG).toBe(DEFAULT_APP_LOCALE);+ });+});diff --git a/packages/locales/src/requestLocale.ts b/packages/locales/src/requestLocale.tsindex 75f6eec3b42..528f1ab0d6b 100644--- a/packages/locales/src/requestLocale.ts+++ b/packages/locales/src/requestLocale.ts@@ -1,73 +1,10 @@-import { DEFAULT_LANG, LOBE_LOCALE_COOKIE } from '@/const/locale';+import { resolveRequestLocale as resolveWithVocabulary } from '@lobehub/edge-contract/request-locale';-import { type Locales, matchLocale, normalizeLocale } from './resources';+import { DEFAULT_LANG } from '@/const/locale';-const LOCALE_QUERY = 'hl';-const AUTO_LOCALE = 'auto';+import { type Locales, locales } from './resources';-const decodeCookieValue = (value: string) => {- try {- return decodeURIComponent(value);- } catch {- // A cookie carrying a malformed percent-escape must not take an SSR render down.- return value;- }-};--const readCookie = (cookieHeader: string | null, name: string): string | undefined => {- if (!cookieHeader) return undefined;-- for (const part of cookieHeader.split(';')) {- const separatorIndex = part.indexOf('=');- if (separatorIndex === -1) continue;-- if (part.slice(0, separatorIndex).trim() !== name) continue;-- return decodeCookieValue(part.slice(separatorIndex + 1).trim());- }-- return undefined;-};--// Accept-Language is case-insensitive, but the supported list is canonical-// BCP 47 — without this `zh-cn` misses `zh-CN` and silently degrades to English.-const canonicalizeTag = (tag: string) => {- const [language, ...rest] = tag.split('-');-- return [- language!.toLowerCase(),- ...rest.map((part) => (part.length === 2 ? part.toUpperCase() : part)),- ].join('-');-};--const parseAcceptLanguage = (header: string | null): string[] =>- (header ?? '')- .split(',')- .map((part) => {- const [tag, ...params] = part.trim().split(';');- const quality = params.map((param) => param.trim()).find((param) => param.startsWith('q='));- const weight = quality ? Number(quality.slice(2)) : 1;-- return { tag: tag?.trim() ?? '', weight: Number.isFinite(weight) ? weight : 0 };- })- .filter((candidate) => candidate.tag.length > 0 && candidate.tag !== '*')- .sort((a, b) => b.weight - a.weight)- .map((candidate) => candidate.tag);--// An explicit choice naming no supported locale falls back to the default instead of-// deferring to the browser, matching the lobehub gateway's `resolveOriginPathVars`: a-// request routed through the gateway and one hitting a worker directly must agree.-export const resolveRequestLocale = (request: Request): Locales => {- const explicit =- new URL(request.url).searchParams.get(LOCALE_QUERY) ||- readCookie(request.headers.get('cookie'), LOBE_LOCALE_COOKIE);-- if (explicit && explicit !== AUTO_LOCALE) return normalizeLocale(canonicalizeTag(explicit));-- for (const tag of parseAcceptLanguage(request.headers.get('accept-language'))) {- const matched = matchLocale(canonicalizeTag(tag));- if (matched) return matched;- }-- return DEFAULT_LANG;-};+// Shared with the lobehub gateway, so a request routed through it and one hitting a worker+// directly pick the same locale.+export const resolveRequestLocale = (request: Request): Locales =>+ resolveWithVocabulary(request, { fallback: DEFAULT_LANG as Locales, tags: locales });diff --git a/packages/locales/src/resources.test.ts b/packages/locales/src/resources.test.tsindex e3533863c03..2bcda9f9d38 100644--- a/packages/locales/src/resources.test.ts+++ b/packages/locales/src/resources.test.ts@@ -61,3 +61,11 @@ describe('matchLocale', () => {expect(matchLocale('ar-EG')).toBe('ar');});});++describe('matchLocale case handling', () => {+ it('matches a tag whatever its case', () => {+ expect(matchLocale('zh-cn')).toBe('zh-CN');+ expect(matchLocale('PT-br')).toBe('pt-BR');+ expect(matchLocale('EN')).toBe('en-US');+ });+});diff --git a/packages/locales/src/resources.ts b/packages/locales/src/resources.tsindex a2f240b1672..20173ae352e 100644--- a/packages/locales/src/resources.ts+++ b/packages/locales/src/resources.ts@@ -1,46 +1,17 @@+import { appLocales, matchLocaleTag } from '@lobehub/edge-contract/request-locale';+import { DEFAULT_LANG } from '@/const/locale';import type resources from './default';-export const locales = [- 'ar',- 'bg-BG',- 'de-DE',- 'en-US',- 'es-ES',- 'fr-FR',- 'ja-JP',- 'ko-KR',- 'pt-BR',- 'ru-RU',- 'tr-TR',- 'zh-CN',- 'zh-TW',- 'vi-VN',- 'fa-IR',- 'it-IT',- 'pl-PL',- 'nl-NL',-] as const;+export const locales = appLocales;export type DefaultResources = typeof resources;export type NS = keyof DefaultResources;export type Locales = (typeof locales)[number];-export const matchLocale = (locale?: string): Locales | undefined => {- if (!locale) return undefined;-- const lowerLocale = locale.toLowerCase();-- if (lowerLocale.startsWith('ar')) return 'ar';- if (lowerLocale.startsWith('fa')) return 'fa-IR';-- if (lowerLocale.startsWith('cn')) return 'zh-CN';- if (lowerLocale.startsWith('zh-hans')) return 'zh-CN';- if (lowerLocale.startsWith('zh-hant')) return 'zh-TW';-- return locales.find((l) => l.startsWith(locale));-};+export const matchLocale = (locale?: string): Locales | undefined =>+ matchLocaleTag(locale, locales);export const normalizeLocale = (locale?: string): Locales => matchLocale(locale) ?? DEFAULT_LANG;