Skip to content

Commit a682c99

Browse files
committed
fix(@angular/build): keep generated locale polyfills cacheable
1 parent 8b26efa commit a682c99

4 files changed

Lines changed: 81 additions & 39 deletions

File tree

‎packages/angular/build/src/tools/esbuild/application-code-bundle.ts‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@ import {
1919
SERVER_APP_MANIFEST_FILENAME,
2020
SERVER_GENERATED_EXTERNALS,
2121
} from '../../utils/server-rendering/manifest';
22+
import { loadLocaleData } from '../i18n/locale-data';
2223
import { AngularCompilationContext } from './angular/compilation-state';
2324
import { createCompilerPlugin } from './angular/compiler-plugin';
2425
import { ComponentStylesheetBundler } from './angular/component-stylesheets';
@@ -706,6 +707,22 @@ function getEsBuildCommonPolyfillsOptions(
706707
if (i18nOptions.shouldInline) {
707708
// Remove localize polyfill when i18n inline transformation have been applied to all the packages.
708709
polyfills = polyfills.filter((path) => !path.startsWith('@angular/localize'));
710+
711+
if (polyfills.length === 0 && !options.watch) {
712+
buildOptions.plugins.push({
713+
name: 'angular-locale-data-hash',
714+
async setup({ initialOptions }) {
715+
// The generated polyfills module only inlines the locale ID and locale data, not messages.
716+
// Account for both in the shared output hash before esbuild assigns the filename.
717+
const data = await Promise.all(
718+
Array.from(i18nOptions.inlineLocales)
719+
.sort()
720+
.map(async (locale) => [locale, (await loadLocaleData(locale)).code]),
721+
);
722+
initialOptions.footer = { js: `/**i18n:${calculateHash(JSON.stringify(data))}*/` };
723+
},
724+
});
725+
}
709726
} else if (i18nOptions.hasDefinedSourceLocale) {
710727
// When not inlining and a source locale is present, use the source locale data directly
711728
polyfills.unshift(`angular:locale/data:${i18nOptions.sourceLocale}`);

‎packages/angular/build/src/tools/i18n/i18n-inliner-worker.ts‎

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -19,7 +19,7 @@ import { deserialize } from 'node:v8';
1919
import { parseSync } from 'oxc-parser';
2020
import { traversePostOrder } from '../oxc/traversal';
2121
import { createSharedTranslationProxy } from './i18n-translation-reader';
22-
import { loadLocaleData } from './locale-data';
22+
import { type LoadedLocaleData, loadLocaleData } from './locale-data';
2323

2424
/**
2525
* The options passed to the inliner for each code request
@@ -152,6 +152,8 @@ const fileDataCache = new Map<string, Promise<CachedFileData>>();
152152
*/
153153
const deserializedTranslations = new Map<string, Promise<Record<string, ɵParsedTranslation>>>();
154154

155+
const localeDataCache = new Map<string, Promise<LoadedLocaleData>>();
156+
155157
/**
156158
* The current inlining generation for this worker.
157159
*/
@@ -502,7 +504,12 @@ async function inlineLocalize(
502504
}
503505

504506
if (metadata.localeInsertSites.length > 0) {
505-
const localeData = await loadLocaleData(locale);
507+
let pendingLocaleData = localeDataCache.get(locale);
508+
if (!pendingLocaleData) {
509+
pendingLocaleData = loadLocaleData(locale);
510+
localeDataCache.set(locale, pendingLocaleData);
511+
}
512+
const localeData = await pendingLocaleData;
506513
if (localeData.error) {
507514
diagnostics.push({ type: 'error', message: localeData.error });
508515
} else if (localeData.warning) {

‎packages/angular/build/src/tools/i18n/locale-data.ts‎

Lines changed: 16 additions & 31 deletions
Original file line numberDiff line numberDiff line change
@@ -37,8 +37,6 @@ export interface LoadedLocaleData {
3737
error?: string;
3838
}
3939

40-
const localeDataCache = new Map<string, Promise<LoadedLocaleData>>();
41-
4240
/**
4341
* Resolves the path to the Angular locale data file for a given locale tag.
4442
*
@@ -98,41 +96,28 @@ export function resolveLocaleDataPath(
9896
* @param projectRoot Optional project root for module resolution.
9997
* @returns A promise resolving to the loaded locale data script code and any diagnostic warnings.
10098
*/
101-
export function loadLocaleData(
99+
export async function loadLocaleData(
102100
rawLocaleTag: string,
103101
projectRoot?: string,
104102
): Promise<LoadedLocaleData> {
105-
let cached = localeDataCache.get(rawLocaleTag);
106-
if (!cached) {
107-
cached = (async () => {
108-
const projectResolve = createProjectResolver(projectRoot ?? process.cwd());
109-
const resolution = resolveLocaleDataPath(rawLocaleTag, (potentialPath) => {
110-
try {
111-
return projectResolve(potentialPath);
112-
} catch {
113-
return undefined;
114-
}
115-
});
116-
117-
if (resolution.error) {
118-
return { error: resolution.error };
119-
}
120-
121-
if (resolution.path) {
122-
try {
123-
const code = await readFile(resolution.path, 'utf8');
103+
const projectResolve = createProjectResolver(projectRoot ?? process.cwd());
104+
const resolution = resolveLocaleDataPath(rawLocaleTag, (potentialPath) =>
105+
projectResolve(potentialPath),
106+
);
124107

125-
return { code, warning: resolution.warning };
126-
} catch (e) {
127-
return { error: `Failed to read locale data file: ${(e as Error).message}` };
128-
}
129-
}
108+
if (resolution.error) {
109+
return { error: resolution.error };
110+
}
130111

131-
return { warning: resolution.warning };
132-
})();
112+
if (resolution.path) {
113+
try {
114+
const code = await readFile(resolution.path, 'utf8');
133115

134-
localeDataCache.set(rawLocaleTag, cached);
116+
return { code, warning: resolution.warning };
117+
} catch (e) {
118+
return { error: `Failed to read locale data file: ${(e as Error).message}` };
119+
}
135120
}
136121

137-
return cached;
122+
return { warning: resolution.warning };
138123
}

‎tests/e2e/tests/i18n/ivy-localize-hashes.ts‎

Lines changed: 39 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,9 +6,12 @@
66
* found in the LICENSE file at https://angular.dev/license
77
*/
88

9-
import * as fs from 'node:fs';
10-
import { appendToFile } from '../../utils/fs';
9+
import assert from 'node:assert/strict';
10+
import { readdirSync, readFileSync } from 'node:fs';
11+
import { getGlobalVariable } from '../../utils/env';
12+
import { replaceInFile } from '../../utils/fs';
1113
import { ng } from '../../utils/process';
14+
import { updateJsonFile } from '../../utils/project';
1215
import { langTranslations, setupI18nConfig } from './setup';
1316

1417
const OUTPUT_RE = /^(?<name>(?:main|vendor|\d+))(?:\.|-)(?<hash>[a-z0-9]+)\.js$/i;
@@ -17,11 +20,27 @@ export default async function () {
1720
// Setup i18n tests and config.
1821
await setupI18nConfig();
1922

23+
const esbuild = getGlobalVariable('argv')['esbuild'];
24+
if (esbuild) {
25+
// Test the polyfills bundle that contains only the CLI-generated locale initialization.
26+
await updateJsonFile('angular.json', (workspace) => {
27+
workspace.projects['test-project'].architect['build'].options.polyfills = [];
28+
});
29+
}
30+
2031
// Build each locale and record output file hashes
2132
const hashes = new Map<string, string>();
33+
const polyfills = new Map<string, { name: string; content: string }>();
2234
await ng('build', '--output-hashing=all', '--configuration=development');
2335
for (const { lang, outputPath } of langTranslations) {
24-
for (const entry of fs.readdirSync(outputPath)) {
36+
for (const entry of readdirSync(outputPath)) {
37+
if (esbuild && /^polyfills-[a-z0-9]+\.js$/i.test(entry)) {
38+
polyfills.set(lang, {
39+
name: entry,
40+
content: readFileSync(`${outputPath}/${entry}`, 'utf-8'),
41+
});
42+
}
43+
2544
const match = entry.match(OUTPUT_RE);
2645
if (!match?.groups) {
2746
continue;
@@ -36,13 +55,27 @@ export default async function () {
3655
throw new Error('No output entries found.');
3756
}
3857

39-
// Alter content of a used translation file
40-
await appendToFile('src/locale/messages.fr.xlf', '\n');
58+
if (esbuild) {
59+
assert.equal(polyfills.size, langTranslations.length);
60+
assert.equal(new Set(Array.from(polyfills.values(), ({ name }) => name)).size, 1);
61+
}
62+
63+
// Change a translated message without changing any application source.
64+
await replaceInFile('src/locale/messages.fr.xlf', 'Bonjour', 'Salut');
4165

4266
// Build each locale and ensure hashes are different
4367
await ng('build', '--output-hashing=all', '--configuration=development');
4468
for (const { lang, outputPath } of langTranslations) {
45-
for (const entry of fs.readdirSync(outputPath)) {
69+
const localePolyfills = polyfills.get(lang);
70+
if (localePolyfills) {
71+
assert.equal(
72+
readFileSync(`${outputPath}/${localePolyfills.name}`, 'utf-8'),
73+
localePolyfills.content,
74+
`Expected the generated polyfills to stay cacheable for ${lang}.`,
75+
);
76+
}
77+
78+
for (const entry of readdirSync(outputPath)) {
4679
const match = entry.match(OUTPUT_RE);
4780
if (!match?.groups) {
4881
continue;

0 commit comments

Comments
 (0)