This commit updates the implementation of the `customElements` patch and also
patches FACE callbacks (`formAssociatedCallback`, `formDisabledCallback`, `formResetCallback`
and `formStateRestoreCallback`). This now allows invoking those callbacks in the same zone
where the custom element has been defined.
PR Close#50686
This commit updates the implementation of the zone.js `fs` patch to
restore the implementation of `realpath.native` and patches it as a macrotask,
along with other functions of the `fs` package. This is the only nested function
that must be patched.
Closes: #45546
PR Close#54208
This commit updates the implementation of the `fetch` patch and additionally
patches `Response` methods which return promises. These are `arrayBuffer`, `blob`,
`formData`, `json` and `text`. This fixes the issue when zone becomes stable too early
before all of the `fetch` tasks complete. Given the following code:
```ts
appRef.isStable.subscribe(console.log);
fetch(...).then(response => response.json()).then(console.log);
```
The `isStable` observer would log `false, true, false, true`. This was happening because
`json()` was returning a native promise (and not a `ZoneAwarePromise`). But calling `then`
on the native promise returns a `ZoneAwarePromise` which notifies Angular about the task
being scheduled and forces to re-calculate the `isStable` state.
Issue: #50327
PR Close#50653
This commit updates the signature of the `ZoneGlobalConfigurations` interface and adds
missing `__Zone_ignore_on_properties` property, which may be setup to ignore specific `on`
properties from being patched.
PR Close#50737
Make Zone.js compatible with moduleDetection:force by turning files that
are currently incompatible from scripts into modules using an empty
export statement.
PR Close#53445
fetch support AbortSignal, zone.js schedules a macroTask when fetch()
```
fetch(..., {signal: abortSignal});
```
we should also be able to cancel fetch with `zoneTask.cancel` call.
So this commit create an internal AbortSignal to handle
`zoneTask.cancel()` call and also delegate the `options.signal` from the
user code.
PR Close#49595
Close#49591
```
const ac = new AbortController();
addEventListener(eventName, handler, {signal: ac.signal);`
ac.abort();
```
Currently `zone.js` doesn't support the `signal` option, this PR allows
the user to use AbortContoller to remove the event listener.
PR Close#49595
In the original `Promise` impelmentation, zone.js follow the spec from
https://promisesaplus.com/#point-51.
```
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(p1);
p1 === p2; // false
```
in this case, `p2` should be the same status with `p1` but they are
still different instances.
And for some edge case.
```
class MyPromise extends Promise {
constructor(sub) {
super((res) => res(null));
this.sub = sub;
}
then(onFufilled, onRejected) {
this.sub.then(onFufilled, onRejected);
}
}
const p1 = new Promise(setTimeout(res), 100);
const myP = new MyPromise(p1);
const r = await myP;
r === 1; // false
```
So in the above code, `myP` is not the same instance with `p1`,
and since `myP` is resolved in constructor, so `await myP` will
just pass without waiting for `p1`.
And in the current `tc39` spec here https://tc39.es/ecma262/multipage/control-abstraction-objects.html#sec-promise-resolve
`Promise.resolve(subP)` should return `subP`.
```
const p1 = Promise.resolve(1);
const p2 = Promise.resolve(p1);
p1 === p2; // true
```
So the above `MyPromise` can wait for the `p1` correctly.
PR Close#53423
Before this commit, zone.js wraps the uncaught promise rejection error
to a new Error object includes more information such as Zone stack
traces. This feature is provided from the very beginning of Zone.js,
but this feature becomes very annoying and make the user difficult to
debug.
So this commit disable this wrapping behavior by default, and user can
enable this feature back by setting
`DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION` to `false`.
PR Close#52492
`globalThis` global property contains the global `this` value, which is usually akin to the global object. This is needed for better compatibility with CloudFlare workers were global nor window are defined as globals.
PR Close#52367
This commit removes access to deep imports and `zone-testing-bundle` and `zone-testing-node-bundle`
This commit removed access to deep and legacy `dist` imports. `zone-testing-bundle` and `zone-testing-node-bundle` are also no longer generated.
BREAKING CHANGE:
Deep and legacy `dist/` imports like `zone.js/bundles/zone-testing.js` and `zone.js/dist/zone` are no longer allowed. `zone-testing-bundle` and `zone-testing-node-bundle` are also no longer part of the package.
The proper way to import `zone.js` and `zone.js/testing` is:
```js
import 'zone.js';
import 'zone.js/testing';
```
PR Close#51752
In https://github.com/angular/angular/pull/49144 we introduced a change to only path `Promise.prototype.then` due to Node.js `SafePromise` complaining about `Promise.prototype.then` called on incompatible receiver. This however introduced a number of regressions. This commit reverts this change and re-introduces the changes to patch the entire promise on Node.
The original `SafePromise` problem is no longer reproducible as of Node.js version 18.13+ as it was addressed as part of https://github.com/nodejs/node/pull/45175.
While the Angular CLI does not yet generate ESM server bundles, users using ESM with dynamic imports will require using Node.js 18.13 or later.
Closes#50513, closes#50457, closes#50414 and closes#49930
PR Close#50552
Close#49110
From jest 29 and jest-preset-angular v13, the module transform logic
changed, and now jest-preset-angular use the use the tsconfig target
other than the hardcoded one, https://github.com/thymikee/jest-preset-angular/issues/2010
But jest-angular-preset doesn't introduce the @babel/plugin-transform-async-to-generator
which is needed by angular since `async/await` still need to be transformed
to promise for ES2017+ target.
So for now, we disable to output the uncaught error console log for a temp solution,
until jest-preset-angular find a proper solution.
PR Close#49325
Close#47872
zone-node only patches `Promise.prototype.then` instead of patch
`Promise` itself. So the new NodeJS `SafePromise` will not complain
the Promise.prototype.then called on incompatible receiver.
We should also do this change on browser zone.js patch, but it will
be a big breaking change, because Promise.prototype.then will not work
with `fakeAsync` any longer.
PR Close#49144
* Adjusts tests to no longer rely on CommonJS features. Switches them to
ESM
* Updates test initialization files to not double-initialize Jasmine now
that bootstrap files are loaded after Jasmine. The `jasmine.boot`
setup was hacky from `rules_nodejs` and will break in the future
regardless if we e.g. use `rules_js` with actual unmodified `jasmine`.
PR Close#48521
Since Karma with Bazel does not support ESM natively, we bundle the
tests using ESBuild into a single AMD file. This not only solves the
ESM issue until we can run browser ESM tests natively (also pending
in the components repo - the esbuild generation follows ESM semantics
but since collapsed we don't rely on the real module system).
A benefit of bundling is also faster and more reliable Karma browser
tests since only a single file needs to be loaded- compared to hundreds
of individual files.
PR Close#48521
Currently, there's no check if the task (that is being canceled) has the right state.
Only `scheduled` and `running` tasks can be canceled. If the task has a non-appropriate
state, then an error will be thrown. Cancelation should not throw an error on an already
canceled task, e.g. `clearTimeout` does not throw errors when it's called multiple times
on the same timer.
PR Close#45711
PR Close#46435
1. Remove `zone-async-tagging` implementation from zone.js and move the
implementation to `@angular/core`, so `@angular/core` can import this
package more easily for better treeshaking.
2. Add `async tagging zone` implemenation into `@angular/core` package.
So we don't need to get the `AsyncStackTaggingZoneSpec` from `global`
instance, we can import the `class` directly for better treeshaking.
3. Only load this ZoneSpec when `ngDevMode` is `true`.
PR Close#47416
Pull request #46672 added some debugging code to trace down the
root cause of its bug, but parts of the debugging code has never
been cleaned up and ended up landing as part of the PR.
This commit removes the code as it might cause unexpected issues.
Likely when e.g. `Error` is patched and would perform XHRs in testing,
unveiling e.g. CORS issues. See #46989.
PR Close#46989
As mentioned in the previous commit that ensured that the Zone name is
included in errors raised by the `SyncTestZoneSpec`, we can now include
the Jasmine describe block descriptions in such errors.
Errors can often happen when users accidentally try to set up Angular
tests without an `it` block. Resulting in errors where it's not clear
at all which describe block (of potentially a large repository) is
involved:
```
An error was thrown in afterAll
error properties: Object({ originalStack: 'Error: Cannot call XX from within a sync test.
at new ZoneAwareError (packages/zone.js/test/browser_test_rollup.umd.js:98:37)
at e.onScheduleTask (packages/zone.js/bundles/zone-testing-bundle.umd.min.js:158:196)
at e.scheduleTask (packages/zone.js/bundles/zone-testing-bundle.umd.min.js:14:7529)
at t.scheduleTask (packages/zone.js/bundles/zone-testing-bundle.umd.min.js:14:3539)
at t.scheduleMicroTask (packages/zone.js/bundles/zone-testing-bundle.umd.min.js:14:3791)
at r.execute (packages/zone.js/bundles/zone-testing-bundle.umd.min.js:166:4372)
at queueRunnerFa ...
at <Jasmine>
```
We now include the describe block description in the error, so that it
is easier to figure out the location of the culprit code.
The sync-test zone is used in e.g. `describe` to raise an error when
there is asynchronous code scheduled in describe blocks. This commit
includes the zone name in such thrown errors to allow for us to include
the jasmine describe name in the error. This will be wired up in the
jasmine zonejs patches separately.
Currently tests written using `waitForAsync` would be prone to Jasmine
warnings or errors (depending on the version) for tests incorrectly
invoking asynchronous jasmine `done` callbacks multiple times.
This can happen because the async test zone logic schedules the
`done` callback to be called using `setTimeout`, but this could
be invoked multiple times, causing multiple `done` invocations to
be scheduled. Most of the issues have been resolved with #45025,
but it does not solve the case of multiple tasks finished and callbacks
being scheduled.
Technically, the current logic is built in way that _should_ result in
`_finishCallbackIfDone` and eventually the `done` callback to be invoked
at maximium once. This is unfortunately not the case in some rather
advanced/unexpected scenarios (like our AngularJS upgrade tests) where
the scenario is the following (and microtasks from before the actual
`waitForAsync` spec are still completing -- which is valid):
```
1. A test `beforeEach` schedules a microtask in the ProxyZone.
2. An actual empty `it` spec executes in the AsyncTestZone` (using e.g. `waitForAsync`).
3. The `onInvoke` invokes `_finishCallbackIfDone` because the spec runs synchronously.
4. We wait the scheduled timeout (see below) to account for unhandled promises.
5. The microtask from (1) finishes and `onHasTask` is invoked.
--> We register a second `_finishCallbackIfDone` even though we have scheduled a timeout.
--> we execute the `done` callback twice because the async zone spec state is "stable"
```
Chrome has an experimental API to improve the debug experience of the
async tasks.
The details can be found here https://bugs.chromium.org/p/chromium/issues/detail?id=332624#c29
This commit add the `async stack tagging` support in the `zone.js`.
User can `import 'zone.js/plugins/async-stack-tagging';` to enable this
feature.
PR Close#46693
We have a file called `test-events.js` (named in an ambiguous way
anyway) that runs for all Karma web tests and configures ZoneJS to
not patch the `scroll` event. There are two issues:
1. The patch applies to all web tests. This could cause unexpected
issues.
2. The file is named ambiguously and also is placed at the project root,
in a wrong spot.
Additionally, the test doesn't even fail when the file is removed. This
commit applies the Zone config locally to the closest build target and
also reworks the test to actually ensure it's testing what it describes.
PR Close#46511
The native promise implementation logs unhandled promise rejections after `onFinally`
has been called. We may rely on the `scheduledByFinally` argument, which is `false` by
default, to avoid creating a breaking change; this will also allow us to reduce the number of
changes. The `finally` function should not silence unhandled promise rejections, because
they're not silenced in any implementation. If the `scheduleResolveOrReject` is called within
the `finally` we won't clear unhandled rejections. We'll keep the same behaviour if the
`scheduleResolveOrReject` is called within the `then`.
PR Close#43206
PR Close#45449
Close#44913
The following case is not handled correctly by `zone.js`.
```
const delayedPromise = new Promise((resolve) => {
setTimeout(resolve, 1, 'timeout');
});
new Promise((resolve) => {
resolve(delayedPromise);
resolve('second call');
}).then(console.log);
```
It should output `timeout`, since the promise is resolved by the
1st resolve, the `second call` should be ignored.
So this is a bug that the original implementation not ensure the
`resolve` is only called once.
PR Close#45283
The `patchCallbacks` is used for patching the `document.registerElement` and
`customElements.define`. We explicitly wrap the patching code into try-catch since
callbacks may be already patched by other web components frameworks (e.g. LWC), and they
make those properties non-writable. This means that patching callback will throw an error
`cannot assign to read-only property`. See this code as an example:
https://github.com/salesforce/lwc/blob/master/packages/@lwc/engine-core/src/framework/base-bridge-element.ts#L180-L186
We don't want to stop the application rendering if we couldn't patch some
callback, e.g. `attributeChangedCallback`.
PR Close#42546
PR Close#45400
Update `@bazel` packages to the latest 5.x version.
Some of the changes here are modeled after
angular/dev-infra@40c0ac8559.
Co-Authored-By: George Kalpakas <kalpakas.g@gmail.com>
PR Close#45431
We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
may be an object without a prototype (created through `Object.create(null)`); thus
`this.constructor` will be undefined. One of the use cases is SystemJS creating
prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
object and copies promise properties into that object (within the `getOrCreateLoad`
function). The zone.js then checks if the resolved value has the `then` method and invokes
it with the `value` context. Otherwise, this will throw an error: `TypeError: Cannot read
properties of undefined (reading 'Symbol(Symbol.species)')`.
PR Close#45369
.substr() is deprecated so we replace it with functions which work similarily but aren't deprecated
Signed-off-by: Tobias Speicher <rootcommander@gmail.com>
PR Close#45397
Before this change, the macrotask for `setInterval(callback, ms)` was no
longer tracked by `TaskTrackingZoneSpec` after the `callback` was
invoked for the first time. Now the periodic macrotask is tracked until
it is cancelled, e.g. `clearInterval(id)`.
BREAKING CHANGE: in TaskTrackingZoneSpec track a periodic task until it is cancelled
The breaking change is scoped only to the plugin
`zone.js/plugins/task-tracking`. If you used `TaskTrackingZoneSpec` and
checked the pending macroTasks e.g. using `(this.ngZone as any)._inner
._parent._properties.TaskTrackingZone.getTasksFor('macroTask')`, then
its behavior slightly changed for periodic macrotasks. For example,
previously the `setInterval` macrotask was no longer tracked after its
callback was executed for the first time. Now it's tracked until
the task is explicitly cancelled, e.g with `clearInterval(id)`.
fixes 45350
PR Close#45391
Jasmine checks internally if `process` and `process.on` is defined. Otherwise,
it installs the browser rejection handler through the `global.addEventListener`.
This code may be run in the browser environment where `process` is not defined, and
this will lead to a runtime exception since Webpack 5 removed automatic Node.js polyfills.
PR Close#42260
PR Close#45392
For legacy browsers, we still use the eventNames array to patch event instead of
using `Object.getOwnPropertyNames()` to keep backward compatibility.
PR Close#40962
Zone.js supports the google closure compiler in the advance optimization mode,
to prevent closure compiler modify the `onProperty` name such as `Element.prototype.onclick`,
Zone.js implements the `onProperty` patch logic by declaring all the
event names in the source code, this increases the bundle size and also require
updating the event names array to keep the information updated.
Now google closure compiler has the required event names defined in the built-in
externs files, so zone.js can use more simple implementation and decrease the bundle size
of zone.js (about 4k).
PR Close#40962
Close#43346
From electron 14, the `CallbacksRegistry` is moved to `@electron/remote` package,
so all `remote` call between `main` process and `renderer` process is
not being patched since the new version of electron released.
Also `CallbacksRegistry` is not exported outside, so this commit make a
`hack` patch to load `CallbacksRegistry` from
`@electron/remote/dist/src/renderer/callbacks-registry` for patching.
PR Close#45073
Close#42834
In the new version fo Mocha, all global test functions are from `global`
object instead of `Mocha` object. Adn the current `zone.js` Mocha
patch's logic looks like this.
```
global.describe = Mocha.describe = function() {
return originalMochaDescribe.apply(this, arguments);
}
```
and `originalMochaDescribe` is the unpathced Mocha implementation
looks like this
```
function describe() {
return context.describe(...);
}
```
And the `context` will finally delegate to `global.describe()`,
so the current `zone.js` patch causes infinite loop.
This commit will not patch function of `Mocha` object any longer.
PR Close#45047
`AsyncTestZoneSpec` triggers jasmine `done()` function multiple times
and causes warning
```
An asynchronous function called its 'done' callback more than once. This is a bug in the spec, beforeAll, beforeEach, afterAll, or afterEach function in question. This will be treated as an error in a future version. See<https://jasmine.github.io/tutorials/upgrading_to_Jasmine_4.0#deprecations-due-to-calling-done-multiple-times> for more information
```
The reproduce case will be running some `Zone.run()` inside
`waitForAsync()`.
```
it('multiple done', waitForAsync(() => {
Zone.current.run(() => {});
Zone.current.run(() => {});
}));
```
The reason the `done()` is called in the `onInvoke()` hook is to handle
the case that the testBody is totally sync, but we should only do this
check for the entry function not for all `Zone.run()` scenario.
Another issue is if we run nested zone inside `waitForAsync()`, the
`onHasTask()` hook will be triggered multiple times, and cause `done()`
be triggered multiple times, so we need to only trigger the `done()`
when the zone is `AsyncTestZone`.
PR Close#45025