diff --git a/src/builders/build/builder.ts b/src/builders/build/builder.ts index fdc40789..3d36a629 100644 --- a/src/builders/build/builder.ts +++ b/src/builders/build/builder.ts @@ -514,8 +514,7 @@ export async function* runBuilder( syncFederationWatcher(); - const hasLocales = i18n?.locales && Object.keys(i18n.locales).length > 0; - if (hasLocales && localeFilter) { + if (i18n && localeFilter) { const start = process.hrtime(); translateFederationArtifacts( @@ -623,7 +622,7 @@ export async function* runBuilder( throw new AbortedError("[builder] After federation build."); } - if (hasLocales && localeFilter) { + if (i18n && localeFilter) { translateFederationArtifacts( i18n, localeFilter, diff --git a/src/builders/build/i18n.integration.spec.ts b/src/builders/build/i18n.integration.spec.ts index 9b2a6114..7a5f4701 100644 --- a/src/builders/build/i18n.integration.spec.ts +++ b/src/builders/build/i18n.integration.spec.ts @@ -1,5 +1,6 @@ import * as fs from 'fs'; import * as path from 'path'; +import { createHash } from 'crypto'; import { translateFederationArtifacts, type I18nConfig } from './i18n.js'; @@ -61,6 +62,75 @@ describe('translateFederationArtifacts with the real localize-translate CLI', () expect(fs.existsSync(path.join(browser, 'de', 'main.js'))).toBe(false); }); + it('inlines the source locale and refreshes the integrity hashes', () => { + const browser = path.join(workspaceRoot, 'dist', 'browser'); + const translation = path.join(workspaceRoot, 'messages.de.xlf'); + + write(translation, xlf); + write( + path.join(browser, 'en', 'remoteEntry.json'), + JSON.stringify({ integrity: { 'cmp.js': 'sha384-stale' } }) + ); + write(path.join(browser, 'en', 'cmp.js'), 'export const t = $localize`:@@greeting:Hello`;'); + + const i18n: I18nConfig = { sourceLocale: 'en', locales: { de: translation } }; + const federationFiles = ['cmp.js']; + + translateFederationArtifacts(i18n, true, 'dist/browser', federationFiles, workspaceRoot); + + for (const locale of ['en', 'de']) { + const file = path.join(browser, locale, 'cmp.js'); + const integrity = JSON.parse( + fs.readFileSync(path.join(browser, locale, 'remoteEntry.json'), 'utf8') + ).integrity; + expect(fs.readFileSync(file, 'utf8')).not.toContain('$localize'); + expect(integrity['cmp.js']).toBe( + `sha384-${createHash('sha384').update(fs.readFileSync(file)).digest('base64')}` + ); + } + expect(fs.readFileSync(path.join(browser, 'en', 'cmp.js'), 'utf8')).toContain('Hello'); + }); + + it('inlines the source locale when it is the only requested locale', () => { + const browser = path.join(workspaceRoot, 'dist', 'browser'); + write(path.join(browser, 'en', 'remoteEntry.json'), '{}'); + write(path.join(browser, 'en', 'cmp.js'), 'export const t = $localize`:@@greeting:Hello`;'); + + const i18n: I18nConfig = { sourceLocale: 'en', locales: {} }; + const federationFiles = ['cmp.js']; + + translateFederationArtifacts(i18n, true, 'dist/browser', federationFiles, workspaceRoot); + + const inlined = fs.readFileSync(path.join(browser, 'en', 'cmp.js'), 'utf8'); + expect(inlined).not.toContain('$localize'); + expect(inlined).toContain('Hello'); + }); + + it('leaves the output and integrity hashes unchanged when the source-only run repeats', () => { + const browser = path.join(workspaceRoot, 'dist', 'browser'); + write( + path.join(browser, 'en', 'remoteEntry.json'), + JSON.stringify({ integrity: { 'cmp.js': 'sha384-stale' } }) + ); + write(path.join(browser, 'en', 'cmp.js'), 'export const t = $localize`:@@greeting:Hello`;'); + + const i18n: I18nConfig = { sourceLocale: 'en', locales: {} }; + const read = (name: string) => fs.readFileSync(path.join(browser, 'en', name), 'utf8'); + + translateFederationArtifacts(i18n, ['en'], 'dist/browser', ['cmp.js'], workspaceRoot); + const firstCmp = read('cmp.js'); + const firstRemoteEntry = read('remoteEntry.json'); + + translateFederationArtifacts(i18n, ['en'], 'dist/browser', ['cmp.js'], workspaceRoot); + + expect(firstCmp).not.toContain('$localize'); + expect(read('cmp.js')).toBe(firstCmp); + expect(read('remoteEntry.json')).toBe(firstRemoteEntry); + expect(JSON.parse(firstRemoteEntry).integrity['cmp.js']).toBe( + `sha384-${createHash('sha384').update(firstCmp).digest('base64')}` + ); + }); + it('fails the build when a listed file is missing', () => { const browser = path.join(workspaceRoot, 'dist', 'browser'); const translation = path.join(workspaceRoot, 'messages.de.xlf'); diff --git a/src/builders/build/i18n.spec.ts b/src/builders/build/i18n.spec.ts index 8427e88b..e3e7c340 100644 --- a/src/builders/build/i18n.spec.ts +++ b/src/builders/build/i18n.spec.ts @@ -1,5 +1,6 @@ import * as fs from 'fs'; import { execFileSync } from 'child_process'; +import { createHash } from 'crypto'; import { logger } from '@softarc/native-federation/internal'; import type { BuilderContext } from '@angular-devkit/architect'; @@ -83,6 +84,8 @@ describe('translateFederationArtifacts', () => { vi.mocked(execFileSync).mockReturnValue(Buffer.from('translated ok')); vi.mocked(fs.mkdtempSync).mockReturnValue('/tmp/nf-i18n-x'); vi.mocked(fs.existsSync).mockReturnValue(true); + // an existing remoteEntry.json without integrity hashes + vi.mocked(fs.readFileSync).mockReturnValue('{}'); }); it('does nothing when no configured locale matches the requested ones', async () => { @@ -93,6 +96,155 @@ describe('translateFederationArtifacts', () => { expect(infoSpy).not.toHaveBeenCalled(); }); + describe('source locale', () => { + it('is inlined by the same run as the translations, without a translation file of its own', () => { + translateFederationArtifacts(i18n, true, 'dist/browser', federationFiles, '/ws'); + + expect(execFileSync).toHaveBeenCalledTimes(1); + expect(valueAfter(localizeArgs(), '-l')).toBe('en'); + expect(fs.writeFileSync).not.toHaveBeenCalled(); + expect( + vi.mocked(fs.cpSync).mock.calls.map(([from, to]) => [posix(String(from)), posix(String(to))]) + ).toContainEqual(['/tmp/nf-i18n-x/en', '/ws/dist/browser/en']); + }); + + it('is inlined when it is the only requested locale', () => { + translateFederationArtifacts(i18n, ['en'], 'dist/browser', federationFiles, '/ws'); + + const args = localizeArgs(); + expect(execFileSync).toHaveBeenCalledTimes(1); + expect(valueAfter(args, '-l')).toBe('en'); + // a bare -t is accepted by the CLI, and there are no target locales to name + expect(args.slice(args.indexOf('-t') + 1, args.indexOf('-o'))).toEqual([]); + expect(args).not.toContain('--target-locales'); + expect(fs.copyFileSync).not.toHaveBeenCalledWith( + expect.stringMatching(/remoteEntry\.json$/), + expect.stringMatching(/remoteEntry\.json$/) + ); + }); + + it('is inlined when localize is true and no locale is configured', () => { + translateFederationArtifacts( + { sourceLocale: 'en', locales: {} }, + true, + 'dist/browser', + federationFiles, + '/ws' + ); + + expect(execFileSync).toHaveBeenCalledTimes(1); + }); + + it('is inlined when the i18n config has no locales at all', () => { + translateFederationArtifacts( + { sourceLocale: 'en' }, + true, + 'dist/browser', + federationFiles, + '/ws' + ); + + expect(execFileSync).toHaveBeenCalledTimes(1); + expect(localizeArgs()).not.toContain('--target-locales'); + }); + }); + + describe('integrity hashes', () => { + const sha384 = (content: string) => + `sha384-${createHash('sha384').update(Buffer.from(content)).digest('base64')}`; + + const withRemoteEntry = (integrity: Record | undefined) => { + vi.mocked(fs.readFileSync).mockImplementation(file => { + if (String(file).endsWith('remoteEntry.json')) { + return JSON.stringify({ name: 'app', ...(integrity && { integrity }) }); + } + return String(file).endsWith('importmap.json') + ? '{}' + : (Buffer.from('translated content') as never); + }); + }; + + const writtenRemoteEntries = () => + Object.fromEntries( + vi + .mocked(fs.writeFileSync) + .mock.calls.filter(c => String(c[0]).endsWith('remoteEntry.json')) + .map(c => [posix(String(c[0])), JSON.parse(String(c[1]))]) + ); + + it('recomputes the hashes in the remoteEntry of every translated locale and the source locale', () => { + withRemoteEntry({ 'a.js': 'sha384-stale' }); + + translateFederationArtifacts(i18n, ['de', 'fr'], 'dist/browser', federationFiles, '/ws'); + + const written = writtenRemoteEntries(); + // the run that translates also writes the inlined source locale + expect(Object.keys(written).sort()).toEqual([ + '/ws/dist/browser/de/remoteEntry.json', + '/ws/dist/browser/en/remoteEntry.json', + '/ws/dist/browser/fr/remoteEntry.json', + ]); + expect(written['/ws/dist/browser/de/remoteEntry.json'].integrity).toEqual({ + 'a.js': sha384('translated content'), + }); + expect(written['/ws/dist/browser/de/remoteEntry.json'].name).toBe('app'); + }); + + it('keeps the algorithm of the existing hash', () => { + withRemoteEntry({ 'a.js': 'sha512-stale' }); + + translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationFiles, '/ws'); + + const hash = createHash('sha512').update(Buffer.from('translated content')).digest('base64'); + expect(writtenRemoteEntries()['/ws/dist/browser/de/remoteEntry.json'].integrity['a.js']).toBe( + `sha512-${hash}` + ); + }); + + it('keeps the hash of a file that is not in the locale folder', () => { + withRemoteEntry({ 'a.js': 'sha384-stale', 'gone.js': 'sha384-keep' }); + vi.mocked(fs.existsSync).mockImplementation(file => !String(file).endsWith('gone.js')); + + translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationFiles, '/ws'); + + const integrity = writtenRemoteEntries()['/ws/dist/browser/de/remoteEntry.json'].integrity; + expect(integrity['gone.js']).toBe('sha384-keep'); + expect(integrity['a.js']).toBe(sha384('translated content')); + }); + + it('recomputes the hashes in importmap.json next to the remoteEntry', () => { + vi.mocked(fs.readFileSync).mockImplementation(file => { + if (String(file).endsWith('importmap.json')) { + return JSON.stringify({ imports: { a: 'a.js' }, integrity: { 'a.js': 'sha384-stale' } }); + } + return String(file).endsWith('remoteEntry.json') + ? '{}' + : (Buffer.from('translated content') as never); + }); + + translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationFiles, '/ws'); + + const written = Object.fromEntries( + vi + .mocked(fs.writeFileSync) + .mock.calls.filter(c => String(c[0]).endsWith('importmap.json')) + .map(c => [posix(String(c[0])), JSON.parse(String(c[1]))]) + ); + expect(written['/ws/dist/browser/de/importmap.json'].integrity).toEqual({ + 'a.js': sha384('translated content'), + }); + expect(written['/ws/dist/browser/de/importmap.json'].imports).toEqual({ a: 'a.js' }); + }); + + it('does not touch a remoteEntry without integrity hashes', () => { + withRemoteEntry(undefined); + + translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationFiles, '/ws'); + + expect(writtenRemoteEntries()).toEqual({}); + }); + }); + it('filters to the intersection of requested and configured locales', async () => { translateFederationArtifacts(i18n, ['de'], 'dist/browser', federationFiles, '/ws'); diff --git a/src/builders/build/i18n.ts b/src/builders/build/i18n.ts index c015dbc7..3af9728d 100644 --- a/src/builders/build/i18n.ts +++ b/src/builders/build/i18n.ts @@ -1,6 +1,7 @@ import type { BuilderContext } from '@angular-devkit/architect'; import { logger } from '@softarc/native-federation/internal'; import { execFileSync } from 'child_process'; +import { createHash } from 'crypto'; import { createRequire } from 'module'; import os from 'os'; import path from 'path'; @@ -20,7 +21,7 @@ type LocaleObject = { export type I18nConfig = { sourceLocale?: string | SourceLocaleObject; - locales: Record; + locales?: Record; }; type SourceLocaleObject = { @@ -49,7 +50,7 @@ export function getLocaleSubPath(i18n: I18nConfig, locale: string): string { if (locale === getSourceLocaleCode(i18n)) { return typeof i18n.sourceLocale === 'string' ? locale : (i18n.sourceLocale?.subPath ?? locale); } - const config = i18n.locales[locale]; + const config = i18n.locales?.[locale]; if (config && typeof config === 'object' && !Array.isArray(config)) { return config.subPath ?? locale; } @@ -64,26 +65,30 @@ export function translateFederationArtifacts( workspaceRoot: string ) { outputPath = path.resolve(workspaceRoot, outputPath); - const neededLocales = Array.isArray(localize) ? localize : Object.keys(i18n.locales); + const sourceLocale = getSourceLocaleCode(i18n); + const configuredLocales = i18n.locales ?? {}; + const neededLocales = Array.isArray(localize) ? localize : Object.keys(configuredLocales); + + const targetLocales = Object.keys(configuredLocales).filter(locale => neededLocales.includes(locale)); - const locales = Object.keys(i18n.locales).filter(locale => neededLocales.includes(locale)); + // The federation output is not built by Angular, so its source locale copy needs inlining too + const inlineSourceLocale = + localize === true || (Array.isArray(localize) && localize.includes(sourceLocale)); - if (locales.length === 0) { + if (targetLocales.length === 0 && !inlineSourceLocale) { return; } logger.info('Writing Translations'); // localize-translate expects a list of files for one locale as `[a,b]` - const translationFiles = locales - .map(loc => i18n.locales[loc]) + const translationFiles = targetLocales + .map(loc => configuredLocales[loc]) .map(config => typeof config === 'string' || Array.isArray(config) ? config : config!.translation! ) .map(files => (Array.isArray(files) ? `[${files.join(',')}]` : files)); - const sourceLocale = getSourceLocaleCode(i18n); - // {{LOCALE}} expands to the locale code, not its subPath, so translate into a staging folder first const stagingPath = fs.mkdtempSync(path.join(os.tmpdir(), 'nf-i18n-')); const translationOutPath = path.join(stagingPath, '{{LOCALE}}'); @@ -106,13 +111,12 @@ export function translateFederationArtifacts( ...translationFiles, '-o', translationOutPath, - '--target-locales', - ...locales, + ...(targetLocales.length > 0 ? ['--target-locales', ...targetLocales] : []), '-l', sourceLocale, ]; - const targetPaths = locales.map(localePath); + const targetPaths = targetLocales.map(localePath); ensureDistFolders(targetPaths); copyRemoteEntry(targetPaths, sourceLocalePath); @@ -122,12 +126,17 @@ export function translateFederationArtifacts( logger.debug('Running: ' + [process.execPath, ...args].join(' ')); execCommand(process.execPath, args, workspaceRoot, 'Successfully translated'); - for (const locale of new Set([sourceLocale, ...locales])) { + const translatedPaths: string[] = []; + for (const locale of new Set([sourceLocale, ...targetLocales])) { const staged = path.join(stagingPath, locale); if (fs.existsSync(staged)) { fs.cpSync(staged, localePath(locale), { recursive: true }); + translatedPaths.push(localePath(locale)); } } + + // Translating changes the bundles, so the integrity hashes in the copied manifests are stale + refreshIntegrity(translatedPaths); } finally { fs.rmSync(stagingPath, { recursive: true, force: true }); } @@ -162,6 +171,39 @@ function execCommand(file: string, args: string[], cwd: string, defaultSuccessIn } } +function refreshIntegrity(localePaths: string[]) { + for (const localePath of localePaths) { + for (const manifest of ['remoteEntry.json', 'importmap.json']) { + refreshManifestIntegrity(localePath, path.join(localePath, manifest)); + } + } +} + +function refreshManifestIntegrity(localePath: string, manifestPath: string) { + if (!fs.existsSync(manifestPath)) { + return; + } + + const manifest = JSON.parse(fs.readFileSync(manifestPath, 'utf-8')) as { + integrity?: Record; + }; + if (!manifest.integrity) { + return; + } + + for (const [file, previous] of Object.entries(manifest.integrity)) { + const filePath = path.join(localePath, file); + if (!fs.existsSync(filePath)) { + continue; + } + const algorithm = previous.split('-')[0]!; + const hash = createHash(algorithm).update(fs.readFileSync(filePath)).digest('base64'); + manifest.integrity[file] = `${algorithm}-${hash}`; + } + + fs.writeFileSync(manifestPath, JSON.stringify(manifest, null, 2)); +} + function copyRemoteEntry(targetPaths: string[], sourceLocalePath: string) { const remoteEntry = path.join(sourceLocalePath, 'remoteEntry.json');