fix(core): race condition when setting locale

Currently we have a global state that tracks the locale. The problem is that it is set asynchronously after a promise which makes it prone to race conditions during SSR.

These changes resolve the issue by tracking the locale in the `LView` instead.
This commit is contained in:
Kristiyan Kostadinov
2026-10-14 12:35:58 +02:00
committed by Kristiyan Kostadinov
parent 2136a25961
commit 38816151b8
22 changed files with 83 additions and 164 deletions
@@ -81,7 +81,6 @@ export {
ɵsetClassDebugInfo,
setClassMetadata as ɵsetClassMetadata,
setClassMetadataAsync as ɵsetClassMetadataAsync,
setLocaleId as ɵsetLocaleId,
ɵsetUnknownElementStrictMode,
ɵsetUnknownPropertyStrictMode,
store as ɵstore,
-7
View File
@@ -11,12 +11,9 @@ import {PROVIDED_NG_ZONE} from '../change_detection/scheduling/ng_zone_schedulin
import {R3Injector} from '../di/r3_injector';
import {INTERNAL_APPLICATION_ERROR_HANDLER} from '../error_handler';
import {formatRuntimeError, RuntimeError, RuntimeErrorCode} from '../errors';
import {DEFAULT_LOCALE_ID} from '../i18n/localization';
import {LOCALE_ID} from '../i18n/tokens';
import {ImagePerformanceWarning} from '../image_performance_warning';
import {Type} from '../interface/type';
import {PLATFORM_DESTROY_LISTENERS} from './platform_destroy_listeners';
import {setLocaleId} from '../render3/i18n/i18n_locale_id';
import {NgZone} from '../zone/ng_zone';
import {ApplicationInitStatus} from '../application/application_init';
@@ -142,10 +139,6 @@ export function bootstrap<M>(
return initStatus.donePromise
.then(() => {
// If the `LOCALE_ID` provider is defined at bootstrap then we set the value for ivy
const localeId = envInjector.get(LOCALE_ID, DEFAULT_LOCALE_ID);
setLocaleId(localeId || DEFAULT_LOCALE_ID);
const enableRootComponentbootstrap = envInjector.get(
ENABLE_ROOT_COMPONENT_BOOTSTRAP,
true,
@@ -83,6 +83,8 @@ import {getComponentLViewByIndex, getTNode, storeLViewOnDestroy} from './util/vi
import {createLView, createTView, getInitialLViewFlagsFromDef} from './view/construction';
import {directiveHostEndFirstCreatePass, directiveHostFirstCreatePass} from './view/elements';
import {ViewRef} from './view_ref';
import {DEFAULT_LOCALE_ID} from '../i18n/localization';
import {LOCALE_ID} from '../i18n/tokens';
const shadowRootSupported = typeof ShadowRoot !== 'undefined';
const documentSupported = typeof Document !== 'undefined';
@@ -171,6 +173,7 @@ function createRootLViewEnvironment(rootLViewInjector: Injector): LViewEnvironme
changeDetectionScheduler,
ngReflect,
tracingService,
locale: rootLViewInjector.get(LOCALE_ID, DEFAULT_LOCALE_ID),
};
}
+4 -5
View File
@@ -38,7 +38,7 @@ import {
import {TNode} from '../interfaces/node';
import {RElement, RNode, RText} from '../interfaces/renderer_dom';
import {SanitizerFn} from '../interfaces/sanitization';
import {HEADER_OFFSET, HYDRATION, LView, RENDERER, TView} from '../interfaces/view';
import {ENVIRONMENT, HEADER_OFFSET, HYDRATION, LView, RENDERER, TView} from '../interfaces/view';
import {
createCommentNode,
createElementNode,
@@ -58,7 +58,6 @@ import {
import {renderStringify} from '../util/stringify_utils';
import {getNativeByIndex, unwrapRNode} from '../util/view_utils';
import {getLocaleId} from './i18n_locale_id';
import {
getCurrentICUCaseIndex,
getParentFromIcuCreateOpCode,
@@ -529,7 +528,7 @@ function applyIcuUpdateCase(tView: TView, tIcu: TIcu, bindingsStartIndex: number
*/
function applyIcuSwitchCase(tView: TView, tIcu: TIcu, lView: LView, value: string) {
// Rebuild a new case for this ICU
const caseIndex = getCaseIndex(tIcu, value);
const caseIndex = getCaseIndex(lView[ENVIRONMENT].locale, tIcu, value);
let activeCaseIndex = getCurrentICUCaseIndex(tIcu, lView);
if (activeCaseIndex !== caseIndex) {
applyIcuSwitchCaseRemove(tView, tIcu, lView);
@@ -579,12 +578,12 @@ function applyIcuSwitchCaseRemove(tView: TView, tIcu: TIcu, lView: LView) {
* @param icuExpression
* @param bindingValue The value of the main binding used by this ICU expression
*/
function getCaseIndex(icuExpression: TIcu, bindingValue: string): number | null {
function getCaseIndex(locale: string, icuExpression: TIcu, bindingValue: string): number | null {
let index = icuExpression.cases.indexOf(bindingValue);
if (index === -1) {
switch (icuExpression.type) {
case IcuType.plural: {
const resolvedCase = getPluralCase(bindingValue, getLocaleId());
const resolvedCase = getPluralCase(bindingValue, locale);
index = icuExpression.cases.indexOf(resolvedCase);
if (index === -1 && resolvedCase !== 'other') {
index = icuExpression.cases.indexOf('other');
@@ -1,40 +0,0 @@
/**
* @license
* Copyright Google LLC All Rights Reserved.
*
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.dev/license
*/
import {DEFAULT_LOCALE_ID} from '../../i18n/localization';
import {assertDefined} from '../../util/assert';
/**
* The locale id that the application is currently using (for translations and ICU expressions).
* This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
* but is now defined as a global value.
*/
let LOCALE_ID = DEFAULT_LOCALE_ID;
/**
* Sets the locale id that will be used for translations and ICU expressions.
* This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
* but is now defined as a global value.
*
* @param localeId
*/
export function setLocaleId(localeId: string) {
ngDevMode && assertDefined(localeId, `Expected localeId to be defined`);
if (typeof localeId === 'string') {
LOCALE_ID = localeId.toLowerCase().replace(/_/g, '-');
}
}
/**
* Gets the locale id that will be used for translations and ICU expressions.
* This is the ivy version of `LOCALE_ID` that was defined as an injection token for the view engine
* but is now defined as a global value.
*/
export function getLocaleId(): string {
return LOCALE_ID;
}
-1
View File
@@ -50,7 +50,6 @@ import {
export {NgModuleType} from '../metadata/ng_module_def';
export {ComponentFactory, ComponentRef} from './component_ref';
export {ɵɵgetInheritedFactory} from './di';
export {getLocaleId, setLocaleId} from './i18n/i18n_locale_id';
export {
ɵɵadvance,
ɵɵariaProperty,
@@ -404,6 +404,9 @@ export interface LViewEnvironment {
* (always disabled in prod mode).
*/
ngReflect: boolean;
/** Locale that should be used in i18n instructions. */
locale: string;
}
/** Flags associated with an LView (saved in LView[FLAGS]) */
+69 -4
View File
@@ -14,8 +14,8 @@ import localeEs from '@angular/common/locales/es';
import localeRo from '@angular/common/locales/ro';
import {computeMsgId} from '@angular/compiler';
import {clearTranslations, loadTranslations} from '@angular/localize';
import {By} from '@angular/platform-browser';
import {isBrowser} from '@angular/private/testing';
import {bootstrapApplication, By} from '@angular/platform-browser';
import {isBrowser, withBody} from '@angular/private/testing';
import {expect} from '@angular/private/testing/matchers';
import {BehaviorSubject} from 'rxjs';
import {
@@ -40,6 +40,9 @@ import {
ViewChild,
ViewContainerRef,
ɵsetDocument,
ɵunregisterLocaleData as unregisterLocaleData,
destroyPlatform,
signal,
} from '../../src/core';
import {provideNgReflectAttributes} from '../../src/ng_reflect';
import {HEADER_OFFSET} from '../../src/render3/interfaces/view';
@@ -1748,7 +1751,6 @@ describe('runtime i18n', () => {
// Spacing will break the ICU parsing
// prettier-ignore
@Component({
template: `
<div i18n="@@idA">{
type, select,
@@ -1807,7 +1809,6 @@ describe('runtime i18n', () => {
// Spacing will break the ICU parsing
// prettier-ignore
@Component({
template: `
<div i18n="@@idA">{count$ | async, select, 1 {{{count$ | async}} item} 2 {two items}}</div>
`,
@@ -3636,6 +3637,70 @@ describe('runtime i18n', () => {
});
}
});
describe('plural locale resolution', () => {
@Component({
selector: 'app',
template: `<div>{count(), plural, one {one item} few {a few items} other {many items}}</div>`,
})
class App {
readonly count = signal(3);
}
beforeEach(() => registerLocaleData(localeRo));
afterEach(() => unregisterLocaleData());
it('should resolve the plural case using the LOCALE_ID provided to TestBed', () => {
TestBed.configureTestingModule({providers: [{provide: LOCALE_ID, useValue: 'ro'}]});
const fixture = TestBed.createComponent(App);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('a few items');
fixture.componentInstance.count.set(1);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('one item');
fixture.componentInstance.count.set(20);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('many items');
fixture.componentInstance.count.set(10);
fixture.detectChanges();
expect(fixture.nativeElement.textContent).toBe('a few items');
});
describe('with bootstrapApplication', () => {
beforeEach(destroyPlatform);
afterEach(destroyPlatform);
it(
'should resolve the plural case using the LOCALE_ID provided during bootstrap',
withBody('<app></app>', async () => {
const appRef = await bootstrapApplication(App, {
providers: [{provide: LOCALE_ID, useValue: 'ro'}],
});
const host = document.querySelector('app')!;
const app = appRef.components[0].instance as App;
appRef.tick();
expect(host.textContent).toBe('a few items');
app.count.set(1);
appRef.tick();
expect(host.textContent).toBe('one item');
app.count.set(20);
appRef.tick();
expect(host.textContent).toBe('many items');
app.count.set(10);
appRef.tick();
expect(host.textContent).toBe('a few items');
appRef.destroy();
}),
);
});
});
});
function initWithTemplate(compType: Type<any>, template: string, imports?: Type<any>[]) {
@@ -8,16 +8,9 @@
import {DEFAULT_CURRENCY_CODE, LOCALE_ID} from '../src/core';
import {DEFAULT_LOCALE_ID} from '../src/i18n/localization';
import {getLocaleId, setLocaleId} from '../src/render3';
import {global} from '../src/util/global';
import {TestBed} from '../testing';
describe('Application module', () => {
beforeEach(() => {
setLocaleId(DEFAULT_LOCALE_ID);
});
it('should set the default locale to "en-US"', () => {
const defaultLocale = TestBed.inject(LOCALE_ID);
expect(defaultLocale).toEqual('en-US');
@@ -27,59 +20,4 @@ describe('Application module', () => {
const defaultCurrencyCode = TestBed.inject(DEFAULT_CURRENCY_CODE);
expect(defaultCurrencyCode).toEqual('USD');
});
it('should set the ivy locale with the configured LOCALE_ID', () => {
TestBed.configureTestingModule({providers: [{provide: LOCALE_ID, useValue: 'fr'}]});
const before = getLocaleId();
const locale = TestBed.inject(LOCALE_ID);
const after = getLocaleId();
expect(before).toEqual('en-us');
expect(locale).toEqual('fr');
expect(after).toEqual('fr');
});
describe('$localize.locale', () => {
beforeEach(() => initLocale('de'));
afterEach(() => restoreLocale());
it('should set the ivy locale to `$localize.locale` value if it is defined', () => {
// Injecting `LOCALE_ID` should also initialize the ivy locale
const locale = TestBed.inject(LOCALE_ID);
expect(locale).toEqual('de');
expect(getLocaleId()).toEqual('de');
});
it('should set the ivy locale to an application provided LOCALE_ID even if `$localize.locale` is defined', () => {
TestBed.configureTestingModule({providers: [{provide: LOCALE_ID, useValue: 'fr'}]});
const locale = TestBed.inject(LOCALE_ID);
expect(locale).toEqual('fr');
expect(getLocaleId()).toEqual('fr');
});
});
});
let hasGlobalLocalize: boolean;
let hasGlobalLocale: boolean;
let originalLocale: string;
function initLocale(locale: string) {
hasGlobalLocalize = Object.getOwnPropertyNames(global).includes('$localize');
if (!hasGlobalLocalize) {
global.$localize = {};
}
hasGlobalLocale = Object.getOwnPropertyNames(global.$localize).includes('locale');
originalLocale = global.$localize.locale;
global.$localize.locale = locale;
}
function restoreLocale() {
if (hasGlobalLocale) {
global.$localize.locale = originalLocale;
} else {
delete global.$localize.locale;
}
if (!hasGlobalLocalize) {
delete global.$localize;
}
}
+1 -17
View File
@@ -40,7 +40,7 @@ import {
import {ERROR_DETAILS_PAGE_BASE_URL} from '../src/error_details_base_url';
import {ErrorHandler} from '../src/error_handler';
import {ComponentRef} from '../src/linker/component_factory';
import {createEnvironmentInjector, getLocaleId} from '../src/render3';
import {createEnvironmentInjector} from '../src/render3';
import {take} from 'rxjs/operators';
import {compileNgModuleFactory} from '../src/application/application_ngmodule_factory_compiler';
@@ -567,22 +567,6 @@ describe('bootstrap', () => {
expect(loadResourceSpy).toHaveBeenCalledWith('/test-template.html');
});
it('should define `LOCALE_ID`', async () => {
@Component({
templateUrl: '',
standalone: false,
})
class I18nComponent {}
const testModule = await createModule({
component: I18nComponent,
providers: [{provide: LOCALE_ID, useValue: 'ro'}],
});
await defaultPlatform.bootstrapModule(testModule);
expect(getLocaleId()).toEqual('ro');
});
it('should wait for APP_INITIALIZER to set providers for `LOCALE_ID`', async () => {
let locale: string = '';
@@ -136,7 +136,6 @@
"LEAVE_TOKEN",
"LEAVE_TOKEN_REGEX",
"LOCALE_ID",
"LOCALE_ID",
"MATH_ML_NAMESPACE",
"MAXIMUM_REFRESH_RERUNS",
"MAXIMUM_REFRESH_RERUNS",
@@ -811,7 +810,6 @@
"setInjectImplementation",
"setInputsFromAttrs",
"setIsRefreshingViews",
"setLocaleId",
"setPropertyAndInputs",
"setRootDomAdapter",
"setSelectedIndex",
@@ -100,7 +100,6 @@
"InputFlags",
"KeyEventsPlugin",
"LOCALE_ID",
"LOCALE_ID",
"MATH_ML_NAMESPACE",
"MAXIMUM_REFRESH_RERUNS",
"MAXIMUM_REFRESH_RERUNS",
@@ -665,7 +664,6 @@
"setInjectImplementation",
"setInputsFromAttrs",
"setIsRefreshingViews",
"setLocaleId",
"setRootDomAdapter",
"setSelectedIndex",
"setShadowStylingInputFlags",
@@ -147,7 +147,6 @@
"InputFlags",
"LOADING_AFTER_SLOT",
"LOCALE_ID",
"LOCALE_ID",
"MATH_ML_NAMESPACE",
"MAXIMUM_REFRESH_RERUNS",
"MAXIMUM_REFRESH_RERUNS",
@@ -705,7 +704,6 @@
"setInputsFromAttrs",
"setIsRefreshingViews",
"setLDeferBlockDetails",
"setLocaleId",
"setSelectedIndex",
"setShadowStylingInputFlags",
"setTDeferBlockDetails",
@@ -141,7 +141,6 @@
"IterableDiffers",
"KeyEventsPlugin",
"LOCALE_ID",
"LOCALE_ID",
"MATH_ML_NAMESPACE",
"MAXIMUM_REFRESH_RERUNS",
"MAXIMUM_REFRESH_RERUNS",
@@ -988,7 +987,6 @@
"setInputsFromAttrs",
"setIsRefreshingViews",
"setJitOptions",
"setLocaleId",
"setModuleBootstrapImpl",
"setNativeDomProperty",
"setPropertyAndInputs",
@@ -134,7 +134,6 @@
"IterableDiffers",
"KeyEventsPlugin",
"LOCALE_ID",
"LOCALE_ID",
"MATH_ML_NAMESPACE",
"MAXIMUM_REFRESH_RERUNS",
"MAXIMUM_REFRESH_RERUNS",
@@ -986,7 +985,6 @@
"setInputsFromAttrs",
"setIsRefreshingViews",
"setJitOptions",
"setLocaleId",
"setModuleBootstrapImpl",
"setNativeDomProperty",
"setPropertyAndInputs",
@@ -157,7 +157,6 @@
"KeyEventsPlugin",
"LOADING_AFTER_SLOT",
"LOCALE_ID",
"LOCALE_ID",
"MATH_ML_NAMESPACE",
"MAXIMUM_REFRESH_RERUNS",
"MAXIMUM_REFRESH_RERUNS",
@@ -918,7 +917,6 @@
"setIsI18nHydrationSupportEnabled",
"setIsRefreshingViews",
"setIsReplay",
"setLocaleId",
"setParsed",
"setResolved",
"setRootDomAdapter",
@@ -140,7 +140,6 @@
"KeyEventsPlugin",
"LINKED_SIGNAL_NODE",
"LOCALE_ID",
"LOCALE_ID",
"LQueries_",
"LQuery_",
"ListComponent",
@@ -1096,7 +1095,6 @@
"setInjectImplementation",
"setInputsFromAttrs",
"setIsRefreshingViews",
"setLocaleId",
"setRootDomAdapter",
"setRouterState",
"setSelectedIndex",
@@ -95,7 +95,6 @@
"InputFlags",
"KeyEventsPlugin",
"LOCALE_ID",
"LOCALE_ID",
"MATH_ML_NAMESPACE",
"MAXIMUM_REFRESH_RERUNS",
"MAXIMUM_REFRESH_RERUNS",
@@ -594,7 +593,6 @@
"setInjectImplementation",
"setInputsFromAttrs",
"setIsRefreshingViews",
"setLocaleId",
"setRootDomAdapter",
"setSelectedIndex",
"setShadowStylingInputFlags",
+1
View File
@@ -156,6 +156,7 @@ describe('di', () => {
changeDetectionScheduler: null,
ngReflect: false,
tracingService: null,
locale: 'en-us',
},
{} as any,
null,
@@ -71,6 +71,7 @@ export function enterViewWithOneDiv() {
changeDetectionScheduler: null,
ngReflect: false,
tracingService: null,
locale: 'en-us',
},
renderer,
null,
@@ -118,6 +118,7 @@ export class ViewFixture {
changeDetectionScheduler: {notify: noop, runningTick: false},
ngReflect: false,
tracingService: null,
locale: 'en-us',
},
hostRenderer,
null,
@@ -34,7 +34,6 @@ import {
ɵINTERNAL_APPLICATION_ERROR_HANDLER as INTERNAL_APPLICATION_ERROR_HANDLER,
ɵInternalEnvironmentProviders as InternalEnvironmentProviders,
ɵisEnvironmentProviders as isEnvironmentProviders,
LOCALE_ID,
ModuleWithProviders,
ɵNG_COMP_DEF as NG_COMP_DEF,
ɵNG_DIR_DEF as NG_DIR_DEF,
@@ -54,7 +53,6 @@ import {
ɵprovideZonelessChangeDetectionInternal as provideZonelessChangeDetectionInternal,
ɵNgModuleFactory as R3NgModuleFactory,
resolveForwardRef,
ɵsetLocaleId as setLocaleId,
StaticProvider,
ɵtransitiveScopesFor as transitiveScopesFor,
Type,
@@ -449,13 +447,6 @@ export class TestBedCompiler {
// ApplicationInitStatus.runInitializers() is marked @internal to core.
// Cast it to any before accessing it.
(this.testModuleRef.injector.get(ApplicationInitStatus) as any).runInitializers();
// Set locale ID after running app initializers, since locale information might be updated while
// running initializers. This is also consistent with the execution order while bootstrapping an
// app (see `packages/core/src/application_ref.ts` file).
const localeId = this.testModuleRef.injector.get(LOCALE_ID, DEFAULT_LOCALE_ID);
setLocaleId(localeId);
return this.testModuleRef;
}
@@ -978,8 +969,6 @@ export class TestBedCompiler {
this.initialNgDefs.clear();
this.scopesWithOverriddenProviders.clear();
this.restoreComponentResolutionQueue();
// Restore the locale ID to the default value, this shouldn't be necessary but we never know
setLocaleId(DEFAULT_LOCALE_ID);
}
private compileTestModule(): void {