Skip to content

Commit 25eaaa2

Browse files
devversionangular-robot[bot]
authored andcommitted
fix(@angular-devkit/build-angular): downlevel class properties when targeting Safari <=v15
The Angular compiler is dependent on static fields being attached to user-defined classes. e.g. `static ecmp = defineComponent`. These static fields sometimes rely on variables from outside of the class. e.g. the Angular compiler generates constants for content projection that are then accessed in the static field initializer. Surprisingly such access to these variables may break in Safari <=v15 when a page is loaded without devtools open. The bug (already solved in v16 of Safari)- is very subtle, hard to re-reproduce but basically variable scope tracking is broken. This bug is triggered by additional parenthesis in the initializer expression. See: https://bugs.webkit.org/show_bug.cgi?id=236843. The TypeScript compiler may generate such additional parenthesis when it tries to adjust the `this` context when invoking methods, such as for defining animations in the `ecmp` definition. More details can be found here: #24355 (comment) To ensure Angular applications are not subject to this bug when targeting Safari <=v15. v15 Safari, both for iOS and Mac is still part of the default CLI browserslist with `last 2 Safari majors` (at time of writing). Note that it is important that the Babel plugin properly handles the downleveling of static block-defined members. TypeScript will transform static fields, like `static ecmp` into `static { this.ecmp = X }` when `useDefineForClassFields = false` (which is the case for CLI apps). The class properties plugin from Babel seems to handle this in an acceptable way. Unlike actual static fields, Babel will not use helpers like `defineProperty` for such extracted static blocks though. e.g. See repro: https://gist.github.com/devversion/dec0dea26e348c509921bf62079b60be ```js class Test { x = true; static b = true; static { this.a = true; } } // into class X { constructor() { _defineProperty(this, "x", true); } } _defineProperty(X, "b", true); X.a = true; ``` note that in practice TypeScript with `useDefineForClassFields = false` will put non-static members into the constructor as normal assignments regardless- so there would be no change by the Babel plugin. Fixes #24355.
1 parent 49b313f commit 25eaaa2

File tree

3 files changed

+90
-12
lines changed

3 files changed

+90
-12
lines changed

packages/angular_devkit/build_angular/src/babel/presets/application.ts

+31-2
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,26 @@ import type {
1414
makeLocalePlugin,
1515
} from '@angular/localize/tools';
1616
import { strict as assert } from 'assert';
17+
import browserslist from 'browserslist';
1718
import * as fs from 'fs';
1819
import * as path from 'path';
1920

21+
/**
22+
* List of browsers which are affected by a WebKit bug where class field
23+
* initializers might have incorrect variable scopes.
24+
*
25+
* See: https://github.com/angular/angular-cli/issues/24355#issuecomment-1333477033
26+
* See: https://github.com/WebKit/WebKit/commit/e8788a34b3d5f5b4edd7ff6450b80936bff396f2
27+
*/
28+
const safariClassFieldScopeBugBrowsers = new Set(
29+
browserslist([
30+
// Safari <15 is technically not supported via https://angular.io/guide/browser-support,
31+
// but we apply the workaround if forcibly selected.
32+
'Safari <=15',
33+
'iOS <=15',
34+
]),
35+
);
36+
2037
export type DiagnosticReporter = (type: 'error' | 'warning' | 'info', message: string) => void;
2138

