The easy-to-use open source Business Intelligence and Embedded Analytics tool that lets everyone work with data :bar_chart:
TypeScript analyticsbibusiness-intelligencebusinessintelligenceclojuredashboarddatadata-analysisdata-visualizationdatabasemetabasemysqlpostgrespostgresqlreportingslacksql-editorvisualization
Serve the locale catalogues as rspack chunks, remove locale api (#81933)
Romeo Van Snicka0845f5373a6
diff --git a/.github/scripts/measure-bundle-sizes.js b/.github/scripts/measure-bundle-sizes.jsindex c45122d085f..c572a011190 100644--- a/.github/scripts/measure-bundle-sizes.js+++ b/.github/scripts/measure-bundle-sizes.js@@ -24,6 +24,15 @@ const SDK_ROOT = "resources/frontend_client/app/embedding-sdk";const SDK_RUNTIME_RE = /embedding-sdk-chunk-runtime\./;const notRuntime = name => !SDK_RUNTIME_RE.test(name);+// One locale catalogue per chunk, named by the `webpackChunkName: "locale-[request]"`+// comment in localization.ts. A session loads exactly one and an English session+// loads none, so counting all 36 in a reachable total overstates it by 35x: 8.5 MB+// gzip against the SDK's 3.1 MB. Their size also tracks the translation process+// rather than any code change, so counting them makes every catalogue update look+// like a bundle regression.+const LOCALE_CHUNK_RE = /(^|\/)locale-/;+const notLocale = name => !LOCALE_CHUNK_RE.test(name);+const assetFiles = (root, names) => names.map(name => path.join(root, name));const unique = files => [...new Set(files)];@@ -116,7 +125,8 @@ function selectAppAssets(stats) {if (!initialAssets) {throw new Error('app: stats-main.json / "app-main" entrypoint missing');}- return { initialAssets, reachableAssets: entrypointJsAssets(stats, "app-main", "reachableAssets") };+ const reachableAssets = entrypointJsAssets(stats, "app-main", "reachableAssets");+ return { initialAssets, reachableAssets: reachableAssets?.filter(notLocale) ?? null };}/**@@ -136,7 +146,9 @@ function selectLegacySdkAssets(stats, { sdkAsyncChunksLoadable }) {const initial = unique(initialNames).filter(notRuntime);return {initialNames: initial,- reachableNames: sdkAsyncChunksLoadable ? unique(reachableNames).filter(notRuntime) : initial,+ reachableNames: sdkAsyncChunksLoadable+ ? unique(reachableNames).filter(notRuntime).filter(notLocale)+ : initial,};}@@ -161,7 +173,9 @@ function selectChunkedSdkAssets(stats, { sdkAsyncChunksLoadable }) {const bootstrapReachable = entrypointJsAssets(stats, "embedding-sdk-bootstrap", "reachableAssets") || bootstrapInitial;return {initialNames: unique([...bootstrapInitial, ...chunkedInitial]).filter(notRuntime),- reachableNames: unique([...bootstrapReachable, ...chunkedReachable]).filter(notRuntime),+ reachableNames: unique([...bootstrapReachable, ...chunkedReachable])+ .filter(notRuntime)+ .filter(notLocale),includesAsyncChunks: chunkedReachableAssets != null && sdkAsyncChunksLoadable,};}diff --git a/.github/scripts/measure-bundle-sizes.unit.spec.js b/.github/scripts/measure-bundle-sizes.unit.spec.jsindex 686c377cf82..d5bd3794768 100644--- a/.github/scripts/measure-bundle-sizes.unit.spec.js+++ b/.github/scripts/measure-bundle-sizes.unit.spec.js@@ -6,6 +6,7 @@ const {} = require("./measure-bundle-sizes");const RUNTIME = "embedding-sdk-chunk-runtime.deadbeef.js";+const LOCALE = "chunks/locale-fr-json.deadbeef.js";const stats = entrypoints => ({ entrypoints });@@ -30,6 +31,13 @@ describe("selectAppAssets", () => {it("throws when the app-main entrypoint is missing", () => {expect(() => selectAppAssets(stats({}))).toThrow("app-main");});++ it("leaves the locale catalogues out of the reachable total", () => {+ const s = stats({+ "app-main": { assets: ["main.js"], reachableAssets: ["main.js", "locale-fr-json.abc.js"] },+ });+ expect(selectAppAssets(s).reachableAssets).toEqual(["main.js"]);+ });});describe("selectChunkedSdkAssets", () => {@@ -50,6 +58,15 @@ describe("selectChunkedSdkAssets", () => {expect(result.includesAsyncChunks).toBe(false);});+ it("leaves the locale catalogues out of the reachable total", () => {+ const withLocale = {+ ...base,+ "embedding-sdk-chunked": { assets: ["a.js", RUNTIME], reachableAssets: ["a.js", "b.js", LOCALE, RUNTIME] },+ };+ const result = selectChunkedSdkAssets(stats(withLocale), { sdkAsyncChunksLoadable: true });+ expect(result.reachableNames).toEqual(["boot.js", "a.js", "b.js"]);+ });+it("collapses total to initial when the stats carry no reachable graph", () => {const noGraph = { "embedding-sdk-chunked": { assets: ["a.js"] } };const result = selectChunkedSdkAssets(stats(noGraph), { sdkAsyncChunksLoadable: true });diff --git a/.gitignore b/.gitignoreindex edb5a391f0c..556626a50eb 100644--- a/.gitignore+++ b/.gitignore@@ -86,7 +86,11 @@ cypress.env.json/resources/frontend_client/app/**/*.hot-update.js/resources/frontend_client/app/**/*.hot-update.json/resources/frontend_client/app/dist/-/resources/frontend_client/app/locales+/resources/frontend_client/app/locales/*+# Keep the directory itself: the frontend build resolves `locales/<locale>.json`+# through it, and rspack fails on a context whose directory does not exist. The+# `:translations` build step fills it in.+!/resources/frontend_client/app/locales/.gitkeep/resources/frontend_client/app/embed.js/resources/frontend_client/app/embedding-sdk.js/resources/frontend_client/app/embedding-sdk.js.mapdiff --git a/bin/build/src/i18n/create_artifacts.clj b/bin/build/src/i18n/create_artifacts.cljindex c02f9b0abfb..4c037b8eb15 100644--- a/bin/build/src/i18n/create_artifacts.clj+++ b/bin/build/src/i18n/create_artifacts.clj@@ -93,10 +93,20 @@(doseq [t [:invalid-message-format :skipped-arg-index :arg-count-mismatch]](u/announce " %s: %d" (name t) (get by-type t 0)))))))+(defn- delete-json-files!+ "Delete the `.json` files in `directory` but keep the directory itself.+ `resources/frontend_client/app/locales` is tracked through a `.gitkeep` so the+ frontend build can resolve `locales/<locale>.json` against it, and deleting+ the directory takes that file with it."+ [directory]+ (doseq [^java.io.File file (some-> ^java.io.File (io/file directory) .listFiles)+ :when (str/ends-with? (.getName file) ".json")]+ (u/delete-file-if-exists! (.getAbsolutePath file))))+(defn- create-artifacts-for-all-locales! []- ;; Empty directory in case some locales were removed+ ;; Empty the targets in case some locales were removed(u/delete-file-if-exists! backend/target-directory)- (u/delete-file-if-exists! frontend/target-directory)+ (delete-json-files! frontend/target-directory)(let [per-locale-violations (doall (pmap create-artifacts-for-locale! (i18n/locales)))all-violations (->> per-locale-violations(apply concat)diff --git a/e2e/test-component/scenarios/embedding-sdk/content-translations.cy.spec.tsx b/e2e/test-component/scenarios/embedding-sdk/content-translations.cy.spec.tsxindex 275b0790dac..675417fa2a1 100644--- a/e2e/test-component/scenarios/embedding-sdk/content-translations.cy.spec.tsx+++ b/e2e/test-component/scenarios/embedding-sdk/content-translations.cy.spec.tsx@@ -25,58 +25,13 @@ const { ORDERS, ORDERS_ID } = SAMPLE_DATABASE;describe("scenarios > embedding-sdk > content-translations", () => {beforeEach(() => {- cy.intercept("GET", "/app/locales/de.json", {- body: {- charset: "utf-8",- headers: {- "mime-version": "1.0",- "x-crowdin-file-id": "2",- "language-team": "German",- "content-type": "text/plain; charset=UTF-8",- "po-revision-date": "2026-04-01 16:19",- "report-msgid-bugs-to": "[email protected]",- "x-crowdin-project": "metabase-i18n",- "pot-creation-date": "2026-04-01 14:56+0000",- "content-transfer-encoding": "8bit",- language: "de",- "x-crowdin-file": "metabase.po",- "x-crowdin-language": "de",- "plural-forms": "nplurals=2; plural=(n != 1);",- "project-id-version": "metabase-i18n",- "x-crowdin-project-id": "758295",- },- translations: {- "": {},- },- },- });-- cy.intercept("GET", "/app/locales/ar.json", {- body: {- charset: "utf-8",- headers: {- "mime-version": "1.0",- "x-crowdin-file-id": "2",- "language-team": "Arabic",- "content-type": "text/plain; charset=UTF-8",- "po-revision-date": "2026-04-01 16:19",- "report-msgid-bugs-to": "[email protected]",- "x-crowdin-project": "metabase-i18n",- "pot-creation-date": "2026-04-01 14:56+0000",- "content-transfer-encoding": "8bit",- language: "ar",- "x-crowdin-file": "metabase.po",- "x-crowdin-language": "ar",- "plural-forms":- "nplurals=6; plural=(n==0 ? 0 : n==1 ? 1 : n==2 ? 2 : n%100>=3 && n%100<=10 ? 3 : n%100>=11 && n%100<=99 ? 4 : 5);",- "project-id-version": "metabase-i18n",- "x-crowdin-project-id": "758295",- },- translations: {- "": {},- },- },- });+ // These tests assert English UI chrome while checking that content is+ // translated, so the UI catalogue has to stay out of the way. It arrives as+ // an rspack chunk, not a JSON fetch, so it cannot be stubbed with a body.+ // Block it instead: LocaleProvider catches the failure and leaves the UI+ // untranslated.+ cy.intercept("GET", "**/locale-de-json*.js", { forceNetworkError: true });+ cy.intercept("GET", "**/locale-ar-json*.js", { forceNetworkError: true });});describe("question", () => {diff --git a/e2e/test/scenarios/embedding/embedding-dashboard.cy.spec.js b/e2e/test/scenarios/embedding/embedding-dashboard.cy.spec.jsindex 06a32bdf7c6..59723e3de47 100644--- a/e2e/test/scenarios/embedding/embedding-dashboard.cy.spec.js+++ b/e2e/test/scenarios/embedding/embedding-dashboard.cy.spec.js@@ -1128,7 +1128,7 @@ describe("scenarios > embedding > dashboard appearance", () => {cy.signOut();// We don't have a de-CH.json file, so it should fallback to de.json, see metabase#51039 for more details- cy.intercept("/app/locales/de.json").as("deLocale");+ cy.intercept("GET", "**/locale-de-json*.js").as("deLocale");H.visitEmbeddedPage({diff --git a/e2e/test/scenarios/embedding/embedding-questions.cy.spec.js b/e2e/test/scenarios/embedding/embedding-questions.cy.spec.jsindex fc631aebf83..225334e731b 100644--- a/e2e/test/scenarios/embedding/embedding-questions.cy.spec.js+++ b/e2e/test/scenarios/embedding/embedding-questions.cy.spec.js@@ -257,7 +257,7 @@ describe("scenarios [EE] > embedding > questions", () => {});// We don't have a de-CH.json file, so it should fallback to de.json, see metabase#51039 for more details- cy.intercept("/app/locales/de.json").as("deLocale");+ cy.intercept("GET", "**/locale-de-json*.js").as("deLocale");H.visitEmbeddedPage({diff --git a/e2e/test/scenarios/onboarding/setup/setup.cy.spec.ts b/e2e/test/scenarios/onboarding/setup/setup.cy.spec.tsindex 75705a7d6de..9b8ec4e2b19 100644--- a/e2e/test/scenarios/onboarding/setup/setup.cy.spec.ts+++ b/e2e/test/scenarios/onboarding/setup/setup.cy.spec.ts@@ -12,7 +12,6 @@ describe("scenarios > setup", () => {beforeEach(() => {H.restore("blank");H.resetSnowplow();- cy.intercept("GET", "/app/locales/*").as("getTranslations");});locales.forEach((locale) => {@@ -356,6 +355,10 @@ describe("scenarios > setup", () => {cy.log("Switching language before user creation should not update setting");selectLanguage("Dutch");+ // A real translation, so a catalogue that never loads fails the test. The+ // `[zz]` assertions below cannot cover this: they run after a second switch+ // and would still pass if this first one had loaded nothing.+ cy.findByTestId("setup-forms").button("Volgende").should("exist");cy.get("@updateSiteLocale.all").should("have.length", 0);selectLanguage("English (ZZ)");cy.get("@updateSiteLocale.all").should("have.length", 0);@@ -1058,7 +1061,10 @@ const selectLanguage = (targetLanguage: string) => {.should("be.visible").click();- if (targetLanguage !== "English") {- cy.wait("@getTranslations");- }+ // Wait on the selection landing rather than on the catalogue request. The+ // catalogue is a hashed chunk now, so a repeat of a language already loaded+ // in this browser is served from cache and makes no request at all. Every+ // caller that needs the catalogue to have been applied asserts a `[zz]`+ // string right after.+ cy.findByTestId("language-selector").should("have.value", targetLanguage);};diff --git a/e2e/test/scenarios/sharing/public-dashboard.cy.spec.js b/e2e/test/scenarios/sharing/public-dashboard.cy.spec.jsindex 171cab1063d..f18c5a974db 100644--- a/e2e/test/scenarios/sharing/public-dashboard.cy.spec.js+++ b/e2e/test/scenarios/sharing/public-dashboard.cy.spec.js@@ -324,7 +324,7 @@ describe("scenarios [EE] > public > dashboard", () => {it("should allow to set locale from the `#locale` hash parameter (metabase#50182)", () => {// We don't have a de-CH.json file, so it should fallback to de.json, see metabase#51039 for more details- cy.intercept("/app/locales/de.json").as("deLocale");+ cy.intercept("GET", "**/locale-de-json*.js").as("deLocale");cy.get("@dashboardId").then((id) => {H.visitPublicDashboard(id, {diff --git a/e2e/test/scenarios/sharing/public-question.cy.spec.js b/e2e/test/scenarios/sharing/public-question.cy.spec.jsindex baac3c36acc..ec058bdfb9a 100644--- a/e2e/test/scenarios/sharing/public-question.cy.spec.js+++ b/e2e/test/scenarios/sharing/public-question.cy.spec.js@@ -246,7 +246,7 @@ describe("scenarios [EE] > public > question", () => {);// We don't have a de-CH.json file, so it should fallback to de.json, see metabase#51039 for more details- cy.intercept("/app/locales/de.json").as("deLocale");+ cy.intercept("GET", "**/locale-de-json*.js").as("deLocale");cy.get("@questionId").then((id) => {H.visitPublicQuestion(id, {diff --git a/frontend/build/shared/rspack/resolve-aliases.js b/frontend/build/shared/rspack/resolve-aliases.jsindex 89d7c6c85c9..78e1677fb65 100644--- a/frontend/build/shared/rspack/resolve-aliases.js+++ b/frontend/build/shared/rspack/resolve-aliases.js@@ -6,6 +6,7 @@ const { IS_DEV_MODE } = require("../constants");const ROOT_PATH = path.resolve(__dirname, "../../../..");const ASSETS_PATH = ROOT_PATH + "/resources/frontend_client/app/assets";+const LOCALES_PATH = ROOT_PATH + "/resources/frontend_client/app/locales";const FONTS_PATH = ROOT_PATH + "/resources/frontend_client/app/fonts";const IMAGES_PATH = ROOT_PATH + "/resources/frontend_client/app/img";const DOCS_PATH = ROOT_PATH + "/docs";@@ -39,6 +40,8 @@ const resolveEnterprisePathOrNoop = (/** @type {string} */ subpath) =>const RESOLVE_ALIASES = {"build-configs": FRONTEND_BUILD_CONFIGS_PATH,assets: ASSETS_PATH,+ // Written by the `:translations` build step, which runs before the frontend one.+ locales: LOCALES_PATH,img: IMAGES_PATH,fonts: FONTS_PATH,docs: DOCS_PATH,diff --git a/frontend/src/metabase/api/localization.ts b/frontend/src/metabase/api/localization.tsdeleted file mode 100644index 5d49cc0bd8a..00000000000--- a/frontend/src/metabase/api/localization.ts+++ /dev/null@@ -1,37 +0,0 @@-import { getBasename } from "metabase/utils/basename";-import {- type LocaleDataWithLanguage,- setLocalization,-} from "metabase/utils/i18n";--// note this won't refresh strings that are evaluated at load time-export async function loadLocalization(- locale: string,-): Promise<LocaleDataWithLanguage> {- // we need to be sure to set the initial localization before loading any files- // so load metabase/services only when we need it- // load and parse the locale- const translationsObject: LocaleDataWithLanguage =- locale !== "en"- ? // We don't use I18NApi.locale/the GET helper because those helpers adds custom headers,- // which will make the browser do the pre-flight request on the SDK.- // The backend doesn't seem to support pre-flight request on the static assets, but even- // if it supported them it's more performant to skip the pre-flight request- await fetch(`${getBasename()}/app/locales/${locale}.json`).then(- (response) => response.json(),- )- : // We don't serve en.json. Instead, use this object to fall back to the literals.- {- headers: {- language: "en",- "plural-forms": "nplurals=2; plural=(n != 1);",- },- translations: {- // eslint-disable-next-line metabase/no-literal-metabase-strings -- Not a user facing string- "": { Metabase: { msgid: "Metabase", msgstr: ["Metabase"] } },- },- };- setLocalization(translationsObject);-- return translationsObject;-}diff --git a/frontend/src/metabase/embedding/LocaleProvider.tsx b/frontend/src/metabase/embedding/LocaleProvider.tsxindex 80104016b2a..aa6eaf25b62 100644--- a/frontend/src/metabase/embedding/LocaleProvider.tsx+++ b/frontend/src/metabase/embedding/LocaleProvider.tsx@@ -1,12 +1,12 @@import { type PropsWithChildren, useEffect, useState } from "react";import { setLocaleHeader } from "metabase/api/client";-import { loadLocalization } from "metabase/api/localization";import { FrontendLocaleContext } from "metabase/common/hooks/use-locale/frontend-locale-context";import { isEmbeddingSdk } from "metabase/embedding-sdk/config";import { useSetting } from "metabase/settings";import { DatesProvider } from "metabase/ui/components/theme/DatesProvider/DatesProvider";import type { LocaleDataWithLanguage } from "metabase/utils/i18n";+import { loadLocalization } from "metabase/utils/localization";interface LocaleProviderProps {locale?: string | null;@@ -39,7 +39,11 @@ export const LocaleProvider = ({setContextLocale(localeToLoad);}).catch(() => {+ // The locale stands whether or not its catalogue arrives. The API+ // header is already set, so content translation still has to run+ // against it.setIsLocaleLoading(false);+ setContextLocale(localeToLoad);});}}, [locale, shouldLoadLocale, availableLocalesData]);diff --git a/frontend/src/metabase/embedding/LocaleProvider.unit.spec.tsx b/frontend/src/metabase/embedding/LocaleProvider.unit.spec.tsxindex f61d151d15e..96f0b4e4fcd 100644--- a/frontend/src/metabase/embedding/LocaleProvider.unit.spec.tsx+++ b/frontend/src/metabase/embedding/LocaleProvider.unit.spec.tsx@@ -1,8 +1,9 @@import { DatePicker } from "@mantine/dates";-import fetchMock from "fetch-mock";+import { t } from "ttag";import { renderWithProviders, screen, waitFor } from "__support__/ui";import { useLocale } from "metabase/common/hooks";+import * as localization from "metabase/utils/localization";import { LocaleProvider, getLocaleToUse } from "./LocaleProvider";@@ -105,67 +106,77 @@ describe("getLocaleToUse", () => {});describe("LocaleProvider", () => {- it("should make Mantine components use correct locale", async () => {- mockLocaleJsonResponse("de");+ afterEach(() => {+ jest.restoreAllMocks();+ });+ it("should make Mantine components use correct locale", async () => {renderWithProviders(<LocaleProvider locale="de"><DatePicker defaultDate={new Date(2020, 0, 1)} onChange={() => {}} /></LocaleProvider>,);- await waitForLocaleJson("de");-- // `waitFor` to ensure the component has time to re-renderawait waitFor(() => {expect(screen.getByText("Januar 2020")).toBeInTheDocument();});});+ it("should still render its children when the catalogue fails to load", async () => {+ jest+ .spyOn(localization, "loadLocalization")+ .mockRejectedValue(new Error("ChunkLoadError"));++ renderWithProviders(+ <LocaleProvider locale="de" shouldWaitForLocale>+ <div>content</div>+ </LocaleProvider>,+ );++ await waitFor(() => {+ expect(screen.getByText("content")).toBeInTheDocument();+ });+ });++ it("should apply the new catalogue to its children when the locale changes", async () => {+ // Reads the locale the way a translated component does, so it re-renders+ // when the provider announces a new one.+ const TestComponent = () => {+ useLocale();+ return <div>{t`Filter`}</div>;+ };++ const { rerender } = renderWithProviders(+ <LocaleProvider locale="en">+ <TestComponent />+ </LocaleProvider>,+ );++ expect(await screen.findByText("Filter")).toBeInTheDocument();++ rerender(+ <LocaleProvider locale="ko">+ <TestComponent />+ </LocaleProvider>,+ );++ expect(await screen.findByText("[ko] Filter")).toBeInTheDocument();+ });+it("should make useLocale return the correct locale", async () => {const TestComponent = () => {const { locale } = useLocale();return <div>{locale}</div>;};- mockLocaleJsonResponse("de");-renderWithProviders(<LocaleProvider locale="de"><TestComponent /></LocaleProvider>,);- await waitForLocaleJson("de");-- // `waitFor` to ensure the component has time to re-renderawait waitFor(() => {expect(screen.getByText("de")).toBeInTheDocument();});});});--const mockLocaleJsonResponse = (locale: string) => {- fetchMock.get(`/app/locales/${locale}.json`, {- charset: "utf-8",- headers: {- language: locale,- // `plural-forms` is required otherwise the loading fails- "plural-forms": "nplurals=2; plural=(n != 1);",- },- translations: {- // at least a key is required otherwise the loading fails- "": {- "": {},- },- },- });-};--async function waitForLocaleJson(locale: string) {- await waitFor(() => {- expect(fetchMock.callHistory.done(`/app/locales/${locale}.json`)).toBe(- true,- );- });-}diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.enterprise.unit.spec.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.enterprise.unit.spec.tsxindex 2b43cab5ae5..e20b256a47a 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.enterprise.unit.spec.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.enterprise.unit.spec.tsx@@ -1,12 +1,14 @@import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";import { setupLastDownloadFormatEndpoints } from "__support__/server-mocks";import { screen, waitFor } from "__support__/ui";+import * as localization from "metabase/utils/localization";import { DASHBOARD_PDF_EXPORT_ROOT_ID } from "metabase/visualizations/lib/save-dashboard-pdf";import { type SetupOpts, setup } from "./setup";+const loadLocalizationSpy = jest.spyOn(localization, "loadLocalization");+const DASHBOARD_TITLE = '"My test dash"';const setupEnterprise = async (opts?: Partial<SetupOpts>) => {@@ -18,6 +20,7 @@ const setupEnterprise = async (opts?: Partial<SetupOpts>) => {describe("PublicOrEmbeddedDashboardPage", () => {beforeEach(() => {+ loadLocalizationSpy.mockClear();setupLastDownloadFormatEndpoints();});@@ -72,9 +75,7 @@ describe("PublicOrEmbeddedDashboardPage", () => {const expectedLocale = "ko";await setupEnterprise({ hash: { locale: expectedLocale } });- expect(- fetchMock.callHistory.calls(`path:/app/locales/${expectedLocale}.json`),- ).toHaveLength(0);+ expect(loadLocalizationSpy).not.toHaveBeenCalled();});});});diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.premium.unit.spec.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.premium.unit.spec.tsxindex 61407b18d7b..f6bdc7a2306 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.premium.unit.spec.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/PublicOrEmbeddedDashboardPage.premium.unit.spec.tsx@@ -1,13 +1,15 @@import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";import { setupLastDownloadFormatEndpoints } from "__support__/server-mocks";import { screen, waitFor } from "__support__/ui";+import * as localization from "metabase/utils/localization";import { DASHBOARD_PDF_EXPORT_ROOT_ID } from "metabase/visualizations/lib/save-dashboard-pdf";import { createMockTokenFeatures } from "metabase-types/api/mocks";import { type SetupOpts, setup } from "./setup";+const loadLocalizationSpy = jest.spyOn(localization, "loadLocalization");+const DASHBOARD_TITLE = '"My test dash"';const setupPremium = async (opts?: Partial<SetupOpts>) => {@@ -24,6 +26,7 @@ const setupPremium = async (opts?: Partial<SetupOpts>) => {describe("PublicOrEmbeddedDashboardPage", () => {beforeEach(() => {+ loadLocalizationSpy.mockClear();setupLastDownloadFormatEndpoints();});@@ -98,9 +101,7 @@ describe("PublicOrEmbeddedDashboardPage", () => {const expectedLocale = "ko";await setupPremium({ hash: { locale: expectedLocale } });- expect(- fetchMock.callHistory.calls(`path:/app/locales/${expectedLocale}.json`),- ).toHaveLength(1);+ expect(loadLocalizationSpy).toHaveBeenCalledWith(expectedLocale);});});});diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/setup.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/setup.tsxindex db73b40a292..34d0961ae0d 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/setup.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedDashboard/PublicOrEmbeddedDashboardPage/tests/setup.tsx@@ -1,4 +1,3 @@-import fetchMock from "fetch-mock";import _ from "underscore";import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";@@ -90,18 +89,6 @@ export async function setup(setupEmbedDashboardEndpoints(MOCK_TOKEN, dashboard, dashcards);- if (hash.locale) {- fetchMock.get(`path:/app/locales/${hash.locale}.json`, {- headers: {- language: "ko",- "plural-forms": "nplurals=1; plural=0;",- },- translations: {- "": {},- },- });- }-const pathname = `/embed/dashboard/${MOCK_TOKEN}`;const hashString = _.isEmpty(hash) ? "" : `#${new URLSearchParams(hash)}`;const href = `${pathname}${queryString}${hashString}`;diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/PublicOrEmbeddedQuestion.enterprise.unit.spec.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/PublicOrEmbeddedQuestion.enterprise.unit.spec.tsxindex 477483d5c8c..025af645d43 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/PublicOrEmbeddedQuestion.enterprise.unit.spec.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/PublicOrEmbeddedQuestion.enterprise.unit.spec.tsx@@ -1,11 +1,13 @@import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";import { setupLastDownloadFormatEndpoints } from "__support__/server-mocks";import { getIcon, screen, within } from "__support__/ui";+import * as localization from "metabase/utils/localization";import { type SetupOpts, setup } from "./setup";+const loadLocalizationSpy = jest.spyOn(localization, "loadLocalization");+const FAKE_UUID = "123456";const QUESTION_NAME = "Public question";@@ -20,6 +22,7 @@ function setupEnterprise(opts?: Partial<SetupOpts>) {describe("PublicOrEmbeddedQuestion", () => {beforeEach(() => {+ loadLocalizationSpy.mockClear();setupLastDownloadFormatEndpoints();});@@ -58,9 +61,7 @@ describe("PublicOrEmbeddedQuestion", () => {await userEvent.hover(getIcon("download"));- expect(- fetchMock.callHistory.calls(`path:/app/locales/${expectedLocale}.json`),- ).toHaveLength(0);+ expect(loadLocalizationSpy).not.toHaveBeenCalled();});});});diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/PublicOrEmbeddedQuestion.premium.unit.spec.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/PublicOrEmbeddedQuestion.premium.unit.spec.tsxindex 2e053ae7bdd..1a1131fe921 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/PublicOrEmbeddedQuestion.premium.unit.spec.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/PublicOrEmbeddedQuestion.premium.unit.spec.tsx@@ -1,12 +1,14 @@import userEvent from "@testing-library/user-event";-import fetchMock from "fetch-mock";import { setupLastDownloadFormatEndpoints } from "__support__/server-mocks";import { getIcon, queryIcon, screen, within } from "__support__/ui";+import * as localization from "metabase/utils/localization";import { createMockTokenFeatures } from "metabase-types/api/mocks";import { type SetupOpts, setup } from "./setup";+const loadLocalizationSpy = jest.spyOn(localization, "loadLocalization");+const FAKE_UUID = "123456";const QUESTION_NAME = "Public question";@@ -23,6 +25,7 @@ function setupPremium(opts?: Partial<SetupOpts>) {describe("PublicOrEmbeddedQuestion", () => {beforeEach(() => {+ loadLocalizationSpy.mockClear();setupLastDownloadFormatEndpoints();});@@ -64,9 +67,7 @@ describe("PublicOrEmbeddedQuestion", () => {await userEvent.hover(getIcon("download"));- expect(- fetchMock.callHistory.calls(`path:/app/locales/${expectedLocale}.json`),- ).toHaveLength(1);+ expect(loadLocalizationSpy).toHaveBeenCalledWith(expectedLocale);});});});diff --git a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/setup.tsx b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/setup.tsxindex 898c26e8c81..68108d651b9 100644--- a/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/setup.tsx+++ b/frontend/src/metabase/public/containers/PublicOrEmbeddedQuestion/PublicOrEmbeddedQuestion/tests/setup.tsx@@ -1,4 +1,3 @@-import fetchMock from "fetch-mock";import _ from "underscore";import { setupEnterpriseOnlyPlugin } from "__support__/enterprise";@@ -98,18 +97,6 @@ export async function setup(}),);- if (hash.locale) {- fetchMock.get(`path:/app/locales/${hash.locale}.json`, {- headers: {- language: "ko",- "plural-forms": "nplurals=1; plural=0;",- },- translations: {- "": {},- },- });- }-renderWithProviders(<Routepath="public/question/:uuid"diff --git a/frontend/src/metabase/redux/auth.ts b/frontend/src/metabase/redux/auth.tsindex c57930ef14b..82fd5e7e9a8 100644--- a/frontend/src/metabase/redux/auth.ts+++ b/frontend/src/metabase/redux/auth.ts@@ -5,7 +5,6 @@ import {} from "@reduxjs/toolkit";import { Api } from "metabase/api";-import { loadLocalization } from "metabase/api/localization";import {type MfaChallengeResponse,type MfaEnrollmentResponse,@@ -21,6 +20,7 @@ import { getSetting, refetchSiteSettings } from "metabase/settings";import * as Urls from "metabase/urls";import { isSmallScreen, reload } from "metabase/utils/dom";import { isResourceNotFoundError } from "metabase/utils/errors";+import { loadLocalization } from "metabase/utils/localization";import type { LoginData } from "metabase-types/api";export const REFRESH_LOCALE = "metabase/user/REFRESH_LOCALE";diff --git a/frontend/src/metabase/setup/actions.ts b/frontend/src/metabase/setup/actions.tsindex 44d4c5d0cbf..c3ebca583c6 100644--- a/frontend/src/metabase/setup/actions.ts+++ b/frontend/src/metabase/setup/actions.ts@@ -2,7 +2,6 @@ import { createAction } from "@reduxjs/toolkit";import { t } from "ttag";import { setupApi, userApi } from "metabase/api";-import { loadLocalization } from "metabase/api/localization";import { isEmailAlreadyInUse } from "metabase/api/utils/errors";import { runRtkEndpoint } from "metabase/api/utils/run-rtk-endpoint";import { trackUserInvited } from "metabase/common/analytics";@@ -21,6 +20,7 @@ import {refetchSiteSettings,settingsApi,} from "metabase/settings";+import { loadLocalization } from "metabase/utils/localization";import MetabaseSettings from "metabase/utils/settings";import type { DatabaseData, Settings, UsageReason } from "metabase-types/api";diff --git a/frontend/src/metabase/utils/localization.ts b/frontend/src/metabase/utils/localization.tsnew file mode 100644index 00000000000..803e0884b8f--- /dev/null+++ b/frontend/src/metabase/utils/localization.ts@@ -0,0 +1,43 @@+import {+ type LocaleDataWithLanguage,+ setLocalization,+} from "metabase/utils/i18n";++/**+ * Loads a locale's catalogue from our own bundle.+ *+ * Imported rather than fetched so the catalogues go through the same pipeline as+ * every other asset: rspack hashes each one, emits it as its own chunk, writes+ * the `.br` and `.gz` siblings, and resolves the URL at runtime. A hashed chunk+ * is cacheable, which a fetch of `app/locales/<locale>.json` never qualified for.+ */+function loadLocaleCatalog(locale: string): Promise<LocaleDataWithLanguage> {+ return import(+ /* webpackChunkName: "locale-[request]" */+ `locales/${locale.replace(/-/g, "_")}.json`+ ).then((module) => module.default);+}++// note this won't refresh strings that are evaluated at load time+export async function loadLocalization(+ locale: string,+): Promise<LocaleDataWithLanguage> {+ const translationsObject: LocaleDataWithLanguage =+ locale !== "en"+ ? await loadLocaleCatalog(locale)+ : // English is the msgid source, so no catalogue is built for it. This+ // stands in for one and falls back to the literals.+ {+ headers: {+ language: "en",+ "plural-forms": "nplurals=2; plural=(n != 1);",+ },+ translations: {+ // eslint-disable-next-line metabase/no-literal-metabase-strings -- Not a user facing string+ "": { Metabase: { msgid: "Metabase", msgstr: ["Metabase"] } },+ },+ };+ setLocalization(translationsObject);++ return translationsObject;+}diff --git a/frontend/test/__mocks__/locales/de.json b/frontend/test/__mocks__/locales/de.jsonnew file mode 100644index 00000000000..2f21e4d07b2--- /dev/null+++ b/frontend/test/__mocks__/locales/de.json@@ -0,0 +1,12 @@+{+ "charset": "utf-8",+ "headers": {+ "language": "de",+ "plural-forms": "nplurals=2; plural=(n != 1);"+ },+ "translations": {+ "": {+ "": {}+ }+ }+}diff --git a/frontend/test/__mocks__/locales/ko.json b/frontend/test/__mocks__/locales/ko.jsonnew file mode 100644index 00000000000..967de93ab1d--- /dev/null+++ b/frontend/test/__mocks__/locales/ko.json@@ -0,0 +1,15 @@+{+ "charset": "utf-8",+ "headers": {+ "language": "ko",+ "plural-forms": "nplurals=1; plural=0;"+ },+ "translations": {+ "": {+ "Filter": {+ "msgid": "Filter",+ "msgstr": ["[ko] Filter"]+ }+ }+ }+}diff --git a/jest.base.conf.js b/jest.base.conf.jsindex 1c9d51f2b17..02723e3ccee 100644--- a/jest.base.conf.js+++ b/jest.base.conf.js@@ -49,6 +49,9 @@ const baseConfig = {"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$":"<rootDir>/frontend/test/__mocks__/fileMock.js","^cljs/(.*)$": "<rootDir>/target/cljs_dev/$1",+ // The real catalogues are a build artifact, so tests resolve a small fixture+ // per locale instead.+ "^locales/(.*)\\.json$": "<rootDir>/frontend/test/__mocks__/locales/$1.json","\\.svg\\?(component|source)":"<rootDir>/frontend/test/__mocks__/svgMock.tsx","csv-parse/browser/esm/sync":diff --git a/resources/frontend_client/app/locales/.gitkeep b/resources/frontend_client/app/locales/.gitkeepnew file mode 100644index 00000000000..e69de29bb2ddiff --git a/rspack.embedding-sdk-bundle.config.js b/rspack.embedding-sdk-bundle.config.jsindex 291117d562f..d7eb59a9a83 100644--- a/rspack.embedding-sdk-bundle.config.js+++ b/rspack.embedding-sdk-bundle.config.js@@ -100,7 +100,11 @@ const config = {// Split chunks and bootstrap go into chunks/ subfolder.// The legacy monolithic bundle goes into legacy/.// The backend serves chunks/ with far-future immutable cache headers.- chunkFilename: "chunks/[id].[contenthash:8].js",+ // `[name]` falls back to the chunk id when a chunk has no name, so this+ // only changes chunks named through a `webpackChunkName` comment. The+ // locale catalogues need their name in the filename: the bundle-size gate+ // recognises them by it.+ chunkFilename: "chunks/[name].[contenthash:8].js",filename: (pathData) => {switch (pathData.chunk?.name) {case "embedding-sdk-bootstrap":