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): align analysis with Vite environment graphs (#42656)
Stephen Zhou11be5332bb7b
diff --git a/oxlint-suppressions.json b/oxlint-suppressions.jsonindex efe10fb0060..40ad8b0544f 100644--- a/oxlint-suppressions.json+++ b/oxlint-suppressions.json@@ -3353,9 +3353,6 @@"web/app/components/workflow/hooks/use-checklist.ts": {"typescript/no-empty-object-type": {"count": 1- },- "typescript/no-explicit-any": {- "count": 4}},"web/app/components/workflow/hooks/use-dynamic-test-run-options.tsx": {diff --git a/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsxindex 83f39732684..f82e42a1d4b 100644--- a/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx+++ b/web/app/components/header/account-setting/model-provider-page/provider-added-card/quota-panel.tsx@@ -257,16 +257,20 @@ const QuotaPanel: FC<QuotaPanelProps> = ({ providers }) => {const providerType = providerMap.get(key)const isLoadingPlugin = loadingPluginId === providerKeyToPluginId[key]const isConfigured = (installedProvidersMap.get(key)?.length ?? 0) > 0- const getTooltipKey = () => {- if (!providerType) return 'modelProvider.card.modelNotSupported'- if (isConfigured && providerType === PreferredProviderTypeEnum.custom)- return 'modelProvider.card.modelAPI'- return 'modelProvider.card.modelSupported'- }- const tooltipText = t(($) => $[getTooltipKey()], {- modelName: modelNameMap[key],- ns: 'common',- })+ const tooltipText = !providerType+ ? t(($) => $['modelProvider.card.modelNotSupported'], {+ modelName: modelNameMap[key],+ ns: 'common',+ })+ : isConfigured && providerType === PreferredProviderTypeEnum.custom+ ? t(($) => $['modelProvider.card.modelAPI'], {+ modelName: modelNameMap[key],+ ns: 'common',+ })+ : t(($) => $['modelProvider.card.modelSupported'], {+ modelName: modelNameMap[key],+ ns: 'common',+ })return (<Tooltip key={key}><TooltipTriggerdiff --git a/web/app/components/main-nav/components/workspace-switcher.tsx b/web/app/components/main-nav/components/workspace-switcher.tsxindex 613f36b369d..3c89005b945 100644--- a/web/app/components/main-nav/components/workspace-switcher.tsx+++ b/web/app/components/main-nav/components/workspace-switcher.tsx@@ -21,7 +21,6 @@ import { WorkspaceMenuItemContent } from './workspace-menu-content'const workspaceSwitchActionIconWrapClassName = 'flex size-5 shrink-0 items-center justify-center'const workspaceSwitchActionIconClassName = 'size-3.5 shrink-0'const workspaceSwitchListClassName = 'max-h-[240px] overflow-y-auto overscroll-contain scroll-py-1'-const workspaceSwitchI18nKey = (key: string) => key as 'mainNav.workspace.settings'type WorkspaceSort = 'lastOpened' | 'createdAt'const getWorkspaceName = (workspace: TenantListItemResponse) => workspace.name || workspace.id@@ -46,19 +45,19 @@ function WorkspaceSwitchControls({}) {const { t } = useTranslation()const [sortMenuOpen, setSortMenuOpen] = useState(false)- const sortMenuLabel = t(($) => $[workspaceSwitchI18nKey('mainNav.workspace.sort.openMenu')], {+ const sortMenuLabel = t(($) => $['mainNav.workspace.sort.openMenu'], {ns: 'common',})const sortOptions: Array<{ value: WorkspaceSort; label: string }> = [{value: 'lastOpened',- label: t(($) => $[workspaceSwitchI18nKey('mainNav.workspace.sort.lastOpened')], {+ label: t(($) => $['mainNav.workspace.sort.lastOpened'], {ns: 'common',}),},{value: 'createdAt',- label: t(($) => $[workspaceSwitchI18nKey('mainNav.workspace.sort.createdTime')], {+ label: t(($) => $['mainNav.workspace.sort.createdTime'], {ns: 'common',}),},@@ -133,10 +132,7 @@ function WorkspaceSwitchControls({<SearchInputvalue={searchText}onValueChange={onSearchTextChange}- placeholder={t(- ($) => $[workspaceSwitchI18nKey('mainNav.workspace.searchPlaceholder')],- { ns: 'common' },- )}+ placeholder={t(($) => $['mainNav.workspace.searchPlaceholder'], { ns: 'common' })}autoFocus/></div>@@ -208,7 +204,7 @@ export function WorkspaceSwitcher({role="status"className="flex h-8 items-center px-3 system-xs-regular text-text-tertiary">- {t(($) => $[workspaceSwitchI18nKey('mainNav.workspace.noResults')], {+ {t(($) => $['mainNav.workspace.noResults'], {ns: 'common',})}</div>diff --git a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/index.tsx b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/index.tsxindex 108c05a8c92..60e9fd8d294 100644--- a/web/app/components/plugins/plugin-detail-panel/subscription-list/create/index.tsx+++ b/web/app/components/plugins/plugin-detail-panel/subscription-list/create/index.tsx@@ -95,6 +95,28 @@ export const CreateSubscriptionButton = ({}}, [t])+ const methodDescriptionMap = {+ [SupportedCreationMethods.OAUTH]: t(+ ($) => $['subscription.addType.options.oauth.description'],+ {+ ns: 'pluginTrigger',+ },+ ),+ [SupportedCreationMethods.APIKEY]: t(+ ($) => $['subscription.addType.options.apikey.description'],+ {+ ns: 'pluginTrigger',+ },+ ),+ [SupportedCreationMethods.MANUAL]: t(+ ($) => $['subscription.addType.options.manual.description'],+ {+ ns: 'pluginTrigger',+ },+ ),+ [DEFAULT_METHOD]: '',+ }+const onClickClientSettings = useCallback((e: React.MouseEvent<HTMLDivElement | HTMLButtonElement>) => {e.stopPropagation()@@ -336,13 +358,7 @@ export const CreateSubscriptionButton = ({<TooltipContent>{subscriptionCount >= MAX_COUNT? t(($) => $['subscription.maxCount'], { ns: 'pluginTrigger', num: MAX_COUNT })- : t(- ($) =>- $[- `subscription.addType.options.${methodType!.toLowerCase() as Lowercase<SupportedCreationMethods>}.description`- ],- { ns: 'pluginTrigger' },- )}+ : methodDescriptionMap[methodType!]}</TooltipContent></Tooltip>)}diff --git a/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts b/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.tsindex 6cd8e7de290..3c7ebfefe34 100644--- a/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts+++ b/web/app/components/rag-pipeline/hooks/use-available-nodes-meta-data.ts@@ -1,5 +1,4 @@import type { AvailableNodesMetaData } from '@/app/components/workflow/hooks-store/store'-import type { I18nKeysWithPrefix } from '@/types/i18n'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import { WORKFLOW_COMMON_NODES } from '@/app/components/workflow/constants/node'@@ -47,11 +46,7 @@ export const useAvailableNodesMetaData = () => {mergedNodesMetaData.map((node) => {const { metaData } = nodeconst title = t(($) => $[`blocks.${metaData.type}`], { ns: 'workflow' })- const description = t(- ($) =>- $[`blocksAbout.${metaData.type}` as I18nKeysWithPrefix<'workflow', 'blocksAbout.'>],- { ns: 'workflow' },- )+ const description = t(($) => $[`blocksAbout.${metaData.type}`], { ns: 'workflow' })return {...node,metaData: {diff --git a/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts b/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.tsindex b1027598994..be0815e22a9 100644--- a/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts+++ b/web/app/components/workflow-app/hooks/use-available-nodes-meta-data.ts@@ -1,6 +1,5 @@import type { AvailableNodesMetaData } from '@/app/components/workflow/hooks-store/store'import type { DocPathWithoutLang } from '@/types/doc-paths'-import type { I18nKeysWithPrefix } from '@/types/i18n'import { useMemo } from 'react'import { useTranslation } from 'react-i18next'import { WORKFLOW_COMMON_NODES } from '@/app/components/workflow/constants/node'@@ -65,11 +64,7 @@ export const useAvailableNodesMetaData = () => {mergedNodesMetaData.map((node) => {const { metaData } = nodeconst title = t(($) => $[`blocks.${metaData.type}`], { ns: 'workflow' })- const description = t(- ($) =>- $[`blocksAbout.${metaData.type}` as I18nKeysWithPrefix<'workflow', 'blocksAbout.'>],- { ns: 'workflow' },- )+ const description = t(($) => $[`blocksAbout.${metaData.type}`], { ns: 'workflow' })const helpLinkPath = getNodeHelpLinkPath(metaData.helpLinkUri)return {...node,diff --git a/web/app/components/workflow/hooks/use-checklist.ts b/web/app/components/workflow/hooks/use-checklist.tsindex d1c7a83f489..2782d19d818 100644--- a/web/app/components/workflow/hooks/use-checklist.ts+++ b/web/app/components/workflow/hooks/use-checklist.ts@@ -18,7 +18,6 @@ import type { ModelItem } from '@/app/components/header/account-setting/model-primport type { Emoji } from '@/app/components/tools/types'import type { AgentToolPublishIssue } from '@/features/agent-v2/agent-detail/configure/tool-provider-catalog'import type { DataSet } from '@/models/datasets'-import type { I18nKeysWithPrefix } from '@/types/i18n'import { useQueries, useQuery, useQueryClient } from '@tanstack/react-query'import isDeepEqual from 'fast-deep-equal'import { useCallback, useEffect, useMemo, useRef } from 'react'@@ -557,22 +556,22 @@ export const useChecklist = (nodes: Node[], edges: Edge[], options?: { flowType?}}- const isRequiredNodesType = Object.keys(nodesExtraData!).filter(- (key: any) => (nodesExtraData as any)[key].metaData.isRequired,- )+ const isRequiredNodesType = Object.entries(nodesExtraData!)+ .filter(([, node]) => node.metaData.isRequired)+ .map(([type]) => type as BlockEnum)- isRequiredNodesType.forEach((type: string) => {+ isRequiredNodesType.forEach((type) => {if (!filteredNodes.some((node) => node.data.type === type)) {list.push({id: `${type}-need-added`,type,- title: t(($) => $[`blocks.${type}` as I18nKeysWithPrefix<'workflow', 'blocks.'>], {+ title: t(($) => $[`blocks.${type}`], {ns: 'workflow',}),errorMessages: [t(($) => $['common.needAdd'], {ns: 'workflow',- node: t(($) => $[`blocks.${type}` as I18nKeysWithPrefix<'workflow', 'blocks.'>], {+ node: t(($) => $[`blocks.${type}`], {ns: 'workflow',}),}),@@ -896,18 +895,16 @@ export const useChecklistBeforePublish = () => {}}- const isRequiredNodesType = Object.keys(nodesExtraData!).filter(- (key: any) => (nodesExtraData as any)[key].metaData.isRequired,- )-- for (let i = 0; i < isRequiredNodesType.length; i++) {- const type = isRequiredNodesType[i]+ const isRequiredNodesType = Object.entries(nodesExtraData!)+ .filter(([, node]) => node.metaData.isRequired)+ .map(([type]) => type as BlockEnum)+ for (const type of isRequiredNodesType) {if (!filteredNodes.some((node) => node.data.type === type)) {toast.error(t(($) => $['common.needAdd'], {ns: 'workflow',- node: t(($) => $[`blocks.${type}` as I18nKeysWithPrefix<'workflow', 'blocks.'>], {+ node: t(($) => $[`blocks.${type}`], {ns: 'workflow',}),}),diff --git a/web/i18n/__tests__/translation-adapters.spec.ts b/web/i18n/__tests__/translation-adapters.spec.tsnew file mode 100644index 00000000000..b7a4f88e74e--- /dev/null+++ b/web/i18n/__tests__/translation-adapters.spec.ts@@ -0,0 +1,55 @@+import type { SelectorParam } from 'i18next'++const mocks = vi.hoisted(() => {+ const t = vi.fn(() => 'Translated')+ const translations = { t }+ return {+ translations,+ t,+ client: vi.fn(() => translations),+ locale: vi.fn(async () => 'en-US'),+ server: vi.fn(async () => translations),+ use: vi.fn((promise: Promise<unknown>) => promise),+ }+})++vi.mock('server-only', () => ({}))+vi.mock('react-i18next', () => ({ useTranslation: mocks.client }))+vi.mock('react', () => ({ use: mocks.use }))+vi.mock('@/i18n/server', () => ({+ getLocaleOnServer: mocks.locale,+ getTranslation: mocks.server,+}))++beforeEach(() => vi.clearAllMocks())++describe('translation adapter contracts', () => {+ it.each(['common', undefined] as const)(+ 'forwards the client namespace %s unchanged',+ async (ns) => {+ const { useTranslation } = await import('../lib.client')+ expect(useTranslation(ns)).toBe(mocks.translations)+ expect(mocks.client).toHaveBeenCalledExactlyOnceWith(ns)+ },+ )++ it.each(['common', undefined] as const)(+ 'loads the server namespace %s with the current locale',+ async (ns) => {+ const { useTranslation } = await import('../lib.server')+ expect(await useTranslation(ns)).toBe(mocks.translations)+ expect(mocks.locale).toHaveBeenCalledTimes(1)+ expect(mocks.server).toHaveBeenCalledExactlyOnceWith('en-US', ns)+ expect(mocks.use).toHaveBeenCalledTimes(1)+ },+ )++ it('loads metadata from exactly the requested namespace and selector', async () => {+ const { getRouteMetadata } = await import('@/app/route-metadata')+ const selector: SelectorParam<'common'> = ($) => $['operation.save']+ expect(await getRouteMetadata('common', selector)).toEqual({ title: 'Translated' })+ expect(mocks.locale).toHaveBeenCalledTimes(1)+ expect(mocks.server).toHaveBeenCalledExactlyOnceWith('en-US', 'common')+ expect(mocks.t).toHaveBeenCalledExactlyOnceWith(selector, { ns: 'common' })+ })+})diff --git a/web/i18n/locales/ar-TN/explore.json b/web/i18n/locales/ar-TN/explore.jsonindex 9091d61282f..c858bf73212 100644--- a/web/i18n/locales/ar-TN/explore.json+++ b/web/i18n/locales/ar-TN/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "إضافة إلى مساحة العمل","appCard.try": "التفاصيل","appCustomize.nameRequired": "اسم التطبيق مطلوب","appCustomize.subTitle": "أيقونة التطبيق واسمه","appCustomize.title": "إنشاء تطبيق من {{name}}","apps.allCategories": "موصى به","apps.description": "قوالب جاهزة للاستخدام من المجتمع وفريق Dify.",- "apps.resetFilter": "مسح الفلتر","apps.resultNum": "{{num}} نتائج","apps.title": "قوالب","apps.viewMore": "عرض المزيد",@@ -30,17 +28,14 @@"continueWork.title": "الأخيرة","learnDify.description": "اتبع المسار — أو انتقل مباشرة إلى الخطوة التي تشعر بأنك مستعد لها.","learnDify.hide": "إخفاء",- "learnDify.moreTemplates": "المزيد من قوالب التعلّم →","learnDify.title": "تعلّم Dify","sidebar.action.delete": "حذف","sidebar.action.pin": "تثبيت","sidebar.action.rename": "إعادة تسمية","sidebar.action.unpin": "إلغاء التثبيت",- "sidebar.chat": "دردشة","sidebar.delete.content": "هل أنت متأكد أنك تريد حذف هذا التطبيق؟","sidebar.delete.title": "حذف التطبيق","sidebar.webApps": "تطبيقات الويب",- "title": "استكشاف","tryApp.category": "الفئة","tryApp.createFromSampleApp": "إنشاء من هذا التطبيق النموذجي","tryApp.requirements": "المتطلبات",diff --git a/web/i18n/locales/az-AZ/explore.json b/web/i18n/locales/az-AZ/explore.jsonindex 68e78f7e5b0..8ec0bc1c3bd 100644--- a/web/i18n/locales/az-AZ/explore.json+++ b/web/i18n/locales/az-AZ/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Şablondan istifadə et","appCard.try": "Təfərrüatlar","appCustomize.nameRequired": "Tətbiqin adı tələb olunur","appCustomize.subTitle": "Tətbiqin nişanı və adı","appCustomize.title": "{{name}} əsasında tətbiqin yaradılması","apps.allCategories": "Hamısı","apps.description": "İcma və Dify komandası tərəfindən hazırlanmış istifadəyə hazır şablonlar.",- "apps.resetFilter": "Süzgəci təmizlə","apps.resultNum": "{{num}} nəticə","apps.title": "Şablonlar","apps.viewMore": "Daha çox göstər",@@ -30,17 +28,14 @@"continueWork.title": "Son istifadə edilənlər","learnDify.description": "Ardıcıllıqla irəliləyin və ya hazır olduğunuz mərhələyə keçin.","learnDify.hide": "Gizlət",- "learnDify.moreTemplates": "Daha çox öyrənmə şablonu →","learnDify.title": "Dify ilə işin öyrənilməsi","sidebar.action.delete": "Sil","sidebar.action.pin": "Sancaqla","sidebar.action.rename": "Adını dəyiş","sidebar.action.unpin": "Sancaqdan çıxar",- "sidebar.chat": "Söhbət","sidebar.delete.content": "Bu tətbiqi silmək istədiyinizə əminsiniz?","sidebar.delete.title": "Tətbiqin silinməsi","sidebar.webApps": "Veb tətbiqləri",- "title": "Kəşf","tryApp.category": "Kateqoriya","tryApp.createFromSampleApp": "Bu nümunə tətbiqdən yarat","tryApp.requirements": "Tələblər",diff --git a/web/i18n/locales/de-DE/explore.json b/web/i18n/locales/de-DE/explore.jsonindex b2919b36f21..b8b40532f4c 100644--- a/web/i18n/locales/de-DE/explore.json+++ b/web/i18n/locales/de-DE/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Vorlage verwenden","appCard.try": "Details","appCustomize.nameRequired": "App-Name ist erforderlich","appCustomize.subTitle": "App-Symbol & Name","appCustomize.title": "App aus {{name}} erstellen","apps.allCategories": "Alle","apps.description": "Sofort nutzbare Vorlagen aus der Community und vom Dify-Team.",- "apps.resetFilter": "Filter löschen","apps.resultNum": "{{num}} Ergebnisse","apps.title": "Vorlagen","apps.viewMore": "Mehr anzeigen",@@ -30,17 +28,14 @@"continueWork.title": "Zuletzt verwendet","learnDify.description": "Folge dem Pfad – oder springe direkt zu dem Schritt, für den du bereit bist.","learnDify.hide": "Ausblenden",- "learnDify.moreTemplates": "Weitere Lernvorlagen →","learnDify.title": "Dify kennenlernen","sidebar.action.delete": "Löschen","sidebar.action.pin": "Anheften","sidebar.action.rename": "Umbenennen","sidebar.action.unpin": "Lösen",- "sidebar.chat": "Chat","sidebar.delete.content": "Sind Sie sicher, dass Sie diese App löschen möchten?","sidebar.delete.title": "App löschen","sidebar.webApps": "Web-Apps",- "title": "Entdecken","tryApp.category": "Kategorie","tryApp.createFromSampleApp": "Aus dieser Beispiel-App erstellen","tryApp.requirements": "Anforderungen",diff --git a/web/i18n/locales/en-US/explore.json b/web/i18n/locales/en-US/explore.jsonindex 67fbf5cf392..da28d9dfc97 100644--- a/web/i18n/locales/en-US/explore.json+++ b/web/i18n/locales/en-US/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Use template","appCard.try": "Details","appCustomize.nameRequired": "App name is required","appCustomize.subTitle": "App icon & name","appCustomize.title": "Create app from {{name}}","apps.allCategories": "All","apps.description": "Ready-to-use templates from the community and Dify team.",- "apps.resetFilter": "Clear filter","apps.resultNum": "{{num}} results","apps.title": "Templates","apps.viewMore": "View more",@@ -30,17 +28,14 @@"continueWork.title": "Recents","learnDify.description": "Follow the path - or jump to whichever step you're ready for.","learnDify.hide": "Hide",- "learnDify.moreTemplates": "More learning templates →","learnDify.title": "Learn Dify","sidebar.action.delete": "Delete","sidebar.action.pin": "Pin","sidebar.action.rename": "Rename","sidebar.action.unpin": "Unpin",- "sidebar.chat": "Chat","sidebar.delete.content": "Are you sure you want to delete this app?","sidebar.delete.title": "Delete app","sidebar.webApps": "Web apps",- "title": "Explore","tryApp.category": "Category","tryApp.createFromSampleApp": "Create from this sample app","tryApp.requirements": "Requirements",diff --git a/web/i18n/locales/es-ES/explore.json b/web/i18n/locales/es-ES/explore.jsonindex b0c21891dcd..c9308865770 100644--- a/web/i18n/locales/es-ES/explore.json+++ b/web/i18n/locales/es-ES/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Usar plantilla","appCard.try": "Detalles","appCustomize.nameRequired": "El nombre de la aplicación es obligatorio","appCustomize.subTitle": "Icono y nombre de la aplicación","appCustomize.title": "Crear aplicación a partir de {{name}}","apps.allCategories": "Todos","apps.description": "Plantillas listas para usar de la comunidad y el equipo de Dify.",- "apps.resetFilter": "Limpiar filtro","apps.resultNum": "{{num}} resultados","apps.title": "Plantillas","apps.viewMore": "Ver más",@@ -30,17 +28,14 @@"continueWork.title": "Recientes","learnDify.description": "Sigue el camino, o salta directamente al paso que prefieras.","learnDify.hide": "Ocultar",- "learnDify.moreTemplates": "Más plantillas de aprendizaje →","learnDify.title": "Aprender Dify","sidebar.action.delete": "Eliminar","sidebar.action.pin": "Anclar","sidebar.action.rename": "Renombrar","sidebar.action.unpin": "Desanclar",- "sidebar.chat": "Chat","sidebar.delete.content": "¿Estás seguro de que quieres eliminar esta aplicación?","sidebar.delete.title": "Eliminar aplicación","sidebar.webApps": "Aplicaciones web",- "title": "Explorar","tryApp.category": "Categoría","tryApp.createFromSampleApp": "Crear desde esta aplicación de ejemplo","tryApp.requirements": "Requisitos",diff --git a/web/i18n/locales/fa-IR/explore.json b/web/i18n/locales/fa-IR/explore.jsonindex d8b6a4bb9d0..a3665afe775 100644--- a/web/i18n/locales/fa-IR/explore.json+++ b/web/i18n/locales/fa-IR/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "استفاده از قالب","appCard.try": "جزئیات","appCustomize.nameRequired": "نام برنامه الزامی است","appCustomize.subTitle": "آیکون و نام برنامه","appCustomize.title": "ایجاد برنامه از {{name}}","apps.allCategories": "همه","apps.description": "الگوهای آماده استفاده از جامعه و تیم Dify.",- "apps.resetFilter": "پاک کردن فیلتر","apps.resultNum": "{{num}} نتیجه","apps.title": "الگوها","apps.viewMore": "بیشتر ببینید",@@ -30,17 +28,14 @@"continueWork.title": "اخیر","learnDify.description": "مسیر را دنبال کنید — یا به هر مرحلهای که آمادهاید بروید.","learnDify.hide": "پنهان کردن",- "learnDify.moreTemplates": "الگوهای یادگیری بیشتر →","learnDify.title": "یادگیری Dify","sidebar.action.delete": "حذف","sidebar.action.pin": "سنجاق کردن","sidebar.action.rename": "تغییر نام","sidebar.action.unpin": "برداشتن سنجاق",- "sidebar.chat": "چت","sidebar.delete.content": "آیا مطمئن هستید که میخواهید این برنامه را حذف کنید؟","sidebar.delete.title": "حذف برنامه","sidebar.webApps": "برنامههای وب",- "title": "کاوش","tryApp.category": "دستهبندی","tryApp.createFromSampleApp": "از این برنامه نمونه ایجاد کنید","tryApp.requirements": "الزامات",diff --git a/web/i18n/locales/fr-FR/explore.json b/web/i18n/locales/fr-FR/explore.jsonindex 9c060148a53..d903eec41aa 100644--- a/web/i18n/locales/fr-FR/explore.json+++ b/web/i18n/locales/fr-FR/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Utiliser le modèle","appCard.try": "Détails","appCustomize.nameRequired": "Le nom de l'application est requis","appCustomize.subTitle": "Icône de l'application & nom","appCustomize.title": "Créer une application à partir de {{name}}","apps.allCategories": "Tous","apps.description": "Des modèles prêts à l'emploi créés par la communauté et l'équipe Dify.",- "apps.resetFilter": "Effacer le filtre","apps.resultNum": "{{num}} résultats","apps.title": "Modèles","apps.viewMore": "Voir plus",@@ -30,17 +28,14 @@"continueWork.title": "Récents","learnDify.description": "Suivez le parcours — ou passez directement à l’étape de votre choix.","learnDify.hide": "Masquer",- "learnDify.moreTemplates": "Plus de modèles d’apprentissage →","learnDify.title": "Découvrir Dify","sidebar.action.delete": "Supprimer","sidebar.action.pin": "Épingle","sidebar.action.rename": "Renommer","sidebar.action.unpin": "Détacher",- "sidebar.chat": "Discussion","sidebar.delete.content": "Êtes-vous sûr de vouloir supprimer cette application ?","sidebar.delete.title": "Supprimer l'application","sidebar.webApps": "Applications web",- "title": "Explorer","tryApp.category": "Catégorie","tryApp.createFromSampleApp": "Créer à partir de cette application exemple","tryApp.requirements": "Exigences",diff --git a/web/i18n/locales/hi-IN/explore.json b/web/i18n/locales/hi-IN/explore.jsonindex 3e5a988c225..abfe96d361c 100644--- a/web/i18n/locales/hi-IN/explore.json+++ b/web/i18n/locales/hi-IN/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "टेम्पलेट का उपयोग करें","appCard.try": "विवरण","appCustomize.nameRequired": "ऐप का नाम आवश्यक है","appCustomize.subTitle": "ऐप आइकन और नाम","appCustomize.title": "{{name}} से ऐप बनाएँ","apps.allCategories": "सभी","apps.description": "समुदाय और Dify टीम के उपयोग के लिए तैयार टेम्पलेट।",- "apps.resetFilter": "फ़िल्टर साफ़ करें","apps.resultNum": "{{num}} परिणाम","apps.title": "टेम्पलेट","apps.viewMore": "और देखें",@@ -30,17 +28,14 @@"continueWork.title": "हाल के","learnDify.description": "पथ का अनुसरण करें — या जिस चरण के लिए आप तैयार हैं, उस पर जाएँ।","learnDify.hide": "छिपाएँ",- "learnDify.moreTemplates": "और अधिक लर्निंग टेम्पलेट →","learnDify.title": "Dify सीखें","sidebar.action.delete": "हटाएं","sidebar.action.pin": "पिन करें","sidebar.action.rename": "नाम बदलें","sidebar.action.unpin": "पिन हटाएँ",- "sidebar.chat": "चैट","sidebar.delete.content": "क्या आप वाकई इस ऐप को हटाना चाहते हैं?","sidebar.delete.title": "ऐप हटाएं","sidebar.webApps": "वेब ऐप्स",- "title": "अन्वेषण करें","tryApp.category": "श्रेणी","tryApp.createFromSampleApp": "इस नमूना ऐप से बनाएं","tryApp.requirements": "आवश्यकताएँ",diff --git a/web/i18n/locales/id-ID/explore.json b/web/i18n/locales/id-ID/explore.jsonindex 1839a273b7a..0135e7d93f4 100644--- a/web/i18n/locales/id-ID/explore.json+++ b/web/i18n/locales/id-ID/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Gunakan templat","appCard.try": "Detail","appCustomize.nameRequired": "Nama aplikasi diperlukan","appCustomize.subTitle": "Ikon & nama aplikasi","appCustomize.title": "Buat aplikasi dari {{name}}","apps.allCategories": "Semua","apps.description": "Templat siap pakai dari komunitas dan tim Dify.",- "apps.resetFilter": "Hapus filter","apps.resultNum": "{{num}} hasil","apps.title": "Templat","apps.viewMore": "Lihat lebih banyak",@@ -30,17 +28,14 @@"continueWork.title": "Terbaru","learnDify.description": "Ikuti alurnya — atau langsung ke langkah yang Anda inginkan.","learnDify.hide": "Sembunyikan",- "learnDify.moreTemplates": "Templat pembelajaran lainnya →","learnDify.title": "Pelajari Dify","sidebar.action.delete": "Hapus","sidebar.action.pin": "Sematkan","sidebar.action.rename": "Ganti nama","sidebar.action.unpin": "Lepaskan sematan",- "sidebar.chat": "Mengobrol","sidebar.delete.content": "Apakah Anda yakin ingin menghapus aplikasi ini?","sidebar.delete.title": "Hapus aplikasi","sidebar.webApps": "Aplikasi web",- "title": "Menjelajahi","tryApp.category": "Kategori","tryApp.createFromSampleApp": "Buat dari aplikasi contoh ini","tryApp.requirements": "Persyaratan",diff --git a/web/i18n/locales/it-IT/explore.json b/web/i18n/locales/it-IT/explore.jsonindex eb3d6c8ddbd..53cb5194e98 100644--- a/web/i18n/locales/it-IT/explore.json+++ b/web/i18n/locales/it-IT/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Usa modello","appCard.try": "Dettagli","appCustomize.nameRequired": "Il nome dell'app è obbligatorio","appCustomize.subTitle": "Icona & nome dell'app","appCustomize.title": "Crea app da {{name}}","apps.allCategories": "Tutti","apps.description": "Modelli pronti all'uso dalla community e dal team Dify.",- "apps.resetFilter": "Cancella filtro","apps.resultNum": "{{num}} risultati","apps.title": "Modelli","apps.viewMore": "Vedi di più",@@ -30,17 +28,14 @@"continueWork.title": "Recenti","learnDify.description": "Segui il percorso, oppure passa direttamente al passo che preferisci.","learnDify.hide": "Nascondi",- "learnDify.moreTemplates": "Altri modelli di apprendimento →","learnDify.title": "Impara Dify","sidebar.action.delete": "Elimina","sidebar.action.pin": "Fissa","sidebar.action.rename": "Rinomina","sidebar.action.unpin": "Sblocca",- "sidebar.chat": "Chat","sidebar.delete.content": "Sei sicuro di voler eliminare questa app?","sidebar.delete.title": "Elimina app","sidebar.webApps": "App web",- "title": "Esplora","tryApp.category": "Categoria","tryApp.createFromSampleApp": "Crea da questa app di esempio","tryApp.requirements": "Requisiti",diff --git a/web/i18n/locales/ja-JP/explore.json b/web/i18n/locales/ja-JP/explore.jsonindex c192ef6b350..ab2d1214d7d 100644--- a/web/i18n/locales/ja-JP/explore.json+++ b/web/i18n/locales/ja-JP/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "テンプレートを使用","appCard.try": "詳細","appCustomize.nameRequired": "アプリ名は必須です","appCustomize.subTitle": "アプリアイコンと名前","appCustomize.title": "{{name}}からアプリを作成","apps.allCategories": "全て","apps.description": "コミュニティと Dify チームによる、すぐに使えるテンプレート。",- "apps.resetFilter": "クリア","apps.resultNum": "{{num}}件の結果","apps.title": "テンプレート","apps.viewMore": "もっと見る",@@ -30,17 +28,14 @@"continueWork.title": "最近の項目","learnDify.description": "ステップ順に進むのも、好きなところから始めるのも自由です。","learnDify.hide": "非表示",- "learnDify.moreTemplates": "その他の学習テンプレート →","learnDify.title": "Difyを学ぶ","sidebar.action.delete": "削除","sidebar.action.pin": "ピン留め","sidebar.action.rename": "名前変更","sidebar.action.unpin": "ピン留め解除",- "sidebar.chat": "チャット","sidebar.delete.content": "このアプリを削除してもよろしいですか?","sidebar.delete.title": "アプリを削除","sidebar.webApps": "Webアプリ",- "title": "探索","tryApp.category": "カテゴリー","tryApp.createFromSampleApp": "テンプレートから作成","tryApp.requirements": "必要項目",diff --git a/web/i18n/locales/ko-KR/explore.json b/web/i18n/locales/ko-KR/explore.jsonindex 2f10d3ea4cb..9cd4076cacf 100644--- a/web/i18n/locales/ko-KR/explore.json+++ b/web/i18n/locales/ko-KR/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "템플릿 사용","appCard.try": "세부 정보","appCustomize.nameRequired": "앱 이름은 필수입니다","appCustomize.subTitle": "앱 아이콘 및 이름","appCustomize.title": "{{name}}으로 앱 만들기","apps.allCategories": "전체","apps.description": "커뮤니티와 Dify 팀이 만든 바로 사용할 수 있는 템플릿입니다.",- "apps.resetFilter": "필터 지우기","apps.resultNum": "{{num}}개 결과","apps.title": "템플릿","apps.viewMore": "더보기",@@ -30,17 +28,14 @@"continueWork.title": "최근 항목","learnDify.description": "순서대로 따라가거나, 원하는 단계로 바로 이동하세요.","learnDify.hide": "숨기기",- "learnDify.moreTemplates": "더 많은 학습 템플릿 →","learnDify.title": "Dify 배우기","sidebar.action.delete": "삭제","sidebar.action.pin": "고정","sidebar.action.rename": "이름 변경","sidebar.action.unpin": "고정 해제",- "sidebar.chat": "채팅","sidebar.delete.content": "이 앱을 삭제해도 괜찮습니까?","sidebar.delete.title": "앱 삭제","sidebar.webApps": "웹 앱",- "title": "탐색","tryApp.category": "카테고리","tryApp.createFromSampleApp": "이 샘플 앱에서 만들기","tryApp.requirements": "요구 사항",diff --git a/web/i18n/locales/lo-LA/explore.json b/web/i18n/locales/lo-LA/explore.jsonindex dd468f96ce0..12190b06027 100644--- a/web/i18n/locales/lo-LA/explore.json+++ b/web/i18n/locales/lo-LA/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "ໃຊ້ແມ່ແບບ","appCard.try": "ລາຍລະອຽດ","appCustomize.nameRequired": "ຈຳເປັນຕ້ອງໃສ່ຊື່ແອັບ","appCustomize.subTitle": "ໄອຄອນ ແລະ ຊື່ແອັບ","appCustomize.title": "ສ້າງແອັບຈາກ {{name}}","apps.allCategories": "ທັງໝົດ","apps.description": "ແມ່ແບບທີ່ພ້ອມໃຊ້ງານຈາກຊຸມຊົນ ແລະ ທີມງານ Dify.",- "apps.resetFilter": "ລ້າງຕົວກອງ","apps.resultNum": "{{num}} ຜົນລັດ","apps.title": "ແມ່ແບບ","apps.viewMore": "ເບິ່ງເພີ່ມເຕີມ",@@ -30,17 +28,14 @@"continueWork.title": "ລາຍການຫຼ້າສຸດ","learnDify.description": "ເຮັດຕາມຂັ້ນຕອນ - ຫຼື ຂ້າມໄປຂັ້ນຕອນທີ່ເຈົ້າພ້ອມໄດ້ເລີຍ.","learnDify.hide": "ເຊື່ອງ",- "learnDify.moreTemplates": "ແມ່ແບບການຮຽນຮູ້ເພີ່ມເຕີມ →","learnDify.title": "ຮຽນຮູ້ Dify","sidebar.action.delete": "ລຶບ","sidebar.action.pin": "ປັກໝຸດ","sidebar.action.rename": "ປ່ຽນຊື່","sidebar.action.unpin": "ຖອນປັກໝຸດ",- "sidebar.chat": "ແຊັດ","sidebar.delete.content": "ເຈົ້າແນ່ໃຈບໍວ່າຕ້ອງການລຶບແອັບນີ້?","sidebar.delete.title": "ລຶບແອັບ","sidebar.webApps": "ແອັບເວັບ",- "title": "ສຳຫຼວດ","tryApp.category": "ໝວດໝູ່","tryApp.createFromSampleApp": "ສ້າງຈາກແອັບຕົວຢ່າງນີ້","tryApp.requirements": "ຂໍ້ກຳນົດ",diff --git a/web/i18n/locales/nl-NL/explore.json b/web/i18n/locales/nl-NL/explore.jsonindex e001a0ed0eb..db3f074778f 100644--- a/web/i18n/locales/nl-NL/explore.json+++ b/web/i18n/locales/nl-NL/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Use template","appCard.try": "Details","appCustomize.nameRequired": "App name is required","appCustomize.subTitle": "App icon & name","appCustomize.title": "Create app from {{name}}","apps.allCategories": "All","apps.description": "Gebruiksklare sjablonen van de community en het Dify-team.",- "apps.resetFilter": "Clear filter","apps.resultNum": "{{num}} results","apps.title": "Sjablonen","apps.viewMore": "View more",@@ -30,17 +28,14 @@"continueWork.title": "Recent","learnDify.description": "Volg het pad – of ga direct naar de stap waarvoor je klaar bent.","learnDify.hide": "Verbergen",- "learnDify.moreTemplates": "Meer leersjablonen →","learnDify.title": "Dify leren","sidebar.action.delete": "Delete","sidebar.action.pin": "Pin","sidebar.action.rename": "Rename","sidebar.action.unpin": "Unpin",- "sidebar.chat": "Chat","sidebar.delete.content": "Are you sure you want to delete this app?","sidebar.delete.title": "Delete app","sidebar.webApps": "Web apps",- "title": "Explore","tryApp.category": "Category","tryApp.createFromSampleApp": "Create from this sample app","tryApp.requirements": "Requirements",diff --git a/web/i18n/locales/pl-PL/explore.json b/web/i18n/locales/pl-PL/explore.jsonindex 9f10cca8482..8079637c5cc 100644--- a/web/i18n/locales/pl-PL/explore.json+++ b/web/i18n/locales/pl-PL/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Użyj szablonu","appCard.try": "Szczegóły","appCustomize.nameRequired": "Nazwa aplikacji jest wymagana","appCustomize.subTitle": "Ikona i nazwa aplikacji","appCustomize.title": "Utwórz aplikację z {{name}}","apps.allCategories": "Wszystkie","apps.description": "Gotowe do użycia szablony od społeczności i zespołu Dify.",- "apps.resetFilter": "Wyczyść filtr","apps.resultNum": "{{num}} wyników","apps.title": "Szablony","apps.viewMore": "Zobacz więcej",@@ -30,17 +28,14 @@"continueWork.title": "Ostatnie","learnDify.description": "Podążaj ścieżką — lub przejdź do kroku, na który jesteś gotowy.","learnDify.hide": "Ukryj",- "learnDify.moreTemplates": "Więcej szablonów do nauki →","learnDify.title": "Poznaj Dify","sidebar.action.delete": "Usuń","sidebar.action.pin": "Przypnij","sidebar.action.rename": "Zmień nazwę","sidebar.action.unpin": "Odepnij",- "sidebar.chat": "Czat","sidebar.delete.content": "Czy na pewno chcesz usunąć tę aplikację?","sidebar.delete.title": "Usuń aplikację","sidebar.webApps": "Aplikacje internetowe",- "title": "Odkryj","tryApp.category": "Kategoria","tryApp.createFromSampleApp": "Utwórz z tej przykładowej aplikacji","tryApp.requirements": "Wymagania",diff --git a/web/i18n/locales/pt-BR/explore.json b/web/i18n/locales/pt-BR/explore.jsonindex 685dc981605..b71094f6b78 100644--- a/web/i18n/locales/pt-BR/explore.json+++ b/web/i18n/locales/pt-BR/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Usar modelo","appCard.try": "Detalhes","appCustomize.nameRequired": "O nome do aplicativo é obrigatório","appCustomize.subTitle": "Ícone e nome do aplicativo","appCustomize.title": "Criar aplicativo a partir de {{name}}","apps.allCategories": "Todos","apps.description": "Modelos prontos para uso da comunidade e da equipe Dify.",- "apps.resetFilter": "Limpar filtro","apps.resultNum": "{{num}} resultados","apps.title": "Modelos","apps.viewMore": "Ver mais",@@ -30,17 +28,14 @@"continueWork.title": "Recentes","learnDify.description": "Siga o caminho — ou vá direto para a etapa que preferir.","learnDify.hide": "Ocultar",- "learnDify.moreTemplates": "Mais modelos de aprendizado →","learnDify.title": "Aprender Dify","sidebar.action.delete": "Excluir","sidebar.action.pin": "Fixar","sidebar.action.rename": "Renomear","sidebar.action.unpin": "Desafixar",- "sidebar.chat": "Chat","sidebar.delete.content": "Tem certeza de que deseja excluir este aplicativo?","sidebar.delete.title": "Excluir aplicativo","sidebar.webApps": "Aplicativos web",- "title": "Explorar","tryApp.category": "Categoria","tryApp.createFromSampleApp": "Criar a partir deste aplicativo de exemplo","tryApp.requirements": "Requisitos",diff --git a/web/i18n/locales/ro-RO/explore.json b/web/i18n/locales/ro-RO/explore.jsonindex 9601a75b56a..1202d2b05b2 100644--- a/web/i18n/locales/ro-RO/explore.json+++ b/web/i18n/locales/ro-RO/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Folosește șablonul","appCard.try": "Detalii","appCustomize.nameRequired": "Numele aplicației este obligatoriu","appCustomize.subTitle": "Pictogramă și nume aplicație","appCustomize.title": "Creați o aplicație din {{name}}","apps.allCategories": "Toate","apps.description": "Șabloane gata de utilizare de la comunitate și echipa Dify.",- "apps.resetFilter": "Șterge filtrul","apps.resultNum": "{{num}} rezultate","apps.title": "Șabloane","apps.viewMore": "Vezi mai mult",@@ -30,17 +28,14 @@"continueWork.title": "Recente","learnDify.description": "Urmează traseul — sau sari direct la pasul pentru care ești pregătit.","learnDify.hide": "Ascunde",- "learnDify.moreTemplates": "Mai multe șabloane de învățare →","learnDify.title": "Învață Dify","sidebar.action.delete": "Ștergeți","sidebar.action.pin": "Fixați","sidebar.action.rename": "Redenumire","sidebar.action.unpin": "Deblocați",- "sidebar.chat": "Chat","sidebar.delete.content": "Sunteți sigur că doriți să ștergeți această aplicație?","sidebar.delete.title": "Ștergeți aplicația","sidebar.webApps": "Aplicații web",- "title": "Explorați","tryApp.category": "Categorie","tryApp.createFromSampleApp": "Creați din această aplicație exemplu","tryApp.requirements": "Cerințe",diff --git a/web/i18n/locales/ru-RU/explore.json b/web/i18n/locales/ru-RU/explore.jsonindex 7388fad47d8..f166f8116a7 100644--- a/web/i18n/locales/ru-RU/explore.json+++ b/web/i18n/locales/ru-RU/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Использовать шаблон","appCard.try": "Подробности","appCustomize.nameRequired": "Название приложения обязательно","appCustomize.subTitle": "Значок и название приложения","appCustomize.title": "Создать приложение из {{name}}","apps.allCategories": "Все","apps.description": "Готовые к использованию шаблоны от сообщества и команды Dify.",- "apps.resetFilter": "Очистить фильтр","apps.resultNum": "{{num}} результатов","apps.title": "Шаблоны","apps.viewMore": "Подробнее",@@ -30,17 +28,14 @@"continueWork.title": "Недавние","learnDify.description": "Следуйте по пути — или переходите к тому шагу, к которому готовы.","learnDify.hide": "Скрыть",- "learnDify.moreTemplates": "Больше обучающих шаблонов →","learnDify.title": "Изучить Dify","sidebar.action.delete": "Удалить","sidebar.action.pin": "Закрепить","sidebar.action.rename": "Переименовать","sidebar.action.unpin": "Открепить",- "sidebar.chat": "Чат","sidebar.delete.content": "Вы уверены, что хотите удалить это приложение?","sidebar.delete.title": "Удалить приложение","sidebar.webApps": "Веб-приложения",- "title": "Обзор","tryApp.category": "Категория","tryApp.createFromSampleApp": "Создать из этого примера приложения","tryApp.requirements": "Требования",diff --git a/web/i18n/locales/sl-SI/explore.json b/web/i18n/locales/sl-SI/explore.jsonindex 8bf04e44868..23bbfc42d05 100644--- a/web/i18n/locales/sl-SI/explore.json+++ b/web/i18n/locales/sl-SI/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Uporabi predlogo","appCard.try": "Podrobnosti","appCustomize.nameRequired": "Ime aplikacije je obvezno","appCustomize.subTitle": "Ikona aplikacije & ime","appCustomize.title": "Ustvari aplikacijo iz {{name}}","apps.allCategories": "Vse","apps.description": "Predloge, pripravljene za uporabo, iz skupnosti in ekipe Dify.",- "apps.resetFilter": "Počisti filter","apps.resultNum": "{{num}} rezultatov","apps.title": "Predloge","apps.viewMore": "Oglejte si več",@@ -30,17 +28,14 @@"continueWork.title": "Nedavni","learnDify.description": "Sledite poti – ali skočite na korak, za katerega ste pripravljeni.","learnDify.hide": "Skrij",- "learnDify.moreTemplates": "Več učnih predlog →","learnDify.title": "Spoznaj Dify","sidebar.action.delete": "Izbriši","sidebar.action.pin": "Pripni","sidebar.action.rename": "Preimenuj","sidebar.action.unpin": "Odpni",- "sidebar.chat": "Klepet","sidebar.delete.content": "Ali ste prepričani, da želite izbrisati to aplikacijo?","sidebar.delete.title": "Izbriši aplikacijo","sidebar.webApps": "Spletne aplikacije",- "title": "Razišči","tryApp.category": "Kategorija","tryApp.createFromSampleApp": "Ustvari iz te vzorčne aplikacije","tryApp.requirements": "Zahteve",diff --git a/web/i18n/locales/th-TH/explore.json b/web/i18n/locales/th-TH/explore.jsonindex f07bab291e1..7fe2daf80a4 100644--- a/web/i18n/locales/th-TH/explore.json+++ b/web/i18n/locales/th-TH/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "ใช้เทมเพลต","appCard.try": "รายละเอียด","appCustomize.nameRequired": "ต้องใช้ชื่อแอป","appCustomize.subTitle": "ไอคอนและชื่อแอป","appCustomize.title": "สร้างแอปจาก {{name}}","apps.allCategories": "ทั้งหมด","apps.description": "เทมเพลตพร้อมใช้งานจากชุมชนและทีม Dify",- "apps.resetFilter": "ล้างตัวกรอง","apps.resultNum": "{{num}} ผลลัพธ์","apps.title": "เทมเพลต","apps.viewMore": "ดูเพิ่มเติม",@@ -30,17 +28,14 @@"continueWork.title": "ล่าสุด","learnDify.description": "ทำตามลำดับขั้นตอน หรือข้ามไปยังขั้นตอนที่คุณพร้อมก็ได้","learnDify.hide": "ซ่อน",- "learnDify.moreTemplates": "เทมเพลตการเรียนรู้เพิ่มเติม →","learnDify.title": "เรียนรู้ Dify","sidebar.action.delete": "ลบ","sidebar.action.pin": "เข็มกลัด","sidebar.action.rename": "ตั้งชื่อใหม่","sidebar.action.unpin": "ปลดหมุด",- "sidebar.chat": "สนทนา","sidebar.delete.content": "คุณแน่ใจหรือไม่ว่าต้องการลบแอปนี้?","sidebar.delete.title": "ลบแอป","sidebar.webApps": "แอปเว็บ",- "title": "สํารวจ","tryApp.category": "หมวดหมู่","tryApp.createFromSampleApp": "สร้างจากแอปตัวอย่างนี้","tryApp.requirements": "ข้อกำหนด",diff --git a/web/i18n/locales/tr-TR/explore.json b/web/i18n/locales/tr-TR/explore.jsonindex 5c25e11ba76..1a4901be1e3 100644--- a/web/i18n/locales/tr-TR/explore.json+++ b/web/i18n/locales/tr-TR/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Şablonu kullan","appCard.try": "Detaylar","appCustomize.nameRequired": "Uygulama ismi gereklidir","appCustomize.subTitle": "Uygulama simgesi ve ismi","appCustomize.title": "{{name}} uygulamasından uygulama oluştur","apps.allCategories": "Tümü","apps.description": "Topluluk ve Dify ekibinden kullanıma hazır şablonlar.",- "apps.resetFilter": "Filtreyi temizle","apps.resultNum": "{{num}} sonuç","apps.title": "Şablonlar","apps.viewMore": "Daha fazla göster",@@ -30,17 +28,14 @@"continueWork.title": "Son kullanılanlar","learnDify.description": "Yolu takip et ya da hazır olduğun adıma geç.","learnDify.hide": "Gizle",- "learnDify.moreTemplates": "Daha fazla öğrenme şablonu →","learnDify.title": "Dify'ı Öğren","sidebar.action.delete": "Sil","sidebar.action.pin": "Sabitle","sidebar.action.rename": "Yeniden Adlandır","sidebar.action.unpin": "Sabitlemeyi Kaldır",- "sidebar.chat": "Sohbet","sidebar.delete.content": "Bu uygulamayı silmek istediğinizden emin misiniz?","sidebar.delete.title": "Uygulamayı sil","sidebar.webApps": "Web uygulamaları",- "title": "Keşfet","tryApp.category": "Kategori","tryApp.createFromSampleApp": "Bu örnek uygulamadan oluştur","tryApp.requirements": "Gereksinimler",diff --git a/web/i18n/locales/uk-UA/explore.json b/web/i18n/locales/uk-UA/explore.jsonindex 0abceab3312..eb859861b61 100644--- a/web/i18n/locales/uk-UA/explore.json+++ b/web/i18n/locales/uk-UA/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Використати шаблон","appCard.try": "Деталі","appCustomize.nameRequired": "Назва програми обов'язкова","appCustomize.subTitle": "Значок програми та назва","appCustomize.title": "Створити додаток з {{name}}","apps.allCategories": "Всі","apps.description": "Готові до використання шаблони від спільноти та команди Dify.",- "apps.resetFilter": "Очистити фільтр","apps.resultNum": "{{num}} результатів","apps.title": "Шаблони","apps.viewMore": "Дивитись більше",@@ -30,17 +28,14 @@"continueWork.title": "Нещодавні","learnDify.description": "Дотримуйтесь шляху — або переходьте до кроку, до якого готові.","learnDify.hide": "Сховати",- "learnDify.moreTemplates": "Більше навчальних шаблонів →","learnDify.title": "Вивчати Dify","sidebar.action.delete": "Видалити","sidebar.action.pin": "Закріпити","sidebar.action.rename": "Перейменувати","sidebar.action.unpin": "Відкріпити",- "sidebar.chat": "Чат","sidebar.delete.content": "Ви впевнені, що хочете видалити цю програму?","sidebar.delete.title": "Видалити додаток","sidebar.webApps": "Веб-додатки",- "title": "Досліджувати","tryApp.category": "Категорія","tryApp.createFromSampleApp": "Створити з цього зразка додатку","tryApp.requirements": "Вимоги",diff --git a/web/i18n/locales/vi-VN/explore.json b/web/i18n/locales/vi-VN/explore.jsonindex 74497be7c1d..7b06b51d70a 100644--- a/web/i18n/locales/vi-VN/explore.json+++ b/web/i18n/locales/vi-VN/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "Sử dụng mẫu","appCard.try": "Chi tiết","appCustomize.nameRequired": "Vui lòng nhập tên ứng dụng","appCustomize.subTitle": "Biểu tượng và tên ứng dụng","appCustomize.title": "Tạo ứng dụng từ {{name}}","apps.allCategories": "Tất cả","apps.description": "Các mẫu sẵn sàng sử dụng từ cộng đồng và đội ngũ Dify.",- "apps.resetFilter": "Xóa bộ lọc","apps.resultNum": "{{num}} kết quả","apps.title": "Mẫu","apps.viewMore": "Xem thêm",@@ -30,17 +28,14 @@"continueWork.title": "Gần đây","learnDify.description": "Đi theo lộ trình — hoặc chuyển đến bước bạn đã sẵn sàng.","learnDify.hide": "Ẩn",- "learnDify.moreTemplates": "Thêm mẫu học tập →","learnDify.title": "Tìm hiểu Dify","sidebar.action.delete": "Xóa","sidebar.action.pin": "Ghim","sidebar.action.rename": "Đổi tên","sidebar.action.unpin": "Bỏ ghim",- "sidebar.chat": "Trò chuyện","sidebar.delete.content": "Bạn có chắc chắn muốn xóa ứng dụng này không?","sidebar.delete.title": "Xóa ứng dụng","sidebar.webApps": "Ứng dụng web",- "title": "Khám phá","tryApp.category": "Danh mục","tryApp.createFromSampleApp": "Tạo từ ứng dụng mẫu này","tryApp.requirements": "Yêu cầu",diff --git a/web/i18n/locales/zh-Hans/explore.json b/web/i18n/locales/zh-Hans/explore.jsonindex 962ba40e3fd..b30fdcb0b43 100644--- a/web/i18n/locales/zh-Hans/explore.json+++ b/web/i18n/locales/zh-Hans/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "使用模板","appCard.try": "详情","appCustomize.nameRequired": "应用程序名称不能为空","appCustomize.subTitle": "应用程序图标和名称","appCustomize.title": "从 {{name}} 创建应用程序","apps.allCategories": "所有","apps.description": "来自社区和 Dify 团队的开箱即用模板。",- "apps.resetFilter": "清除筛选","apps.resultNum": "{{num}} 个结果","apps.title": "模板","apps.viewMore": "查看更多",@@ -30,17 +28,14 @@"continueWork.title": "最近","learnDify.description": "按顺序学,或直接跳到你想开始的那一步。","learnDify.hide": "隐藏",- "learnDify.moreTemplates": "更多学习模板 →","learnDify.title": "了解 Dify","sidebar.action.delete": "删除","sidebar.action.pin": "置顶","sidebar.action.rename": "重命名","sidebar.action.unpin": "取消置顶",- "sidebar.chat": "智聊","sidebar.delete.content": "您确定要删除此程序吗?","sidebar.delete.title": "删除程序","sidebar.webApps": "WEB APPS",- "title": "探索","tryApp.category": "分类","tryApp.createFromSampleApp": "从此模板创建应用","tryApp.requirements": "必须配置项",diff --git a/web/i18n/locales/zh-Hant/explore.json b/web/i18n/locales/zh-Hant/explore.jsonindex a9c667dfe78..398f1b01e50 100644--- a/web/i18n/locales/zh-Hant/explore.json+++ b/web/i18n/locales/zh-Hant/explore.json@@ -1,12 +1,10 @@{- "appCard.addToWorkspace": "使用範本","appCard.try": "詳情","appCustomize.nameRequired": "應用程式名稱不能為空","appCustomize.subTitle": "應用程式圖示和名稱","appCustomize.title": "從 {{name}} 建立應用程式","apps.allCategories": "全部","apps.description": "來自社群和 Dify 團隊的即用範本。",- "apps.resetFilter": "清除篩選","apps.resultNum": "{{num}} 個結果","apps.title": "範本","apps.viewMore": "查看更多",@@ -30,17 +28,14 @@"continueWork.title": "最近","learnDify.description": "依序學習,或直接跳到你想開始的那一步。","learnDify.hide": "隱藏",- "learnDify.moreTemplates": "更多學習範本 →","learnDify.title": "了解 Dify","sidebar.action.delete": "刪除","sidebar.action.pin": "置頂","sidebar.action.rename": "重新命名","sidebar.action.unpin": "取消置頂",- "sidebar.chat": "智聊","sidebar.delete.content": "您確定要刪除此程式嗎?","sidebar.delete.title": "刪除程式","sidebar.webApps": "WEB APPS",- "title": "探索","tryApp.category": "分類","tryApp.createFromSampleApp": "從此範本建立應用","tryApp.requirements": "必須配置項",diff --git a/web/plugins/vite/__tests__/i18n-analysis.spec.ts b/web/plugins/vite/__tests__/i18n-analysis.spec.tsindex d24cb489e94..6e50837ecc9 100644--- a/web/plugins/vite/__tests__/i18n-analysis.spec.ts+++ b/web/plugins/vite/__tests__/i18n-analysis.spec.ts@@ -1,10 +1,32 @@+import type { AnalysisReport } from '../i18n-analysis'// @vitest-environment nodeimport { mkdirSync, mkdtempSync, readFileSync, realpathSync, rmSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import path from 'node:path'import { build, createBuilder, createLogger, createServer } from 'vite'import { afterEach, beforeEach, describe, expect, it, vi } from 'vite-plus/test'-import { i18nAnalysisPlugin } from '../i18n-analysis'+import { i18nAnalysisPlugin as createI18nAnalysisPlugin } from '../i18n-analysis'++const i18nAnalysisPlugin = (options: Parameters<typeof createI18nAnalysisPlugin>[0] = {}) =>+ createI18nAnalysisPlugin({+ ...options,+ adapters: options.adapters ?? [+ { module: 'i18n/lib.client.ts', exportName: 'useTranslation', namespaceArgument: 0 },+ {+ module: 'i18n/lib.server.ts',+ exportName: 'useTranslation',+ namespaceArgument: 0,+ implementationFunctions: ['getI18nConfig'],+ },+ { module: 'i18n/server.ts', exportName: 'getTranslation', namespaceArgument: 1 },+ {+ module: 'app/route-metadata.ts',+ exportName: 'getRouteMetadata',+ namespaceArgument: 0,+ selectorArgument: 1,+ },+ ],+ })describe('i18n build check', () => {let root: string@@ -90,35 +112,33 @@ describe('i18n build check', () => {.map(([message]) => message).filter((message) => message.startsWith('[i18n] Route'))expect(reports).toHaveLength(1)- expect(reports[0]).toContain(- '/items/[id] (app/(group)/items/[id]/page.ts): client, common, group, lazy, ssr',- )- expect(reports[0]).toContain('/other (app/other/page.ts): common, other')- expect(reports[0]).toContain(' page: client, ssr')- expect(reports[0]).toContain(' shared: common, group')- expect(reports[0]).toContain(' lazy: lazy')- expect(reports[0]).not.toContain('ignored')+ expect(reports[0]).toBe(+ '[i18n] Routes: 2; unknown namespace records: 0; dynamic key records: 0; protected namespaces: (none).',+ )+ expect(info.mock.calls.some(([message]) => message.includes('/items/[id]'))).toBe(false)const artifact: unknown = JSON.parse(readFileSync(path.join(root, 'dist/i18n-routes.json'), 'utf8'),)expect(artifact).toMatchObject({- version: 1,+ version: 3,routes: expect.arrayContaining([expect.objectContaining({route: '/items/[id]',+ namespaces: ['client', 'common', 'group', 'lazy', 'ssr'],groups: {page: [- { namespace: 'client', sources: ['component.ts'] },- { namespace: 'ssr', sources: ['component.ts'] },+ expect.objectContaining({ namespace: 'client', sources: ['component.ts'] }),+ expect.objectContaining({ namespace: 'ssr', sources: ['component.ts'] }),],shared: [- { namespace: 'common', sources: ['app/layout.ts'] },- { namespace: 'group', sources: ['app/(group)/layout.ts'] },+ expect.objectContaining({ namespace: 'common', sources: ['app/layout.ts'] }),+ expect.objectContaining({ namespace: 'group', sources: ['app/(group)/layout.ts'] }),],- lazy: [{ namespace: 'lazy', sources: ['lazy.ts'] }],+ lazy: [expect.objectContaining({ namespace: 'lazy', sources: ['lazy.ts'] })],slots: [],},}),+ expect.objectContaining({ route: '/other', namespaces: ['common', 'other'] }),]),})})@@ -355,6 +375,889 @@ describe('i18n build check', () => {)})+ it('uses Vite aliases for imported namespace values', async () => {+ writeFileSync(localeFile, '{}')+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(+ path.join(root, 'i18n/lib.client.ts'),+ `export function useTranslation(namespace: string) { return namespace }`,+ )+ writeFileSync(path.join(root, 'app/ns.ts'), `export const ns = 'old'`)+ writeFileSync(path.join(root, 'app/actual.ts'), `export const ns = 'actual'`)+ writeFileSync(+ path.join(root, 'app/page.ts'),+ `+ import { ns } from './ns'+ import { useTranslation } from '../i18n/lib.client'+ export const page = useTranslation(ns)+ `,+ )+ const run = (declared: string[]) =>+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ resolve: { alias: [{ find: './ns', replacement: path.join(root, 'app/actual.ts') }] },+ plugins: [i18nAnalysisPlugin({ getDeclaredNamespaces: () => declared })],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ })+ await expect(run(['actual'])).resolves.toBeDefined()+ await expect(run(['old'])).rejects.toThrow('Undeclared namespace: actual')+ })++ it.each([+ "export {ns} from './ns'",+ "export {\n ns,\n} from './ns'",+ "export { ns, type Key } from './ns'",+ "export { value as ns } from './ns'",+ ])('preserves runtime re-export bindings: %s', async (declaration) => {+ writeFileSync(localeFile, '{}')+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(+ path.join(root, 'i18n/lib.client.ts'),+ `export function useTranslation(namespace: string) { return namespace }`,+ )+ writeFileSync(+ path.join(root, 'app/ns.ts'),+ `export const ns = 'actual'; export const value = 'actual'; export type Key = 'used'`,+ )+ writeFileSync(path.join(root, 'app/barrel.ts'), declaration)+ writeFileSync(+ path.join(root, 'app/page.ts'),+ `+ import { ns } from './barrel'+ import { useTranslation } from '../i18n/lib.client'+ export const page = useTranslation(ns)+ `,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({+ onAnalysis: (report) => reports.push(report),+ getDeclaredNamespaces: () => ['old'],+ }),+ ],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ }),+ ).rejects.toThrow('Undeclared namespace: actual')+ expect(reports[0]!.routes[0]!.namespaces).toEqual(['actual'])+ expect(reports[0]!.evidence.some((item) => item.kind === 'unresolved-import')).toBe(false)+ })++ it('preserves query variants and resolves their imported selectors independently', async () => {+ writeFileSync(localeFile, JSON.stringify({ a: 'A', b: 'B' }))+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(+ path.join(root, 'app/page.ts'),+ `+ import { selector as a } from './selector.ts?a'+ import { selector as b } from './selector.ts?b'+ export function page(t: (selector: (source: Record<string, string>) => string) => string) {+ return [t(a), t(b)]+ }+ `,+ )+ writeFileSync(+ path.join(root, 'app/selector.ts'),+ `+ export const selector = ($: Record<string, string>) => $.placeholder+ `,+ )+ const run = () =>+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ {+ name: 'query-selectors',+ enforce: 'pre',+ transform(code, id) {+ if (id.includes('/selector.ts?'))+ return code.replace('$.placeholder', id.endsWith('?a') ? '$.a' : '$.b')+ },+ },+ i18nAnalysisPlugin(),+ ],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ })+ await expect(run()).resolves.toBeDefined()+ writeFileSync(localeFile, JSON.stringify({ a: 'A', b: 'B', unused: 'Unused' }))+ await expect(run()).rejects.toThrow(/Found 1 potentially unused i18n keys[\s\S]*app:unused/)+ })++ it('keeps route dependencies separate for query variants of the same module', async () => {+ writeFileSync(localeFile, '{}')+ for (const namespace of ['a', 'b']) {+ mkdirSync(path.join(root, `app/${namespace}`), { recursive: true })+ writeFileSync(+ path.join(root, `i18n/locales/en-US/${namespace}.json`),+ JSON.stringify({ title: namespace }),+ )+ writeFileSync(+ path.join(root, `app/${namespace}/page.ts`),+ `export { label as page } from '../../label.ts?${namespace}'`,+ )+ }+ writeFileSync(+ path.join(root, 'entry.ts'),+ `+ export { page as a } from './app/a/page'+ export { page as b } from './app/b/page'+ `,+ )+ writeFileSync(+ path.join(root, 'label.ts'),+ `+ export function label(t: (key: string) => string) { return t('placeholder:title') }+ `,+ )+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ {+ name: 'query-labels',+ enforce: 'pre',+ transform(code, id) {+ if (id.includes('/label.ts?'))+ return code.replace('placeholder:title', id.endsWith('?a') ? 'a:title' : 'b:title')+ },+ },+ i18nAnalysisPlugin({ getDeclaredNamespaces: (route) => [route.slice(1)] }),+ ],+ build: { write: false, lib: { entry: path.join(root, 'entry.ts'), formats: ['es'] } },+ }),+ ).resolves.toBeDefined()+ })++ it('leaves erased type-only packages to TypeScript resolution', async () => {+ writeFileSync(localeFile, JSON.stringify({ used: 'Used', unused: 'Unused' }))+ mkdirSync(path.join(root, 'node_modules/labels'), { recursive: true })+ writeFileSync(+ path.join(root, 'node_modules/labels/package.json'),+ JSON.stringify({ name: 'labels', types: './index.d.ts' }),+ )+ writeFileSync(path.join(root, 'node_modules/labels/index.d.ts'), `export type Label = 'used'`)+ writeFileSync(+ path.join(root, 'entry.ts'),+ `+ import type { Label } from 'labels'+ export function label(t: (key: string) => string, key: Label) { return t(key) }+ `,+ )+ await expect(buildFixture()).rejects.toThrow(+ /Found 1 potentially unused i18n keys[\s\S]*app:unused/,+ )+ })++ it.each(["export type { Key } from './types'", "export { type Key } from './types'"])(+ 'preserves erased type re-exports: %s',+ async (declaration) => {+ writeFileSync(localeFile, JSON.stringify({ used: 'Used', unused: 'Unused' }))+ writeFileSync(path.join(root, 'types.ts'), `export type Key = 'used'`)+ writeFileSync(path.join(root, 'barrel.ts'), `${declaration}; export const marker = 1`)+ writeFileSync(+ path.join(root, 'entry.ts'),+ `+ import { type Key, marker } from './barrel'+ export function label(t: (key: string) => string, key: Key) { return [marker, t(key)] }+ `,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [i18nAnalysisPlugin({ onAnalysis: (report) => reports.push(report) })],+ build: { write: false, lib: { entry: path.join(root, 'entry.ts'), formats: ['es'] } },+ }),+ ).rejects.toThrow(/Found 1 potentially unused i18n keys[\s\S]*app:unused/)+ expect(+ reports[0]!.evidence.some(+ (item) => item.kind === 'unresolved-import' || item.kind === 'dynamic-key',+ ),+ ).toBe(false)+ },+ )++ it.each(['type', 'prefix'] as const)(+ 'uses transformed JSON for %s key analysis',+ async (mode) => {+ writeFileSync(localeFile, JSON.stringify({ 'category.used': 'Used', unused: 'Unused' }))+ writeFileSync(path.join(root, 'labels.json'), JSON.stringify({ old: 'Old' }))+ writeFileSync(+ path.join(root, 'entry.ts'),+ mode === 'type'+ ? `+ import labels from './labels.json'+ export function label(t: (key: string) => string, key: keyof typeof labels) { return [labels, t(key)] }+ `+ : `+ import labels from './labels.json'+ export function label(t: (selector: (value: Record<string, string>) => string) => string, name: string) {+ const key = \`category.\${name}\` as keyof typeof labels+ return [labels, t($ => $[key])]+ }+ `,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({ onAnalysis: (report) => reports.push(report) }),+ {+ name: 'replace-json-data',+ transform(_code, id) {+ if (id.endsWith('/labels.json')) return 'export default { "category.used": "Used" }'+ },+ },+ ],+ build: { write: false, lib: { entry: path.join(root, 'entry.ts'), formats: ['es'] } },+ }),+ ).rejects.toThrow(/Found 1 potentially unused i18n keys[\s\S]*app:unused/)+ expect(+ reports[0]!.evidence.some(+ (item) => item.kind === 'unresolved-import' || item.kind === 'dynamic-key',+ ),+ ).toBe(false)+ },+ )++ it.each([+ "function load(ns: string) { return useTranslation(ns) }; export const page = load('app')",+ "function load(ns = 'app') { return useTranslation(ns) }; export const page = load(...[] as [])",+ "const ns = ['app']; export const page = useTranslation(ns)",+ "let ns = 'app'; ns = 'login'; export const page = useTranslation(ns)",+ "const ns = ['app']; const alias = ns; alias['push']('login'); export const page = useTranslation(ns)",+ "function policy() { return ['app'] }; export const page = useTranslation(policy())",+ ])('rejects runtime namespace values in strict mode: %s', async (body) => {+ writeFileSync(localeFile, '{}')+ writeFileSync(+ path.join(root, 'i18n/lib.client.ts'),+ 'export function useTranslation(ns: unknown) { return ns }',+ )+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(+ path.join(root, 'app/page.ts'),+ `import { useTranslation } from '../i18n/lib.client'; ${body}`,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({+ strictNamespaces: true,+ getDeclaredNamespaces: () => ['app'],+ onAnalysis: (report) => reports.push(report),+ }),+ ],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ }),+ ).rejects.toThrow('Cannot verify namespace usage')+ expect(reports[0]!.routes[0]!.unknownNamespaceSources).toEqual(['app/page.ts'])+ })++ it.each(['broken', 'good'] as const)(+ 'limits strict unknown namespace validation to the %s route',+ async (selected) => {+ writeFileSync(localeFile, '{}')+ writeFileSync(+ path.join(root, 'i18n/lib.client.ts'),+ `export function useTranslation(ns: string) { return ns }`,+ )+ for (const route of ['broken', 'good']) {+ mkdirSync(path.join(root, `app/${route}`), { recursive: true })+ writeFileSync(+ path.join(root, `app/${route}/page.ts`),+ `+ import { useTranslation } from '../../i18n/lib.client'+ export function page(ns: string) { return useTranslation(${route === 'broken' ? 'ns' : "'app'"}) }+ `,+ )+ }+ writeFileSync(+ path.join(root, 'entry.ts'),+ `export { page as broken } from './app/broken/page'; export { page as good } from './app/good/page'`,+ )+ const reports: AnalysisReport[] = []+ const result = build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({+ strictNamespaces: true,+ onAnalysis: (report) => reports.push(report),+ getDeclaredNamespaces: (route) => (route === `/${selected}` ? ['app'] : undefined),+ }),+ ],+ build: { write: false, lib: { entry: path.join(root, 'entry.ts'), formats: ['es'] } },+ })+ if (selected === 'broken')+ await expect(result).rejects.toThrow(/Cannot verify namespace usage: app\/broken\/page.ts/)+ else await expect(result).resolves.toBeDefined()+ expect(+ reports[0]!.routes.find((route) => route.route === '/broken')!.unknownNamespaceSources,+ ).toEqual(['app/broken/page.ts'])+ expect(+ reports[0]!.routes.find((route) => route.route === '/good')!.unknownNamespaceSources,+ ).toEqual([])+ },+ )++ it.each(['named', 'namespace'] as const)(+ 'does not treat a local Vite alias as the official API through %s imports',+ async (kind) => {+ writeFileSync(localeFile, '{}')+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(+ path.join(root, 'replacement.ts'),+ `export function useTranslation(value: string) { return value }`,+ )+ writeFileSync(+ path.join(root, 'app/page.ts'),+ kind === 'named'+ ? `import { useTranslation as load } from 'react-i18next'; export const page = load('placeholder')`+ : `import * as labels from 'react-i18next'; export const page = labels.useTranslation('placeholder')`,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ resolve: { alias: { 'react-i18next': path.join(root, 'replacement.ts') } },+ plugins: [+ i18nAnalysisPlugin({+ strictNamespaces: true,+ getDeclaredNamespaces: () => [],+ onAnalysis: (report) => reports.push(report),+ }),+ ],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ }),+ ).resolves.toBeDefined()+ expect(reports[0]!.routes[0]!.namespaces).toEqual([])+ expect(reports[0]!.routes[0]!.unknownNamespaceSources).toEqual([])+ },+ )++ it.each(['static', 'dynamic', 'undeclared'] as const)(+ 'validates %s metadata adapter calls through aliased exports and re-exports',+ async (mode) => {+ writeFileSync(localeFile, '{}')+ writeFileSync(+ path.join(root, 'i18n/locales/en-US/common.json'),+ JSON.stringify({ used: 'Used' }),+ )+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(+ path.join(root, 'i18n/server.ts'),+ `+ export function getTranslation(locale: string, ns: string) {+ return { t: (selector: (source: Record<string, string>) => string, options: { ns: string }) => selector({ used: 'Used' }) }+ }+ `,+ )+ writeFileSync(+ path.join(root, 'app/route-metadata.ts'),+ `+ import { getTranslation } from '../i18n/server'+ async function internalMetadata(namespace: string, selector: (source: Record<string, string>) => string) {+ const { t } = getTranslation('en-US', namespace)+ return { title: t(selector, { ns: namespace }) }+ }+ export { internalMetadata as getRouteMetadata }+ `,+ )+ writeFileSync(+ path.join(root, 'metadata.ts'),+ `export { getRouteMetadata as title } from './app/route-metadata'`,+ )+ writeFileSync(+ path.join(root, 'app/page.ts'),+ `+ import { title as metadata } from '../metadata'+ export function page(ns: string) { return metadata(${mode === 'dynamic' ? 'ns' : "'common'"}, $ => $.used) }+ `,+ )+ const reports: AnalysisReport[] = []+ const result = build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({+ strictNamespaces: true,+ getDeclaredNamespaces: () => (mode === 'undeclared' ? ['app'] : ['common']),+ onAnalysis: (report) => reports.push(report),+ }),+ ],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ })+ if (mode === 'dynamic')+ await expect(result).rejects.toThrow('Cannot verify namespace usage: app/page.ts')+ else if (mode === 'undeclared')+ await expect(result).rejects.toThrow('Undeclared namespace: common')+ else await expect(result).resolves.toBeDefined()+ expect(reports[0]!.routes[0]!.unknownNamespaceSources).toEqual(+ mode === 'dynamic' ? ['app/page.ts'] : [],+ )+ expect(reports[0]!.routes[0]!.namespaces).toEqual(+ mode === 'dynamic' ? ['app', 'common'] : ['common'],+ )+ },+ )++ it.each(["['login', ns]", "[...ns, 'login']", "[...['login', ...ns]]"])(+ 'rejects known undeclared namespaces in partially dynamic arrays: %s',+ async (argument) => {+ writeFileSync(localeFile, '{}')+ writeFileSync(+ path.join(root, 'i18n/lib.client.ts'),+ 'export function useTranslation(ns: unknown) { return ns }',+ )+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(+ path.join(root, 'app/page.ts'),+ `+ import { useTranslation } from '../i18n/lib.client'+ export function page(ns: string[]) { return useTranslation(${argument}) }+ `,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({+ getDeclaredNamespaces: () => ['app'],+ onAnalysis: (report) => reports.push(report),+ }),+ ],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ }),+ ).rejects.toThrow('Undeclared namespace: login')+ expect(reports[0]!.routes[0]!.namespaces).toEqual(['login'])+ expect(reports[0]!.routes[0]!.unknownNamespaceSources).toEqual(['app/page.ts'])+ },+ )++ it('reports runtime provider namespaces without blocking non-strict validation', async () => {+ writeFileSync(localeFile, '{}')+ writeFileSync(+ path.join(root, 'i18n/lib.client.ts'),+ 'export function useTranslation(ns: unknown) { return ns }',+ )+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(+ path.join(root, 'app/page.ts'),+ `import { useTranslation } from '../i18n/lib.client';+ function policy() { return ['app'] }; export const page = useTranslation(policy())`,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({+ getDeclaredNamespaces: () => ['app'],+ onAnalysis: (report) => reports.push(report),+ }),+ ],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ }),+ ).resolves.toBeDefined()+ expect(reports[0]!.routes[0]!.namespaces).toEqual([])+ expect(reports[0]!.routes[0]!.unknownNamespaceSources).toEqual(['app/page.ts'])+ })++ it('tracks rewritten imports and analyzes multiple output formats only once', async () => {+ writeFileSync(localeFile, JSON.stringify({ actual: 'Actual' }))+ writeFileSync(+ path.join(root, 'old.ts'),+ `export const selector = ($: Record<string, string>) => $.old`,+ )+ writeFileSync(+ path.join(root, 'actual.ts'),+ `export const selector = ($: Record<string, string>) => $.actual`,+ )+ writeFileSync(+ path.join(root, 'entry.ts'),+ `+ import { selector } from './old'+ export function label(t: (selector: (value: Record<string, string>) => string) => string) { return t(selector) }+ `,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({ onAnalysis: (report) => reports.push(report) }),+ {+ name: 'rewrite-import',+ transform(code, id) {+ if (id.endsWith('/entry.ts')) return code.replace('./old', './actual')+ },+ },+ ],+ build: {+ write: false,+ lib: { entry: path.join(root, 'entry.ts'), formats: ['es', 'cjs'] },+ },+ }),+ ).resolves.toBeDefined()+ expect(reports).toHaveLength(1)+ expect(reports[0]!.metrics.environments).toEqual([+ expect.objectContaining({ modules: 2, resolveCalls: 1 }),+ ])+ expect(reports[0]!.evidence.some((item) => item.kind === 'unresolved-import')).toBe(false)+ expect(reports[0]!.metrics.totalMs).toBeGreaterThan(0)+ })++ it.each(['virtual', 'external'] as const)(+ 'does not read a disk namespace when Vite resolves the unchanged import to an %s module',+ async (target) => {+ writeFileSync(localeFile, '{}')+ for (const namespace of ['old', 'actual'])+ writeFileSync(+ path.join(root, `i18n/locales/en-US/${namespace}.json`),+ JSON.stringify({ title: namespace }),+ )+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(path.join(root, 'app/ns.ts'), `export const ns = 'old'`)+ writeFileSync(+ path.join(root, 'app/page.ts'),+ `import { ns } from './ns'; export function page(t: (key: string, options: { ns: string }) => string) { return t('title', { ns: ns }) }`,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({+ onAnalysis: (report) => reports.push(report),+ getDeclaredNamespaces: () => ['old'],+ }),+ {+ name: 'virtual-namespace',+ enforce: 'pre',+ resolveId(id) {+ if (id === './ns')+ return target === 'virtual'+ ? '\0namespace'+ : { id: 'external-namespace', external: true }+ },+ load(id) {+ if (id === '\0namespace') return `export const ns = 'actual'`+ },+ },+ ],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ }),+ ).rejects.toThrow(/Undeclared namespace: actual/)+ expect(reports[0]!.evidence).toEqual(+ expect.arrayContaining([+ expect.objectContaining({ kind: 'unresolved-import', file: 'app/page.ts' }),+ ]),+ )+ },+ )++ it.each(['rewrite', 'inline', 'retained static import', 'retained dynamic import'] as const)(+ 'blocks disk fallback after a dynamic import %s',+ async (mode) => {+ writeFileSync(localeFile, '{}')+ for (const namespace of ['old', 'actual'])+ writeFileSync(path.join(root, `i18n/locales/en-US/${namespace}.json`), '{}')+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(path.join(root, 'app/old.ts'), `export const ns = 'old'`)+ writeFileSync(path.join(root, 'app/actual.ts'), `export const ns = 'actual'`)+ writeFileSync(+ path.join(root, 'app/page.ts'),+ `${mode === 'retained static import' ? "import { ns } from './old'; export const keep = ns;" : ''}+ export async function page(t: (key: string, options: { ns: string }) => string) {+ const resource = await import('./old')+ return t('title', { ns: resource.ns })+ }+ ${mode === 'retained dynamic import' ? "export const keep = () => import('./old')" : ''}`,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({+ onAnalysis: (report) => reports.push(report),+ getDeclaredNamespaces: () => ['old'],+ }),+ {+ name: 'rewrite-dynamic-import',+ enforce: 'pre',+ transform(code, id) {+ if (id.endsWith('/app/page.ts'))+ return code.replace(+ "import('./old')",+ mode === 'inline' ? "Promise.resolve({ ns: 'actual' })" : "import('./actual')",+ )+ },+ },+ ],+ build: { write: false, lib: { entry: path.join(root, 'app/page.ts'), formats: ['es'] } },+ }),+ ).rejects.toThrow(/Undeclared namespace: actual/)+ expect(reports[0]!.evidence).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ kind: 'unresolved-import',+ file: 'app/page.ts',+ message: expect.stringContaining('./old'),+ }),+ ]),+ )+ },+ )++ it('reports untraceable rewrites instead of reading the old runtime module', async () => {+ writeFileSync(localeFile, '{}')+ writeFileSync(path.join(root, 'old.ts'), `export const value = 'old'`)+ writeFileSync(+ path.join(root, 'entry.ts'),+ `import { value } from './old'; export const label = value`,+ )+ const reports: AnalysisReport[] = []+ await build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({ onAnalysis: (report) => reports.push(report) }),+ {+ name: 'inline-import',+ transform(code, id) {+ if (id.endsWith('/entry.ts')) return `export const label = 'actual'`+ },+ },+ ],+ build: { write: false, lib: { entry: path.join(root, 'entry.ts'), formats: ['es'] } },+ })+ expect(reports[0]!.evidence).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ kind: 'unresolved-import',+ file: 'entry.ts',+ line: 1,+ environment: 'client',+ }),+ ]),+ )+ })++ it('connects RSC client stubs to implementation dependencies without scanning their removed bodies', async () => {+ writeFileSync(localeFile, JSON.stringify({ used: 'Used' }))+ mkdirSync(path.join(root, 'app'), { recursive: true })+ writeFileSync(path.join(root, 'app/page.ts'), `export { widget as page } from '../widget'`)+ writeFileSync(+ path.join(root, 'widget.ts'),+ `+ 'use strict'; 'use client';+ export { label as widget } from './label'+ `,+ )+ writeFileSync(+ path.join(root, 'label.ts'),+ `export function label(t: (key: string) => string) { return t('app:used') }`,+ )+ const reports: AnalysisReport[] = []+ const builder = await createBuilder({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({ onAnalysis: (report) => reports.push(report) }),+ {+ name: 'client-reference-stub',+ transform(code, id) {+ if (this.environment.name === 'rsc' && id.endsWith('/widget.ts'))+ return `export const widget = 'client reference'`+ },+ },+ ],+ environments: Object.fromEntries(+ ['rsc', 'ssr', 'client'].map((name) => [+ name,+ {+ build: {+ write: false,+ lib: {+ entry: path.join(root, name === 'rsc' ? 'app/page.ts' : 'widget.ts'),+ formats: ['es'],+ },+ },+ },+ ]),+ ),+ })+ await builder.buildApp()+ expect(reports).toHaveLength(1)+ expect(reports[0]!.routes).toMatchObject([{ route: '/', namespaces: ['app'] }])+ expect(reports[0]!.evidence.some((item) => item.kind === 'unresolved-import')).toBe(false)+ const report = reports[0]!+ const paths = report.routes[0]!.groups.page[0]!.dependencyPaths!.map((index) => {+ const chain: AnalysisReport['modules'] = []+ let current: number | null = index+ while (current !== null) {+ const [module, parent]: [number, number | null] = report.paths[current]!+ chain.unshift(report.modules[module]!)+ current = parent+ }+ return chain+ })+ expect(paths).toEqual(+ expect.arrayContaining([+ [+ { environment: 'rsc', moduleId: path.join(root, 'app/page.ts') },+ { environment: 'rsc', moduleId: path.join(root, 'widget.ts') },+ { environment: 'client', moduleId: path.join(root, 'widget.ts') },+ { environment: 'client', moduleId: path.join(root, 'label.ts') },+ ],+ ]),+ )+ })++ it('preserves package declarations after split imports and ignores Vite asset rewrites', async () => {+ writeFileSync(localeFile, JSON.stringify({ used: 'Used', unused: 'Unused' }))+ const directory = path.join(root, 'node_modules/test-hooks')+ mkdirSync(directory, { recursive: true })+ writeFileSync(+ path.join(directory, 'package.json'),+ JSON.stringify({+ name: 'test-hooks',+ type: 'module',+ types: './index.d.ts',+ exports: { '.': './index.js', './identity': './identity.js' },+ }),+ )+ writeFileSync(+ path.join(directory, 'index.js'),+ `export { default as identity } from './identity.js'`,+ )+ writeFileSync(path.join(directory, 'identity.js'), `export default value => value`)+ writeFileSync(+ path.join(directory, 'index.d.ts'),+ `export declare function identity(value: string): 'used'`,+ )+ writeFileSync(path.join(root, 'icon.svg'), '<svg/>')+ writeFileSync(+ path.join(root, 'entry.ts'),+ `+ import { identity } from 'test-hooks'+ import icon from './icon.svg'+ export const asset = identity(icon)+ export function label(t: (key: string) => string, key: ReturnType<typeof identity>) { return t(key) }+ `,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({ onAnalysis: (report) => reports.push(report) }),+ {+ name: 'optimize-fixture-imports',+ enforce: 'pre',+ transform(code, id) {+ if (id.endsWith('/entry.ts'))+ return code+ .replace(+ "import { identity } from 'test-hooks'",+ "import identity from 'test-hooks/identity'",+ )+ .replace("import icon from './icon.svg'", "const icon = 'data:image/svg+xml,svg'")+ },+ },+ ],+ build: { write: false, lib: { entry: path.join(root, 'entry.ts'), formats: ['es'] } },+ }),+ ).rejects.toThrow(/Found 1 potentially unused i18n keys[\s\S]*app:unused/)+ expect(reports[0]!.evidence.some((item) => item.kind === 'unresolved-import')).toBe(false)+ })++ it('omits opaque dependency diagnostics while retaining application key analysis', async () => {+ writeFileSync(localeFile, JSON.stringify({ used: 'Used', unused: 'Unused' }))+ writeFileSync(path.join(root, 'package.json'), JSON.stringify({ name: 'opaque-fixture' }))+ const packageDirectory = path.join(root, 'node_modules/actual-package')+ mkdirSync(packageDirectory, { recursive: true })+ writeFileSync(path.join(packageDirectory, 'index.js'), 'export default 1')+ writeFileSync(path.join(root, 'style.css'), '.example { color: red }')+ writeFileSync(+ path.join(root, 'entry.ts'),+ `+ import value from 'package-alias'+ import 'server-only'+ import './style.css'+ import image from './icon.svg?metadata'+ export const dependencies = [value, image]+ export function translate(t: (key: string) => string) { return t('app:used') }+ `,+ )+ const reports: AnalysisReport[] = []+ await expect(+ build({+ root,+ configFile: false,+ logLevel: 'silent',+ plugins: [+ i18nAnalysisPlugin({ onAnalysis: (report) => reports.push(report) }),+ {+ name: 'opaque-dependencies',+ resolveId(id) {+ if (id === 'package-alias') return path.join(packageDirectory, 'index.js')+ if (id === 'server-only' || id === './icon.svg?metadata' || id === 'virtual:helper')+ return `\0${id}`+ },+ load(id) {+ if (id.startsWith('\0')) return 'export default 1'+ },+ transform(code, id) {+ if (id.endsWith('/entry.ts')) return `import 'virtual:helper';\n${code}`+ },+ },+ ],+ build: { write: false, lib: { entry: path.join(root, 'entry.ts'), formats: ['es'] } },+ }),+ ).rejects.toThrow(/Found 1 potentially unused i18n keys[\s\S]*app:unused/)+ expect(reports[0]!.evidence.some((item) => item.kind === 'unresolved-import')).toBe(false)+ })+it('does not block development when unused translations exist', async () => {writeFileSync(localeFile, JSON.stringify({ used: 'Used', unused: 'Unused' }))const server = await createServer({diff --git a/web/plugins/vite/__tests__/i18n-graph.spec.ts b/web/plugins/vite/__tests__/i18n-graph.spec.tsindex 2efcd3a1486..51270f72540 100644--- a/web/plugins/vite/__tests__/i18n-graph.spec.ts+++ b/web/plugins/vite/__tests__/i18n-graph.spec.ts@@ -1,9 +1,35 @@// @vitest-environment node-import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from 'node:fs'+import { mkdirSync, mkdtempSync, readFileSync, rmSync, symlinkSync, writeFileSync } from 'node:fs'import { tmpdir } from 'node:os'import path from 'node:path'import { afterEach, beforeEach, describe, expect, it } from 'vite-plus/test'-import { checkTranslationGraph } from '../i18n-analysis/graph'+import {+ checkTranslationGraph as analyzeTranslationGraph,+ createAnalysisContext,+} from '../i18n-analysis/graph'++const checkTranslationGraph = (root: string, modules: ReadonlyMap<string, string>) =>+ analyzeTranslationGraph(+ root,+ modules,+ undefined,+ createAnalysisContext(root, [+ { module: 'i18n/lib.client.ts', exportName: 'useTranslation', namespaceArgument: 0 },+ {+ module: 'i18n/lib.server.ts',+ exportName: 'useTranslation',+ namespaceArgument: 0,+ implementationFunctions: ['getI18nConfig'],+ },+ { module: 'i18n/server.ts', exportName: 'getTranslation', namespaceArgument: 1 },+ {+ module: 'app/route-metadata.ts',+ exportName: 'getRouteMetadata',+ namespaceArgument: 0,+ selectorArgument: 1,+ },+ ]),+ )let webRoot: stringlet modules: Map<string, string>@@ -29,7 +55,20 @@ describe('translation graph analysis', () => {beforeEach(() => {modules = new Map()webRoot = mkdtempSync(path.join(tmpdir(), 'dify-i18n-analysis-'))+ mkdirSync(path.join(webRoot, 'node_modules'), { recursive: true })+ symlinkSync(+ path.resolve(import.meta.dirname, '../../../node_modules/react-i18next'),+ path.join(webRoot, 'node_modules/react-i18next'),+ )writeSource('placeholder.ts', '')+ writeSource(+ 'i18n/server.ts',+ 'export function getTranslation(locale: string, ns: string) { return {} }',+ )+ writeFileSync(+ path.join(webRoot, 'tsconfig.json'),+ JSON.stringify({ compilerOptions: { paths: { '@/*': [path.join(webRoot, '*')] } } }),+ )})afterEach(() => {@@ -37,13 +76,197 @@ describe('translation graph analysis', () => {})describe('Usage Analysis', () => {+ it.each(['static', 'dynamic'] as const)(+ 'analyzes repository adapter calls with %s namespaces',+ (mode) => {+ writeJson('i18n/locales/en-US/common.json', { used: 'Used', unused: 'Unused' })+ for (const file of ['i18n/lib.client.ts', 'i18n/lib.server.ts', 'app/route-metadata.ts']) {+ writeSource(+ file,+ readFileSync(path.resolve(import.meta.dirname, '../../..', file), 'utf8'),+ )+ }+ writeSource(+ 'src/page.ts',+ `+ import { useTranslation as clientTranslation } from '../i18n/lib.client'+ import { useTranslation as serverTranslation } from '../i18n/lib.server'+ import { getRouteMetadata as metadata } from '../app/route-metadata'+ export function page(ns: string) {+ clientTranslation(${mode === 'static' ? "'common'" : 'ns'})+ serverTranslation(${mode === 'static' ? "'common'" : 'ns'})+ return metadata(${mode === 'static' ? "'common'" : 'ns'}, $ => $.used)+ }+ `,+ )+ const result = checkTranslationGraph(webRoot, modules)+ const unknown = result.evidence.filter((item) => item.kind === 'unknown-namespace')+ expect(unknown).toHaveLength(mode === 'static' ? 0 : 3)+ expect(unknown.every((item) => item.file === 'src/page.ts')).toBe(true)+ expect(result.unused).toEqual({ common: ['unused'] })+ expect(result.protectedNamespaces).toEqual([])+ for (const file of ['i18n/lib.client.ts', 'i18n/lib.server.ts', 'app/route-metadata.ts']) {+ expect(result.moduleNamespaces.get(path.join(webRoot, file))).toEqual(new Set())+ }+ },+ )++ it.each(['direct', 'alias', 'barrel'] as const)(+ 'supports custom adapters exported through %s exports',+ (kind) => {+ writeJson('i18n/locales/en-US/common.json', {+ used: 'Used',+ other: 'Other',+ unused: 'Unused',+ })+ writeSource(+ 'custom/labels.ts',+ `+ import { useTranslation } from 'react-i18next'+ ${kind === 'direct' ? 'export const label' : 'const internal'} = (selector: (source: Record<string, string>) => string, ns: string) => {+ const { t } = useTranslation(ns)+ return t(selector)+ }+ ${kind === 'direct' ? '' : 'export { internal as label }'}+ `,+ )+ writeSource('custom/barrel.ts', `export { label as caption } from './labels'`)+ writeSource(+ 'entry.ts',+ `+ import { label as caption } from './custom/labels'+ import * as labels from './custom/labels'+ caption($ => $.used, 'common')+ labels.label($ => $.other, 'common')+ `,+ )+ const unconfigured = analyzeTranslationGraph(webRoot, modules)+ expect(+ unconfigured.evidence.some(+ (item) => item.kind === 'unknown-namespace' && item.file === 'custom/labels.ts',+ ),+ ).toBe(true)+ const configured = analyzeTranslationGraph(+ webRoot,+ modules,+ undefined,+ createAnalysisContext(webRoot, [+ {+ module: kind === 'barrel' ? 'custom/barrel.ts' : 'custom/labels.ts',+ exportName: kind === 'barrel' ? 'caption' : 'label',+ namespaceArgument: 1,+ selectorArgument: 0,+ },+ ]),+ )+ expect(configured.evidence.some((item) => item.kind === 'unknown-namespace')).toBe(false)+ expect(configured.unused).toEqual({ common: ['unused'] })+ expect(configured.protectedNamespaces).toEqual([])+ },+ )++ it('does not exempt unrelated functions or all code in an adapter module', () => {+ writeJson('i18n/locales/en-US/common.json', { unused: 'Unused' })+ writeSource(+ 'app/route-metadata.ts',+ `+ import { useTranslation } from 'react-i18next'+ export function other(ns: string) { useTranslation(ns) }+ `,+ )+ writeSource(+ 'src/other.ts',+ `+ import { useTranslation } from 'react-i18next'+ export function getRouteMetadata(ns: string) { useTranslation(ns) }+ `,+ )+ const result = checkTranslationGraph(webRoot, modules)+ expect(+ result.evidence+ .filter((item) => item.kind === 'unknown-namespace')+ .map((item) => item.file)+ .sort(),+ ).toEqual(['app/route-metadata.ts', 'src/other.ts'])+ })++ it.each([+ "function load(ns: string) { return useTranslation(ns) }; load('login')",+ "function load(ns = 'login') { return useTranslation(ns) }; load()",+ "function load(...ns: string[]) { return useTranslation(ns) }; load('login')",+ "const ns = ['login'] as const; useTranslation(ns)",+ "let ns = 'app'; ns = 'login'; useTranslation(ns)",+ "const holder = { ns: 'login' }; useTranslation(holder.ns)",+ "function namespace() { return 'login' }; useTranslation(namespace())",+ ])('leaves runtime namespace values unknown: %s', (body) => {+ writeJson('i18n/locales/en-US/app.json', {})+ writeSource('page.ts', `import { useTranslation } from 'react-i18next'; ${body}`)+ const result = checkTranslationGraph(webRoot, modules)+ expect(result.moduleNamespaces.get(path.join(webRoot, 'page.ts'))).toEqual(new Set())+ expect(result.evidence.some((item) => item.kind === 'unknown-namespace')).toBe(true)+ })++ it('keeps known loads and conservatively checks keys for unknown array members', () => {+ writeJson('i18n/locales/en-US/app.json', { used: 'Used', unused: 'Unused' })+ writeJson('i18n/locales/en-US/common.json', { used: 'Used', unused: 'Unused' })+ writeSource(+ 'page.ts',+ `+ import { useTranslation } from 'react-i18next'+ export function page(ns: string) {+ const { t } = useTranslation(['login', ns])+ return t('used')+ }+ `,+ )+ const result = checkTranslationGraph(webRoot, modules)+ expect(result.moduleNamespaces.get(path.join(webRoot, 'page.ts'))).toEqual(+ new Set(['login', 'app', 'common']),+ )+ expect(result.evidence.filter((item) => item.kind === 'unknown-namespace')).toHaveLength(1)+ expect(result.unused).toEqual({ app: ['unused'], common: ['unused'] })+ })++ it('preserves a finite key type when an initializer cannot be evaluated', () => {+ writeJson('i18n/locales/en-US/app.json', { used: 'Used', unused: 'Unused' })+ writeSource(+ 'entry.ts',+ `+ declare function remote(): any+ export function label(t: (selector: (value: Record<string, string>) => string) => string) {+ const key: 'used' = remote()+ return t($ => $[key])+ }+ `,+ )+ const result = checkTranslationGraph(webRoot, modules)+ expect(result.unused.app).toEqual(['unused'])+ expect(result.protectedNamespaces).toEqual([])+ })++ it('reports unknown namespaces in shorthand options and Trans attributes', () => {+ writeJson('i18n/locales/en-US/app.json', { used: 'Used' })+ writeSource(+ 'entry.tsx',+ `+ import { Trans } from 'react-i18next'+ export function label(t: (key: string, options: { ns: string }) => string, ns: string) {+ t('used', { ns })+ return <Trans ns={ns} i18nKey="used" />+ }+ `,+ )+ const result = checkTranslationGraph(webRoot, modules)+ expect(result.evidence.filter((item) => item.kind === 'unknown-namespace')).toHaveLength(2)+ })+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+ import { useTranslation } from 'react-i18next'+ import { getTranslation } from '@/i18n/server'useTranslation(['app', 'common'])getTranslation('en-US', 'login')export function boundary(requiredNamespaces: ('workflow' | 'dataset')[]) {@@ -60,7 +283,7 @@ describe('translation graph analysis', () => {expect(result.unused).toEqual({ app: ['unused'] })})- it('resolves namespace constants, imported arrays and nested static spreads without consuming keys', () => {+ it('resolves const strings but keeps bound arrays and cyclic values unknown', () => {writeJson('i18n/locales/en-US/workflow.json', { unused: 'Unused' })writeSource('src/namespaces.ts',@@ -73,10 +296,11 @@ describe('translation graph analysis', () => {'src/page.ts',`import { workflow, extras } from './namespaces'- declare function useTranslation(ns: readonly string[]): unknown- declare function getTranslation(locale: string, ns: string): unknown+ import { useTranslation } from 'react-i18next'+ import { getTranslation } from '@/i18n/server'const shared = ['common', ...extras] as const- useTranslation([workflow, ...shared])+ useTranslation([workflow, ...['common']])+ useTranslation(shared)const cyclic = [cyclic]useTranslation(cyclic)`,@@ -84,12 +308,76 @@ describe('translation graph analysis', () => {const result = checkTranslationGraph(webRoot, modules)expect([...result.moduleNamespaces.get(path.join(webRoot, 'src/page.ts'))!].sort()).toEqual(['common',- 'login','workflow',])+ expect(result.evidence.filter((item) => item.kind === 'unknown-namespace')).toHaveLength(2)expect(result.unused).toEqual({ workflow: ['unused'] })})+ it('recognizes imported aliases and ignores unrelated same-name functions', () => {+ writeJson('i18n/locales/en-US/app.json', { used: 'Used', unused: 'Unused' })+ writeSource(+ 'src/aliases.tsx',+ `+ import { useTranslation as useT, Trans as Translation } from 'react-i18next'+ const load = useT+ load('common')+ export function View() { return <Translation ns="app" i18nKey="used" /> }+ function useTranslation(value: string) { return value }+ function getTranslation(locale: string, value: string) { return value }+ useTranslation('unrelated')+ getTranslation('en-US', 'also-unrelated')+ `,+ )+ const result = checkTranslationGraph(webRoot, modules)+ expect(+ [...result.moduleNamespaces.get(path.join(webRoot, 'src/aliases.tsx'))!].sort(),+ ).toEqual(['app', 'common'])+ expect(result.unused).toEqual({ app: ['unused'] })+ })++ it('follows API re-exports and namespace imports through their declarations', () => {+ writeJson('i18n/locales/en-US/app.json', { unused: 'Unused' })+ writeSource('i18n/lib.client.ts', `export function useTranslation(ns: string) { return ns }`)+ writeSource('src/barrel.ts', `export { useTranslation as useT } from '../i18n/lib.client'`)+ writeSource(+ 'src/page.ts',+ `+ import { useT } from './barrel'+ import * as reactI18n from 'react-i18next'+ useT('login')+ reactI18n.useTranslation('common')+ `,+ )+ const result = checkTranslationGraph(webRoot, modules)+ expect([...result.moduleNamespaces.get(path.join(webRoot, 'src/page.ts'))!].sort()).toEqual([+ 'common',+ 'login',+ ])+ })++ it('reports dynamic protection with the originating module and line', () => {+ writeJson('i18n/locales/en-US/app.json', { dynamic: 'Dynamic' })+ writeSource(+ 'src/dynamic.ts',+ `export function label(t: (key: string) => string, key: string) {+ return t(key)+}`,+ )+ const result = checkTranslationGraph(webRoot, modules)+ expect(result.evidence).toEqual(+ expect.arrayContaining([+ expect.objectContaining({+ kind: 'dynamic-key',+ file: 'src/dynamic.ts',+ line: 2,+ namespaces: ['app'],+ }),+ ]),+ )+ expect(result.unused).toEqual({})+ })+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', {@@ -1124,7 +1412,7 @@ describe('translation graph analysis', () => {})})- it('should treat simple i18n key identity helpers as their literal argument', () => {+ it('protects the namespace for keys returned by runtime helpers', () => {// ArrangewriteJson('i18n/locales/en-US/common.json', {'mainNav.workspace.searchPlaceholder': 'Search',@@ -1148,9 +1436,8 @@ describe('translation graph analysis', () => {const result = checkTranslationGraph(webRoot, modules)// Assert- expect(sortedUnusedKeysByNamespace(result)).toEqual({- common: ['mainNav.workspace.unused'],- })+ expect(sortedUnusedKeysByNamespace(result)).toEqual({})+ expect(result.protectedNamespaces).toEqual(['common'])})it('should keep i18next plural variants when the base key is referenced', () => {diff --git a/web/plugins/vite/__tests__/i18n-routes.spec.ts b/web/plugins/vite/__tests__/i18n-routes.spec.tsindex f31d08f9039..0d76668d69f 100644--- a/web/plugins/vite/__tests__/i18n-routes.spec.ts+++ b/web/plugins/vite/__tests__/i18n-routes.spec.ts@@ -1,6 +1,10 @@// @vitest-environment nodeimport { describe, expect, it } from 'vite-plus/test'-import { analyzeRouteNamespaces, validateRouteNamespaces } from '../i18n-analysis/routes'+import {+ analyzeEnvironmentRoutes,+ analyzeRouteNamespaces,+ validateRouteNamespaces,+} from '../i18n-analysis/routes'describe('route namespace analysis', () => {it('includes ancestor boundaries and parallel slots without leaking sibling layouts', () => {@@ -88,3 +92,124 @@ describe('route namespace analysis', () => {})})})++describe('environment route boundaries', () => {+ const edge = (ids: string[]) => ({ static: new Set(ids), dynamic: new Set<string>() })+ it('shares dependency paths across routes and namespaces', () => {+ const report = analyzeEnvironmentRoutes(+ '/web',+ new Map([+ [+ 'client',+ {+ usage: new Map([+ ['/web/app/a/page.ts', new Set<string>()],+ ['/web/app/b/page.ts', new Set<string>()],+ ['/web/app/layout.ts', new Set<string>()],+ ['/web/shared.ts', new Set(['common', 'app'])],+ ]),+ dependencies: new Map([+ ['/web/app/layout.ts', edge(['/web/shared.ts'])],+ ['/web/shared.ts', edge(['/web/app/layout.ts'])],+ ]),+ clientReferences: new Set<string>(),+ },+ ],+ ]),+ )+ expect(report.routes).toHaveLength(2)+ const references = report.routes.flatMap((route) =>+ route.groups.shared.flatMap((group) => group.dependencyPaths!),+ )+ expect(references).toHaveLength(4)+ expect(new Set(references).size).toBe(1)+ const [moduleIndex, parentIndex] = report.paths[references[0]!]!+ expect(report.modules[moduleIndex]).toEqual({+ environment: 'client',+ moduleId: '/web/shared.ts',+ })+ const [rootIndex, rootParent] = report.paths[parentIndex!]!+ expect(report.modules[rootIndex]).toEqual({+ environment: 'client',+ moduleId: '/web/app/layout.ts',+ })+ expect(rootParent).toBeNull()+ expect(report.paths).toHaveLength(2)+ })++ it('does not combine unrelated paths from different environments', () => {+ const usage = new Map([+ ['/web/app/page.ts', new Set<string>()],+ ['/web/bridge.ts', new Set<string>()],+ ['/web/extra.ts', new Set(['extra'])],+ ])+ const graphs = new Map([+ [+ 'client',+ {+ usage,+ dependencies: new Map([['/web/app/page.ts', edge(['/web/bridge.ts'])]]),+ clientReferences: new Set<string>(),+ },+ ],+ [+ 'ssr',+ {+ usage,+ dependencies: new Map([['/web/bridge.ts', edge(['/web/extra.ts'])]]),+ clientReferences: new Set<string>(),+ },+ ],+ ])+ expect(analyzeEnvironmentRoutes('/web', graphs).routes[0]!.namespaces).toEqual([])+ })++ it('follows explicit client references into both SSR and client implementations', () => {+ const graphs = new Map([+ [+ 'rsc',+ {+ usage: new Map([+ ['/web/app/page.ts', new Set<string>()],+ ['/web/widget.tsx', new Set<string>()],+ ]),+ dependencies: new Map([+ ['/web/app/page.ts', edge(['/web/widget.tsx'])],+ ['/web/widget.tsx', edge([])],+ ]),+ clientReferences: new Set(['/web/widget.tsx']),+ },+ ],+ [+ 'ssr',+ {+ usage: new Map([+ ['/web/widget.tsx', new Set<string>()],+ ['/web/server-label.ts', new Set(['server'])],+ ]),+ dependencies: new Map([['/web/widget.tsx', edge(['/web/server-label.ts'])]]),+ clientReferences: new Set<string>(),+ unknownNamespaces: new Set(['/web/server-label.ts']),+ },+ ],+ [+ 'client',+ {+ usage: new Map([+ ['/web/widget.tsx', new Set<string>()],+ ['/web/browser-label.ts', new Set(['browser'])],+ ]),+ dependencies: new Map([['/web/widget.tsx', edge(['/web/browser-label.ts'])]]),+ clientReferences: new Set<string>(),+ },+ ],+ ])+ expect(analyzeEnvironmentRoutes('/web', graphs).routes).toMatchObject([+ {+ route: '/',+ namespaces: ['browser', 'server'],+ unknownNamespaceSources: ['server-label.ts'],+ },+ ])+ })+})diff --git a/web/plugins/vite/i18n-analysis.ts b/web/plugins/vite/i18n-analysis.tsindex f1c0a816503..c08d16f8fea 100644--- a/web/plugins/vite/i18n-analysis.ts+++ b/web/plugins/vite/i18n-analysis.ts@@ -1,16 +1,49 @@import type { Logger, Plugin } from 'vite'-import type { ModuleDependencies } from './i18n-analysis/routes'+import type { TranslationAdapter } from './i18n-analysis/api'+import type { ModuleResolutions } from './i18n-analysis/compiler'+import type { AnalysisEvidence } from './i18n-analysis/graph'+import type {+ EnvironmentUsage,+ ModuleDependencies,+ ModuleLocation,+ RouteNamespaceReport,+} from './i18n-analysis/routes'+import { createHash } from 'node:crypto'import fs from 'node:fs/promises'import path from 'node:path'import { normalizePath } from 'vite'-import { analyzeRouteNamespaces, validateRouteNamespaces } from './i18n-analysis/routes'+import { analyzeEnvironmentRoutes, validateRouteNamespaces } from './i18n-analysis/routes'const SOURCE_META = 'dify:i18n-source'+export type AnalysisReport = {+ version: 3+ routes: RouteNamespaceReport[]+ modules: ModuleLocation[]+ paths: [module: number, parent: number | null][]+ evidence: (AnalysisEvidence & { environment: string })[]+ metrics: {+ totalMs: number+ setupMs: number+ routesMs: number+ environments: {+ environment: string+ modules: number+ resolveCalls: number+ resolutionMs: number+ programMs: number+ analysisMs: number+ }[]+ }+}+// 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(options: {+ adapters?: readonly TranslationAdapter[]+ onAnalysis?: (report: AnalysisReport) => void+ strictNamespaces?: booleangetDeclaredNamespaces?: (route: string) => readonly string[] | undefined} = {},): Plugin[] {@@ -18,38 +51,56 @@ export function i18nAnalysisPlugin(let logger: Loggerlet reportPath: string | undefinedlet buildingApp = false- const graphs = new Map<string, Map<string, string>>()- const edges = new Map<string, Map<string, ModuleDependencies>>()- const moduleId = (id: string) => normalizePath(id.split('?')[0]!)+ const graphs = new Map<+ string,+ {+ modules: Map<string, string>+ dependencies: Map<string, ModuleDependencies>+ resolutions: ModuleResolutions+ clientReferences: Set<string>+ resolveCalls: number+ resolutionMs: number+ }+ >()+ const moduleId = normalizePath+ const checks = new Map<string, Promise<void>>()+ const snapshots = new Map<string, string>()const check = async () => {- const { checkTranslationGraph } = await import('./i18n-analysis/graph')- const usage = new Map<string, Set<string>>()- const dependencies = new Map<string, ModuleDependencies>()- for (const graph of edges.values()) {- for (const [id, imports] of graph) {- const merged = dependencies.get(id) ?? {- static: new Set<string>(),- dynamic: new Set<string>(),- }- for (const dependency of imports.static) merged.static.add(dependency)- for (const dependency of imports.dynamic) merged.dynamic.add(dependency)- dependencies.set(id, merged)- }+ const started = performance.now()+ const { checkTranslationGraph, createAnalysisContext } = await import('./i18n-analysis/graph')+ const context = createAnalysisContext(root, options.adapters)+ const setupMs = performance.now() - started+ const environments = new Map<string, EnvironmentUsage>()+ const evidence: AnalysisReport['evidence'] = []+ const metrics: AnalysisReport['metrics'] = {+ totalMs: 0,+ setupMs,+ routesMs: 0,+ environments: [],}let unused: Record<string, string[]> | undefinedconst protectedNamespaces = new Set<string>()- for (const graph of graphs.values()) {- // Keep original paths in a separate compiler program per environment so- // imports resolve against that environment's source, not the first build.- const modules = new Map<string, string>()- for (const [id, code] of graph) modules.set(normalizePath(id.split('?')[0]!), code)- const result = checkTranslationGraph(root, modules)- for (const [id, namespaces] of result.moduleNamespaces) {- const merged = usage.get(id) ?? new Set<string>()- for (const namespace of namespaces) merged.add(namespace)- usage.set(id, merged)- }+ for (const [environment, graph] of graphs) {+ const result = checkTranslationGraph(root, graph.modules, graph.resolutions, context)+ environments.set(environment, {+ dependencies: graph.dependencies,+ usage: result.moduleNamespaces,+ clientReferences: graph.clientReferences,+ unknownNamespaces: new Set(+ result.evidence+ .filter((item) => item.kind === 'unknown-namespace')+ .map((item) => item.moduleId),+ ),+ })+ evidence.push(...result.evidence.map((item) => ({ ...item, environment })))+ metrics.environments.push({+ environment,+ modules: graph.modules.size,+ resolveCalls: graph.resolveCalls,+ resolutionMs: graph.resolutionMs,+ ...result.timings,+ })for (const namespace of result.protectedNamespaces) protectedNamespaces.add(namespace)// Intersect unused sets: usage (or protection) in any environment keeps a key.unused =@@ -62,29 +113,46 @@ export function i18nAnalysisPlugin(}),)}- const routes = analyzeRouteNamespaces(normalizePath(root), dependencies, usage)- if (routes.length) {- logger.info(- [- '[i18n] Route namespace analysis (static build graph; may overestimate or miss runtime usage):',- 'Includes ancestor boundaries, dynamic imports and all built parallel-slot branches. Interception segments remain in route labels.',- ...routes.flatMap(({ route, page, namespaces, groups }) => [- ` ${route} (${page}): ${namespaces.join(', ') || '(none detected)'}`,- ...Object.entries(groups).map(- ([name, entries]) =>- ` ${name}: ${entries.map((entry) => entry.namespace).join(', ') || '(none detected)'}`,- ),- ]),- ].join('\n'),+ const routesStarted = performance.now()+ const { routes, modules, paths } = analyzeEnvironmentRoutes(normalizePath(root), environments)+ metrics.routesMs = performance.now() - routesStarted+ metrics.totalMs =+ performance.now() -+ started ++ metrics.environments.reduce((sum, item) => sum + item.resolutionMs, 0)+ const report: AnalysisReport = { version: 3, routes, modules, paths, evidence, metrics }+ options.onAnalysis?.(report)+ logger.info(+ `[i18n] Analysis: ${metrics.totalMs.toFixed(0)}ms; ${metrics.environments.reduce((sum, item) => sum + item.modules, 0)} environment modules; ${metrics.environments.reduce((sum, item) => sum + item.resolveCalls, 0)} resolver calls.`,+ )+ const unresolved = evidence.filter((item) => item.kind === 'unresolved-import')+ if (unresolved.length) {+ const categories = new Map<string, number>()+ for (const item of unresolved) {+ const category = item.import?.kind ?? 'source'+ categories.set(category, (categories.get(category) ?? 0) + 1)+ }+ logger.warn(+ `[i18n] ${unresolved.length} runtime imports could not be traced (${[...categories].map(([kind, count]) => `${kind}: ${count}`).join(', ')}); inspect the report before trusting unused-key findings.`,)}- if (routes.length && reportPath) {+ const incomplete = routes.filter((route) => route.unknownNamespaceSources?.length)+ if (incomplete.length)+ logger.warn(+ `[i18n] Namespace analysis is incomplete for ${incomplete.length} routes; inspect unknownNamespaceSources before treating validation as complete.`,+ )+ const unknown = evidence.filter((item) => item.kind === 'unknown-namespace').length+ const dynamic = evidence.filter((item) => item.kind === 'dynamic-key').length+ logger.info(+ `[i18n] Routes: ${routes.length}; unknown namespace records: ${unknown}; dynamic key records: ${dynamic}; protected namespaces: ${[...protectedNamespaces].sort().join(', ') || '(none)'}.`,+ )+ if (reportPath) {await fs.mkdir(path.dirname(reportPath), { recursive: true })- await fs.writeFile(reportPath, `${JSON.stringify({ version: 1, routes }, null, 2)}\n`)+ await fs.writeFile(reportPath, `${JSON.stringify(report, null, 2)}\n`)logger.info(`[i18n] Full namespace sources: ${reportPath}`)}if (options.getDeclaredNamespaces)- validateRouteNamespaces(routes, options.getDeclaredNamespaces)+ validateRouteNamespaces(routes, options.getDeclaredNamespaces, options.strictNamespaces)const keys = Object.entries(unused ?? {}).flatMap(([namespace, unused]) =>unused.map((key) => `${namespace}:${key}`),)@@ -121,30 +189,34 @@ export function i18nAnalysisPlugin(},async buildApp() {graphs.clear()- edges.clear()+ checks.clear()+ snapshots.clear()buildingApp = true},buildStart() {- if (!buildingApp) {+ if (this.meta.watchMode) {+ checks.delete(this.environment.name)+ snapshots.delete(this.environment.name)+ }+ if (!buildingApp && !snapshots.has(this.environment.name)) {graphs.clear()- edges.clear()}},- transform(code, id) {- const file = normalizePath(id.split('?')[0]!)- if (- id.startsWith('\0') ||- !path.isAbsolute(file) ||- file.includes('/node_modules/') ||- !/\.[cm]?[jt]sx?$/.test(file)- )- return- // Persist the original source in module metadata, including cached modules- // on rebuilds, before JSX/TypeScript and RSC transforms discard selectors.- return { code, map: null, meta: { [SOURCE_META]: code } }+ transform: {+ filter: {+ id: { include: /\.[cm]?[jt]sx?(?:\?.*)?$/, exclude: /(?:^\0|\/node_modules\/)/ },+ },+ handler(code, id) {+ if (!path.isAbsolute(id.split('?')[0]!)) return+ // Keep original source in cached metadata before TS/JSX/RSC transforms.+ return { code, map: null, meta: { [SOURCE_META]: code } }+ },},- async generateBundle() {+ async buildEnd(error) {+ if (error) return+ const resolutionStarted = performance.now()const graph = new Map<string, string>()+ const compiledModules = new Map<string, string>()const dependencies = new Map<string, ModuleDependencies>()for (const id of this.getModuleIds()) {const info = this.getModuleInfo(id)@@ -158,12 +230,78 @@ export function i18nAnalysisPlugin(imports.dynamic.add(moduleId(dependency))dependencies.set(moduleId(id), imports)}+ // Analyze the actual JSON module produced by Vite, never the raw disk file.+ if (id.endsWith('.json') && info?.code) {+ graph.set(moduleId(id), info.code)+ compiledModules.set(moduleId(id), info.code)+ }const source: unknown = info?.meta[SOURCE_META]- if (typeof source === 'string') graph.set(id, source)+ if (typeof source === 'string') {+ graph.set(moduleId(id), source)+ compiledModules.set(moduleId(id), info?.code ?? '')+ }+ }+ // Rolldown may rebuild for another output format. Reuse only within+ // this open bundle and only when source, transforms and edges agree.+ const hash = createHash('sha256')+ for (const [id, imports] of [...dependencies].sort(([a], [b]) => a.localeCompare(b))) {+ hash.update(+ JSON.stringify([+ id,+ graph.get(id),+ compiledModules.get(id),+ [...imports.static].sort(),+ [...imports.dynamic].sort(),+ ]),+ )+ }+ const snapshot = hash.digest('hex')+ if (snapshots.get(this.environment.name) === snapshot) return+ checks.delete(this.environment.name)+ snapshots.set(this.environment.name, snapshot)+ const { hasClientDirective, resolveTranslationImports } =+ await import('./i18n-analysis/compiler')+ const clientReferences = new Set<string>()+ if (this.environment.name === 'rsc') {+ for (const [id, code] of graph) {+ if (!hasClientDirective(code)) continue+ clientReferences.add(id)+ graph.set(id, compiledModules.get(id) ?? '')+ }+ }+ const { resolutions, resolveCalls } = await resolveTranslationImports(+ graph,+ compiledModules,+ async (specifier, importer) => {+ const resolved = await this.resolve(specifier, importer)+ return resolved+ ? { id: moduleId(resolved.id), external: !!resolved.external }+ : undefined+ },+ (specifier) =>+ !specifier.includes('?') && this.environment.config.assetsInclude(specifier),+ )+ graphs.set(this.environment.name, {+ modules: graph,+ dependencies,+ resolutions,+ resolveCalls,+ resolutionMs: performance.now() - resolutionStarted,+ clientReferences,+ })+ },+ closeBundle() {+ snapshots.delete(this.environment.name)+ checks.delete(this.environment.name)+ },+ async generateBundle() {+ if (buildingApp) return+ let pending = checks.get(this.environment.name)+ if (!pending) {+ pending = check()+ checks.set(this.environment.name, pending)}- graphs.set(this.environment.name, graph)- edges.set(this.environment.name, dependencies)- if (!buildingApp) await check()+ await pending},},{@@ -184,7 +322,6 @@ export function i18nAnalysisPlugin(} finally {buildingApp = falsegraphs.clear()- edges.clear()}},},diff --git a/web/plugins/vite/i18n-analysis/README.md b/web/plugins/vite/i18n-analysis/README.mdindex 0d0ff105bfc..ff55863f28a 100644--- a/web/plugins/vite/i18n-analysis/README.md+++ b/web/plugins/vite/i18n-analysis/README.md@@ -1,18 +1,15 @@# i18n build analysis-`i18nAnalysisPlugin()` prints a route namespace report during production Vite builds,+`i18nAnalysisPlugin()` prints a compact summary during production Vite builds,before the existing unused-key check. With Vinext it reports once, after combiningthe completed client, SSR and RSC graphs. Development does not run the analysis.-Each route contains its pattern, source page, sorted namespaces and four groups:--```text-/items/[id] (app/(console)/items/[id]/page.tsx): app, common, workflow- page: app- shared: common- lazy: workflow- slots: (none detected)-```+The console shows route and diagnostic counts, namespaces protected by dynamic+keys, and the report path. Diagnostic counts include separate environment records.+Individual route/group listings are available in `i18n-routes.json` (or through+`onAnalysis` when `build.write` is false). Each route retains its pattern, source+page, sorted namespaces and the page/shared/lazy/slots groups. Validation failures+still print the affected route and source details.The report follows resolved static and dynamic imports, including virtual modules,and adds ancestor layouts, templates, loading/error/not-found boundaries. Route@@ -20,6 +17,30 @@ groups are omitted from the URL pattern. Parallel slots include all built branchbecause their active page can depend on navigation history. Interception segmentsremain visible in labels; the source page disambiguates entries with the same URL.+## Module resolution++Vite owns module identity and runtime import resolution. Each completed environment+retains original source in module metadata and resolves surviving imports through+that environment's plugin resolver. When a transform changes an import specifier,+matching import/export bindings connect it back to the original source. Ambiguous+or removed application value imports, including unchanged imports resolved to unanalyzed virtual+modules, are reported as unresolved instead of silently reading+the old runtime module from disk. Rewritten or removed literal dynamic imports+are also blocked: without a stable binding, their replacement cannot be inferred+from call order. Matching checks binding signatures and occurrence counts rather+than merely whether a specifier survives. If uses of one specifier disagree, the+TypeScript host blocks that specifier as a whole because its resolution is shared+across import occurrences. Explicit type-only imports and package declarations+continue to use TypeScript resolution. Package barrel rewrites retain declaration+resolution only when every imported local binding is traced to the same external+package. Resource imports are excluded from diagnostics, while application source+query variants remain distinct throughout dependency and+usage analysis, with separate in-memory compiler filenames. Built JSON modules use+Vite-transformed JavaScript under synthetic compiler filenames, preserving inferred+object keys without loading a different JSON file from disk. JSON data modules inform+types but are not scanned as translation call sites. Reports display their+underlying source paths.+This is a conservative module-level estimate, not a runtime loading manifest.It shares the unused-key analyzer's translation recognition and dynamic-keyfallbacks. Unresolved namespaces can include the entire catalog. Unused exports,@@ -41,16 +62,114 @@ change translation loading or introduce additional build failures.Page and shared groups can overlap. A namespace can appear in multiple groupswhen different modules use it; group counts must not be added to obtain the total.-Environment graphs are combined conservatively, so a static path in any environment-makes a module static for this report. This is not a client-only bundle analysis.+Dependencies retain their environment identity. Only explicit `use client`+directives connect an RSC reference to the same module's SSR and client versions;+ordinary shared filenames do not connect environments. The RSC reference stub is+analyzed as generated code, with implementation usage coming from SSR and client.+Route reports are then merged by source page. A group can differ across environments.+This is not a client-only bundle analysis. Custom environment names or other+framework-specific cross-environment reference mechanisms are not inferred.When build output writing is enabled, `<build.outDir>/i18n-routes.json` contains-`{ version: 1, routes }`. Every route retains `route`, `page` and `namespaces`, with-`groups` mapping each category to `{ namespace, sources }` entries. Sources are+`{ version: 3, routes, modules, paths, evidence, metrics }`, including when no routes were detected.+Every route retains `route`, `page` and `namespaces`, with `groups` mapping each+category to `{ namespace, sources, dependencyPaths }` entries. Each dependency+path is an index into the shared `paths` table. Each table entry is a+`[moduleIndex, parentPathIndex]` tuple; a null parent starts a chain. `moduleIndex`+indexes `modules`, whose entries contain `{ environment, moduleId }`, preserving+queries and virtual IDs. Follow parents and reverse the steps to reconstruct a+chain. Shared prefixes are stored once across routes and namespaces.+Paths provide one shortest discovered explanation per reachable source and environment,+not an enumeration of every possible path. 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 namespace validation and the unused-key check, soit remains available if either check fails. `build.write: false` only prints the summary and writes no report.+The optional `onAnalysis(report)` callback receives the same report before validation.++`evidence` records recognized usage, dynamic-key protection and unresolved imports,+with environment, full module ID, relative file path and one-based line/column.+`unknown-namespace` records explicit namespace expressions that cannot be fully+resolved. Each route includes `unknownNamespaceSources` for reachable affected+modules, including shared boundaries, lazy dependencies, slots, and client bridges.+An empty list means no unknown expression was detected, not proof that all APIs or+dependencies were understood.+Namespace loading recognizes string literals, inline arrays/spreads of supported+values, and local/imported `const` string bindings. Const string aliases are followed+with a cycle guard. Parameters, defaults, function results, object properties and+arrays stored in variables remain unknown, even with literal types or `as const`.+No mutation/escape analysis, cross-function namespace forwarding, JSX prop tracking,+or route-policy trust exceptions are performed. Prefer a visible unknown result+over inferring runtime behavior.++## Custom translation APIs++Only official translation API names are built in. Register custom+wrappers with `adapters`, using source module paths relative to the Vite root and+zero-based argument indexes:++```ts+i18nAnalysisPlugin({+ adapters: [+ { module: 'i18n/lib.client.ts', exportName: 'useTranslation', namespaceArgument: 0 },+ {+ module: 'app/route-metadata.ts',+ exportName: 'getRouteMetadata',+ namespaceArgument: 0,+ selectorArgument: 1,+ },+ ],+})+```++`selectorArgument` identifies the key/selector argument of a direct translation+adapter. Omit it for a hook/helper returning an object with a `t` function. Imports+are matched by resolved declarations, including aliases, namespace imports and+re-exports, rather than by function name alone. Named functions and function-valued+variables are supported. A registration is an explicit forwarding contract: the+registered implementation is not scanned for translation usage. Optional+`implementationFunctions` lists additional private forwarding functions in the+same module; other functions remain analyzed. Keep contract tests for registered+wrappers and update the configuration if their behavior changes.++Dify's registrations live in `web/vite.config.ts`, including the server hook's+private `getI18nConfig` and the locale-first `getTranslation` helper. The plugin+contains no Dify wrapper paths or names. Dynamic namespace arguments are diagnosed+at call sites and fail opted-in strict validation. Runtime route Providers are not+registered as adapters. This does not infer arbitrary wrapper implementations.++## Key matching++Key matching retains TypeScript selector and finite key types, direct selectors,+static object-map lookup, and syntactic template-prefix protection. Function bodies+are not executed to infer call results; keys returned by runtime helpers protect+the relevant namespace. This deliberately accepts fewer unused-key findings.++Unresolved import warnings focus on untraceable application source imports.+External packages, explicit node_modules paths, styles, Vite assets (including+query variants), server/client boundary markers and imports introduced only by+transforms are opaque analysis boundaries, not individual warnings. This does not+allow TypeScript to fall back to stale runtime files: blocked targets stay blocked.+Local imports rewritten to virtual or external targets still produce diagnostics.+Missing key or namespace information continues to use the normal conservative+fallbacks. No dependency implementations are scanned to classify their behavior.+An empty unresolved-import list does not imply complete dependency coverage.++A dynamic key can protect an entire namespace; these records explain which calls+prevent an unused-key conclusion.++`metrics` records shared setup, per-environment resolution, Program/checker setup,+semantic analysis and route traversal durations, plus module and resolver-call+counts. `totalMs` sums work for the final environment graphs and final analysis;+it excludes superseded scan graphs, output serialization and the rest of the build,+and is not wall-clock build duration when environments run concurrently.++Catalog, exact-key/plural indexes, wildcard matches and compiler options are shared+within one analysis. Runtime template prefixes are retained even when an assertion+widens the key to every property of a JSON catalog. Identical multi-format builds in the same open bundle reuse+analysis; changes to source, transformed code or graph edges invalidate that reuse.+Closing the bundle or starting a watch rebuild clears it. Programs and type state+are not cached across environments or independent builds.## Opt-in route namespace validation@@ -59,12 +178,19 @@ subtrees. Returning `undefined` skips validation for that route; an empty arraymeans no namespaces are allowed. Any detected namespace outside the declarationfails the production build, with the route, namespace, group and source file.All four groups are checked, including lazy dependencies and parallel slots.+Set `strictNamespaces: true` to also fail declared routes whose+`unknownNamespaceSources` is nonempty. By default these routes emit an incomplete+analysis warning; unrelated unresolved imports do not automatically fail route+validation. Undeclared routes remain exempt from strict validation.Explicit, statically resolved `useTranslation` / `getTranslation` namespacearguments 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.+and client navigation. Currently only `/signin` and its descendants opt in. The+application uses the default non-strict mode: runtime providers emit+unknown warnings, while statically detected undeclared namespaces still fail.+No policy callback substitutes configured values for unknown expressions.Undeclared routes keep the full catalog and can be migrated independently.This validates statically detected usage, with the recognition and conservativediff --git a/web/plugins/vite/i18n-analysis/api.ts b/web/plugins/vite/i18n-analysis/api.tsnew file mode 100644index 00000000000..eb0b7d18ec1--- /dev/null+++ b/web/plugins/vite/i18n-analysis/api.ts@@ -0,0 +1,118 @@+import path from 'node:path'+import * as ts from 'typescript'++export type TranslationAdapter = {+ /** Source module path, relative to the Vite root. */+ module: string+ exportName: string+ namespaceArgument: number+ /** Omit for APIs returning a translation object with a t function. */+ selectorArgument?: number+ /** Additional private forwarding functions in the same source module. */+ implementationFunctions?: readonly string[]+}++type TranslationApi =+ | { kind: 'translation'; namespaceArgument: number; selectorArgument?: number }+ | { kind: 'trans' }++function declarationIdentity(root: string, node: ts.Node) {+ if (+ (!ts.isFunctionDeclaration(node) && !ts.isVariableDeclaration(node)) ||+ !node.name ||+ !ts.isIdentifier(node.name)+ )+ return+ return {+ module: path.relative(root, node.getSourceFile().fileName).replaceAll('\\', '/'),+ name: node.name.text,+ }+}++export function createTranslationApiResolver(+ root: string,+ program: ts.Program,+ adapters: readonly TranslationAdapter[],+) {+ const checker = program.getTypeChecker()+ const exportedAdapters = new Map<ts.Node, TranslationAdapter>()+ for (const adapter of adapters) {+ const source = program.getSourceFile(path.resolve(root, adapter.module))+ const module = source && checker.getSymbolAtLocation(source)+ const exported =+ module &&+ checker.getExportsOfModule(module).find((symbol) => symbol.name === adapter.exportName)+ if (!exported) continue+ const target =+ exported.flags & ts.SymbolFlags.Alias ? checker.getAliasedSymbol(exported) : exported+ for (const declaration of target.declarations ?? []) exportedAdapters.set(declaration, adapter)+ }+ function isAdapter(node: ts.Node) {+ if (exportedAdapters.has(node)) return true+ const identity = declarationIdentity(root, node)+ return (+ !!identity &&+ adapters.some(+ (adapter) =>+ adapter.module === identity.module &&+ adapter.implementationFunctions?.includes(identity.name),+ )+ )+ }+ const known = (name: string, module: string): TranslationApi | undefined => {+ if (module !== 'react-i18next') return+ if (name === 'useTranslation') return { kind: 'translation', namespaceArgument: 0 }+ if (name === 'Trans') return { kind: 'trans' }+ }+ const cache = new Map<ts.Node, TranslationApi | undefined>()+ function resolve(node: ts.Node, seen = new Set<ts.Node>()): TranslationApi | undefined {+ if (cache.has(node)) return cache.get(node)+ if (seen.has(node)) return+ const next = new Set(seen).add(node)+ const symbol = checker.getSymbolAtLocation(+ ts.isPropertyAccessExpression(node) ? node.name : node,+ )+ const declarations = symbol?.declarations ?? []+ for (const declaration of declarations) {+ if (ts.isVariableDeclaration(declaration) && declaration.initializer) {+ const api = resolve(declaration.initializer, next)+ if (api) return api+ }+ }+ if (symbol && symbol.flags & ts.SymbolFlags.Alias) {+ for (const declaration of checker.getAliasedSymbol(symbol).declarations ?? []) {+ const api = resolveDeclaration(declaration)+ if (api) return api+ if (ts.isVariableDeclaration(declaration) && declaration.initializer) {+ const aliased = resolve(declaration.initializer, next)+ if (aliased) return aliased+ }+ }+ }+ for (const declaration of declarations) {+ const api = resolveDeclaration(declaration)+ if (api) return api+ }+ }+ function resolveDeclaration(declaration: ts.Declaration): TranslationApi | undefined {+ const file = declaration.getSourceFile().fileName.replaceAll('\\', '/')+ const identity = declarationIdentity(root, declaration)+ const adapter = exportedAdapters.get(declaration)+ if (adapter)+ return {+ kind: 'translation',+ namespaceArgument: adapter.namespaceArgument,+ selectorArgument: adapter.selectorArgument,+ }+ if (file.includes('/node_modules/react-i18next/') && identity)+ return known(identity.name, 'react-i18next')+ }++ return {+ isAdapter,+ resolve(node: ts.Node) {+ if (!cache.has(node)) cache.set(node, resolve(node))+ return cache.get(node)+ },+ }+}diff --git a/web/plugins/vite/i18n-analysis/catalog.ts b/web/plugins/vite/i18n-analysis/catalog.tsnew file mode 100644index 00000000000..b3dd8f9d6b1--- /dev/null+++ b/web/plugins/vite/i18n-analysis/catalog.ts@@ -0,0 +1,50 @@+import fs from 'node:fs'+import path from 'node:path'++const PLURAL = /_(?:zero|one|two|few|many|other)$/+export const camelCase = (name: string) =>+ name.replace(/[-_]+([a-z0-9])/gi, (_, char: string) => char.toUpperCase())++export function readTranslationCatalog(root: string) {+ const directory = path.join(root, 'i18n/locales/en-US')+ const catalog = new Map<string, Set<string>>()+ const exact = new Map<string, Map<string, Set<string>>>()+ for (const file of fs+ .readdirSync(directory)+ .filter((file) => file.endsWith('.json'))+ .sort()) {+ const content: unknown = JSON.parse(fs.readFileSync(path.join(directory, file), 'utf8'))+ if (!content || typeof content !== 'object' || Array.isArray(content))+ throw new Error(`Invalid translation catalog: ${file}`)+ const namespace = camelCase(file.slice(0, -5))+ const keys = new Set(Object.keys(content))+ catalog.set(namespace, keys)+ const index = new Map<string, Set<string>>()+ for (const key of keys) {+ for (const lookup of new Set([key, key.replace(PLURAL, '')])) {+ const matches = index.get(lookup) ?? new Set<string>()+ matches.add(key)+ index.set(lookup, matches)+ }+ }+ exact.set(namespace, index)+ }+ const patterns = new Map<string, Map<string, string[]>>()+ return {+ catalog,+ match(namespace: string, text: string, wildcard: boolean): Iterable<string> {+ if (!wildcard) return exact.get(namespace)?.get(text) ?? []+ const cached = patterns.get(namespace) ?? new Map<string, string[]>()+ let matches = cached.get(text)+ if (!matches) {+ const regex = new RegExp(`^${text}$`)+ matches = [...(catalog.get(namespace) ?? [])].filter(+ (key) => regex.test(key) || regex.test(key.replace(PLURAL, '')),+ )+ cached.set(text, matches)+ patterns.set(namespace, cached)+ }+ return matches+ },+ }+}diff --git a/web/plugins/vite/i18n-analysis/compiler.ts b/web/plugins/vite/i18n-analysis/compiler.tsnew file mode 100644index 00000000000..b53c0ae26f0--- /dev/null+++ b/web/plugins/vite/i18n-analysis/compiler.ts@@ -0,0 +1,372 @@+import path from 'node:path'+import * as ts from 'typescript'++type ModuleResolution = { id: string | null; diagnostic: boolean }+export type ModuleResolutions = ReadonlyMap<string, ReadonlyMap<string, ModuleResolution>>++// Resolve in Vite's environment before creating the synchronous TypeScript host.+// Read surviving imports from Vite's transformed code so erased type imports+// never reach the runtime resolver. Only collected source modules override TS+// resolution; packages and type-only dependencies still use TS declarations.+type ImportBinding = { specifier: string; signature: string; typeOnly: boolean; locals: string[] }++function importBindings(code: string): ImportBinding[] {+ const source = ts.createSourceFile(+ 'module.tsx',+ code,+ ts.ScriptTarget.Latest,+ true,+ ts.ScriptKind.TSX,+ )+ const result: ImportBinding[] = []+ for (const statement of source.statements) {+ if (ts.isImportDeclaration(statement) && ts.isStringLiteral(statement.moduleSpecifier)) {+ const clause = statement.importClause+ const bindings = clause?.namedBindings+ const names =+ bindings && ts.isNamedImports(bindings)+ ? bindings.elements+ .filter((element) => !element.isTypeOnly)+ .map(+ (element) =>+ `${element.propertyName?.text ?? element.name.text}:${element.name.text}`,+ )+ .sort()+ : bindings && ts.isNamespaceImport(bindings)+ ? [`*:${bindings.name.text}`]+ : []+ result.push({+ specifier: statement.moduleSpecifier.text,+ signature: JSON.stringify(['import', clause?.name?.text, names]),+ locals: [+ ...(clause?.name ? [clause.name.text] : []),+ ...(bindings && ts.isNamedImports(bindings)+ ? bindings.elements+ .filter((element) => !element.isTypeOnly)+ .map((element) => element.name.text)+ : bindings+ ? [bindings.name.text]+ : []),+ ],+ typeOnly:+ !!clause?.isTypeOnly ||+ !!(+ bindings &&+ ts.isNamedImports(bindings) &&+ bindings.elements.length &&+ !names.length &&+ !clause?.name+ ),+ })+ }+ if (+ ts.isExportDeclaration(statement) &&+ statement.moduleSpecifier &&+ ts.isStringLiteral(statement.moduleSpecifier)+ ) {+ result.push({+ specifier: statement.moduleSpecifier.text,+ signature: JSON.stringify([+ 'export',+ !statement.exportClause+ ? ['all']+ : ts.isNamespaceExport(statement.exportClause)+ ? ['namespace', statement.exportClause.name.text]+ : [+ 'named',+ statement.exportClause.elements+ .filter((element) => !element.isTypeOnly)+ .map((element) =>+ JSON.stringify([+ (element.propertyName ?? element.name).text,+ element.name.text,+ ]),+ )+ .sort(),+ ],+ ]),+ locals: [],+ typeOnly:+ statement.isTypeOnly ||+ !!(+ statement.exportClause &&+ ts.isNamedExports(statement.exportClause) &&+ statement.exportClause.elements.length > 0 &&+ statement.exportClause.elements.every((element) => element.isTypeOnly)+ ),+ })+ }+ }+ function visit(node: ts.Node) {+ if (+ ts.isCallExpression(node) &&+ node.expression.kind === ts.SyntaxKind.ImportKeyword &&+ node.arguments[0] &&+ ts.isStringLiteralLike(node.arguments[0])+ ) {+ const specifier = node.arguments[0].text+ // Dynamic imports have no stable local binding after arbitrary transforms.+ // Do not pair them by position: rewrites may reorder, split or inline calls.+ result.push({+ specifier,+ signature: JSON.stringify(['dynamic', specifier]),+ typeOnly: false,+ locals: [],+ })+ }+ ts.forEachChild(node, visit)+ }+ visit(source)+ return result+}++export function hasClientDirective(code: string) {+ if (!code.includes('use client')) return false+ const source = ts.createSourceFile(+ 'module.tsx',+ code,+ ts.ScriptTarget.Latest,+ false,+ ts.ScriptKind.TSX,+ )+ for (const statement of source.statements) {+ if (!ts.isExpressionStatement(statement) || !ts.isStringLiteral(statement.expression)) break+ if (statement.expression.text === 'use client') return true+ }+ return false+}++export async function resolveTranslationImports(+ modules: ReadonlyMap<string, string>,+ compiled: ReadonlyMap<string, string>,+ resolve: (+ specifier: string,+ importer: string,+ ) => Promise<{ id: string; external?: boolean } | undefined>,+ isAsset: (specifier: string) => boolean = () => false,+) {+ const resolutions = new Map<string, Map<string, ModuleResolution>>()+ let resolveCalls = 0+ await Promise.all(+ [...modules].map(async ([id, source]) => {+ const imports = new Map<string, string | null>()+ const code = compiled.get(id) ?? ''+ const surviving = new Set(+ ts.preProcessFile(code, true, true).importedFiles.map((file) => file.fileName),+ )+ const targets = new Map<string, string | undefined>()+ const declarationImports = new Set<string>()+ const externalImports = new Set<string>()+ await Promise.all(+ [...surviving].map(async (specifier) => {+ resolveCalls+++ const resolved = await resolve(specifier, id)+ targets.set(specifier, resolved?.id)+ if (+ !/^[.#/]/.test(specifier) &&+ !specifier.startsWith('@/') &&+ (resolved?.external || resolved?.id.includes('/node_modules/'))+ )+ externalImports.add(specifier)+ const packageName = specifier.startsWith('@')+ ? specifier.split('/').slice(0, 2).join('/')+ : specifier.split('/')[0]!+ // A bare external package or its resolved node_modules implementation+ // may use TS declarations. Virtual/local replacements must not fall back.+ if (+ !/^[.#/]/.test(specifier) &&+ !specifier.startsWith('@/') &&+ (resolved?.id.includes(`/node_modules/${packageName}/`) ||+ (resolved?.external && resolved.id === specifier))+ )+ declarationImports.add(specifier)+ }),+ )+ for (const [specifier, target] of targets) {+ if (target && modules.has(target)) imports.set(specifier, target)+ else if (!declarationImports.has(specifier) && !isAsset(specifier))+ imports.set(specifier, null)+ }+ const before = importBindings(source)+ const after = importBindings(code)+ const proposals = new Map<string, Set<string | null | undefined>>()+ const record = (specifier: string, target: string | null | undefined) => {+ const values = proposals.get(specifier) ?? new Set<string | null | undefined>()+ values.add(target)+ proposals.set(specifier, values)+ }+ for (const binding of before) {+ if (binding.typeOnly || isAsset(binding.specifier)) continue+ const sameBinding = (candidate: ImportBinding) =>+ !candidate.typeOnly &&+ candidate.specifier === binding.specifier &&+ candidate.signature === binding.signature+ const originalCount = before.filter(sameBinding).length+ const survivingCount = after.filter(sameBinding).length+ if (originalCount === survivingCount) {+ record(binding.specifier, imports.get(binding.specifier))+ continue+ }+ // Barrel optimizers may split named imports into per-binding default+ // imports. Preserve TS declarations only if every binding still comes+ // from the same external package; local rewrites remain strict.+ const packageName = binding.specifier.startsWith('@')+ ? binding.specifier.split('/').slice(0, 2).join('/')+ : binding.specifier.split('/')[0]!+ const externalBindings =+ !/^[.#/]/.test(binding.specifier) &&+ !binding.specifier.startsWith('@/') &&+ binding.locals.length > 0 &&+ binding.locals.every((local) =>+ after.some((candidate) => {+ const target = targets.get(candidate.specifier)+ return (+ candidate.locals.includes(local) &&+ target?.includes(`/node_modules/${packageName}/`) &&+ !modules.has(target)+ )+ }),+ )+ if (externalBindings) {+ record(binding.specifier, undefined)+ continue+ }+ const candidates = after.filter(+ (candidate) => !candidate.typeOnly && candidate.signature === binding.signature,+ )+ const replacement =+ originalCount === 1 && candidates.length === 1+ ? targets.get(candidates[0]!.specifier)+ : undefined+ record(binding.specifier, replacement && modules.has(replacement) ? replacement : null)+ }+ // The TS host resolves by module specifier, not by import occurrence. If+ // bindings using one specifier diverge, block all rather than use a stale target.+ for (const [specifier, values] of proposals) {+ if (values.size > 1 || values.has(null)) imports.set(specifier, null)+ else {+ const [target] = values+ if (target !== undefined) imports.set(specifier, target)+ else imports.delete(specifier)+ }+ }+ // Resolution and diagnostics have different scopes: opaque dependencies+ // still block stale disk fallback, but only source imports need warnings.+ const sourceImports = new Set(+ before.filter((binding) => !binding.typeOnly).map((binding) => binding.specifier),+ )+ resolutions.set(+ id,+ new Map(+ [...imports].map(([specifier, target]) => [+ specifier,+ {+ id: target,+ diagnostic:+ target === null &&+ sourceImports.has(specifier) &&+ !externalImports.has(specifier) &&+ !specifier.includes('/node_modules/') &&+ specifier !== 'server-only' &&+ specifier !== 'client-only' &&+ !/\.(?:css|scss|sass|less|styl)(?:\?|$)/.test(specifier) &&+ !isAsset(specifier.split('?')[0]!),+ },+ ]),+ ),+ )+ }),+ )+ return { resolutions, resolveCalls }+}++export function readCompilerOptions(root: string): ts.CompilerOptions {+ const configPath = ts.findConfigFile(root, ts.sys.fileExists)+ const config = configPath ? ts.readConfigFile(configPath, ts.sys.readFile) : undefined+ if (config?.error)+ throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))+ const options =+ configPath && config+ ? ts.parseJsonConfigFileContent(+ config.config,+ { ...ts.sys, readDirectory: () => [] },+ path.dirname(configPath),+ ).options+ : {}+ return {+ ...options,+ allowJs: true,+ jsx: ts.JsxEmit.ReactJSX,+ noEmit: true,+ skipLibCheck: true,+ }+}++export function createTranslationProgram(+ root: string,+ modules: ReadonlyMap<string, string>,+ resolutions: ModuleResolutions,+ compilerOptions = readCompilerOptions(root),+) {+ // TypeScript needs recognizable extensions. Give query variants distinct,+ // in-memory filenames in the same directory, retaining their Vite identities.+ const fileNames = new Map<string, string>()+ const moduleIds = new Map<string, string>()+ const sources = new Map<string, string>()+ for (const [id, source] of modules) {+ const file = id.split('?')[0]!+ let fileName = id.endsWith('.json') ? `${id}.__dify_i18n.ts` : id+ if (id !== file) {+ fileName = `${file}.__dify_i18n_${fileNames.size}${path.extname(file)}`+ while (modules.has(fileName) || moduleIds.has(fileName))+ fileName = `${fileName}${path.extname(file)}`+ }+ fileNames.set(id, fileName)+ moduleIds.set(fileName, id)+ sources.set(fileName, source)+ }+ const host = ts.createCompilerHost(compilerOptions)+ const readFile = host.readFile.bind(host)+ host.readFile = (file) => sources.get(file) ?? readFile(file)+ const fileExists = host.fileExists.bind(host)+ host.fileExists = (file) => sources.has(file) || fileExists(file)+ const getSourceFile = host.getSourceFile.bind(host)+ host.getSourceFile = (file, languageVersion, onError, shouldCreateNewSourceFile) => {+ const source = sources.get(file)+ return source === undefined+ ? getSourceFile(file, languageVersion, onError, shouldCreateNewSourceFile)+ : ts.createSourceFile(file, source, languageVersion, true)+ }+ const cache = ts.createModuleResolutionCache(root, host.getCanonicalFileName, compilerOptions)+ host.resolveModuleNameLiterals = (+ literals,+ containingFile,+ redirectedReference,+ options,+ containingSourceFile,+ ) =>+ literals.map((literal) => {+ const importer = moduleIds.get(containingFile)+ const resolvedId = importer && resolutions.get(importer)?.get(literal.text)?.id+ if (resolvedId === null) return { resolvedModule: undefined }+ const resolvedFileName = resolvedId && fileNames.get(resolvedId)+ if (resolvedFileName) {+ const extension = Object.values(ts.Extension).find((extension) =>+ resolvedFileName.endsWith(extension),+ )+ return { resolvedModule: { resolvedFileName, extension: extension ?? ts.Extension.Ts } }+ }+ return ts.resolveModuleName(+ literal.text,+ containingFile,+ options,+ host,+ cache,+ redirectedReference,+ ts.getModeForUsageLocation(containingSourceFile, literal, options),+ )+ })+ const roots = [...fileNames].filter(([id]) => !id.endsWith('.json')).map(([, file]) => file)+ const program = ts.createProgram(roots, compilerOptions, host)+ return { program, fileNames }+}diff --git a/web/plugins/vite/i18n-analysis/graph.ts b/web/plugins/vite/i18n-analysis/graph.tsindex dd06df4cae8..0fb61d0a464 100644--- a/web/plugins/vite/i18n-analysis/graph.ts+++ b/web/plugins/vite/i18n-analysis/graph.ts@@ -1,11 +1,12 @@-import fs from 'node:fs'+import type { TranslationAdapter } from './api'+import type { ModuleResolutions } from './compiler'import path from 'node:path'import * as ts from 'typescript'+import { createTranslationApiResolver } from './api'+import { camelCase, readTranslationCatalog } from './catalog'+import { createTranslationProgram, readCompilerOptions } from './compiler'-const PLURAL = /_(?:zero|one|two|few|many|other)$/const MAX_VALUES = 200-const camelCase = (name: string) =>- name.replace(/[-_]+([a-z0-9])/gi, (_, char: string) => char.toUpperCase())const escapeRegex = (text: string) => text.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')type Translation = { namespaces: string[]; prefix: string; argument: number }@@ -52,53 +53,78 @@ function initializer(node: ts.Node): Value | undefined {if (ts.isFunctionDeclaration(node) && node.body) return node}-// Only module IDs supplied by Vite are visited. Type dependencies inform static-// expressions but never contribute usage merely by existing on disk.-export function checkTranslationGraph(root: string, modules: ReadonlyMap<string, string>) {- const catalog = new Map<string, Set<string>>()- const directory = path.join(root, 'i18n/locales/en-US')- for (const file of fs- .readdirSync(directory)- .filter((file) => file.endsWith('.json'))- .sort()) {- const content: unknown = JSON.parse(fs.readFileSync(path.join(directory, file), 'utf8'))- if (!content || typeof content !== 'object' || Array.isArray(content))- throw new Error(`Invalid translation catalog: ${file}`)- catalog.set(camelCase(file.slice(0, -5)), new Set(Object.keys(content)))- }- const configPath = ts.findConfigFile(root, ts.sys.fileExists)- const config = configPath ? ts.readConfigFile(configPath, ts.sys.readFile) : undefined- if (config?.error)- throw new Error(ts.flattenDiagnosticMessageText(config.error.messageText, '\n'))- const options =- configPath && config- ? ts.parseJsonConfigFileContent(- config.config,- { ...ts.sys, readDirectory: () => [] },- path.dirname(configPath),- ).options- : {}- const compilerOptions: ts.CompilerOptions = {- ...options,- allowJs: true,- jsx: ts.JsxEmit.ReactJSX,- noEmit: true,- skipLibCheck: true,+export type AnalysisEvidence = {+ kind: 'usage' | 'dynamic-key' | 'unresolved-import' | 'unknown-namespace'+ moduleId: string+ file: string+ line: number+ column: number+ namespaces: string[]+ message: string+ import?: {+ specifier: string+ kind: 'style' | 'asset' | 'package' | 'virtual' | 'source'+ origin: 'source' | 'generated'}- const host = ts.createCompilerHost(compilerOptions)- const readFile = host.readFile.bind(host)- host.readFile = (file) => modules.get(file) ?? readFile(file)- const fileExists = host.fileExists.bind(host)- host.fileExists = (file) => modules.has(file) || fileExists(file)- const getSourceFile = host.getSourceFile.bind(host)- host.getSourceFile = (file, languageVersion, onError, shouldCreateNewSourceFile) => {- const source = modules.get(file)- return source === undefined- ? getSourceFile(file, languageVersion, onError, shouldCreateNewSourceFile)- : ts.createSourceFile(file, source, languageVersion, true)+}++export function createAnalysisContext(root: string, adapters: readonly TranslationAdapter[] = []) {+ return {+ adapters,+ translations: readTranslationCatalog(root),+ compilerOptions: readCompilerOptions(root),}- const program = ts.createProgram([...modules.keys()], compilerOptions, host)+}++// Only module IDs supplied by Vite are visited. Type dependencies inform static+// expressions but never contribute usage merely by existing on disk.+export function checkTranslationGraph(+ root: string,+ modules: ReadonlyMap<string, string>,+ resolutions: ModuleResolutions = new Map(),+ context = createAnalysisContext(root),+) {+ const { catalog } = context.translations+ const programStarted = performance.now()+ const { program, fileNames } = createTranslationProgram(+ root,+ modules,+ resolutions,+ context.compilerOptions,+ )const checker = program.getTypeChecker()+ const programMs = performance.now() - programStarted+ const analysisStarted = performance.now()+ const { resolve: translationApi, isAdapter } = createTranslationApiResolver(+ root,+ program,+ context.adapters,+ )+ const evidence = new Map<string, AnalysisEvidence>()+ let currentModule = ''+ let currentSite: ts.Node | undefined+ function explain(+ kind: AnalysisEvidence['kind'],+ namespaces: string[],+ message: string,+ importInfo?: AnalysisEvidence['import'],+ ) {+ if (!currentSite) return+ const location = currentSite+ .getSourceFile()+ .getLineAndCharacterOfPosition(currentSite.getStart())+ const item = {+ kind,+ moduleId: currentModule,+ file: path.relative(root, currentModule.split('?')[0]!).replaceAll('\\', '/'),+ line: location.line + 1,+ column: location.character + 1,+ namespaces: [...namespaces].sort(),+ message,+ ...(importInfo ? { import: importInfo } : {}),+ }+ evidence.set(JSON.stringify(item), item)+ }const used = new Map<string, Set<string>>()const protectedNamespaces = new Set<string>()const moduleNamespaces = new Map<string, Set<string>>()@@ -124,31 +150,6 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,const next = new Set(seen).add(node)if (ts.isConditionalExpression(node))return [...alternatives(node.whenTrue, next), ...alternatives(node.whenFalse, next)]- if (ts.isCallExpression(node)) {- for (const fn of alternatives(node.expression, next)) {- if (- !fn ||- !(- ts.isArrowFunction(fn) ||- ts.isFunctionExpression(fn) ||- ts.isFunctionDeclaration(fn)- ) ||- !fn.body- )- continue- const body = ts.isBlock(fn.body)- ? fn.body.statements.length === 1 && ts.isReturnStatement(fn.body.statements[0]!)- ? fn.body.statements[0]!.expression- : undefined- : fn.body- if (!body) continue- const returned = unwrap(body)- const index = fn.parameters.findIndex(- (parameter) => parameter.name.getText() === returned.getText(),- )- if (index >= 0 && node.arguments[index]) return alternatives(node.arguments[index]!, next)- }- }if (ts.isIdentifier(node)) {if (node.text === 'undefined') return []const values = declarations(node)@@ -197,6 +198,7 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,if (!expression) returnconst node = unwrap(expression)if (ts.isStringLiteralLike(node)) return [node.text]+ if (ts.isCallExpression(node)) return undefinedif (ts.isArrayLiteralExpression(node)) {const values = node.elements.map((element) => strings(element))return values.every((value) => value !== undefined) ? values.flat() : undefined@@ -212,6 +214,7 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,const node = unwrap(expression)if (!ts.isObjectLiteralExpression(node)) returnfor (const member of node.properties) {+ if (ts.isShorthandPropertyAssignment(member) && member.name.text === name) return member.nameif (ts.isPropertyAssignment(member) &&member.name.getText().replace(/^['"]|['"]$/g, '') === name@@ -268,12 +271,12 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,if (ts.isVariableDeclaration(variable) && variable.initializer) {const call = unwrap(variable.initializer)if (ts.isCallExpression(call)) {- const name = call.expression.getText()- if (/(?:^|\.)(?:useTranslation|getTranslation)$/.test(name)) {- const nsIndex = name.endsWith('getTranslation') ? 1 : 0+ const api = translationApi(call.expression)+ if (api?.kind === 'translation' && api.selectorArgument === undefined) {+ const nsIndex = api.namespaceArgumentreturn {namespaces:- strings(call.arguments[nsIndex]) ??+ (call.arguments[nsIndex] && namespaceStrings(call.arguments[nsIndex]!)) ??(call.arguments[nsIndex] ? [...catalog.keys()] : ['app']),prefix: strings(property(call.arguments[nsIndex + 1], 'keyPrefix'))?.[0] ?? '',argument: 0,@@ -315,9 +318,16 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,function keyPatterns(expression: ts.Expression): Key[] {const node = unwrap(expression)- if (ts.isCallExpression(node)) {+ if (ts.isCallExpression(node)) return [{ text: '.*', wildcard: true }]+ if (ts.isIdentifier(node)) {const values = alternatives(node)- if (values.some((value) => value !== node)) {+ if (+ values.some((value) => value !== node) &&+ values.some(+ (value) =>+ value && !ts.isFunctionDeclaration(value) && ts.isTemplateExpression(unwrap(value)),+ )+ ) {return values.flatMap((value) =>value && !ts.isFunctionDeclaration(value)? keyPatterns(value)@@ -325,7 +335,7 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,)}}- const values = strings(expression)+ const values = ts.isTemplateExpression(node) ? undefined : strings(expression)if (values) return values.map((text) => ({ text }))if ((ts.isAsExpression(expression) || ts.isTypeAssertionExpression(expression)) &&@@ -424,16 +434,26 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,if (!catalog.has(namespace)) continueif (key.wildcard && text === '.*' && !info.prefix) {protectedNamespaces.add(namespace)+ explain(+ 'dynamic-key',+ [namespace],+ 'The key cannot be narrowed; every key in this namespace is protected.',+ )continue}const prefix = info.prefix ? `${info.prefix}.` : ''- const pattern = key.wildcard ? new RegExp(`^${escapeRegex(prefix)}${text}$`) : undefined- const matches = (candidate: string) =>- pattern ? pattern.test(candidate) : candidate === prefix + textconst kept = used.get(namespace) ?? new Set<string>()- for (const candidate of catalog.get(namespace)!) {- if (matches(candidate) || matches(candidate.replace(PLURAL, ''))) kept.add(candidate)- }+ const matches = context.translations.match(+ namespace,+ key.wildcard ? `${escapeRegex(prefix)}${text}` : prefix + text,+ !!key.wildcard,+ )+ for (const candidate of matches) kept.add(candidate)+ explain(+ 'usage',+ [namespace],+ key.wildcard ? `Static key pattern: ${prefix}${text}` : `Static key: ${prefix}${text}`,+ )used.set(namespace, kept)}}@@ -456,34 +476,69 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,) {record(selectorKeys(value), info)} else {- record(- value && !ts.isFunctionDeclaration(value)- ? keyPatterns(value)- : [{ text: '.*', wildcard: true }],- info,- )+ record(value ? keyPatterns(value) : [{ text: '.*', wildcard: true }], info)}}}- function recordLoadedNamespaces(expression: ts.Expression, seen = new Set<ts.Node>()) {+ // Namespace values are deliberately narrower than key/type matching. Only+ // inline arrays and immutable string bindings are concrete loading evidence.+ function namespaceValues(+ expression: ts.Expression,+ seen = new Set<ts.Node>(),+ allowArray = true,+ ): { namespaces: string[]; unknown: boolean } {+ const unknown = { namespaces: [], unknown: true }const node = unwrap(expression)- if (seen.has(node)) return+ if (seen.has(node)) return unknownconst 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)+ if (ts.isStringLiteralLike(node)) return { namespaces: [node.text], unknown: false }+ if (allowArray && ts.isArrayLiteralExpression(node)) {+ const values = node.elements.map((element) => namespaceValues(element, next))+ return {+ namespaces: values.flatMap((value) => value.namespaces),+ unknown: values.some((value) => value.unknown),}}+ if (allowArray && ts.isSpreadElement(node)) return namespaceValues(node.expression, next)+ if (+ !ts.isIdentifier(node) &&+ !ts.isPropertyAccessExpression(node) &&+ !ts.isElementAccessExpression(node)+ )+ return unknown+ const values = declarations(node).filter(ts.isVariableDeclaration)+ if (!values.length) return unknown+ const resolved = values.map((declaration) =>+ ts.isVariableDeclarationList(declaration.parent) &&+ declaration.parent.flags & ts.NodeFlags.Const &&+ declaration.initializer+ ? namespaceValues(declaration.initializer, next, false)+ : unknown,+ )+ return {+ namespaces: resolved.flatMap((value) => value.namespaces),+ unknown: resolved.some((value) => value.unknown),+ }+ }+ function namespaceStrings(expression: ts.Expression): string[] {+ const { namespaces, unknown } = namespaceValues(expression)+ // Unknown values may select any catalog namespace. Preserve known values+ // outside the catalog too, so route validation still sees those requests.+ return unknown ? [...new Set([...namespaces, ...catalog.keys()])] : namespaces+ }+ function recordLoadedNamespaces(expression: ts.Expression): boolean {+ const { namespaces, unknown } = namespaceValues(expression)+ for (const namespace of namespaces) {+ currentNamespaces.add(namespace)+ explain('usage', [namespace], 'Explicit namespace load.')+ }+ return !unknown}function visit(node: ts.Node) {+ if (isAdapter(node)) return+ currentSite = nodeif (ts.isStringLiteralLike(node) && (node.text.includes('.') || node.text.includes(':'))) {const contextual = checker.getContextualType(node)const values = contextual && literalTypes(contextual)@@ -496,20 +551,43 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,}}if (ts.isCallExpression(node)) {- const name = node.expression.getText()- if (/(?:^|\.)(?:useTranslation|getTranslation)$/.test(name)) {+ currentSite = node+ const api = translationApi(node.expression)+ if (api?.kind === 'translation') {// 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 nsIndex = api.namespaceArgumentconst argument = node.arguments[nsIndex]- if (argument) recordLoadedNamespaces(argument)+ if (argument && !recordLoadedNamespaces(argument))+ explain(+ 'unknown-namespace',+ [],+ 'Only literal namespaces, inline arrays and const string bindings are resolved; runtime values remain unknown.',+ )}- const info = translation(node.expression, node)+ const info =+ api?.kind === 'translation' && api.selectorArgument !== undefined+ ? {+ namespaces: (node.arguments[api.namespaceArgument] &&+ namespaceStrings(node.arguments[api.namespaceArgument]!)) || [...catalog.keys()],+ prefix: '',+ argument: api.selectorArgument,+ }+ : translation(node.expression, node)const argument = info && node.arguments[info.argument]if (info && argument) {- const options = node.arguments.at(-1)+ const options =+ api?.kind === 'translation' && api.selectorArgument !== undefined+ ? undefined+ : node.arguments.at(-1)const namespaceOption = property(options, 'ns')- const namespaces = strings(namespaceOption)+ const namespaces = namespaceOption && namespaceStrings(namespaceOption)+ if (namespaceOption && namespaceValues(namespaceOption).unknown)+ explain(+ 'unknown-namespace',+ [],+ 'The translation namespace cannot be narrowed to finite values.',+ )consume(argument, {...info,namespaces: namespaces ?? (namespaceOption ? [...catalog.keys()] : info.namespaces),@@ -518,8 +596,9 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,}if ((ts.isJsxSelfClosingElement(node) || ts.isJsxOpeningElement(node)) &&- node.tagName.getText() === 'Trans'+ translationApi(node.tagName)?.kind === 'trans') {+ currentSite = nodeconst attributes = new Map<string, ts.Expression>()for (const attribute of node.attributes.properties) {if (!ts.isJsxAttribute(attribute) || !attribute.initializer) continue@@ -529,10 +608,13 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,if (value) attributes.set(attribute.name.getText(), value)}const key = attributes.get('i18nKey')+ if (attributes.has('ns') && namespaceValues(attributes.get('ns')!).unknown)+ explain('unknown-namespace', [], 'The Trans namespace cannot be narrowed to finite values.')if (key)consume(key, {namespaces:- strings(attributes.get('ns')) ?? (attributes.has('ns') ? [...catalog.keys()] : ['app']),+ (attributes.get('ns') && namespaceStrings(attributes.get('ns')!)) ??+ (attributes.has('ns') ? [...catalog.keys()] : ['app']),prefix: '',argument: 0,})@@ -540,10 +622,46 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,ts.forEachChild(node, visit)}for (const id of modules.keys()) {- const source = program.getSourceFile(id)+ if (id.endsWith('.json')) continue+ currentModule = id+ const source = program.getSourceFile(fileNames.get(id)!)currentNamespaces = new Set<string>()moduleNamespaces.set(id, currentNamespaces)- if (source) visit(source)+ if (source) {+ const sourceImports = new Set(+ ts.preProcessFile(source.text, true, true).importedFiles.map((item) => item.fileName),+ )+ for (const [specifier, resolved] of resolutions.get(id) ?? []) {+ if (!resolved.diagnostic) continue+ currentSite =+ source.statements.find(+ (statement) =>+ ts.isImportDeclaration(statement) &&+ ts.isStringLiteral(statement.moduleSpecifier) &&+ statement.moduleSpecifier.text === specifier,+ ) ?? source+ explain(+ 'unresolved-import',+ [],+ `Cannot trace runtime import ${specifier} after transforms; the original file was not used as a fallback.`,+ {+ specifier,+ kind: /\.(?:css|scss|sass|less|styl)(?:\?|$)|vite-rsc\/css/.test(specifier)+ ? 'style'+ : /\.(?:svg|png|jpe?g|webp|gif|ico|woff2?)(?:\?|$)/.test(specifier)+ ? 'asset'+ : specifier.startsWith('\0') || specifier.startsWith('virtual:')+ ? 'virtual'+ : specifier.includes('/node_modules/') ||+ /^(?:@[^/]+\/[^/]+|[\w-]+)(?:\/|$)/.test(specifier)+ ? 'package'+ : 'source',+ origin: sourceImports.has(specifier) ? 'source' : 'generated',+ },+ )+ }+ visit(source)+ }}const unused: Record<string, string[]> = {}for (const [namespace, keys] of catalog) {@@ -553,8 +671,9 @@ export function checkTranslationGraph(root: string, modules: ReadonlyMap<string,}return {unused,+ evidence: [...evidence.values()],+ timings: { programMs, analysisMs: performance.now() - analysisStarted },protectedNamespaces: [...protectedNamespaces].sort(),- moduleCount: modules.size,moduleNamespaces,}}diff --git a/web/plugins/vite/i18n-analysis/routes.ts b/web/plugins/vite/i18n-analysis/routes.tsindex ce3ee43814c..a2bc6d0395f 100644--- a/web/plugins/vite/i18n-analysis/routes.ts+++ b/web/plugins/vite/i18n-analysis/routes.ts@@ -1,28 +1,37 @@import path from 'node:path'export type ModuleDependencies = { static: Set<string>; dynamic: Set<string> }-type NamespaceSources = { namespace: string; sources: string[] }+export type ModuleLocation = { environment: string; moduleId: string }+type NamespaceSources = {+ namespace: string+ sources: string[]+ dependencyPaths?: number[]+}export type RouteNamespaceReport = {route: stringpage: stringnamespaces: string[]+ unknownNamespaceSources?: string[]groups: Record<'page' | 'shared' | 'lazy' | 'slots', NamespaceSources[]>}export function validateRouteNamespaces(routes: readonly RouteNamespaceReport[],getDeclaredNamespaces: (route: string) => readonly string[] | undefined,+ strictNamespaces = false,) {const violations: string[] = []for (const report of routes) {const declared = getDeclaredNamespaces(report.route)if (declared === undefined) continueconst missing = report.namespaces.filter((namespace) => !declared.includes(namespace))- if (!missing.length) continue+ const unknown = strictNamespaces ? (report.unknownNamespaceSources ?? []) : []+ if (!missing.length && !unknown.length) continueviolations.push(` ${report.route} (${report.page})`,` Declared: ${declared.join(', ') || '(none)'}`,)+ for (const source of unknown) violations.push(` Cannot verify namespace usage: ${source}`)for (const namespace of missing) {violations.push(` Undeclared namespace: ${namespace}`)for (const [group, entries] of Object.entries(report.groups)) {@@ -49,24 +58,40 @@ export function analyzeRouteNamespaces(root: string,dependencies: ReadonlyMap<string, ModuleDependencies>,usage: ReadonlyMap<string, ReadonlySet<string>>,+ options: {+ sourcePath?: (id: string) => string+ entries?: ReadonlySet<string>+ unknownNamespaces?: ReadonlySet<string>+ recordPath?: (id: string, parent: number | null) => number+ } = {},): RouteNamespaceReport[] {+ const sourcePath = (id: string) => (options.sourcePath?.(id) ?? id).split('?')[0]!const app = `${root.replaceAll('\\', '/')}/app/`- const files = [...usage.keys()].filter((file) => file.startsWith(app))+ const files = [...usage.keys()].filter(+ (file) => sourcePath(file).startsWith(app) && (!options.entries || options.entries.has(file)),+ )const boundaries = files.filter((file) =>- /\/(?:layout|template|loading|error|not-found|global-error)\.[jt]sx?$/.test(file),+ /\/(?:layout|template|loading|error|not-found|global-error)\.[jt]sx?$/.test(sourcePath(file)),)+ const reachability = new Map<+ string,+ { modules: Set<string>; parents: Map<string, string | null> }+ >()return files- .filter((file) => /\/page\.[jt]sx?$/.test(file))+ .filter((file) => /\/page\.[jt]sx?$/.test(sourcePath(file))).sort().map((page) => {- const segments = page.slice(app.length).split('/').slice(0, -1)+ const segments = sourcePath(page).slice(app.length).split('/').slice(0, -1)+ const route = `/${segments.filter((segment) => !/^\([^)]*\)$/.test(segment) && !segment.startsWith('@')).join('/')}`const ancestors = new Set([app.slice(0, -1)])for (let i = 1; i <= segments.length; i++) ancestors.add(app + segments.slice(0, i).join('/'))- const sharedEntries = boundaries.filter((file) => ancestors.has(path.posix.dirname(file)))+ const sharedEntries = boundaries.filter((file) =>+ ancestors.has(path.posix.dirname(sourcePath(file))),+ )const slotEntries: string[] = []// Parallel slots can retain previously active pages on navigation.for (const file of files) {- const parts = file.slice(app.length).split('/')+ const parts = sourcePath(file).slice(app.length).split('/')if (parts.some((part, index) =>@@ -76,27 +101,56 @@ export function analyzeRouteNamespaces()slotEntries.push(file)}- function reachable(entries: string[], includeDynamic: boolean) {+ function reachable(entries: string[], includeDynamic: boolean, cache = false) {+ const key = JSON.stringify([includeDynamic, [...entries].sort()])+ const cached = cache && reachability.get(key)+ if (cached) return cachedconst visited = new Set<string>()const pending = [...entries]- while (pending.length) {- const id = pending.pop()!+ const parents = new Map<string, string | null>(entries.map((id) => [id, null]))+ for (let cursor = 0; cursor < pending.length; cursor++) {+ const id = pending[cursor]!if (visited.has(id)) continuevisited.add(id)const imports = dependencies.get(id)- for (const dependency of imports?.static ?? []) pending.push(dependency)- if (includeDynamic)- for (const dependency of imports?.dynamic ?? []) pending.push(dependency)+ for (const dependency of [+ ...(imports?.static ?? []),+ ...(includeDynamic ? (imports?.dynamic ?? []) : []),+ ]) {+ if (parents.has(dependency)) continue+ parents.set(dependency, id)+ pending.push(dependency)+ }}- return visited+ const result = { modules: visited, parents }+ if (cache) reachability.set(key, result)+ return result}- function sources(modules: Set<string>): NamespaceSources[] {+ function sources(+ modules: Set<string>,+ parents: Map<string, string | null>,+ ): NamespaceSources[] {+ const paths = new Map<string, Set<number>>()+ const recorded = new Map<string, number>()+ function recordPath(id: string): number {+ const existing = recorded.get(id)+ if (existing !== undefined) return existing+ const parent = parents.get(id)+ const index = options.recordPath!(id, parent ? recordPath(parent) : null)+ recorded.set(id, index)+ return index+ }const byNamespace = new Map<string, Set<string>>()for (const id of modules) {for (const namespace of usage.get(id) ?? []) {const files = byNamespace.get(namespace) ?? new Set<string>()- files.add(path.posix.relative(root.replaceAll('\\', '/'), id))+ files.add(path.posix.relative(root.replaceAll('\\', '/'), sourcePath(id)))byNamespace.set(namespace, files)+ if (options.recordPath) {+ const entries = paths.get(namespace) ?? new Set<number>()+ entries.add(recordPath(id))+ paths.set(namespace, entries)+ }}}return [...byNamespace]@@ -104,32 +158,155 @@ export function analyzeRouteNamespaces(.map(([namespace, files]) => ({namespace,sources: [...files].sort(),+ ...(options.recordPath ? { dependencyPaths: [...(paths.get(namespace) ?? [])] } : {}),}))}const pageModules = reachable([page], false)- const sharedModules = reachable(sharedEntries, false)+ const sharedModules = reachable(sharedEntries, false, true)const mainModules = reachable([page, ...sharedEntries], true)const lazyModules = new Set(- [...mainModules].filter((id) => !pageModules.has(id) && !sharedModules.has(id)),- )- const slotModules = new Set(- [...reachable(slotEntries, true)].filter((id) => !mainModules.has(id)),+ [...mainModules.modules].filter(+ (id) => !pageModules.modules.has(id) && !sharedModules.modules.has(id),+ ),)+ const slots = reachable(slotEntries, true, true)+ const slotModules = new Set([...slots.modules].filter((id) => !mainModules.modules.has(id)))const groups = {- page: sources(pageModules),- shared: sources(sharedModules),- lazy: sources(lazyModules),- slots: sources(slotModules),+ page: sources(pageModules.modules, pageModules.parents),+ shared: sources(sharedModules.modules, sharedModules.parents),+ lazy: sources(lazyModules, mainModules.parents),+ slots: sources(slotModules, slots.parents),}const namespaces = new Set(Object.values(groups).flatMap((group) => group.map((item) => item.namespace)),)return {// Keep interception segments visible; their URL depends on navigation.- route: `/${segments.filter((segment) => !/^\([^)]*\)$/.test(segment) && !segment.startsWith('@')).join('/')}`,- page: page.slice(root.replaceAll('\\', '/').length + 1),+ route,+ page: sourcePath(page).slice(root.replaceAll('\\', '/').length + 1),namespaces: [...namespaces].sort(),groups,+ ...(options.unknownNamespaces+ ? {+ unknownNamespaceSources: [+ ...new Set(+ [...mainModules.modules, ...slotModules]+ .filter((id) => options.unknownNamespaces!.has(id))+ .map((id) => path.posix.relative(root.replaceAll('\\', '/'), sourcePath(id))),+ ),+ ].sort(),+ }+ : {}),}})}++export type EnvironmentUsage = {+ dependencies: ReadonlyMap<string, ModuleDependencies>+ usage: ReadonlyMap<string, ReadonlySet<string>>+ clientReferences: ReadonlySet<string>+ unknownNamespaces?: ReadonlySet<string>+}++export function analyzeEnvironmentRoutes(+ root: string,+ environments: ReadonlyMap<string, EnvironmentUsage>,+) {+ const modules: ModuleLocation[] = []+ const moduleIndexes = new Map<string, number>()+ const paths: [module: number, parent: number | null][] = []+ const pathIndexes = new Map<string, number>()+ function recordPath(id: string, parent: number | null) {+ let module = moduleIndexes.get(id)+ if (module === undefined) {+ const [environment, moduleId] = JSON.parse(id) as [string, string]+ module = modules.length+ modules.push({ environment, moduleId })+ moduleIndexes.set(id, module)+ }+ const key = `${module}:${parent}`+ let index = pathIndexes.get(key)+ if (index === undefined) {+ index = paths.length+ paths.push([module, parent])+ pathIndexes.set(key, index)+ }+ return index+ }+ const key = (environment: string, id: string) => JSON.stringify([environment, id])+ const sourcePaths = new Map<string, string>()+ const dependencies = new Map<string, ModuleDependencies>()+ const usage = new Map<string, ReadonlySet<string>>()+ const unknownNamespaces = new Set<string>()+ for (const [environment, graph] of environments) {+ for (const id of graph.unknownNamespaces ?? []) unknownNamespaces.add(key(environment, id))+ for (const [id, namespaces] of graph.usage) {+ const identity = key(environment, id)+ usage.set(identity, namespaces)+ sourcePaths.set(identity, id)+ }+ for (const [id, edges] of graph.dependencies) {+ const identity = key(environment, id)+ sourcePaths.set(identity, id)+ const imports = {+ static: new Set([...edges.static].map((id) => key(environment, id))),+ dynamic: new Set([...edges.dynamic].map((id) => key(environment, id))),+ }+ // RSC imports a client reference stub. Only this explicit boundary may+ // cross into the corresponding SSR and browser implementations.+ if (environment === 'rsc' && graph.clientReferences.has(id)) {+ for (const target of ['ssr', 'client']) {+ if (environments.get(target)?.usage.has(id)) imports.static.add(key(target, id))+ }+ }+ dependencies.set(identity, imports)+ }+ }+ const reports = new Map<string, RouteNamespaceReport>()+ for (const [environment, graph] of environments) {+ const entries = new Set([...graph.usage.keys()].map((id) => key(environment, id)))+ for (const report of analyzeRouteNamespaces(root, dependencies, usage, {+ entries,+ sourcePath: (id) => sourcePaths.get(id) ?? id,+ recordPath,+ unknownNamespaces,+ })) {+ const previous = reports.get(report.page)+ if (!previous) {+ reports.set(report.page, report)+ continue+ }+ previous.unknownNamespaceSources = [+ ...new Set([+ ...(previous.unknownNamespaceSources ?? []),+ ...(report.unknownNamespaceSources ?? []),+ ]),+ ].sort()+ previous.namespaces = [...new Set([...previous.namespaces, ...report.namespaces])].sort()+ for (const group of ['page', 'shared', 'lazy', 'slots'] as const) {+ const byNamespace = new Map<string, Set<string>>()+ const paths = new Map<string, Set<number>>()+ for (const item of [...previous.groups[group], ...report.groups[group]]) {+ const chains = paths.get(item.namespace) ?? new Set<number>()+ for (const chain of item.dependencyPaths ?? []) chains.add(chain)+ paths.set(item.namespace, chains)+ const sources = byNamespace.get(item.namespace) ?? new Set<string>()+ for (const source of item.sources) sources.add(source)+ byNamespace.set(item.namespace, sources)+ }+ previous.groups[group] = [...byNamespace]+ .sort(([a], [b]) => a.localeCompare(b))+ .map(([namespace, sources]) => ({+ namespace,+ sources: [...sources].sort(),+ dependencyPaths: [...(paths.get(namespace) ?? [])],+ }))+ }+ }+ }+ return {+ routes: [...reports.values()].sort((a, b) => a.page.localeCompare(b.page)),+ modules,+ paths,+ }+}diff --git a/web/vite.config.ts b/web/vite.config.tsindex 1744973e77b..217228dd98a 100644--- a/web/vite.config.ts+++ b/web/vite.config.ts@@ -41,7 +41,26 @@ export default defineConfig(({ command, mode, isPreview }) => {: undefinedreturn [- i18nAnalysisPlugin({ getDeclaredNamespaces: getDeclaredRouteNamespaces }),+ i18nAnalysisPlugin({+ adapters: [+ { module: 'i18n/lib.client.ts', exportName: 'useTranslation', namespaceArgument: 0 },+ {+ module: 'i18n/lib.server.ts',+ exportName: 'useTranslation',+ namespaceArgument: 0,+ implementationFunctions: ['getI18nConfig'],+ },+ { module: 'i18n/server.ts', exportName: 'getTranslation', namespaceArgument: 1 },+ {+ module: 'app/route-metadata.ts',+ exportName: 'getRouteMetadata',+ namespaceArgument: 0,+ selectorArgument: 1,+ },+ ],+ getDeclaredNamespaces: getDeclaredRouteNamespaces,+ // Runtime namespace providers remain unknown; validate detected usage only.+ }),Inspect(),inspector,tailwindcss(),