Skip to content

Free, Open Source, Self-Hosted WhatsApp API Gateway

perf(dashboard): load locale catalogues on demand

Yudhi Armyndharis245967b218cd
diff --git a/CHANGELOG.md b/CHANGELOG.md
index bcaa6896b..9ce901c80 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -15,6 +15,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Fixed
+- The dashboard bundled all thirteen locales into one 476 KB chunk the page preloaded, so every visitor downloaded twelve languages to read one; each is now fetched on demand.
- `check:sdk-routes` scanned the JavaScript client for backtick-delimited paths only, while its PHP and Python rules already accepted every quote style, so the nine routes that client writes as single-quoted strings were never compared to the contract — `/api/health/ready` among them, which is also the container healthcheck and Kubernetes readiness path. Renaming one of those server-side passed every gate and the JS suite, and the published client would have 404'd with CI green.
- The JavaScript, Python, Go and Java SDKs omitted `contact`, `call` and `ephemeralDuration` from their chat-history message type, so a typed client had to cast to read three fields the endpoint returns; all four now mirror the engine payload.
- `POST /api/infra/import-data` bound its body to an inline type, which erases at runtime, so on the replace-all restore the global ValidationPipe's `whitelist` and `forbidNonWhitelisted` never ran: a body carrying no `tables` failed as a 500 from inside the import, and a misspelled key was accepted in silence. It now takes a DTO — a missing `tables` answers 400 naming the field, an unknown key is refused, and `force`/`stopOrphans` accept only a real boolean or an exact `'true'`/`'false'`, so an ambiguous spelling cannot open the orphan-engine escape.
diff --git a/dashboard/src/i18n/index.ts b/dashboard/src/i18n/index.ts
index 3e51f9464..d9b909ec3 100644
--- a/dashboard/src/i18n/index.ts
+++ b/dashboard/src/i18n/index.ts
@@ -1,19 +1,7 @@
import i18n from 'i18next';
+import type { BackendModule, ReadCallback, ResourceKey } from 'i18next';
import { initReactI18next } from 'react-i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
-import en from './locales/en.json';
-import de from './locales/de.json';
-import es from './locales/es.json';
-import tr from './locales/tr.json';
-import he from './locales/he.json';
-import zhCN from './locales/zh-CN.json';
-import zhHK from './locales/zh-HK.json';
-import ar from './locales/ar.json';
-import te from './locales/te.json';
-import fr from './locales/fr.json';
-import it from './locales/it.json';
-import ptBR from './locales/pt-BR.json';
-import ko from './locales/ko.json';
export const supportedLanguages = [
'en',
@@ -66,28 +54,52 @@ export function resolveSupportedLanguage(lang?: string): SupportedLanguage {
return supportedLanguages.find(supported => supported === base) ?? 'en';
}
-void i18n
+/**
+ * i18next's own loading extension point. Using it rather than fetching by hand is what keeps a
+ * runtime language switch correct: i18next resolves `read` for the requested language before it
+ * emits `languageChanged`, so no component ever renders against a half-loaded catalogue and neither
+ * language picker has to sequence anything itself.
+ */
+const lazyLocaleBackend: BackendModule = {
+ type: 'backend',
+ init: () => {},
+ read: (language: string, _namespace: string, callback: ReadCallback) => {
+ // A dynamic import with a variable rather than `import.meta.glob`: Vite splits one chunk per
+ // matched file either way, but this stays a real runtime import under the bare node test runner
+ // that renders the components, where the Vite transform does not run and `import.meta.glob` is
+ // undefined. Keep the directory and the extension literal or the split stops happening.
+ void import(`./locales/${language}.json`).then(
+ (module: { default: ResourceKey }) => callback(null, module.default),
+ (error: Error) => callback(error, false),
+ );
+ },
+};
+
+function applyDirection(lang: string) {
+ const resolved = resolveSupportedLanguage(lang);
+ const dir = rtlLanguages.includes(resolved) ? 'rtl' : 'ltr';
+ if (typeof document !== 'undefined') {
+ document.documentElement.lang = resolved;
+ document.documentElement.dir = dir;
+ }
+}
+
+// Subscribed before init, which is also what sets the initial direction: init resolves the detected
+// language through `changeLanguage`, so the first event is the initial one. Registering afterwards
+// happens to work too, but only because init defers — this way the order cannot matter.
+i18n.on('languageChanged', applyDirection);
+
+export const i18nReady = i18n
+ .use(lazyLocaleBackend)
.use(LanguageDetector)
.use(initReactI18next)
.init({
- resources: {
- en: { translation: en },
- de: { translation: de },
- tr: { translation: tr },
- es: { translation: es },
- he: { translation: he },
- 'zh-CN': { translation: zhCN },
- 'zh-HK': { translation: zhHK },
- ar: { translation: ar },
- te: { translation: te },
- fr: { translation: fr },
- it: { translation: it },
- 'pt-BR': { translation: ptBR },
- ko: { translation: ko },
- },
fallbackLng: 'en',
supportedLngs: supportedLanguages as unknown as string[],
nonExplicitSupportedLngs: false,
+ // Fetch only the resolved language (plus the fallback). i18next's default would also request a
+ // bare 'zh' catalogue for a 'zh-CN' visitor, and no such file exists.
+ load: 'currentOnly',
interpolation: { escapeValue: false },
detection: {
order: ['localStorage', 'navigator'],
@@ -98,16 +110,4 @@ void i18n
react: { useSuspense: false },
});
-function applyDirection(lang: string) {
- const resolved = resolveSupportedLanguage(lang);
- const dir = rtlLanguages.includes(resolved) ? 'rtl' : 'ltr';
- if (typeof document !== 'undefined') {
- document.documentElement.lang = resolved;
- document.documentElement.dir = dir;
- }
-}
-
-applyDirection(i18n.language);
-i18n.on('languageChanged', applyDirection);
-
export default i18n;
diff --git a/dashboard/src/i18n/lazy-locales.test.ts b/dashboard/src/i18n/lazy-locales.test.ts
new file mode 100644
index 000000000..a2049cf5a
--- /dev/null
+++ b/dashboard/src/i18n/lazy-locales.test.ts
@@ -0,0 +1,77 @@
+// Everything the lazy locale split can break is runtime behaviour no build gate can see: the active
+// catalogue has to be in place before anything renders, a language switch has to pull its catalogue
+// in before components re-read it, and the direction flip that dresses Hebrew and Arabic has to
+// survive both. Exercised against the real i18n module under the same JSDOM bootstrap the page
+// render tests use, because the loader only exists at runtime — `locales.test.ts` deliberately reads
+// this module as text and so can say nothing about any of it.
+//
+// Runner constraints honored here: loader hooks registered before any app-module import (see
+// test-helpers/register-hooks), and JSDOM installed before importing a module that touches
+// `document` and `localStorage` while it initializes.
+import '../test-helpers/register-hooks.ts';
+import { test, before } from 'node:test';
+import assert from 'node:assert/strict';
+import { readFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+import type { installJsdomGlobals as installJsdomGlobalsFn } from '../test-helpers/jsdom.ts';
+
+type I18nModule = typeof import('./index.ts');
+
+let i18n: I18nModule['default'];
+
+before(async () => {
+ const { installJsdomGlobals } = (await import('../test-helpers/jsdom.ts')) as {
+ installJsdomGlobals: typeof installJsdomGlobalsFn;
+ };
+ await installJsdomGlobals();
+ const module = (await import('./index.ts')) as I18nModule;
+ i18n = module.default;
+ await module.i18nReady;
+});
+
+// If the catalogue were still in flight when this settles, `t` would hand back the raw key and the
+// shell would paint it before swapping in real copy a tick later.
+test('the detected catalogue is loaded by the time i18nReady settles', () => {
+ assert.equal(i18n.t('sessionStatus.failed'), 'Failed');
+ assert.equal(document.documentElement.lang, 'en');
+ assert.equal(document.documentElement.dir, 'ltr');
+});
+
+// The whole reason the loader is an i18next backend rather than a hand-rolled fetch: i18next holds
+// `languageChanged` until the catalogue has arrived. Reading the Arabic copy straight after the
+// await is what proves that ordering — a half-loaded switch would answer with the English fallback.
+test('switching language at runtime loads that catalogue before it resolves', async () => {
+ await i18n.changeLanguage('ar');
+ assert.equal(i18n.t('sessionStatus.failed'), 'فشل');
+
+ await i18n.changeLanguage('de');
+ assert.equal(i18n.t('sessionStatus.failed'), 'Fehlgeschlagen');
+});
+
+test('direction follows the language in both directions, for both RTL locales', async () => {
+ await i18n.changeLanguage('he');
+ assert.equal(document.documentElement.dir, 'rtl');
+ assert.equal(document.documentElement.lang, 'he');
+
+ await i18n.changeLanguage('ar');
+ assert.equal(document.documentElement.dir, 'rtl');
+
+ // Back to an LTR language: a direction that only ever gets set is a direction that sticks.
+ await i18n.changeLanguage('en');
+ assert.equal(document.documentElement.dir, 'ltr');
+ assert.equal(document.documentElement.lang, 'en');
+});
+
+// The catalogue is fetched now instead of bundled, so first paint is only free of untranslated text
+// while the entry keeps rendering behind that promise. Nothing in a build or a type check notices
+// if the gate is dropped, and the flash it brings back is a tick long — easy to miss by hand.
+test('main.tsx renders behind i18nReady', () => {
+ const source = readFileSync(join(dirname(fileURLToPath(import.meta.url)), '..', 'main.tsx'), 'utf8');
+ assert.match(source, /i18nReady\.then\(/, 'main.tsx no longer defers the first render until the catalogue is loaded');
+ assert.doesNotMatch(
+ source,
+ /^createRoot\(/m,
+ 'main.tsx calls createRoot at module scope again — the first paint no longer waits for the catalogue',
+ );
+});
diff --git a/dashboard/src/i18n/locales.test.ts b/dashboard/src/i18n/locales.test.ts
index 38f9ed665..bdbf23b30 100644
--- a/dashboard/src/i18n/locales.test.ts
+++ b/dashboard/src/i18n/locales.test.ts
@@ -179,12 +179,15 @@ test('English start teardown-pending copy is a retryable warning, not an error',
assert.ok(title && title !== 'sessions.start.teardownPendingTitle');
});
-// A locale JSON file is only reachable in the UI once it is wired into index.ts in four separate
-// places. `check-i18n-parity.mjs` scans the locales DIRECTORY and never opens index.ts, so a fully
-// translated catalogue can pass that gate while being unreachable — no import, absent from the
-// language picker, or missing from i18next's resources. Read index.ts as text (the same technique
-// this file already uses for Sessions.tsx) rather than importing it, which would pull in
-// `i18next-browser-languagedetector` and `document` under the bare node test runner.
+// A locale JSON file is only reachable in the UI once it is wired into index.ts. The catalogues are
+// loaded by a dynamic import whose specifier is built from the language id, which reaches every file
+// in the directory at once, so what is left to get wrong by hand is the pair of lists: a locale
+// absent from `supportedLanguages` is refused by i18next, and one absent from `languageOptions`
+// cannot be picked. `check-i18n-parity.mjs` scans the locales DIRECTORY and never opens index.ts, so
+// a fully translated catalogue can pass that gate while being unreachable. Read index.ts as text
+// (the same technique this file already uses for Sessions.tsx) rather than importing it, which would
+// pull in `i18next-browser-languagedetector` and `document`; `lazy-locales.test.ts` is where the
+// module is imported for real, under JSDOM, to exercise what it does at runtime.
const I18N_INDEX_SOURCE = readFileSync(join(dirname(fileURLToPath(import.meta.url)), 'index.ts'), 'utf8');
const section = (start: string, source = I18N_INDEX_SOURCE): string => {
@@ -201,18 +204,10 @@ const localeIdsIn = (text: string): string[] => [
...new Set([...text.matchAll(/['"]([a-z]{2}(?:-[A-Za-z]{2,4})?)['"]/g)].map(m => m[1])),
];
-test('every locale file is registered in all four index.ts sites', () => {
+test('every locale file is registered in both hand-maintained index.ts sites', () => {
const registrations: Array<[string, string[]]> = [
- ['import', [...I18N_INDEX_SOURCE.matchAll(/from '\.\/locales\/([^']+)\.json'/g)].map(m => m[1])],
['supportedLanguages', localeIdsIn(section('export const supportedLanguages = ['))],
['languageOptions', localeIdsIn(section('export const languageOptions:'))],
- // Anchored on `: { translation:` — the resources map is the only place that shape occurs, and
- // it quotes only hyphenated ids ('zh-CN') while leaving simple ones bare (en), so both forms
- // must be accepted.
- [
- 'resources',
- [...I18N_INDEX_SOURCE.matchAll(/(?:'([\w-]+)'|([\w-]+))\s*:\s*\{\s*translation:/g)].map(m => m[1] ?? m[2]),
- ],
];
for (const [site, found] of registrations) {
@@ -224,6 +219,28 @@ test('every locale file is registered in all four index.ts sites', () => {
}
});
+// The variable dynamic import is the third registration site, and the only one that covers a new
+// locale file for free. It is also what makes the build split one chunk per language: Vite can only
+// do that while the directory and the extension around the variable stay literal, so a specifier
+// assembled further up would quietly stop splitting while still loading correctly in dev.
+test('the locale loader imports the whole locales directory by variable', () => {
+ assert.match(
+ I18N_INDEX_SOURCE,
+ /import\(\s*`\.\/locales\/\$\{\s*\w+\s*\}\.json`\s*\)/,
+ 'index.ts no longer loads locales through a variable dynamic import over ./locales/*.json',
+ );
+});
+
+// Every catalogue used to be imported statically, which put all of them in one chunk the page
+// preloaded to read a single language. A reinstated import would restore that quietly: the build
+// stays green, the parity gates stay green, and only the byte count moves.
+test('no locale catalogue is imported statically', () => {
+ const staticImports = [...I18N_INDEX_SOURCE.matchAll(/^import\s[^\n]*from\s*['"]\.\/locales\/[^\n]*$/gm)].map(
+ m => m[0],
+ );
+ assert.deepEqual(staticImports, [], 'a static locale import is back — every language is on the critical path again');
+});
+
// rtlLanguages is deliberately a SUBSET (only he/ar today), so it is checked for validity, not parity:
// an id here that is not a shipped locale would set dir="rtl" for a language that cannot be selected.
test('rtlLanguages only names shipped locales', () => {
diff --git a/dashboard/src/main.tsx b/dashboard/src/main.tsx
index a4987a48d..ba39a5310 100644
--- a/dashboard/src/main.tsx
+++ b/dashboard/src/main.tsx
@@ -1,6 +1,6 @@
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
-import './i18n';
+import { i18nReady } from './i18n';
import './index.css';
import App from './App.tsx';
@@ -12,8 +12,14 @@ if (storedTheme === 'light' || storedTheme === 'dark') {
document.documentElement.setAttribute('data-theme', storedTheme);
}
-createRoot(document.getElementById('root')!).render(
- <StrictMode>
- <App />
- </StrictMode>,
-);
+// The active locale is fetched rather than bundled into the entry, so first paint waits for it —
+// otherwise the shell renders raw keys and swaps to real copy a tick later. Rendering on rejection
+// too: a locale that fails to load must degrade to untranslated text, never to a blank page.
+const render = () =>
+ createRoot(document.getElementById('root')!).render(
+ <StrictMode>
+ <App />
+ </StrictMode>,
+ );
+
+void i18nReady.then(render, render);