2239
/**
@@ -45,7 +62,6 @@ export interface ApplicationPresetOptions {
4562
linkerPluginCreator: typeof import('@angular/compiler-cli/linker/babel').createEs2015LinkerPlugin;
4663
};
4764

48-
forcePresetEnv?: boolean;
4965
forceAsyncTransformation?: boolean;
5066
instrumentCode?: {
5167
includedBasePath: string;
@@ -171,13 +187,26 @@ export default function (api: unknown, options: ApplicationPresetOptions) {
171187
);
172188
}
173189

174-
if (options.forcePresetEnv) {
190+
// Applications code ES version can be controlled using TypeScript's `target` option.
191+
// However, this doesn't effect libraries and hence we use preset-env to downlevel ES features
192+
// based on the supported browsers in browserslist.
193+
if (options.supportedBrowsers) {
194+
const includePlugins: string[] = [];
195+
196+
// If a Safari browser affected by the class field scope bug is selected, we
197+
// downlevel class properties by ensuring the class properties Babel plugin
198+
// is always included- regardless of the preset-env targets.
199+
if (options.supportedBrowsers.some((b) => safariClassFieldScopeBugBrowsers.has(b))) {
200+
includePlugins.push('@babel/plugin-proposal-class-properties');
201+
}
202+
175203
presets.push([
176204
require('@babel/preset-env').default,
177205
{
178206
bugfixes: true,
179207
modules: false,
180208
targets: options.supportedBrowsers,
209+
include: includePlugins,
181210
exclude: ['transform-typeof-symbol'],
182211
},
183212
]);

packages/angular_devkit/build_angular/src/babel/webpack-loader.ts

+3-10
Original file line numberDiff line numberDiff line change
@@ -79,7 +79,6 @@ export default custom<ApplicationPresetOptions>(() => {
7979

8080
const customOptions: ApplicationPresetOptions = {
8181
forceAsyncTransformation: false,
82-
forcePresetEnv: false,
8382
angularLinker: undefined,
8483
i18n: undefined,
8584
instrumentCode: undefined,
@@ -105,14 +104,6 @@ export default custom<ApplicationPresetOptions>(() => {
105104
shouldProcess = true;
106105
}
107106

108-
// Analyze for ES target processing
109-
if (customOptions.supportedBrowsers?.length) {
110-
// Applications code ES version can be controlled using TypeScript's `target` option.
111-
// However, this doesn't effect libraries and hence we use preset-env to downlevel ES fetaures
112-
// based on the supported browsers in browserlist.
113-
customOptions.forcePresetEnv = true;
114-
}
115-
116107
// Application code (TS files) will only contain native async if target is ES2017+.
117108
// However, third-party libraries can regardless of the target option.
118109
// APF packages with code in [f]esm2015 directories is downlevelled to ES2015 and
@@ -121,7 +112,9 @@ export default custom<ApplicationPresetOptions>(() => {
121112
!/[\\/][_f]?esm2015[\\/]/.test(this.resourcePath) && source.includes('async');
122113

123114
shouldProcess ||=
124-
customOptions.forceAsyncTransformation || customOptions.forcePresetEnv || false;
115+
customOptions.forceAsyncTransformation ||
116+
customOptions.supportedBrowsers !== undefined ||
117+
false;
125118

126119
// Analyze for i18n inlining
127120
if (
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,56 @@
1+
import { expectFileToExist, readFile, writeFile } from '../../utils/fs';
2+
import { ng } from '../../utils/process';
3+
import { updateJsonFile } from '../../utils/project';
4+
5+
const unexpectedStaticFieldErrorMessage =
6+
'Found unexpected static field. This indicates that the Safari <=v15 ' +
7+
'workaround for a scope variable tracking is not working. ' +
8+
'See: https://github.com/angular/angular-cli/pull/24357';
9+
10+
export default async function () {
11+
await updateJsonFile('angular.json', (workspace) => {
12+
const build = workspace.projects['test-project'].architect.build;
13+
build.defaultConfiguration = undefined;
14+
build.options = {
15+
...build.options,
16+
optimization: false,
17+
outputHashing: 'none',
18+
};
19+
});
20+
21+
// Matches two types of static fields that indicate that the Safari bug
22+
// may still occur. With the workaround this should not appear in bundles.
23+
// - static { this.ecmp = bla }
24+
// - static #_ = this.ecmp = bla
25+
const staticIndicatorRegex = /static\s+(\{|#[_\d]+\s+=)/;
26+
27+
await ng('build');
28+
await expectFileToExist('dist/test-project/main.js');
29+
const mainContent = await readFile('dist/test-project/main.js');
30+
31+
// TODO: This default cause can be removed in the future when Safari v15
32+
// is longer included in the default browserlist configuration of CLI apps.
33+
if (staticIndicatorRegex.test(mainContent)) {
34+
throw new Error(unexpectedStaticFieldErrorMessage);
35+
}
36+
37+
await writeFile('.browserslistrc', 'last 1 chrome version');
38+
39+
await ng('build');
40+
await expectFileToExist('dist/test-project/main.js');
41+
const mainContentChromeLatest = await readFile('dist/test-project/main.js');
42+
43+
if (!staticIndicatorRegex.test(mainContentChromeLatest)) {
44+
throw new Error('Expected static fields to be used when Safari <=v15 is not targeted.');
45+
}
46+
47+
await writeFile('.browserslistrc', 'Safari <=15');
48+
49+
await ng('build');
50+
await expectFileToExist('dist/test-project/main.js');
51+
const mainContentSafari15Explicit = await readFile('dist/test-project/main.js');
52+
53+
if (staticIndicatorRegex.test(mainContentSafari15Explicit)) {
54+
throw new Error(unexpectedStaticFieldErrorMessage);
55+
}
56+
}

0 commit comments

Comments
 (0)