Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 2 additions & 3 deletions src/builders/build/builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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(
Expand Down Expand Up @@ -623,7 +622,7 @@ export async function* runBuilder(
throw new AbortedError("[builder] After federation build.");
}

if (hasLocales && localeFilter) {
if (i18n && localeFilter) {
translateFederationArtifacts(
i18n,
localeFilter,
Expand Down
70 changes: 70 additions & 0 deletions src/builders/build/i18n.integration.spec.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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');
Expand Down
152 changes: 152 additions & 0 deletions src/builders/build/i18n.spec.ts
Original file line number Diff line number Diff line change
@@ -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';

Expand Down Expand Up @@ -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 () => {
Expand All @@ -93,6 +96,155 @@ describe('translateFederationArtifacts', () => {
expect(infoSpy).not.toHaveBeenCalled();
});

describe('source locale', () => {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Since #176, callers pass base/browser and localePath no longer adds browser. These dist/browser/<locale> expectations (and the ones in the integration spec) will fail after a rebase on main.

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<string, string> | 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');

Expand Down
Loading
Loading