Skip to content

Commit

Permalink
refactor: standardize the way we detect ngDevMode
Browse files Browse the repository at this point in the history
typeof ngDevMode !== 'undefined' && ngDevMode is easier to understand than typeof ngDevMode === 'undefined' || ngDevMode, we also don't want the condition to be truthy if the ngDdevMode is undefined.
We're also keeping (ngDevMode === 'undefined' || ngDevMode) for cases where we need to actually check if it's missing such as initNgDevMode
  • Loading branch information
kirjs committed Dec 13, 2024
1 parent 4c2cdd2 commit 67cf4dd
Show file tree
Hide file tree
Showing 68 changed files with 180 additions and 148 deletions.
4 changes: 2 additions & 2 deletions packages/animations/browser/src/dsl/animation_ast_builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -141,7 +141,7 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor {
visitDslNode(this, normalizeAnimationEntry(metadata), context)
);

if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
if (context.unsupportedCSSPropertiesFound.size) {
pushUnrecognizedPropertiesWarning(warnings, [
...context.unsupportedCSSPropertiesFound.keys(),
Expand Down Expand Up @@ -387,7 +387,7 @@ export class AnimationAstBuilderVisitor implements AnimationDslVisitor {
if (typeof tuple === 'string') return;

tuple.forEach((value, prop) => {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
if (!this._driver.validateStyleProperty(prop)) {
tuple.delete(prop);
context.unsupportedCSSPropertiesFound.add(prop);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -128,7 +128,7 @@ export class AnimationTransitionFactory {
}
});

if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
checkNonAnimatableInTimelines(timelines, this._triggerName, driver);
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,15 @@ import {WebAnimationsPlayer} from './web_animations_player';
export class WebAnimationsDriver implements AnimationDriver {
validateStyleProperty(prop: string): boolean {
// Perform actual validation in dev mode only, in prod mode this check is a noop.
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
return validateStyleProperty(prop);
}
return true;
}

validateAnimatableStyleProperty(prop: string): boolean {
// Perform actual validation in dev mode only, in prod mode this check is a noop.
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
const cssProp = camelCaseToDashCase(prop);
return validateWebAnimatableStyleProperty(cssProp);
}
Expand Down
12 changes: 8 additions & 4 deletions packages/animations/browser/src/warning_helpers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,12 +15,14 @@ function createListOfWarnings(warnings: string[]): string {
}

export function warnValidation(warnings: string[]): void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
console.warn(`animation validation warnings:${createListOfWarnings(warnings)}`);
}

export function warnTriggerBuild(name: string, warnings: string[]): void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
console.warn(
`The animation trigger "${name}" has built with the following warnings:${createListOfWarnings(
warnings,
Expand All @@ -29,12 +31,14 @@ export function warnTriggerBuild(name: string, warnings: string[]): void {
}

export function warnRegister(warnings: string[]): void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
console.warn(`Animation built with the following warnings:${createListOfWarnings(warnings)}`);
}

export function triggerParsingWarnings(name: string, warnings: string[]): void {
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
console.warn(
`Animation parsing for the ${name} trigger presents the following warnings:${createListOfWarnings(
warnings,
Expand Down
3 changes: 2 additions & 1 deletion packages/animations/src/animation_builder.ts
Original file line number Diff line number Diff line change
Expand Up @@ -121,7 +121,8 @@ export class BrowserAnimationBuilder extends AnimationBuilder {

throw new RuntimeError(
RuntimeErrorCode.BROWSER_ANIMATION_BUILDER_INJECTED_WITHOUT_ANIMATIONS,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
'Angular detected that the `AnimationBuilder` was injected, but animation support was not enabled. ' +
'Please make sure that you enable animations in your application by calling `provideAnimations()` or `provideAnimationsAsync()` function.',
);
Expand Down
2 changes: 1 addition & 1 deletion packages/common/http/src/headers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ export class HttpHeaders {
});
} else {
this.lazyInit = () => {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
assertValidHeaders(headers);
}
this.headers = new Map<string, string[]>();
Expand Down
2 changes: 1 addition & 1 deletion packages/common/http/src/interceptor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ export class HttpInterceptorHandler extends HttpHandler {
// We strongly recommend using fetch backend for HTTP calls when SSR is used
// for an application. The logic below checks if that's the case and produces
// a warning otherwise.
if ((typeof ngDevMode === 'undefined' || ngDevMode) && !fetchBackendWarningDisplayed) {
if (typeof ngDevMode !== 'undefined' && ngDevMode && !fetchBackendWarningDisplayed) {
const isServer = isPlatformServer(injector.get(PLATFORM_ID));

// This flag is necessary because provideHttpClientTesting() overrides the backend
Expand Down
4 changes: 2 additions & 2 deletions packages/common/http/src/transfer_cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ export function transferCacheInterceptorFn(
// That HttpTransferCache alters the headers
// The warning will be logged a single time by HttpHeaders instance
let headers = new HttpHeaders(httpHeaders);
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
// Append extra logic in dev mode to produce a warning when a header
// that was not transferred to the client is accessed in the code via `get`
// and `has` calls.
Expand Down Expand Up @@ -401,7 +401,7 @@ function mapRequestOriginUrl(url: string, originMap: Record<string, string>): st
return url;
}

if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
verifyMappedOrigin(mappedOrigin);
}

Expand Down
3 changes: 2 additions & 1 deletion packages/common/http/src/xhr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,8 @@ export class HttpXhrBackend implements HttpBackend {
if (req.method === 'JSONP') {
throw new RuntimeError(
RuntimeErrorCode.MISSING_JSONP_MODULE,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
`Cannot make a JSONP request without JSONP support. To fix the problem, either add the \`withJsonpSupport()\` call (if \`provideHttpClient()\` is used) or import the \`HttpClientJsonpModule\` in the root NgModule.`,
);
}
Expand Down
4 changes: 2 additions & 2 deletions packages/common/src/directives/ng_for_of.ts
Original file line number Diff line number Diff line change
Expand Up @@ -198,7 +198,7 @@ export class NgForOf<T, U extends NgIterable<T> = NgIterable<T>> implements DoCh
*/
@Input()
set ngForTrackBy(fn: TrackByFunction<T>) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && fn != null && typeof fn !== 'function') {
if (typeof ngDevMode !== 'undefined' && ngDevMode && fn != null && typeof fn !== 'function') {
console.warn(
`trackBy must be a function, but received ${JSON.stringify(fn)}. ` +
`See https://angular.io/api/common/NgForOf#change-propagation for more information.`,
Expand Down Expand Up @@ -249,7 +249,7 @@ export class NgForOf<T, U extends NgIterable<T> = NgIterable<T>> implements DoCh
// React on ngForOf changes only once all inputs have been initialized
const value = this._ngForOf;
if (!this._differ && value) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
try {
// CAUTION: this logic is duplicated for production mode below, as the try-catch
// is only present in development builds.
Expand Down
4 changes: 2 additions & 2 deletions packages/common/src/directives/ng_switch.ts
Original file line number Diff line number Diff line change
Expand Up @@ -212,7 +212,7 @@ export class NgSwitchCase implements DoCheck {
templateRef: TemplateRef<Object>,
@Optional() @Host() private ngSwitch: NgSwitch,
) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) {
if (typeof ngDevMode !== 'undefined' && ngDevMode && !ngSwitch) {
throwNgSwitchProviderNotFoundError('ngSwitchCase', 'NgSwitchCase');
}

Expand Down Expand Up @@ -252,7 +252,7 @@ export class NgSwitchDefault {
templateRef: TemplateRef<Object>,
@Optional() @Host() ngSwitch: NgSwitch,
) {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && !ngSwitch) {
if (typeof ngDevMode !== 'undefined' && ngDevMode && !ngSwitch) {
throwNgSwitchProviderNotFoundError('ngSwitchDefault', 'NgSwitchDefault');
}

Expand Down
2 changes: 1 addition & 1 deletion packages/common/src/pipes/number_pipe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -274,7 +274,7 @@ export class CurrencyPipe implements PipeTransform {
locale ||= this._locale;

if (typeof display === 'boolean') {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && <any>console && <any>console.warn) {
if (typeof ngDevMode !== 'undefined' && ngDevMode && <any>console && <any>console.warn) {
console.warn(
`Warning: the currency pipe has been changed in Angular v5. The symbolDisplay option (third parameter) is now a string instead of a boolean. The accepted values are "code", "symbol" or "symbol-narrow".`,
);
Expand Down
6 changes: 4 additions & 2 deletions packages/core/rxjs-interop/src/to_signal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -186,7 +186,8 @@ export function toSignal<T, U = undefined>(
if (options?.requireSync && state().kind === StateKind.NoValue) {
throw new ɵRuntimeError(
ɵRuntimeErrorCode.REQUIRE_SYNC_WITHOUT_SYNC_EMIT,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
'`toSignal()` called with `requireSync` but `Observable` did not emit synchronously.',
);
}
Expand All @@ -208,7 +209,8 @@ export function toSignal<T, U = undefined>(
// This shouldn't really happen because the error is thrown on creation.
throw new ɵRuntimeError(
ɵRuntimeErrorCode.REQUIRE_SYNC_WITHOUT_SYNC_EMIT,
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
'`toSignal()` called with `requireSync` but `Observable` did not emit synchronously.',
);
}
Expand Down
2 changes: 1 addition & 1 deletion packages/core/src/application/application_init.ts
Original file line number Diff line number Diff line change
Expand Up @@ -224,7 +224,7 @@ export class ApplicationInitStatus {
private readonly injector = inject(Injector);

constructor() {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && !Array.isArray(this.appInits)) {
if (typeof ngDevMode !== 'undefined' && ngDevMode && !Array.isArray(this.appInits)) {
throw new RuntimeError(
RuntimeErrorCode.INVALID_MULTI_PROVIDER,
'Unexpected type of the `APP_INITIALIZER` token value ' +
Expand Down
21 changes: 11 additions & 10 deletions packages/core/src/application/application_ref.ts
Original file line number Diff line number Diff line change
Expand Up @@ -531,14 +531,15 @@ export class ApplicationRef {
componentOrFactory: ComponentFactory<C> | Type<C>,
rootSelectorOrNode?: string | any,
): ComponentRef<C> {
(typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
typeof ngDevMode !== 'undefined' && ngDevMode && this.warnIfDestroyed();
const isComponentFactory = componentOrFactory instanceof ComponentFactory;
const initStatus = this._injector.get(ApplicationInitStatus);

if (!initStatus.done) {
const standalone = !isComponentFactory && isStandalone(componentOrFactory);
const errorMessage =
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
'Cannot bootstrap as there are still asynchronous initializers running.' +
(standalone
? ''
Expand Down Expand Up @@ -572,7 +573,7 @@ export class ApplicationRef {
});

this._loadComponent(compRef);
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
const _console = this._injector.get(Console);
_console.log(`Angular is running in development mode.`);
}
Expand Down Expand Up @@ -610,7 +611,7 @@ export class ApplicationRef {
return;
}

(typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
typeof ngDevMode !== 'undefined' && ngDevMode && this.warnIfDestroyed();
if (this._runningTick) {
throw new RuntimeError(
RuntimeErrorCode.RECURSIVE_APPLICATION_REF_TICK,
Expand All @@ -623,7 +624,7 @@ export class ApplicationRef {
this._runningTick = true;
this.synchronize();

if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
for (let view of this.allViews) {
view.checkNoChanges();
}
Expand Down Expand Up @@ -656,7 +657,7 @@ export class ApplicationRef {
this.synchronizeOnce();
}

if ((typeof ngDevMode === 'undefined' || ngDevMode) && runs >= MAXIMUM_REFRESH_RERUNS) {
if (typeof ngDevMode !== 'undefined' && ngDevMode && runs >= MAXIMUM_REFRESH_RERUNS) {
throw new RuntimeError(
RuntimeErrorCode.INFINITE_CHANGE_DETECTION,
ngDevMode &&
Expand Down Expand Up @@ -768,7 +769,7 @@ export class ApplicationRef {
* This will throw if the view is already attached to a ViewContainer.
*/
attachView(viewRef: ViewRef): void {
(typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
typeof ngDevMode !== 'undefined' && ngDevMode && this.warnIfDestroyed();
const view = viewRef as InternalViewRef<unknown>;
this._views.push(view);
view.attachToAppRef(this);
Expand All @@ -778,7 +779,7 @@ export class ApplicationRef {
* Detaches a view from dirty checking again.
*/
detachView(viewRef: ViewRef): void {
(typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
typeof ngDevMode !== 'undefined' && ngDevMode && this.warnIfDestroyed();
const view = viewRef as InternalViewRef<unknown>;
remove(this._views, view);
view.detachFromAppRef();
Expand Down Expand Up @@ -829,7 +830,7 @@ export class ApplicationRef {
* @returns A function which unregisters a listener.
*/
onDestroy(callback: () => void): VoidFunction {
(typeof ngDevMode === 'undefined' || ngDevMode) && this.warnIfDestroyed();
typeof ngDevMode !== 'undefined' && ngDevMode && this.warnIfDestroyed();
this._destroyListeners.push(callback);
return () => remove(this._destroyListeners, callback);
}
Expand Down Expand Up @@ -865,7 +866,7 @@ export class ApplicationRef {
}

private warnIfDestroyed() {
if ((typeof ngDevMode === 'undefined' || ngDevMode) && this._destroyed) {
if (typeof ngDevMode !== 'undefined' && ngDevMode && this._destroyed) {
console.warn(
formatRuntimeError(
RuntimeErrorCode.APPLICATION_REF_ALREADY_DESTROYED,
Expand Down
4 changes: 2 additions & 2 deletions packages/core/src/application/create_application.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ export function internalCreateApplication(config: {
try {
const {rootComponent, appProviders, platformProviders} = config;

if ((typeof ngDevMode === 'undefined' || ngDevMode) && rootComponent !== undefined) {
if (typeof ngDevMode !== 'undefined' && ngDevMode && rootComponent !== undefined) {
assertStandaloneComponentType(rootComponent);
}

Expand All @@ -56,7 +56,7 @@ export function internalCreateApplication(config: {
const adapter = new EnvironmentNgModuleRefAdapter({
providers: allAppProviders,
parent: platformInjector as EnvironmentInjector,
debugName: typeof ngDevMode === 'undefined' || ngDevMode ? 'Environment Injector' : '',
debugName: typeof ngDevMode !== 'undefined' && ngDevMode ? 'Environment Injector' : '',
// We skip environment initializers because we need to run them inside the NgZone, which
// happens after we get the NgZone instance from the Injector.
runEnvironmentInitializers: false,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export function provideExperimentalCheckNoChangesForDebug(options: {
useNgZoneOnStable?: boolean;
exhaustive?: boolean;
}) {
if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
if (options.interval === undefined && !options.useNgZoneOnStable) {
throw new Error('Must provide one of `useNgZoneOnStable` or `interval`');
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export class NgZoneChangeDetectionScheduler {
* with the bootstrapModule API.
*/
export const PROVIDED_NG_ZONE = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'provideZoneChangeDetection token' : '',
typeof ngDevMode !== 'undefined' && ngDevMode ? 'provideZoneChangeDetection token' : '',
{factory: () => false},
);

Expand All @@ -95,7 +95,8 @@ export function internalProvideZoneChangeDetection({
optional: true,
});
if (
(typeof ngDevMode === 'undefined' || ngDevMode) &&
typeof ngDevMode !== 'undefined' &&
ngDevMode &&
ngZoneChangeDetectionScheduler === null
) {
throw new RuntimeError(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -66,21 +66,21 @@ export abstract class ChangeDetectionScheduler {

/** Token used to indicate if zoneless was enabled via provideZonelessChangeDetection(). */
export const ZONELESS_ENABLED = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless enabled' : '',
typeof ngDevMode !== 'undefined' && ngDevMode ? 'Zoneless enabled' : '',
{providedIn: 'root', factory: () => false},
);

/** Token used to indicate `provideExperimentalZonelessChangeDetection` was used. */
export const PROVIDED_ZONELESS = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'Zoneless provided' : '',
typeof ngDevMode !== 'undefined' && ngDevMode ? 'Zoneless provided' : '',
{providedIn: 'root', factory: () => false},
);

export const ZONELESS_SCHEDULER_DISABLED = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'scheduler disabled' : '',
typeof ngDevMode !== 'undefined' && ngDevMode ? 'scheduler disabled' : '',
);

// TODO(atscott): Remove in v19. Scheduler should be done with runOutsideAngular.
export const SCHEDULE_IN_ROOT_ZONE = new InjectionToken<boolean>(
typeof ngDevMode === 'undefined' || ngDevMode ? 'run changes outside zone in root' : '',
typeof ngDevMode !== 'undefined' && ngDevMode ? 'run changes outside zone in root' : '',
);
Original file line number Diff line number Diff line change
Expand Up @@ -203,7 +203,7 @@ export class ChangeDetectionSchedulerImpl implements ChangeDetectionScheduler {
return;
}

if (typeof ngDevMode === 'undefined' || ngDevMode) {
if (typeof ngDevMode !== 'undefined' && ngDevMode) {
if (this.useMicrotaskScheduler) {
trackMicrotaskNotificationForDebugging();
} else {
Expand Down Expand Up @@ -381,7 +381,7 @@ export class ChangeDetectionSchedulerImpl implements ChangeDetectionScheduler {
export function provideExperimentalZonelessChangeDetection(): EnvironmentProviders {
performanceMarkFeature('NgZoneless');

if ((typeof ngDevMode === 'undefined' || ngDevMode) && typeof Zone !== 'undefined' && Zone) {
if (typeof ngDevMode !== 'undefined' && ngDevMode && typeof Zone !== 'undefined' && Zone) {
const message = formatRuntimeError(
RuntimeErrorCode.UNEXPECTED_ZONEJS_PRESENT_IN_ZONELESS_MODE,
`The application is using zoneless change detection, but is still loading Zone.js. ` +
Expand All @@ -396,7 +396,7 @@ export function provideExperimentalZonelessChangeDetection(): EnvironmentProvide
{provide: NgZone, useClass: NoopNgZone},
{provide: ZONELESS_ENABLED, useValue: true},
{provide: SCHEDULE_IN_ROOT_ZONE, useValue: false},
typeof ngDevMode === 'undefined' || ngDevMode
typeof ngDevMode !== 'undefined' && ngDevMode
? [{provide: PROVIDED_ZONELESS, useValue: true}]
: [],
]);
Expand Down
Loading

0 comments on commit 67cf4dd

Please sign in to comment.