Files
3x-ui/frontend/src/i18n/react.ts
T
MHSanaei 72fb4d9358 fix(frontend): keep node-reported text out of i18next's nesting parser
The SPA initialised i18next with nesting on, though no locale uses
$t(...), so its nesting regex, exponential on an unclosed "$t(", ran
over every missing key and interpolated value, including the status and
name a node reports for its sub-nodes. One crafted status froze the
Nodes page.

Nesting is switched off for every i18next instance the project creates,
an unknown status renders as Unknown instead of being used as a key,
and a sub-node is never named as the parent it is reached through.
2026-11-01 13:34:21 +01:00

65 lines
2.0 KiB
TypeScript

import i18next from 'i18next';
import type { InterpolationOptions } from 'i18next';
import { initReactI18next } from 'react-i18next';
import { LanguageManager } from '@/utils';
import type { LanguageScope } from '@/utils';
import { loadAntdLocale } from './AntdRootConfig';
import enUS from '../../../internal/web/translation/en-US.json';
const FALLBACK = 'en-US';
// No locale uses $t(...) nesting, and its regex backtracks exponentially on an unclosed
// "$t(" in untrusted text (node-reported names, remarks); no off switch, so never match.
export const INTERPOLATION: InterpolationOptions = {
escapeValue: false,
prefix: '{',
suffix: '}',
nestingPrefix: '',
nestingPrefixEscaped: '(?!)',
};
const lazyModules = import.meta.glob([
'../../../internal/web/translation/*.json',
'!../../../internal/web/translation/en-US.json',
]);
function moduleKeyFor(code: string): string {
return `../../../internal/web/translation/${code}.json`;
}
export async function readyI18n(scope: LanguageScope = 'panel') {
let active = LanguageManager.getLanguage(scope);
if (
active !== FALLBACK &&
!Object.prototype.hasOwnProperty.call(lazyModules, moduleKeyFor(active))
) {
active = FALLBACK;
}
await i18next.use(initReactI18next).init({
lng: active,
fallbackLng: FALLBACK,
resources: { [FALLBACK]: { translation: enUS } },
interpolation: INTERPOLATION,
returnNull: false,
});
if (active !== FALLBACK) {
const loader = lazyModules[moduleKeyFor(active)] as
| (() => Promise<{ default: Record<string, unknown> }>)
| undefined;
if (loader) {
const mod = await loader();
const messages = (mod.default ?? mod) as Record<string, unknown>;
i18next.addResourceBundle(active, 'translation', messages, true, true);
await i18next.changeLanguage(active);
}
}
// The html files ship lang="en"; screen readers pick their voice from it (s-ui#1293).
document.documentElement.lang = i18next.language;
await loadAntdLocale(i18next.language);
return i18next;
}
export { i18next as i18n };