Build Agentic workflows, RAG pipelines, with rich AI model and tool support on one collaborative workspace. Deploy on cloud, VPC, or self-hosted, so teams move from prototype to production without rebuilding the stack.
Python agentagentic-aiagentic-frameworkagentic-workflowaiautomationclaudedeepseekgenaigptllmlow-codemcpnextjsno-codeopenaipythonskillsworkflow
refactor(i18n): scope and validate sign-in translation namespaces (#42506)
Stephen Zhoude8433277fb0
diff --git a/e2e/features/accessibility/keyboard-navigation.feature b/e2e/features/accessibility/keyboard-navigation.featureindex 229552affa8..1c3d764cefa 100644--- a/e2e/features/accessibility/keyboard-navigation.feature+++ b/e2e/features/accessibility/keyboard-navigation.feature@@ -5,7 +5,8 @@ Feature: Keyboard navigationScenario: Skip repeated navigation and move focus to the main contentGiven I am signed in as the default E2E adminWhen I open the default console entry- And I focus and activate the skip navigation link with the keyboard+ Then I should be on the console home+ When I focus and activate the skip navigation link with the keyboardThen the console main content should have keyboard focus@unauthenticateddiff --git a/e2e/features/step-definitions/apps/web-app-service.steps.ts b/e2e/features/step-definitions/apps/web-app-service.steps.tsindex 8bd2717a62e..8937ba9b3c8 100644--- a/e2e/features/step-definitions/apps/web-app-service.steps.ts+++ b/e2e/features/step-definitions/apps/web-app-service.steps.ts@@ -28,6 +28,23 @@ const getWebAppSwitch = (world: DifyWorld) => {return webAppCard.getByRole('switch', { name: 'Web App' })}+async function waitForPersistedWebAppState(world: DifyWorld, enabled: boolean) {+ const appId = world.createdAppIds.at(-1)+ if (!appId) throw new Error('No workflow app has been created.')+ const client = world.getConsoleClient()+ // The status label updates optimistically. A different browser must wait for+ // the saved state before reloading the published app.+ await expect+ .poll(+ async () => {+ const app = await client.apps.byAppId.get({ params: { app_id: appId } })+ return app.enable_site+ },+ { timeout: 10_000 },+ )+ .toBe(enabled)+}+When('an anonymous visitor opens the Web App', async function (this: DifyWorld) {if (!this.shareURL) throw new Error('No Web App URL is available.')if (!this.context) throw new Error('Playwright browser context has not been initialized.')@@ -67,6 +84,7 @@ Then('the Web App should be in service', async function (this: DifyWorld) {await expect(webAppCard.getByText(/^In service$/i)).toBeVisible({timeout: 10_000,})+ await waitForPersistedWebAppState(this, true)})Then('the Web App should be disabled', async function (this: DifyWorld) {@@ -74,6 +92,7 @@ Then('the Web App should be disabled', async function (this: DifyWorld) {await expect(webAppCard.getByText('Disabled', { exact: true })).toBeVisible({timeout: 10_000,})+ await waitForPersistedWebAppState(this, false)})Then('the published workflow Web App should be accessible', async function (this: DifyWorld) {diff --git a/web/app/components/provider/i18n-server.tsx b/web/app/components/provider/i18n-server.tsxindex aa6745a2061..3ea4cd77341 100644--- a/web/app/components/provider/i18n-server.tsx+++ b/web/app/components/provider/i18n-server.tsx@@ -1,9 +1,18 @@+import { getDeclaredRouteNamespaces, getRouteNamespaces } from '@/i18n/route-namespaces'import { getLocaleOnServer, getResources } from '@/i18n/server'+import { headers } from '@/next/headers'+import { basePath } from '@/utils/var'import { I18nClientProvider } from './i18n'export async function I18nServerProvider({ children }: { children: React.ReactNode }) {const locale = await getLocaleOnServer()- const resource = await getResources(locale)+ const pathname = (await headers()).get('x-dify-pathname')+ const requiredNamespaces = getRouteNamespaces(pathname, basePath)+ const resource = await getResources(+ locale,+ requiredNamespaces,+ getDeclaredRouteNamespaces(pathname, basePath) !== undefined,+ )return (<I18nClientProvider locale={locale} resource={resource}>diff --git a/web/app/components/provider/i18n.tsx b/web/app/components/provider/i18n.tsxindex ca8b41e894d..5d91b09f3e1 100644--- a/web/app/components/provider/i18n.tsx+++ b/web/app/components/provider/i18n.tsx@@ -2,8 +2,13 @@import type { Resource } from 'i18next'import type { Locale } from '@/i18n'-import { I18nextProvider } from 'react-i18next'+import type { Namespace } from '@/i18n/resources'+import { Suspense, useEffect, useState } from 'react'+import { I18nextProvider, useTranslation } from 'react-i18next'import { createI18nextInstance } from '@/i18n/client'+import { getRouteNamespaces } from '@/i18n/route-namespaces'+import { usePathname } from '@/next/navigation'+import { basePath } from '@/utils/var'export function I18nClientProvider({locale,@@ -14,7 +19,37 @@ export function I18nClientProvider({resource: Resourcechildren: React.ReactNode}) {- const i18n = createI18nextInstance(locale, resource)+ const requiredNamespaces = getRouteNamespaces(usePathname(), basePath)+ const [i18n] = useState(() => createI18nextInstance(locale, resource))+ const defaultNamespace = requiredNamespaces.includes('app') ? 'app' : 'common'+ return (+ <I18nextProvider i18n={i18n} defaultNS={defaultNamespace}>+ <Suspense fallback={null}>+ <RouteTranslations+ key={requiredNamespaces.join(':')}+ i18n={i18n}+ requiredNamespaces={requiredNamespaces}+ />+ {children}+ </Suspense>+ </I18nextProvider>+ )+}- return <I18nextProvider i18n={i18n}>{children}</I18nextProvider>+function RouteTranslations({+ i18n,+ requiredNamespaces,+}: {+ requiredNamespaces: readonly Namespace[]+ i18n: ReturnType<typeof createI18nextInstance>+}) {+ const defaultNamespace = requiredNamespaces.includes('app') ? 'app' : 'common'+ useTranslation([...requiredNamespaces], { i18n })+ useEffect(() => {+ // i18next remembers every namespace ever requested. Keep language switching+ // scoped to the active route while retaining already fetched bundles.+ i18n.options.ns = [...requiredNamespaces]+ i18n.setDefaultNamespace(defaultNamespace)+ }, [i18n, requiredNamespaces, defaultNamespace])+ return null}diff --git a/web/i18n/README.md b/web/i18n/README.mdindex 632a41e9e7d..826985292b3 100644--- a/web/i18n/README.md+++ b/web/i18n/README.md@@ -75,3 +75,82 @@ not load Vite plugins.Changes to `web/i18n/locales/en-US/*.json` on `main` trigger the scoped translation workflow. The workflow derives target locales from `languages.ts`, translates only the changed namespaces and keys, verifies them with `i18n:check`, and opens a pull request when translations change.Use the `Translate i18n Files with Claude Code` workflow dispatch for a manual scoped sync. Full mode requires an explicit file list.++## Initial route resources++`route-namespaces.ts` owns the explicit `routeNamespaceDeclarations` opt-in map+shared by server selection, client navigation and production build validation. `/signin` and its child routes use `common` and+`login`. Other routes retain the complete registry until they are migrated.++The server reads the pathname that `proxy.ts` overwrites on every request. Missing+or unknown paths conservatively use the full registry. Base paths are supported.+For sign-in, the serialized resources include the requested locale and, when it+differs, English fallback resources for those same two namespaces. Unmigrated+routes retain their existing fallback loading behavior.++Client initialization uses only the provided namespaces. The default namespace is+`common` for sign-in, so a bare `useTranslation()` does not request `app`. The+provider keeps the same i18next instance across rerenders and locale changes.+A namespace-set change resets only the translation readiness component; the+provider and business subtree retain their state, including active notifications.+Suspense reveals children after the destination's namespaces are loaded. The current route's namespace list also+controls language switching, without discarding previously loaded bundles.++Server metadata requests initialize an empty instance and load their requested+namespace. Existing server consumers without a namespace keep the full-catalog+behavior for cross-namespace calls.++### Build validation++Production Vite builds check every opted-in route against its declaration using+the combined client, SSR and RSC module graphs. The check includes page imports,+shared layouts and boundaries, dynamic imports and conservative parallel slots.+An undeclared namespace fails the build and lists the route and source files.+The JSON analysis report is written before validation, so it remains available+when validation fails. Unregistered routes are not checked against a restricted+list and continue to load the full catalog.++Add a subtree to `routeNamespaceDeclarations` after auditing its dependencies;+more specific declarations override ancestor declarations. The check covers+statically recognized translation usage, including namespace constants, imported+arrays and nested static spreads passed to translation hooks or server loaders,+not arbitrary runtime imports or+unknown translation APIs. Consult the analyzer README for its limitations.++### Production validation of the sign-in migration++Measured locally on 2026-09-18 against layer 2 (`b6405a857a`), using production+Vinext standalone builds and fresh Chromium contexts. Both builds used the same+controlled API fixture: `createSystemFeaturesFixture({ is_allow_register: true })`,+completed setup/init, and an unauthenticated account-profile response. These are+frontend transfer diagnostics, not production-backend latency measurements.++| `/signin` metric | Before | After |+| --------------------------------------------- | ------: | ------: |+| English HTML response body, bytes | 438,163 | 95,915 |+| Chinese HTML response body, bytes | 424,123 | 148,172 |+| English RSC response body, bytes | 380,526 | 59,829 |+| Chinese RSC response body, bytes | 366,751 | 108,608 |+| English initial translation-module requests | 0 | 0 |+| Chinese initial translation-module requests | 36 | 0 |+| English → Chinese translation-module requests | 37 | 2 |++HTML includes embedded RSC and other page data; HTML and standalone RSC sizes+must not be added. RSC was requested separately using `RSC: 1` on `/signin?_rsc`+with an explicit locale cookie. Body sizes are decoded bytes, not compressed+wire transfer sizes. Estimated gzip sizes for the HTML bodies were approximately+106 KB → 23 KB (English) and 112 KB → 38 KB (Chinese).++Translation requests were identified using the production client manifest's+`i18n/locales/` entries, rather than chunk-name guesses. The new language-switch+waterfall loads the locale loader module, then the common and login modules in+parallel. No translation modules are requested on initial English or Chinese+sign-in hydration. Rendered page text matched the baseline and no browser runtime+errors were recorded. Client navigation to `/signup` and back rendered correctly;+unmigrated destinations still load their complete namespace set on entry.++Unit coverage uses real i18next/react-i18next to check initial loading, missing-key+fallback, locale persistence, route transitions and active-route language changes.+The route-analysis report is diagnostic guidance, not an automatic resource manifest.+Datasets and authenticated feature-navigation/network validation remain follow-up+work for issue #42442; this migration does not close that issue.diff --git a/web/i18n/__tests__/route-loading.spec.tsx b/web/i18n/__tests__/route-loading.spec.tsxnew file mode 100644index 00000000000..4f42d09fa31--- /dev/null+++ b/web/i18n/__tests__/route-loading.spec.tsx@@ -0,0 +1,148 @@+import { createToast, createToastManager } from '@langgenius/dify-ui/toast'+import { act, render, screen, waitFor } from '@testing-library/react'+import { useTranslation } from 'react-i18next'+import { I18nClientProvider } from '@/app/components/provider/i18n'+import { AppToastHost } from '@/app/notifications/host'+import { changeLanguage } from '../client'+import { getDeclaredRouteNamespaces, getRouteNamespaces } from '../route-namespaces'++vi.unmock('react-i18next')+const mocks = vi.hoisted(() => ({ pathname: '/signin', loadResource: vi.fn() }))+vi.mock('@/next/navigation', () => ({ usePathname: () => mocks.pathname }))+vi.mock('../load-resource', () => ({ loadI18nResource: mocks.loadResource }))++const makeResources = () => ({+ 'en-US': {+ common: { 'operation.save': 'Save', 'operation.cancel': 'Cancel' },+ login: { signBtn: 'Sign in' },+ },+ 'zh-Hans': { common: { 'operation.save': '保存' }, login: { signBtn: '登录' } },+})+let resources = makeResources()+function Label() {+ const { t } = useTranslation()+ return (+ <span>+ {t(($) => $['operation.save'], { ns: 'common' })} /{' '}+ {t(($) => $['operation.cancel'], { ns: 'common' })}+ </span>+ )+}++describe('route translation loading', () => {+ beforeEach(() => {+ resources = makeResources()+ mocks.pathname = '/signin'+ mocks.loadResource.mockReset()+ mocks.loadResource.mockImplementation(+ async (locale: keyof typeof resources, namespace: string) => ({+ default: resources[locale]?.[namespace as 'common' | 'login'] ?? {},+ }),+ )+ })++ it('renders localized text and fallback without requesting missing unrelated namespaces', async () => {+ render(+ <I18nClientProvider locale="zh-Hans" resource={resources}>+ <Label />+ </I18nClientProvider>,+ )+ expect(await screen.findByText('保存 / Cancel')).toBeVisible()+ expect(mocks.loadResource).not.toHaveBeenCalled()+ })++ it('loads only active namespaces when switching language and retains that language on rerender', async () => {+ const view = render(+ <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>+ <Label />+ </I18nClientProvider>,+ )+ await waitFor(() => expect(screen.getByText('Save / Cancel')).toBeVisible())+ await act(() => changeLanguage('zh-Hans'))+ expect(await screen.findByText('保存 / Cancel')).toBeVisible()+ expect(mocks.loadResource.mock.calls.map(([, ns]) => ns).sort()).toEqual(['common', 'login'])+ view.rerender(+ <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>+ <Label />+ </I18nClientProvider>,+ )+ expect(screen.getByText('保存 / Cancel')).toBeVisible()+ })++ it('loads unmigrated route resources on navigation, then scopes the next language change back to signin', async () => {+ const view = render(+ <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>+ <Label />+ </I18nClientProvider>,+ )+ await waitFor(() => expect(screen.getByText('Save / Cancel')).toBeVisible())+ mocks.pathname = '/apps'+ view.rerender(+ <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>+ <Label />+ </I18nClientProvider>,+ )+ await waitFor(() => expect(screen.getByText('Save / Cancel')).toBeVisible())+ expect(mocks.loadResource.mock.calls.map(([, ns]) => ns)).toContain('workflow')+ mocks.pathname = '/signin'+ view.rerender(+ <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>+ <Label />+ </I18nClientProvider>,+ )+ mocks.loadResource.mockClear()+ await act(() => changeLanguage('zh-Hans'))+ expect(await screen.findByText('保存 / Cancel')).toBeVisible()+ expect(mocks.loadResource.mock.calls.map(([, ns]) => ns).sort()).toEqual(['common', 'login'])+ })++ it('preserves global notifications across namespace changes, including suspended navigation', async () => {+ const manager = createToastManager()+ const toast = createToast(manager)+ const content = () => (+ <I18nClientProvider locale="en-US" resource={{ 'en-US': resources['en-US'] }}>+ <AppToastHost manager={manager} timeout={0} />+ <Label />+ </I18nClientProvider>+ )+ const view = render(content())+ await screen.findByText('Save / Cancel')+ act(() => {+ toast.success('Still relevant after navigation')+ })+ await screen.findByText('Still relevant after navigation')++ let finishLoading!: () => void+ const pending = new Promise<void>((resolve) => {+ finishLoading = resolve+ })+ mocks.loadResource.mockImplementation(async () => {+ await pending+ return { default: {} }+ })+ mocks.pathname = '/apps'+ view.rerender(content())+ await waitFor(() => expect(mocks.loadResource).toHaveBeenCalled())+ await act(async () => {+ finishLoading()+ await pending+ })+ expect(await screen.findByText('Still relevant after navigation')).toBeVisible()++ mocks.pathname = '/signin'+ view.rerender(content())+ expect(await screen.findByText('Still relevant after navigation')).toBeVisible()+ })++ it('matches signin segments with a base path and keeps unknown routes complete', () => {+ expect(getRouteNamespaces('/console/signin/check-code', '/console')).toEqual([+ 'common',+ 'login',+ ])+ expect(getDeclaredRouteNamespaces('/signin/check-code')).toEqual(['common', 'login'])+ expect(getDeclaredRouteNamespaces('/signin-other')).toBeUndefined()+ expect(getDeclaredRouteNamespaces('/datasets')).toBeUndefined()+ expect(getRouteNamespaces('/signin-other')).toContain('workflow')+ expect(getRouteNamespaces(null)).toContain('workflow')+ })+})diff --git a/web/i18n/__tests__/server.spec.ts b/web/i18n/__tests__/server.spec.tsindex df1ccce8525..6fc93525b51 100644--- a/web/i18n/__tests__/server.spec.ts+++ b/web/i18n/__tests__/server.spec.ts@@ -37,6 +37,26 @@ describe('server translations', () => {}))})+ it('serializes only requested namespaces, including fallback resources when requested', async () => {+ const { getResources } = await import('../server')+ const resources = await getResources('zh-Hans', ['common', 'login'], true)+ expect(Object.keys(resources)).toEqual(['zh-Hans', 'en-US'])+ expect(Object.keys(resources['zh-Hans']!)).toEqual(['common', 'login'])+ expect(resources).toMatchObject({ 'en-US': { common: { 'operation.cancel': 'Cancel' } } })+ expect(mocks.loadResource.mock.calls.map(([lng, ns]) => `${lng}/${ns}`).sort()).toEqual([+ 'en-US/common',+ 'en-US/login',+ 'zh-Hans/common',+ 'zh-Hans/login',+ ])+ })++ it('does not preload the complete catalog for namespaced server metadata', async () => {+ const { getTranslation } = await import('../server')+ await getTranslation('en-US', 'login')+ expect(mocks.loadResource).toHaveBeenCalledExactlyOnceWith('en-US', 'login')+ })+it('loads resources once for concurrent consumers and reuses them after initialization', async () => {const { getTranslation } = await import('../server')const translations = await Promise.all([diff --git a/web/i18n/client.ts b/web/i18n/client.tsindex d1234f5c5cd..6379fff925d 100644--- a/web/i18n/client.ts+++ b/web/i18n/client.ts@@ -9,6 +9,7 @@ import { getI18n, initReactI18next } from 'react-i18next'import { LOCALE_COOKIE_NAME } from '@/config'import { loadI18nResource } from './load-resource'import { normalizeLocale } from './locale'+import { namespaces } from './resources'import { getInitOptions } from './settings'export function createI18nextInstance(lng: Locale, resources: Resource) {@@ -21,7 +22,9 @@ export function createI18nextInstance(lng: Locale, resources: Resource) {),).init({- ...getInitOptions(),+ ...getInitOptions(+ namespaces.filter((namespace) => Object.hasOwn(resources[lng] ?? {}, namespace)),+ ),lng,resources,})diff --git a/web/i18n/resources.ts b/web/i18n/resources.tsindex 6447c457510..2ca4493fe7a 100644--- a/web/i18n/resources.ts+++ b/web/i18n/resources.ts@@ -183,5 +183,5 @@ export const namespaces = [] as const satisfies ReadonlyArray<keyof Resources>export type Namespace = (typeof namespaces)[number]-export const namespacesInFileName = namespaces.map((ns) => kebabCase(ns))+const namespacesInFileName = namespaces.map((ns) => kebabCase(ns))export type NamespaceInFileName = (typeof namespacesInFileName)[number]diff --git a/web/i18n/route-namespaces.ts b/web/i18n/route-namespaces.tsnew file mode 100644index 00000000000..971dd493d9f--- /dev/null+++ b/web/i18n/route-namespaces.ts@@ -0,0 +1,26 @@+import type { Namespace } from './resources'+import { namespaces } from './resources'++// Opt in route subtrees only after auditing their complete namespace usage.+// More specific declarations override an ancestor declaration.+const routeNamespaceDeclarations: Readonly<Record<string, readonly Namespace[]>> = {+ '/signin': ['common', 'login'],+}+const declaredRoutes = Object.keys(routeNamespaceDeclarations).sort((a, b) => b.length - a.length)++export function getDeclaredRouteNamespaces(+ pathname: string | null,+ basePath = '',+): readonly Namespace[] | undefined {+ const route =+ basePath && pathname?.startsWith(`${basePath}/`) ? pathname.slice(basePath.length) : pathname+ const declaredRoute = declaredRoutes.find(+ (path) => route === path || route?.startsWith(`${path}/`),+ )+ return declaredRoute ? routeNamespaceDeclarations[declaredRoute] : undefined+}++// Unmigrated routes retain their complete namespace set.+export function getRouteNamespaces(pathname: string | null, basePath = ''): readonly Namespace[] {+ return getDeclaredRouteNamespaces(pathname, basePath) ?? namespaces+}diff --git a/web/i18n/server.ts b/web/i18n/server.tsindex aa6fab82c08..141ac477cbc 100644--- a/web/i18n/server.ts+++ b/web/i18n/server.ts@@ -2,7 +2,6 @@ import type { Resource, ResourceLanguage } from 'i18next'import type { Locale } from '.'import type { Namespace, NamespaceInFileName } from './resources'import { match } from '@formatjs/intl-localematcher'-import { camelCase } from 'es-toolkit/string'import { createInstance } from 'i18next'import resourcesToBackend from 'i18next-resources-to-backend'import Negotiator from 'negotiator'@@ -12,7 +11,7 @@ import { LOCALE_COOKIE_NAME } from '@/config'import { cookies, headers } from '@/next/headers'import { loadI18nResource } from './load-resource'import { canonicalizeLanguageTag, defaultLocale, supportedLocales } from './locale'-import { namespacesInFileName } from './resources'+import { namespaces } from './resources'import { getInitOptions } from './settings'const getOrCreateI18next = cache(async (lng: Locale) => {@@ -25,7 +24,8 @@ const getOrCreateI18next = cache(async (lng: Locale) => {),).init({- ...getInitOptions(),+ ...getInitOptions([]),+ defaultNS: 'app',lng,})return instance@@ -34,7 +34,7 @@ const getOrCreateI18next = cache(async (lng: Locale) => {export async function getTranslation<T extends Namespace>(lng: Locale, ns?: T) {const i18nextInstance = await getOrCreateI18next(lng)- if (ns && !i18nextInstance.hasLoadedNamespace(ns)) await i18nextInstance.loadNamespaces(ns)+ await i18nextInstance.loadNamespaces(ns ? [ns] : [...namespaces])return {t: i18nextInstance.getFixedT(lng, ns),@@ -57,15 +57,26 @@ export const getLocaleOnServer = cache(async (): Promise<Locale> => {return match(languages, supportedLocales, defaultLocale) as Locale})-export const getResources = cache(async (lng: Locale): Promise<Resource> => {- const messages = {} as ResourceLanguage-- await Promise.all(- namespacesInFileName.map(async (ns) => {- const mod = await loadI18nResource(lng, ns)- messages[camelCase(ns)] = mod.default- }),- )-- return { [lng]: messages }-})+export const getResources = cache(+ async (+ lng: Locale,+ requiredNamespaces: readonly Namespace[] = namespaces,+ includeFallback = false,+ ): Promise<Resource> => {+ const locales = includeFallback && lng !== defaultLocale ? [lng, defaultLocale] : [lng]+ const resources: Resource = {}+ await Promise.all(+ locales.map(async (locale) => {+ const messages: ResourceLanguage = {}+ await Promise.all(+ requiredNamespaces.map(async (namespace) => {+ const mod = await loadI18nResource(locale, namespace)+ messages[namespace] = mod.default+ }),+ )+ resources[locale] = messages+ }),+ )+ return resources+ },+)diff --git a/web/i18n/settings.ts b/web/i18n/settings.tsindex a6b7400ab6f..7731218f1a8 100644--- a/web/i18n/settings.ts+++ b/web/i18n/settings.ts@@ -1,17 +1,18 @@import type { InitOptions } from 'i18next'+import type { Namespace } from './resources'import { defaultLocale } from './locale'import { defaultNS, namespaces } from './resources'-export function getInitOptions(): InitOptions {+export function getInitOptions(requiredNamespaces: readonly Namespace[] = namespaces): InitOptions {return {// We do not have en for fallbackload: 'currentOnly',fallbackLng: defaultLocale,partialBundledLanguages: true,- defaultNS,+ defaultNS: requiredNamespaces.includes(defaultNS) ? defaultNS : 'common',enableSelector: 'optimize',keySeparator: false,- ns: namespaces,+ ns: [...requiredNamespaces],interpolation: {escapeValue: false,},diff --git a/web/plugins/vite/__tests__/i18n-analysis.spec.ts b/web/plugins/vite/__tests__/i18n-analysis.spec.tsindex 2af75d477e9..d24cb489e94 100644--- a/web/plugins/vite/__tests__/i18n-analysis.spec.ts+++ b/web/plugins/vite/__tests__/i18n-analysis.spec.ts@@ -123,6 +123,42 @@ describe('i18n build check', () => {})})+ it('fails opted-in route builds with undeclared dynamic dependencies and their source paths', async () => {+ writeFileSync(localeFile, JSON.stringify({ used: 'Used' }))+ mkdirSync(path.join(root, 'app/signin/check-code'), { recursive: true })+ writeFileSync(+ path.join(root, 'app/signin/check-code/page.ts'),+ `export const page = () => import('../../../lazy')`,+ )+ writeFileSync(+ path.join(root, 'lazy.ts'),+ `export function label(t: (key: string) => string) { return t('app:used') }`,+ )+ writeFileSync(+ path.join(root, 'entry.ts'),+ `export { page } from './app/signin/check-code/page'`,+ )+ let enabled = true+ const run = () =>+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({+ getDeclaredNamespaces: (route) =>+ enabled && route.startsWith('/signin/') ? ['common', 'login'] : undefined,+ }),+ ],+ build: { write: false, lib: { entry: path.join(root, 'entry.ts'), formats: ['es'] } },+ })+ await expect(run()).rejects.toThrow(+ /\/signin\/check-code[\s\S]*Undeclared namespace: app[\s\S]*\[lazy\] lazy.ts/,+ )+ enabled = false+ await expect(run()).resolves.toBeDefined()+ })+it('fails builds with actionable findings without modifying translations', async () => {const content = JSON.stringify({ used: 'Used', unused: 'Unused' })writeFileSync(localeFile, content)diff --git a/web/plugins/vite/__tests__/i18n-graph.spec.ts b/web/plugins/vite/__tests__/i18n-graph.spec.tsindex 3f28f385649..2efcd3a1486 100644--- a/web/plugins/vite/__tests__/i18n-graph.spec.ts+++ b/web/plugins/vite/__tests__/i18n-graph.spec.ts@@ -37,6 +37,59 @@ describe('translation graph analysis', () => {})describe('Usage Analysis', () => {+ it('reports explicit namespace loads even when no translation key is consumed', () => {+ writeJson('i18n/locales/en-US/app.json', { unused: 'Unused' })+ writeSource(+ 'src/page.ts',+ `+ declare function useTranslation(ns: string[]): unknown+ declare function getTranslation(locale: string, ns: string): unknown+ useTranslation(['app', 'common'])+ getTranslation('en-US', 'login')+ export function boundary(requiredNamespaces: ('workflow' | 'dataset')[]) {+ useTranslation([...requiredNamespaces])+ }+ `,+ )+ const result = checkTranslationGraph(webRoot, modules)+ expect([...result.moduleNamespaces.get(path.join(webRoot, 'src/page.ts'))!].sort()).toEqual([+ 'app',+ 'common',+ 'login',+ ])+ expect(result.unused).toEqual({ app: ['unused'] })+ })++ it('resolves namespace constants, imported arrays and nested static spreads without consuming keys', () => {+ writeJson('i18n/locales/en-US/workflow.json', { unused: 'Unused' })+ writeSource(+ 'src/namespaces.ts',+ `+ export const workflow = 'workflow'+ export const extras = ['login', workflow] as const+ `,+ )+ writeSource(+ 'src/page.ts',+ `+ import { workflow, extras } from './namespaces'+ declare function useTranslation(ns: readonly string[]): unknown+ declare function getTranslation(locale: string, ns: string): unknown+ const shared = ['common', ...extras] as const+ useTranslation([workflow, ...shared])+ const cyclic = [cyclic]+ useTranslation(cyclic)+ `,+ )+ const result = checkTranslationGraph(webRoot, modules)+ expect([...result.moduleNamespaces.get(path.join(webRoot, 'src/page.ts'))!].sort()).toEqual([+ 'common',+ 'login',+ 'workflow',+ ])+ expect(result.unused).toEqual({ workflow: ['unused'] })+ })+it('resolves generic metadata selectors using the namespace at each call site', () => {writeJson('i18n/locales/en-US/app.json', { resetPassword: 'Unused app key' })writeJson('i18n/locales/en-US/login.json', {diff --git a/web/plugins/vite/__tests__/i18n-routes.spec.ts b/web/plugins/vite/__tests__/i18n-routes.spec.tsindex 36076a54f1d..f31d08f9039 100644--- a/web/plugins/vite/__tests__/i18n-routes.spec.ts+++ b/web/plugins/vite/__tests__/i18n-routes.spec.ts@@ -1,6 +1,6 @@// @vitest-environment nodeimport { describe, expect, it } from 'vite-plus/test'-import { analyzeRouteNamespaces } from '../i18n-analysis/routes'+import { analyzeRouteNamespaces, validateRouteNamespaces } from '../i18n-analysis/routes'describe('route namespace analysis', () => {it('includes ancestor boundaries and parallel slots without leaking sibling layouts', () => {@@ -44,6 +44,29 @@ describe('route namespace analysis', () => {'sidebar',],})+ expect(() => validateRouteNamespaces(report, () => undefined)).not.toThrow()+ expect(() =>+ validateRouteNamespaces(report, (route) =>+ route === '/items'+ ? [+ 'common',+ 'console',+ 'detail',+ 'error',+ 'items',+ 'lazy',+ 'loading',+ 'shared',+ 'sidebar',+ ]+ : undefined,+ ),+ ).not.toThrow()+ expect(() =>+ validateRouteNamespaces(report, (route) => (route === '/items' ? [] : undefined)),+ ).toThrow(+ /Route namespace declarations[\s\S]*\/items[\s\S]*\[shared\] app\/layout.tsx[\s\S]*\[slots\][\s\S]*\[page\][\s\S]*\[lazy\] lazy.ts/,+ )const groups = report.find((item) => item.page === 'app/(console)/items/page.tsx')!.groupsexpect(groups.page).toEqual([{ namespace: 'items', sources: ['app/(console)/items/page.tsx'] },diff --git a/web/plugins/vite/i18n-analysis.ts b/web/plugins/vite/i18n-analysis.tsindex a0cf29ba4f6..f1c0a816503 100644--- a/web/plugins/vite/i18n-analysis.ts+++ b/web/plugins/vite/i18n-analysis.ts@@ -3,13 +3,17 @@ import type { ModuleDependencies } from './i18n-analysis/routes'import fs from 'node:fs/promises'import path from 'node:path'import { normalizePath } from 'vite'-import { analyzeRouteNamespaces } from './i18n-analysis/routes'+import { analyzeRouteNamespaces, validateRouteNamespaces } from './i18n-analysis/routes'const SOURCE_META = 'dify:i18n-source'// Vite shares these instances across client, SSR, and RSC environments. Each// completed graph replaces its preceding scan build; only buildApp finalizes it.-export function i18nAnalysisPlugin(): Plugin[] {+export function i18nAnalysisPlugin(+ options: {+ getDeclaredNamespaces?: (route: string) => readonly string[] | undefined+ } = {},+): Plugin[] {let root: stringlet logger: Loggerlet reportPath: string | undefined@@ -79,6 +83,8 @@ export function i18nAnalysisPlugin(): Plugin[] {await fs.writeFile(reportPath, `${JSON.stringify({ version: 1, routes }, null, 2)}\n`)logger.info(`[i18n] Full namespace sources: ${reportPath}`)}+ if (options.getDeclaredNamespaces)+ validateRouteNamespaces(routes, options.getDeclaredNamespaces)const keys = Object.entries(unused ?? {}).flatMap(([namespace, unused]) =>unused.map((key) => `${namespace}:${key}`),)diff --git a/web/plugins/vite/i18n-analysis/README.md b/web/plugins/vite/i18n-analysis/README.mdindex 87e7b135a73..0d0ff105bfc 100644--- a/web/plugins/vite/i18n-analysis/README.md+++ b/web/plugins/vite/i18n-analysis/README.md@@ -25,8 +25,8 @@ It shares the unused-key analyzer's translation recognition and dynamic-keyfallbacks. Unresolved namespaces can include the entire catalog. Unused exports,conditional branches, lazy features and parallel slots can overestimate usage;runtime-only imports or unrecognized translation APIs can be missed. Only pages-and boundaries present in the build graph are reported. Translation loading is-unchanged, and this report does not introduce additional build failures.+and boundaries present in the build graph are reported. Reporting alone does not+change translation loading or introduce additional build failures.## Groups and source files@@ -49,5 +49,24 @@ When build output writing is enabled, `<build.outDir>/i18n-routes.json` contains`groups` mapping each category to `{ namespace, sources }` entries. Sources aresorted paths relative to the Vite root and identify modules containing recognizedtranslation usage, not necessarily the entire chain of imports leading to them.-The report is written before the unused-key check, so it remains available if that-check fails. `build.write: false` only prints the summary and writes no report.+The report is written before namespace validation and the unused-key check, so+it remains available if either check fails. `build.write: false` only prints the summary and writes no report.++## Opt-in route namespace validation++Pass `getDeclaredNamespaces(route)` to enable validation for selected route+subtrees. Returning `undefined` skips validation for that route; an empty array+means no namespaces are allowed. Any detected namespace outside the declaration+fails the production build, with the route, namespace, group and source file.+All four groups are checked, including lazy dependencies and parallel slots.+Explicit, statically resolved `useTranslation` / `getTranslation` namespace+arguments are included even when no translation key is consumed.++The application passes `getDeclaredRouteNamespaces` from+`i18n/route-namespaces.ts`, sharing declarations with server resource selection+and client navigation. Currently only `/signin` and its descendants opt in.+Undeclared routes keep the full catalog and can be migrated independently.++This validates statically detected usage, with the recognition and conservative+limitations described above. It does not prove that arbitrary runtime-generated+imports or unrecognized translation APIs stay within the declaration.diff --git a/web/plugins/vite/i18n-analysis/graph.ts b/web/plugins/vite/i18n-analysis/graph.tsindex 0a68f4a43eb..dd06df4cae8 100644--- a/web/plugins/vite/i18n-analysis/graph.ts+++ b/web/plugins/vite/i18n-analysis/graph.ts@@ -466,6 +466,23 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,}}+ function recordLoadedNamespaces(expression: ts.Expression, seen = new Set<ts.Node>()) {+ const node = unwrap(expression)+ if (seen.has(node)) return+ const next = new Set(seen).add(node)+ if (ts.isStringLiteralLike(node)) currentNamespaces.add(node.text)+ else if (ts.isArrayLiteralExpression(node))+ node.elements.forEach((element) => recordLoadedNamespaces(element, next))+ else if (ts.isSpreadElement(node)) recordLoadedNamespaces(node.expression, next)+ else {+ // Resolve values, not type unions: a route parameter's type lists possible+ // namespaces rather than requests made on every route by a shared provider.+ for (const value of alternatives(node)) {+ if (value && !ts.isFunctionDeclaration(value)) recordLoadedNamespaces(value, next)+ }+ }+ }+function visit(node: ts.Node) {if (ts.isStringLiteralLike(node) && (node.text.includes('.') || node.text.includes(':'))) {const contextual = checker.getContextualType(node)@@ -479,6 +496,14 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,}}if (ts.isCallExpression(node)) {+ const name = node.expression.getText()+ if (/(?:^|\.)(?:useTranslation|getTranslation)$/.test(name)) {+ // Explicit loading requests matter even when their t function is unused.+ // Do not mark translation keys as used merely because a namespace loads.+ const nsIndex = name.endsWith('getTranslation') ? 1 : 0+ const argument = node.arguments[nsIndex]+ if (argument) recordLoadedNamespaces(argument)+ }const info = translation(node.expression, node)const argument = info && node.arguments[info.argument]if (info && argument) {diff --git a/web/plugins/vite/i18n-analysis/routes.ts b/web/plugins/vite/i18n-analysis/routes.tsindex e5e917f744d..ce3ee43814c 100644--- a/web/plugins/vite/i18n-analysis/routes.ts+++ b/web/plugins/vite/i18n-analysis/routes.ts@@ -9,6 +9,40 @@ export type RouteNamespaceReport = {groups: Record<'page' | 'shared' | 'lazy' | 'slots', NamespaceSources[]>}+export function validateRouteNamespaces(+ routes: readonly RouteNamespaceReport[],+ getDeclaredNamespaces: (route: string) => readonly string[] | undefined,+) {+ const violations: string[] = []+ for (const report of routes) {+ const declared = getDeclaredNamespaces(report.route)+ if (declared === undefined) continue+ const missing = report.namespaces.filter((namespace) => !declared.includes(namespace))+ if (!missing.length) continue+ violations.push(+ ` ${report.route} (${report.page})`,+ ` Declared: ${declared.join(', ') || '(none)'}`,+ )+ for (const namespace of missing) {+ violations.push(` Undeclared namespace: ${namespace}`)+ for (const [group, entries] of Object.entries(report.groups)) {+ for (const source of entries.find((entry) => entry.namespace === namespace)?.sources ?? [])+ violations.push(` [${group}] ${source}`)+ }+ }+ }+ if (violations.length) {+ throw new Error(+ [+ 'Route namespace declarations do not cover statically detected usage:',+ ...violations,+ 'Remove the dependency or update the route namespace declaration after reviewing its usage.',+ 'Includes shared boundaries, dynamic imports and conservative parallel-slot additions; inspect the reported sources before changing declarations.',+ ].join('\n'),+ )+ }+}+// Use resolved build edges (including virtual modules), not an independent// resolver which could disagree with aliases, exports or environment conditions.export function analyzeRouteNamespaces(diff --git a/web/vite.config.ts b/web/vite.config.tsindex 51fd1f405bf..1744973e77b 100644--- a/web/vite.config.ts+++ b/web/vite.config.ts@@ -1,6 +1,7 @@import { fileURLToPath } from 'node:url'import { configDefaults, defineConfig, lazyPlugins } from 'vite-plus'import { playwright } from 'vite-plus/test/browser-playwright'+import { getDeclaredRouteNamespaces } from './i18n/route-namespaces.ts'import { customI18nHmrPlugin } from './plugins/vite/custom-i18n-hmr.ts'import { i18nAnalysisPlugin } from './plugins/vite/i18n-analysis.ts'import { getRootClientInjectTarget } from './plugins/vite/inject-target.ts'@@ -40,7 +41,7 @@ export default defineConfig(({ command, mode, isPreview }) => {: undefinedreturn [- i18nAnalysisPlugin(),+ i18nAnalysisPlugin({ getDeclaredNamespaces: getDeclaredRouteNamespaces }),Inspect(),inspector,tailwindcss(),