diff --git a/docs/ThemeTranslations.md b/docs/ThemeTranslations.md index 749461cc385..8eb68748b57 100644 --- a/docs/ThemeTranslations.md +++ b/docs/ThemeTranslations.md @@ -28,7 +28,9 @@ An override file only has to contain the keys it changes; every other key falls file. A theme also does not have to provide a file for every language. The build copies these files to `assets//i18n/.json5` in the output, where the -translate loaders pick them up. +server loader picks them up. Like the base files, they are also copied as +`assets//i18n/..json` with a content hash in the name; the browser requests +that copy, so a changed translation is never served from the browser cache. The build also records which themes provide a file for which language, so the browser only requests override files that exist; a theme without overrides is not requested at all. That diff --git a/src/ngx-translate-loaders/translate-browser.loader.spec.ts b/src/ngx-translate-loaders/translate-browser.loader.spec.ts index 6c6db267499..ac48b84d692 100644 --- a/src/ngx-translate-loaders/translate-browser.loader.spec.ts +++ b/src/ngx-translate-loaders/translate-browser.loader.spec.ts @@ -14,7 +14,8 @@ describe('TranslateBrowserLoader', () => { let http: { get: jasmine.Spy }; let loader: TranslateBrowserLoader; let originalThemes: typeof environment.themes; - let themeLanguages: jasmine.Spy; + let originalProduction: boolean; + let themeLanguageHashes: jasmine.Spy; /** Match the base i18n request regardless of the production content hash. */ const isBaseRequest = (url: string): boolean => url.startsWith(`${PREFIX}en`) && url.endsWith(SUFFIX); @@ -28,19 +29,23 @@ describe('TranslateBrowserLoader', () => { loader = new TranslateBrowserLoader(transferState as any, http as any, PREFIX, SUFFIX); // Default to every configured theme having an override, so the merge expectations // below need no setup; tests that check which files are requested override this. - themeLanguages = spyOn(loader as any, 'themeLanguages').and.callFake(() => { - const declared: Record = {}; + themeLanguageHashes = spyOn(loader as any, 'themeLanguageHashes').and.callFake(() => { + const declared: Record> = {}; (environment.themes ?? []).forEach((theme: any) => { - declared[theme.name] = ['en']; + declared[theme.name] = { 'en.json5': 'abc123' }; }); return declared; }); originalThemes = environment.themes; + originalProduction = environment.production; + // other specs may leave production on; the tests below expect unhashed file names unless they set it + environment.production = false; spyOn(console, 'warn'); }); afterEach(() => { environment.themes = originalThemes; + environment.production = originalProduction; }); it('returns the cached translations from the TransferState without any HTTP call', (done) => { @@ -61,7 +66,7 @@ describe('TranslateBrowserLoader', () => { if (isBaseRequest(url)) { return of(JSON.stringify({ 'home.title': 'Base', 'home.subtitle': 'Base sub' })); } - if (url === 'assets/custom/i18n/en.json5') { + if (url === 'assets/custom/i18n/en.json') { return of('{ "home.title": "Custom" }'); } return throwError(() => new Error('404')); @@ -86,13 +91,31 @@ describe('TranslateBrowserLoader', () => { loader.getTranslation('en').subscribe((messages) => { expect(messages).toEqual({ 'home.title': 'Base' }); expect(console.warn).toHaveBeenCalledWith( - '[TranslateBrowserLoader] Failed to load theme i18n file assets/custom/i18n/en.json5:', + '[TranslateBrowserLoader] Failed to load theme i18n file assets/custom/i18n/en.json:', jasmine.any(Error), ); done(); }); }); + it('requests the theme override file by its content hash in production', (done) => { + environment.production = true; + environment.themes = [{ name: 'custom' }]; + transferState.get.and.returnValue({}); + http.get.and.callFake((url: string) => { + if (url === 'assets/custom/i18n/en.abc123.json') { + return of(JSON.stringify({ 'home.title': 'Custom' })); + } + return of(JSON.stringify({ 'home.title': 'Base' })); + }); + + loader.getTranslation('en').subscribe((messages) => { + expect(messages).toEqual({ 'home.title': 'Custom' }); + expect(http.get).toHaveBeenCalledWith('assets/custom/i18n/en.abc123.json', jasmine.anything()); + done(); + }); + }); + it('warns and returns no translations when the base file cannot be loaded', (done) => { environment.themes = []; transferState.get.and.returnValue({}); @@ -112,11 +135,11 @@ describe('TranslateBrowserLoader', () => { if (isBaseRequest(url)) { return of(JSON.stringify({ key: 'base' })); } - if (url === 'assets/parent-theme/i18n/en.json5') { - return of('{ key: "parent" }'); + if (url === 'assets/parent-theme/i18n/en.json') { + return of(JSON.stringify({ key: 'parent' })); } - if (url === 'assets/child-theme/i18n/en.json5') { - return of('{ key: "child" }'); + if (url === 'assets/child-theme/i18n/en.json') { + return of(JSON.stringify({ key: 'child' })); } return throwError(() => new Error('404')); }); @@ -155,12 +178,12 @@ describe('TranslateBrowserLoader', () => { if (isBaseRequest(url)) { return of(JSON.stringify({ key: 'base' })); } - if (url === 'assets/parent-theme/i18n/en.json5') { - return of('{ key: "parent" }'); + if (url === 'assets/parent-theme/i18n/en.json') { + return of(JSON.stringify({ key: 'parent' })); } - if (url === 'assets/sibling-theme/i18n/en.json5') { + if (url === 'assets/sibling-theme/i18n/en.json') { // sibling has its own value for the same key — must NOT win when parent-theme is active - return of('{ key: "sibling" }'); + return of(JSON.stringify({ key: 'sibling' })); } return throwError(() => new Error('404')); }); @@ -183,10 +206,10 @@ describe('TranslateBrowserLoader', () => { if (isBaseRequest(url)) { return of(JSON.stringify({ 'key.a': 'base-a', 'key.b': 'base-b' })); } - if (url === 'assets/parent-theme/i18n/en.json5') { + if (url === 'assets/parent-theme/i18n/en.json') { return of('{ "key.a": "parent-a" }'); } - if (url === 'assets/child-theme/i18n/en.json5') { + if (url === 'assets/child-theme/i18n/en.json') { return of('{ "key.b": "child-b" }'); } return throwError(() => new Error('404')); @@ -202,7 +225,7 @@ describe('TranslateBrowserLoader', () => { it('does not request any theme override file when the build contains none for the language', (done) => { // Requesting a file that was never built costs a 404 and delays the first render. environment.themes = [{ name: 'dspace' }]; - themeLanguages.and.returnValue({}); + themeLanguageHashes.and.returnValue({}); transferState.get.and.returnValue({}); http.get.and.callFake((url: string) => { if (isBaseRequest(url)) { @@ -214,7 +237,7 @@ describe('TranslateBrowserLoader', () => { loader.getTranslation('en').subscribe((messages) => { expect(messages).toEqual({ 'home.title': 'Base' }); expect(http.get).toHaveBeenCalledTimes(1); - expect(http.get).not.toHaveBeenCalledWith('assets/dspace/i18n/en.json5', jasmine.anything()); + expect(http.get).not.toHaveBeenCalledWith('assets/dspace/i18n/en.json', jasmine.anything()); done(); }); }); @@ -225,22 +248,22 @@ describe('TranslateBrowserLoader', () => { { name: 'parent-theme' }, ]; // Only the ancestor ships an override, so the active child theme must not be requested. - themeLanguages.and.returnValue({ 'parent-theme': ['en'] }); + themeLanguageHashes.and.returnValue({ 'parent-theme': { 'en.json5': 'abc123' } }); transferState.get.and.returnValue({}); http.get.and.callFake((url: string) => { if (isBaseRequest(url)) { return of(JSON.stringify({ key: 'base' })); } - if (url === 'assets/parent-theme/i18n/en.json5') { - return of('{ key: "parent" }'); + if (url === 'assets/parent-theme/i18n/en.json') { + return of(JSON.stringify({ key: 'parent' })); } return throwError(() => new Error('404')); }); loader.getTranslation('en').subscribe((messages) => { expect(messages.key).toBe('parent'); - expect(http.get).toHaveBeenCalledWith('assets/parent-theme/i18n/en.json5', jasmine.anything()); - expect(http.get).not.toHaveBeenCalledWith('assets/child-theme/i18n/en.json5', jasmine.anything()); + expect(http.get).toHaveBeenCalledWith('assets/parent-theme/i18n/en.json', jasmine.anything()); + expect(http.get).not.toHaveBeenCalledWith('assets/child-theme/i18n/en.json', jasmine.anything()); done(); }); }); diff --git a/src/ngx-translate-loaders/translate-browser.loader.ts b/src/ngx-translate-loaders/translate-browser.loader.ts index 55efde57f38..99e7587fc4d 100644 --- a/src/ngx-translate-loaders/translate-browser.loader.ts +++ b/src/ngx-translate-loaders/translate-browser.loader.ts @@ -4,7 +4,6 @@ import { AppConfig } from '@dspace/config/app-config.interface'; import { getDefaultThemeConfig } from '@dspace/config/config.util'; import { hasValue } from '@dspace/shared/utils/empty.util'; import { TranslateLoader } from '@ngx-translate/core'; -import JSON5 from 'json5'; import { forkJoin, Observable, @@ -26,7 +25,7 @@ import { resolveActiveThemeChain } from './theme-i18n.util'; * A TranslateLoader for ngx-translate to retrieve i18n messages from the TransferState, or download * them if they're not available there. * - * Also fetches per-theme translation overrides from `assets//i18n/.json5` for the + * Also fetches per-theme translation overrides from `assets//i18n/..json` for the * active theme and its ancestors (root → active), merging them on top of the base translations * so the active theme's keys win. Only the active theme's inheritance chain is loaded — sibling * themes are excluded to prevent cross-theme key pollution. @@ -95,13 +94,16 @@ export class TranslateBrowserLoader implements TranslateLoader { } /** - * Fetch the override JSON5 file for the given theme/language. - * Returns an empty object if the file is missing (most themes won't override every language). + * Fetch the override file for the given theme/language (the hashed JSON produced by the build pipeline). + * Returns an empty object if the file can't be loaded. */ protected fetchThemeOverride(themeName: string, lang: string): Observable> { - const url = `assets/${themeName}/i18n/${lang}.json5`; + const translationHash: string = environment.production + ? `.${this.themeLanguageHashes()[themeName]?.[lang + '.json5']}` + : ''; + const url = `assets/${themeName}/i18n/${lang}${translationHash}.json`; return this.http.get(url, { responseType: 'text' }).pipe( - map((text: string) => JSON5.parse(text) as Record), + map((json: string) => JSON.parse(json) as Record), catchError((error: unknown) => { // eslint-disable-next-line no-console console.warn(`[TranslateBrowserLoader] Failed to load theme i18n file ${url}:`, error); @@ -111,10 +113,10 @@ export class TranslateBrowserLoader implements TranslateLoader { } /** - * The languages each theme provides an override file for, as collected at build time + * The hashes of the i18n override files of each theme, as collected at build time */ - protected themeLanguages(): Record { - return (process.env.themeLanguages as any) ?? {}; + protected themeLanguageHashes(): Record> { + return (process.env.themeLanguageHashes as any) ?? {}; } /** @@ -122,6 +124,6 @@ export class TranslateBrowserLoader implements TranslateLoader { * Requesting a file that isn't there costs a 404 before the merge can complete. */ protected hasThemeOverride(themeName: string, lang: string): boolean { - return this.themeLanguages()[themeName]?.includes(lang) === true; + return this.themeLanguageHashes()[themeName]?.[lang + '.json5'] !== undefined; } } diff --git a/webpack/helpers.ts b/webpack/helpers.ts index bf4dd693ed3..8b6cd033319 100644 --- a/webpack/helpers.ts +++ b/webpack/helpers.ts @@ -57,16 +57,15 @@ export function getFileHashes(folderPath: string, regExp: RegExp): { [fileName: } /** - * Collect the languages each theme provides an i18n override file for, e.g. { custom: ['en'] } + * Calculate the hashes of the i18n override files of each theme, e.g. { custom: { 'en.json5': '' } } * * @param themesPath The path of the folder containing the themes */ -export function getThemeLanguages(themesPath: string): { [themeName: string]: string[] } { - const extension = '.json5'; - const themeLanguages: { [themeName: string]: string[] } = {}; +export function getThemeLanguageHashes(themesPath: string): { [themeName: string]: { [fileName: string]: string } } { + const themeHashes: { [themeName: string]: { [fileName: string]: string } } = {}; if (!existsSync(themesPath)) { - return themeLanguages; + return themeHashes; } for (const theme of readdirSync(themesPath)) { @@ -76,14 +75,12 @@ export function getThemeLanguages(themesPath: string): { [themeName: string]: st continue; } - const languages: string[] = readdirSync(i18nPath) - .filter((file: string) => file.endsWith(extension) && statSync(join(i18nPath, file)).isFile()) - .map((file: string) => file.slice(0, -extension.length)); + const hashes = getFileHashes(i18nPath, /.*\.json5/g); - if (languages.length > 0) { - themeLanguages[theme] = languages; + if (Object.keys(hashes).length > 0) { + themeHashes[theme] = hashes; } } - return themeLanguages; + return themeHashes; } diff --git a/webpack/webpack.common.ts b/webpack/webpack.common.ts index 70af8338bcc..36097cc60ce 100644 --- a/webpack/webpack.common.ts +++ b/webpack/webpack.common.ts @@ -6,7 +6,7 @@ import { EnvironmentPlugin } from 'webpack'; import { calculateFileHash, getFileHashes, - getThemeLanguages, + getThemeLanguageHashes, globalCSSImports, projectRoot, } from './helpers'; @@ -57,6 +57,23 @@ export const copyWebpackOptions = { } }, }, + { + // theme i18n override files get a content hash as well, like the base files above + from: join(__dirname, '..', 'src', 'themes', '*', 'assets', 'i18n', '*.json5').replace(/\\/g, '/'), + noErrorOnMissing: true, + to({ absoluteFilename }) { + // use [\/|\\] to match both POSIX and Windows separators + const matches = absoluteFilename.match(/.*[\/|\\]themes[\/|\\]([^\/|^\\]+)[\/|\\]assets[\/|\\]i18n[\/|\\](.+)\.json5$/); + if (matches) { + const fileHash: string = process.env.NODE_ENV === 'production' ? `.${calculateFileHash(absoluteFilename)}` : ''; + // e.g. themes/custom/assets/i18n/en.json5 will end up in assets/custom/i18n/en..json + return join('assets', matches[1], 'i18n', `${matches[2]}${fileHash}.json`); + } + }, + transform(content) { + return JSON.stringify(parse(content.toString())); + }, + }, { from: join(__dirname, '..', 'src', 'robots.txt.ejs'), to: 'assets/robots.txt.ejs', @@ -87,7 +104,7 @@ export const commonExports = { new GenerateDecoratorRegistriesPlugin(), new EnvironmentPlugin({ languageHashes: getFileHashes(join(__dirname, '..', 'src', 'assets', 'i18n'), /.*\.json5/g), - themeLanguages: getThemeLanguages(join(__dirname, '..', 'src', 'themes')), + themeLanguageHashes: getThemeLanguageHashes(join(__dirname, '..', 'src', 'themes')), }), new CopyWebpackPlugin(copyWebpackOptions), ],