🤯 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
🐛 fix: locale resolve bug with ESM module loading (#11018)
Innei770c87256b1a
diff --git a/apps/desktop/src/main/core/infrastructure/I18nManager.ts b/apps/desktop/src/main/core/infrastructure/I18nManager.tsindex 98a45b8e562..6e879053f9e 100644--- a/apps/desktop/src/main/core/infrastructure/I18nManager.ts+++ b/apps/desktop/src/main/core/infrastructure/I18nManager.ts@@ -175,6 +175,7 @@ export class I18nManager {try {logger.debug(`Loading namespace: ${lng}/${ns}`);const resources = await loadResources(lng, ns);+this.i18n.addResourceBundle(lng, ns, resources, true, true);return true;} catch (error) {diff --git a/apps/desktop/src/main/locales/resources.ts b/apps/desktop/src/main/locales/resources.tsindex 288332a498a..0b0e9a99315 100644--- a/apps/desktop/src/main/locales/resources.ts+++ b/apps/desktop/src/main/locales/resources.ts@@ -22,7 +22,9 @@ export const loadResources = async (lng: string, ns: string) => {}try {- return await import(`@/../../resources/locales/${lng}/${ns}.json`);+ const { default: content } = await import(`@/../../resources/locales/${lng}/${ns}.json`);++ return content;} catch (error) {console.error(`无法加载翻译文件: ${lng} - ${ns}`, error);return {};diff --git a/packages/builtin-tool-page-agent/package.json b/packages/builtin-tool-page-agent/package.jsonindex c0994300677..96f70963a45 100644--- a/packages/builtin-tool-page-agent/package.json+++ b/packages/builtin-tool-page-agent/package.json@@ -9,10 +9,12 @@"./executionRuntime": "./src/ExecutionRuntime/index.ts"},"main": "./src/index.ts",+ "dependencies": {+ "lexical": "^0.39.0"+ },"devDependencies": {"@lobechat/types": "workspace:*",- "@lobehub/editor": "^3",- "lexical": "^0.39.0"+ "@lobehub/editor": "^3"},"peerDependencies": {"@lobehub/editor": "^3",diff --git a/packages/utils/src/esm/unwrapESMModule.ts b/packages/utils/src/esm/unwrapESMModule.tsnew file mode 100644index 00000000000..9b36c1c100c--- /dev/null+++ b/packages/utils/src/esm/unwrapESMModule.ts@@ -0,0 +1,12 @@+export const unwrapESMModule = <T>(mod: unknown): T => {+ if (!mod) return mod as T;+ if (typeof mod !== 'object') return mod as T;++ // In Vitest, mocked ESM modules are proxied and accessing a missing export can throw,+ // so we must check existence without reading `mod.default` first.+ const record = mod as Record<string, unknown>;+ if ('default' in record) return (record.default as T) ?? (mod as T);++ return mod as T;+};+diff --git a/src/locales/create.ts b/src/locales/create.tsindex 3a24681ae07..042daed9165 100644--- a/src/locales/create.ts+++ b/src/locales/create.ts@@ -8,6 +8,9 @@ import { DEFAULT_LANG } from '@/const/locale';import { getDebugConfig } from '@/envs/debug';import { normalizeLocale } from '@/locales/resources';import { isOnServerSide } from '@/utils/env';+import { unwrapESMModule } from '@/utils/esm/unwrapESMModule';++import { loadI18nNamespaceModule } from '../utils/i18n/loadI18nNamespaceModule';const { I18N_DEBUG, I18N_DEBUG_BROWSER, I18N_DEBUG_SERVER } = getDebugConfig();const debugMode = (I18N_DEBUG ?? isOnServerSide) ? I18N_DEBUG_SERVER : I18N_DEBUG_BROWSER;@@ -18,15 +21,14 @@ export const createI18nNext = (lang?: string) => {.use(LanguageDetector).use(resourcesToBackend(async (lng: string, ns: string) => {- if (ns === 'models' || ns === 'providers') {- return import(`@/../locales/${normalizeLocale(lng)}/${ns}.json`);- }-- if (lng === DEFAULT_LANG) {- return import(`./default/${ns}`);- }-- return import(`@/../locales/${normalizeLocale(lng)}/${ns}.json`);+ return unwrapESMModule(+ await loadI18nNamespaceModule({+ defaultLang: DEFAULT_LANG,+ lng,+ normalizeLocale,+ ns,+ }),+ );}),);// Dynamically set HTML direction on language changediff --git a/src/server/translation.test.ts b/src/server/translation.test.tsindex eaef613fd43..ef8af4fa282 100644--- a/src/server/translation.test.ts+++ b/src/server/translation.test.ts@@ -25,8 +25,8 @@ vi.mock('@/utils/env', () => ({isDev: false,}));-// Use `en-US` (DEFAULT_LANG) as the baseline and mock default locale modules.-// We provide dotted keys directly to avoid Vitest's mocked-module export checks.+// Mock default locale modules with flat key structure (i18n keys are flat, not nested objects)+// Keys like 'nested.key' are direct string keys, not nested property pathsvi.mock('@/locales/default/common', () => ({key1: 'Value 1',key2: 'Value 2 with {{param}}',@@ -35,12 +35,27 @@ vi.mock('@/locales/default/common', () => ({simpleText: 'Just a simple text',withParam: 'Text with {{param}}','very.deeply.nested.key': 'Found the nested value',+ // Add exports for testing missing keys (will be undefined, triggering fallback)+ nonexistent: undefined,+ 'totally.missing.key': undefined,}));vi.mock('@/locales/default/chat', () => ({welcome: 'Welcome to the chat',}));+vi.mock('@/locales/default/models', () => ({+ default: {+ 'gpt-4.description': 'GPT-4 description',+ },+}));++vi.mock('@/locales/default/providers', () => ({+ default: {+ 'openai.description': 'OpenAI provider description',+ },+}));+describe('getLocale', () => {const mockCookieStore = {get: vi.fn(),@@ -93,7 +108,7 @@ describe('translation', () => {expect(t('welcome')).toBe('Welcome to the chat');});- it('should handle deep nested objects in translations', async () => {+ it('should handle dotted keys (flat structure with dots in key names)', async () => {const { t } = await translation('common', 'en-US');expect(t('very.deeply.nested.key')).toBe('Found the nested value');});@@ -108,4 +123,31 @@ describe('translation', () => {// 当缺少参数时应保留占位符expect(t('withParam')).toBe('Text with {{param}}');});++ it('should return key when translation not found', async () => {+ const { t } = await translation('common', 'en-US');+ expect(t('nonexistent')).toBe('nonexistent');+ });++ it('should handle missing i18ns object gracefully', async () => {+ // Test the case where i18ns might be empty due to import failure+ const { t } = await translation('common', 'en-US');+ // When a key doesn't exist, it should return the key itself+ const result = t('totally.missing.key');+ expect(result).toBe('totally.missing.key');+ });++ it('should fallback to default module when locale JSON is missing (models)', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});++ const { t } = await translation('models', 'zz-ZZ');+ expect(t('gpt-4.description')).toBe('GPT-4 description');+ });++ it('should fallback to default module when locale JSON is missing (providers)', async () => {+ vi.spyOn(console, 'warn').mockImplementation(() => {});++ const { t } = await translation('providers', 'zz-ZZ');+ expect(t('openai.description')).toBe('OpenAI provider description');+ });});diff --git a/src/server/translation.ts b/src/server/translation.tsindex 6e2c1ea4075..098dbc61993 100644--- a/src/server/translation.ts+++ b/src/server/translation.ts@@ -1,7 +1,8 @@-import { get } from 'es-toolkit/compat';-import { DEFAULT_LANG } from '@/const/locale';import { type Locales, type NS, normalizeLocale } from '@/locales/resources';+import { unwrapESMModule } from '@/utils/esm/unwrapESMModule';++import { loadI18nNamespaceModuleWithFallback } from '../utils/i18n/loadI18nNamespaceModule';export const getLocale = async (hl?: string): Promise<Locales> => {if (hl) return normalizeLocale(hl) as Locales;@@ -9,16 +10,26 @@ export const getLocale = async (hl?: string): Promise<Locales> => {};export const translation = async (ns: NS = 'common', hl: string) => {- let i18ns = {};+ let i18ns: Record<string, string> = {};const lng = await getLocale(hl);++ const loadTranslations = async () => {+ // Keep the same fallback rule as `src/locales/create.ts`:+ // - DEFAULT_LANG loads from `src/locales/default`+ // - other languages load from `locales/<lng>/*.json`, and fallback to default if missing+ return loadI18nNamespaceModuleWithFallback({+ defaultLang: DEFAULT_LANG,+ lng,+ normalizeLocale,+ ns,+ onFallback: () => {+ console.warn(`Translation file for ${lng}/${ns} not found, falling back to default`);+ },+ });+ };+try {- if (ns === 'models' || ns === 'providers') {- i18ns = await import(`@/../locales/${normalizeLocale(lng)}/${ns}.json`);- } else if (lng === DEFAULT_LANG || lng.startsWith('en')) {- i18ns = await import(`@/locales/default/${ns}`);- } else {- i18ns = await import(`@/../locales/${normalizeLocale(lng)}/${ns}.json`);- }+ i18ns = unwrapESMModule(await loadTranslations());} catch (e) {console.error('Error while reading translation file', e);}@@ -27,11 +38,11 @@ export const translation = async (ns: NS = 'common', hl: string) => {locale: lng,t: (key: string, options: { [key: string]: string } = {}) => {if (!i18ns) return key;- let content = get(i18ns, key);+ let content = i18ns[key];if (!content) return key;if (options) {- Object.entries(options).forEach(([key, value]) => {- content = content.replace(`{{${key}}}`, value);+ Object.entries(options).forEach(([k, value]) => {+ content = content.replace(`{{${k}}}`, value);});}return content;diff --git a/src/utils/i18n/loadI18nNamespaceModule.ts b/src/utils/i18n/loadI18nNamespaceModule.tsnew file mode 100644index 00000000000..bc2a9a2ec7a--- /dev/null+++ b/src/utils/i18n/loadI18nNamespaceModule.ts@@ -0,0 +1,31 @@+export interface LoadI18nNamespaceModuleParams {+ defaultLang: string;+ lng: string;+ normalizeLocale: (locale?: string) => string;+ ns: string;+}++export const loadI18nNamespaceModule = async (params: LoadI18nNamespaceModuleParams) => {+ const { defaultLang, normalizeLocale, lng, ns } = params;++ if (lng === defaultLang) return import(`@/locales/default/${ns}`);++ return import(`@/../locales/${normalizeLocale(lng)}/${ns}.json`);+};++export interface LoadI18nNamespaceModuleWithFallbackParams extends LoadI18nNamespaceModuleParams {+ onFallback?: (params: { error: unknown; lng: string; ns: string }) => void;+}++export const loadI18nNamespaceModuleWithFallback = async (+ params: LoadI18nNamespaceModuleWithFallbackParams,+) => {+ const { onFallback, ...rest } = params;++ try {+ return await loadI18nNamespaceModule(rest);+ } catch (error) {+ onFallback?.({ error, lng: rest.lng, ns: rest.ns });+ return import(`@/locales/default/${rest.ns}`);+ }+};