|
1 | 1 | // Copyright (c) 2025 ObjectStack. Licensed under the Apache-2.0 license. |
2 | 2 |
|
| 3 | +/** |
| 4 | + * Recursively merge `source` into `target`. Nested plain objects are merged |
| 5 | + * rather than replaced, so multiple plugins can each contribute their own |
| 6 | + * slice of a locale's translations (e.g. `{objects: {account: ...}}` and |
| 7 | + * `{objects: {task: ...}}`) without clobbering one another. |
| 8 | + */ |
| 9 | +function deepMerge( |
| 10 | + target: Record<string, unknown>, |
| 11 | + source: Record<string, unknown>, |
| 12 | +): Record<string, unknown> { |
| 13 | + const result: Record<string, unknown> = { ...target }; |
| 14 | + for (const key of Object.keys(source)) { |
| 15 | + const tVal = target[key]; |
| 16 | + const sVal = source[key]; |
| 17 | + if ( |
| 18 | + tVal && sVal |
| 19 | + && typeof tVal === 'object' && !Array.isArray(tVal) |
| 20 | + && typeof sVal === 'object' && !Array.isArray(sVal) |
| 21 | + ) { |
| 22 | + result[key] = deepMerge( |
| 23 | + tVal as Record<string, unknown>, |
| 24 | + sVal as Record<string, unknown>, |
| 25 | + ); |
| 26 | + } else { |
| 27 | + result[key] = sVal; |
| 28 | + } |
| 29 | + } |
| 30 | + return result; |
| 31 | +} |
| 32 | + |
3 | 33 | /** |
4 | 34 | * Resolve a locale code against available locales with fallback. |
5 | 35 | * |
@@ -93,8 +123,12 @@ export function createMemoryI18n() { |
93 | 123 | }, |
94 | 124 |
|
95 | 125 | loadTranslations(locale: string, data: Record<string, unknown>): void { |
96 | | - const existing = translations.get(locale) ?? {}; |
97 | | - translations.set(locale, { ...existing, ...data }); |
| 126 | + const existing = translations.get(locale); |
| 127 | + if (existing) { |
| 128 | + translations.set(locale, deepMerge(existing, data)); |
| 129 | + } else { |
| 130 | + translations.set(locale, { ...data }); |
| 131 | + } |
98 | 132 | }, |
99 | 133 |
|
100 | 134 | getLocales(): string[] { |
|
0 commit comments