diff --git a/CHANGELOG.md b/CHANGELOG.md
index a8d1cb7ff..aa1b47247 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -1,3 +1,39 @@
+
+## [0.8.27](https://github.com/angular/zone.js/compare/v0.8.26...0.8.27) (2019-01-08)
+
+
+### Bug Fixes
+
+* **bluebird:** fix [#1112](https://github.com/angular/zone.js/issues/1112), bluebird chained callback should return a Bluebird Promise ([#1114](https://github.com/angular/zone.js/issues/1114)) ([6ba3169](https://github.com/angular/zone.js/commit/6ba3169))
+* **core:** fix [#1108](https://github.com/angular/zone.js/issues/1108), window.onerror should have (message, source, lineno, colno, error) signiture ([#1109](https://github.com/angular/zone.js/issues/1109)) ([49e0548](https://github.com/angular/zone.js/commit/49e0548))
+* **core:** fix [#1153](https://github.com/angular/zone.js/issues/1153), ZoneTask.toString should always be a string ([#1166](https://github.com/angular/zone.js/issues/1166)) ([afa1363](https://github.com/angular/zone.js/commit/afa1363))
+* **core:** fix interval will still run after cancelled error ([#1156](https://github.com/angular/zone.js/issues/1156)) ([eb72ff4](https://github.com/angular/zone.js/commit/eb72ff4))
+* **core:** use then directly when promise is not patchable ([#1079](https://github.com/angular/zone.js/issues/1079)) ([d7e0a31](https://github.com/angular/zone.js/commit/d7e0a31))
+* **duplicate:** fix [#1081](https://github.com/angular/zone.js/issues/1081), load patch should also check the duplicate flag ([#1121](https://github.com/angular/zone.js/issues/1121)) ([8ce5e33](https://github.com/angular/zone.js/commit/8ce5e33))
+* **event:** fix [#1110](https://github.com/angular/zone.js/issues/1110), nodejs EventEmitter should support Symbol eventName ([#1113](https://github.com/angular/zone.js/issues/1113)) ([96420d6](https://github.com/angular/zone.js/commit/96420d6))
+* **event:** should pass boolean to addEventListener if not support passive ([#1053](https://github.com/angular/zone.js/issues/1053)) ([e9536ec](https://github.com/angular/zone.js/commit/e9536ec))
+* **format:** update clang-format to 1.2.3 ([f238908](https://github.com/angular/zone.js/commit/f238908))
+* **memory:** Add protection against excessive on prop patching ([#1106](https://github.com/angular/zone.js/issues/1106)) ([875086f](https://github.com/angular/zone.js/commit/875086f))
+* **node:** fix [#1164](https://github.com/angular/zone.js/issues/1164), don't patch uncaughtException to prevent endless loop ([#1170](https://github.com/angular/zone.js/issues/1170)) ([33a0ad6](https://github.com/angular/zone.js/commit/33a0ad6))
+* **node:** node patched method should copy original delegate's symbol properties ([#1095](https://github.com/angular/zone.js/issues/1095)) ([0a2f6ff](https://github.com/angular/zone.js/commit/0a2f6ff))
+* **onProperty:** user quoted access for __Zone_ignore_on_properties ([#1134](https://github.com/angular/zone.js/issues/1134)) ([7201d44](https://github.com/angular/zone.js/commit/7201d44))
+* **test:** karma-dist should test bundle under dist ([#1049](https://github.com/angular/zone.js/issues/1049)) ([0720d79](https://github.com/angular/zone.js/commit/0720d79))
+* **tsc:** tsconfig.json strict:true ([915042d](https://github.com/angular/zone.js/commit/915042d))
+* **xhr:** fix [#1072](https://github.com/angular/zone.js/issues/1072), should set scheduled flag to target ([#1074](https://github.com/angular/zone.js/issues/1074)) ([34c12e5](https://github.com/angular/zone.js/commit/34c12e5))
+* **xhr:** should invoke xhr task after onload is triggered ([#1055](https://github.com/angular/zone.js/issues/1055)) ([2aab9c8](https://github.com/angular/zone.js/commit/2aab9c8))
+
+
+### Features
+
+* **build:** Upgrade to TypeScript 2.9 and rxjs6 ([#1122](https://github.com/angular/zone.js/issues/1122)) ([31fc127](https://github.com/angular/zone.js/commit/31fc127))
+* **core:** upgrade to typescript 3.0.3 ([#1132](https://github.com/angular/zone.js/issues/1132)) ([60adc9c](https://github.com/angular/zone.js/commit/60adc9c))
+* **Core:** fix [#910](https://github.com/angular/zone.js/issues/910), add a flag to allow user to ignore duplicate Zone error ([#1093](https://github.com/angular/zone.js/issues/1093)) ([a86c6d5](https://github.com/angular/zone.js/commit/a86c6d5))
+* **custom-element:** patch customElement v1 APIs ([#1133](https://github.com/angular/zone.js/issues/1133)) ([427705f](https://github.com/angular/zone.js/commit/427705f))
+* **error:** fix [#975](https://github.com/angular/zone.js/issues/975), can config how to load blacklist zone stack frames ([#1045](https://github.com/angular/zone.js/issues/1045)) ([ff3d545](https://github.com/angular/zone.js/commit/ff3d545))
+* **fetch:** schedule macroTask when fetch ([#1075](https://github.com/angular/zone.js/issues/1075)) ([bf88c34](https://github.com/angular/zone.js/commit/bf88c34))
+
+
+
## [0.8.26](https://github.com/angular/zone.js/compare/v0.8.25...0.8.26) (2018-04-08)
diff --git a/dist/fake-async-test.js b/dist/fake-async-test.js
index 9bc27674e..348de8d0f 100644
--- a/dist/fake-async-test.js
+++ b/dist/fake-async-test.js
@@ -154,7 +154,11 @@ var __spread = (undefined && undefined.__spread) || function () {
}
}
}
+ lastCurrentTime = this._currentTime;
this._currentTime = finalTime;
+ if (doTick) {
+ doTick(this._currentTime - lastCurrentTime);
+ }
};
Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
if (limit === void 0) { limit = 20; }
@@ -243,14 +247,14 @@ var __spread = (undefined && undefined.__spread) || function () {
args[_i] = arguments[_i];
}
fn.apply(global, args);
- if (_this._lastError === null) {
+ if (_this._lastError === null) { // Success
if (completers.onSuccess != null) {
completers.onSuccess.apply(global);
}
// Flush microtasks only on success.
_this.flushMicrotasks();
}
- else {
+ else { // Failure
if (completers.onError != null) {
completers.onError.apply(global);
}
@@ -549,23 +553,23 @@ Zone.__load_patch('fakeasync', function (global, Zone, api) {
ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
}
/**
- * Wraps a function to be executed in the fakeAsync zone:
- * - microtasks are manually executed by calling `flushMicrotasks()`,
- * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
- *
- * If there are any pending timers at the end of the function, an exception will be thrown.
- *
- * Can be used to wrap inject() calls.
- *
- * ## Example
- *
- * {@example core/testing/ts/fake_async.ts region='basic'}
- *
- * @param fn
- * @returns The function wrapped to be executed in the fakeAsync zone
- *
- * @experimental
- */
+ * Wraps a function to be executed in the fakeAsync zone:
+ * - microtasks are manually executed by calling `flushMicrotasks()`,
+ * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
+ *
+ * If there are any pending timers at the end of the function, an exception will be thrown.
+ *
+ * Can be used to wrap inject() calls.
+ *
+ * ## Example
+ *
+ * {@example core/testing/ts/fake_async.ts region='basic'}
+ *
+ * @param fn
+ * @returns The function wrapped to be executed in the fakeAsync zone
+ *
+ * @experimental
+ */
function fakeAsync(fn) {
// Not using an arrow function to preserve context passed from call site
return function () {
diff --git a/dist/proxy.js b/dist/proxy.js
index 5766ee978..d2535215a 100644
--- a/dist/proxy.js
+++ b/dist/proxy.js
@@ -23,6 +23,7 @@ var ProxyZoneSpec = /** @class */ (function () {
if (defaultSpecDelegate === void 0) { defaultSpecDelegate = null; }
this.defaultSpecDelegate = defaultSpecDelegate;
this.name = 'ProxyZone';
+ this._delegateSpec = null;
this.properties = { 'ProxyZoneSpec': this };
this.propertyKeys = null;
this.lastTaskState = null;
diff --git a/dist/proxy.min.js b/dist/proxy.min.js
index c0c44d725..2d4c72c21 100644
--- a/dist/proxy.min.js
+++ b/dist/proxy.min.js
@@ -1 +1 @@
-!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t():"function"==typeof define&&define.amd?define(t):t()}(this,function(){"use strict";var e=function(){function e(e){void 0===e&&(e=null),this.defaultSpecDelegate=e,this.name="ProxyZone",this.properties={ProxyZoneSpec:this},this.propertyKeys=null,this.lastTaskState=null,this.isNeedToTriggerHasTask=!1,this.tasks=[],this.setDelegate(e)}return e.get=function(){return Zone.current.get("ProxyZoneSpec")},e.isLoaded=function(){return e.get()instanceof e},e.assertPresent=function(){if(!e.isLoaded())throw new Error("Expected to be running in 'ProxyZone', but it was not found.");return e.get()},e.prototype.setDelegate=function(e){var t=this,s=this._delegateSpec!==e;this._delegateSpec=e,this.propertyKeys&&this.propertyKeys.forEach(function(e){return delete t.properties[e]}),this.propertyKeys=null,e&&e.properties&&(this.propertyKeys=Object.keys(e.properties),this.propertyKeys.forEach(function(s){return t.properties[s]=e.properties[s]})),s&&this.lastTaskState&&(this.lastTaskState.macroTask||this.lastTaskState.microTask)&&(this.isNeedToTriggerHasTask=!0)},e.prototype.getDelegate=function(){return this._delegateSpec},e.prototype.resetDelegate=function(){this.getDelegate();this.setDelegate(this.defaultSpecDelegate)},e.prototype.tryTriggerHasTask=function(e,t,s){this.isNeedToTriggerHasTask&&this.lastTaskState&&(this.isNeedToTriggerHasTask=!1,this.onHasTask(e,t,s,this.lastTaskState))},e.prototype.removeFromTasks=function(e){if(this.tasks)for(var t=0;t';
this._properties = zoneSpec && zoneSpec.properties || {};
@@ -76,7 +89,9 @@ var Zone$1 = (function (global) {
});
Zone.__load_patch = function (name, fn) {
if (patches.hasOwnProperty(name)) {
- throw Error('Already loaded patch: ' + name);
+ if (checkDuplicate) {
+ throw Error('Already loaded patch: ' + name);
+ }
}
else if (!global['__Zone_disable_' + name]) {
var perfName = 'Zone:' + name;
@@ -120,7 +135,7 @@ var Zone$1 = (function (global) {
return this._zoneDelegate.fork(this, zoneSpec);
};
Zone.prototype.wrap = function (callback, source) {
- if (typeof callback !== FUNCTION) {
+ if (typeof callback !== 'function') {
throw new Error('Expecting function got: ' + callback);
}
var _callback = this._zoneDelegate.intercept(this, callback, source);
@@ -130,9 +145,6 @@ var Zone$1 = (function (global) {
};
};
Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
- if (applyThis === void 0) { applyThis = undefined; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
@@ -143,8 +155,6 @@ var Zone$1 = (function (global) {
};
Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
try {
@@ -168,10 +178,7 @@ var Zone$1 = (function (global) {
// https://github.com/angular/zone.js/issues/778, sometimes eventTask
// will run in notScheduled(canceled) state, we should not try to
// run such kind of task but just return
- // we have to define an variable here, if not
- // typescript compiler will complain below
- var isNotScheduled = task.state === notScheduled;
- if (isNotScheduled && task.type === eventTask) {
+ if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
return;
}
var reEntryGuard = task.state != running;
@@ -182,7 +189,7 @@ var Zone$1 = (function (global) {
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
if (task.type == macroTask && task.data && !task.data.isPeriodic) {
- task.cancelFn = null;
+ task.cancelFn = undefined;
}
try {
return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
@@ -218,8 +225,7 @@ var Zone$1 = (function (global) {
var newZone = this;
while (newZone) {
if (newZone === task.zone) {
- throw Error("can not reschedule task to " + this
- .name + " which is descendants of the original zone " + task.zone.name);
+ throw Error("can not reschedule task to " + this.name + " which is descendants of the original zone " + task.zone.name);
}
newZone = newZone.parent;
}
@@ -249,7 +255,7 @@ var Zone$1 = (function (global) {
return task;
};
Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
- return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, null));
+ return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
};
Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
@@ -290,16 +296,14 @@ var Zone$1 = (function (global) {
}());
var DELEGATE_ZS = {
name: '',
- onHasTask: function (delegate, _, target, hasTaskState) {
- return delegate.hasTask(target, hasTaskState);
- },
+ onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
onScheduleTask: function (delegate, _, target, task) {
return delegate.scheduleTask(target, task);
},
- onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); },
- onCancelTask: function (delegate, _, target, task) {
- return delegate.cancelTask(target, task);
- }
+ onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) {
+ return delegate.invokeTask(target, task, applyThis, applyArgs);
+ },
+ onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
};
var ZoneDelegate = /** @class */ (function () {
function ZoneDelegate(zone, parentDelegate, zoneSpec) {
@@ -327,8 +331,8 @@ var Zone$1 = (function (global) {
zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);
this._scheduleTaskZS =
zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
- this._scheduleTaskDlgt =
- zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
+ this._scheduleTaskDlgt = zoneSpec &&
+ (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
this._scheduleTaskCurrZone =
zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);
this._invokeTaskZS =
@@ -383,8 +387,7 @@ var Zone$1 = (function (global) {
callback;
};
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
- return this._invokeZS ?
- this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
+ return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.handleError = function (targetZone, error) {
@@ -416,8 +419,7 @@ var Zone$1 = (function (global) {
return returnTask;
};
ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
- return this._invokeTaskZS ?
- this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
+ return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
task.callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
@@ -437,7 +439,7 @@ var Zone$1 = (function (global) {
// hasTask should not throw error so other ZoneDelegate
// can still trigger hasTask callback
try {
- return this._hasTaskZS &&
+ this._hasTaskZS &&
this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
}
catch (err) {
@@ -527,14 +529,12 @@ var Zone$1 = (function (global) {
}
}
else {
- throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ?
- ' or \'' + fromState2 + '\'' :
- '') + ", was '" + this._state + "'.");
+ throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ? ' or \'' + fromState2 + '\'' : '') + ", was '" + this._state + "'.");
}
};
ZoneTask.prototype.toString = function () {
if (this.data && typeof this.data.handleId !== 'undefined') {
- return this.data.handleId;
+ return this.data.handleId.toString();
}
else {
return Object.prototype.toString.call(this);
@@ -575,7 +575,13 @@ var Zone$1 = (function (global) {
}
}
if (nativeMicroTaskQueuePromise) {
- nativeMicroTaskQueuePromise[symbolThen](drainMicroTaskQueue);
+ var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
+ if (!nativeThen) {
+ // native Promise is not patchable, we need to use `then` directly
+ // issue 1078
+ nativeThen = nativeMicroTaskQueuePromise['then'];
+ }
+ nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
}
else {
global[symbolSetTimeout](drainMicroTaskQueue, 0);
@@ -622,12 +628,13 @@ var Zone$1 = (function (global) {
patchEventTarget: function () { return []; },
patchOnProperties: noop,
patchMethod: function () { return noop; },
- bindArguments: function () { return null; },
+ bindArguments: function () { return []; },
+ patchThen: function () { return noop; },
setNativePromise: function (NativePromise) {
// sometimes NativePromise.resolve static function
// is not ready yet, (such as core-js/es6.promise)
// so we need to check here.
- if (NativePromise && typeof NativePromise.resolve === FUNCTION) {
+ if (NativePromise && typeof NativePromise.resolve === 'function') {
nativeMicroTaskQueuePromise = NativePromise.resolve(0);
}
},
@@ -643,6 +650,16 @@ var Zone$1 = (function (global) {
return global['Zone'] = Zone;
})(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
+var __values = (undefined && undefined.__values) || function (o) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
+ if (m) return m.call(o);
+ return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+};
Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var ObjectDefineProperty = Object.defineProperty;
@@ -785,7 +802,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var queue = promise[symbolValue];
promise[symbolValue] = value;
if (promise[symbolFinally] === symbolFinally) {
- // the promise is generated by Promise.prototype.finally
+ // the promise is generated by Promise.prototype.finally
if (state === RESOLVED) {
// the state is resolved, should ignore the value
// and use parent promise value
@@ -869,7 +886,9 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
chainPromise[symbolParentPromiseState] = promiseState;
}
// should not pass value to finally callback
- var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ? [] : [parentPromiseValue]);
+ var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
+ [] :
+ [parentPromiseValue]);
resolvePromise(chainPromise, true, value);
}
catch (error) {
@@ -904,6 +923,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
return resolvePromise(new this(null), REJECTED, error);
};
ZoneAwarePromise.race = function (values) {
+ var e_1, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
@@ -916,40 +936,70 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
function onReject(error) {
promise && (promise = null || reject(error));
}
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- if (!isThenable(value)) {
- value = this.resolve(value);
+ try {
+ for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
+ var value = values_1_1.value;
+ if (!isThenable(value)) {
+ value = this.resolve(value);
+ }
+ value.then(onResolve, onReject);
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
}
- value.then(onResolve, onReject);
+ finally { if (e_1) throw e_1.error; }
}
return promise;
};
ZoneAwarePromise.all = function (values) {
+ var e_2, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
resolve = res;
reject = rej;
});
- var count = 0;
+ // Start at 2 to prevent prematurely resolving if .then is called immediately.
+ var unresolvedCount = 2;
+ var valueIndex = 0;
var resolvedValues = [];
- for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
- var value = values_2[_i];
+ var _loop_2 = function (value) {
if (!isThenable(value)) {
- value = this.resolve(value);
+ value = this_1.resolve(value);
}
- value.then((function (index) { return function (value) {
- resolvedValues[index] = value;
- count--;
- if (!count) {
+ var curValueIndex = valueIndex;
+ value.then(function (value) {
+ resolvedValues[curValueIndex] = value;
+ unresolvedCount--;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
}
- }; })(count), reject);
- count++;
+ }, reject);
+ unresolvedCount++;
+ valueIndex++;
+ };
+ var this_1 = this;
+ try {
+ for (var values_2 = __values(values), values_2_1 = values_2.next(); !values_2_1.done; values_2_1 = values_2.next()) {
+ var value = values_2_1.value;
+ _loop_2(value);
+ }
}
- if (!count)
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
+ finally {
+ try {
+ if (values_2_1 && !values_2_1.done && (_a = values_2.return)) _a.call(values_2);
+ }
+ finally { if (e_2) throw e_2.error; }
+ }
+ // Make the unresolvedCount zero-based again.
+ unresolvedCount -= 2;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
+ }
return promise;
};
ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
@@ -1045,25 +1095,9 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
};
Ctor[symbolThenPatched] = true;
}
- function zoneify(fn) {
- return function () {
- var resultPromise = fn.apply(this, arguments);
- if (resultPromise instanceof ZoneAwarePromise) {
- return resultPromise;
- }
- var ctor = resultPromise.constructor;
- if (!ctor[symbolThenPatched]) {
- patchThen(ctor);
- }
- return resultPromise;
- };
- }
+ api.patchThen = patchThen;
if (NativePromise) {
patchThen(NativePromise);
- var fetch_1 = global['fetch'];
- if (typeof fetch_1 == 'function') {
- global['fetch'] = zoneify(fetch_1);
- }
}
// This is not part of public API, but it is useful for tests, so we expose it.
Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
@@ -1185,9 +1219,23 @@ var wrapFn = function (event) {
}
var target = this || event.target || _global;
var listener = target[eventNameSymbol];
- var result = listener && listener.apply(this, arguments);
- if (result != undefined && !result) {
- event.preventDefault();
+ var result;
+ if (isBrowser && target === internalWindow && event.type === 'error') {
+ // window.onerror have different signiture
+ // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
+ // and onerror callback will prevent default when callback return true
+ var errorEvent = event;
+ result = listener &&
+ listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
+ if (result === true) {
+ event.preventDefault();
+ }
+ }
+ else {
+ result = listener && listener.apply(this, arguments);
+ if (result != undefined && !result) {
+ event.preventDefault();
+ }
}
return result;
};
@@ -1205,6 +1253,10 @@ function patchProperty(obj, prop, prototype) {
if (!desc || !desc.configurable) {
return;
}
+ var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
+ if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
+ return;
+ }
// A property descriptor cannot have getter/setter and be writable
// deleting the writable and value properties avoids this error:
//
@@ -1282,6 +1334,7 @@ function patchProperty(obj, prop, prototype) {
return null;
};
ObjectDefineProperty(obj, prop, desc);
+ obj[onPropPatchedSymbol] = true;
}
function patchOnProperties(obj, properties, prototype) {
if (properties) {
@@ -1372,6 +1425,33 @@ function patchClass(className) {
}
}
}
+function copySymbolProperties(src, dest) {
+ if (typeof Object.getOwnPropertySymbols !== 'function') {
+ return;
+ }
+ var symbols = Object.getOwnPropertySymbols(src);
+ symbols.forEach(function (symbol) {
+ var desc = Object.getOwnPropertyDescriptor(src, symbol);
+ Object.defineProperty(dest, symbol, {
+ get: function () {
+ return src[symbol];
+ },
+ set: function (value) {
+ if (desc && (!desc.writable || typeof desc.set !== 'function')) {
+ // if src[symbol] is not writable or not have a setter, just return
+ return;
+ }
+ src[symbol] = value;
+ },
+ enumerable: desc ? desc.enumerable : true,
+ configurable: desc ? desc.configurable : true
+ });
+ });
+}
+var shouldCopySymbolProperties = false;
+function setShouldCopySymbolProperties(flag) {
+ shouldCopySymbolProperties = flag;
+}
function patchMethod(target, name, patchFn) {
var proto = target;
while (proto && !proto.hasOwnProperty(name)) {
@@ -1382,7 +1462,7 @@ function patchMethod(target, name, patchFn) {
proto = target;
}
var delegateName = zoneSymbol(name);
- var delegate;
+ var delegate = null;
if (proto && !(delegate = proto[delegateName])) {
delegate = proto[delegateName] = proto[name];
// check whether proto[name] is writable
@@ -1394,6 +1474,9 @@ function patchMethod(target, name, patchFn) {
return patchDelegate_1(this, arguments);
};
attachOriginToPatched(proto[name], delegate);
+ if (shouldCopySymbolProperties) {
+ copySymbolProperties(delegate, proto[name]);
+ }
}
}
return delegate;
@@ -1412,7 +1495,7 @@ function patchMacroTask(obj, funcName, metaCreator) {
setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
var meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
- return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask, null);
+ return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
}
else {
// cause an error by calling it directly.
@@ -1446,6 +1529,17 @@ function attachOriginToPatched(patched, original) {
}
var isDetectedIEOrEdge = false;
var ieOrEdge = false;
+function isIE() {
+ try {
+ var ua = internalWindow.navigator.userAgent;
+ if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
+ return true;
+ }
+ }
+ catch (error) {
+ }
+ return false;
+}
function isIEOrEdge() {
if (isDetectedIEOrEdge) {
return ieOrEdge;
@@ -1527,6 +1621,21 @@ Zone.__load_patch('toString', function (global) {
* @fileoverview
* @suppress {missingRequire}
*/
+var passiveSupported = false;
+if (typeof window !== 'undefined') {
+ try {
+ var options = Object.defineProperty({}, 'passive', {
+ get: function () {
+ passiveSupported = true;
+ }
+ });
+ window.addEventListener('test', options, options);
+ window.removeEventListener('test', options, options);
+ }
+ catch (err) {
+ passiveSupported = false;
+ }
+}
// an identifier to tell ZoneTask do not create a new invoke closure
var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
useG: true
@@ -1662,6 +1771,7 @@ function patchEventTarget(_global, apis, patchOptions) {
if (proto[zoneSymbolAddEventListener]) {
return false;
}
+ var eventNameToString = patchOptions && patchOptions.eventNameToString;
// a shared global taskData to pass data for scheduleEventTask
// so we do not need to create a new object just for pass some data
var taskData = {};
@@ -1677,12 +1787,24 @@ function patchEventTarget(_global, apis, patchOptions) {
nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
proto[patchOptions.prepend];
}
- var customScheduleGlobal = function () {
+ function checkIsPassive(task) {
+ if (!passiveSupported && typeof taskData.options !== 'boolean' &&
+ typeof taskData.options !== 'undefined' && taskData.options !== null) {
+ // options is a non-null non-undefined object
+ // passive is not supported
+ // don't pass options as object
+ // just pass capture as a boolean
+ task.options = !!taskData.options.capture;
+ taskData.options = task.options;
+ }
+ }
+ var customScheduleGlobal = function (task) {
// if there is already a task for the eventName + capture,
// just return, because we use the shared globalZoneAwareCallback here.
if (taskData.isExisting) {
return;
}
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
};
var customCancelGlobal = function (task) {
@@ -1723,6 +1845,7 @@ function patchEventTarget(_global, apis, patchOptions) {
return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
};
var customScheduleNonGlobal = function (task) {
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
};
var customSchedulePrepend = function (task) {
@@ -1745,10 +1868,15 @@ function patchEventTarget(_global, apis, patchOptions) {
if (prepend === void 0) { prepend = false; }
return function () {
var target = this || _global;
+ var eventName = arguments[0];
var delegate = arguments[1];
if (!delegate) {
return nativeListener.apply(this, arguments);
}
+ if (isNode && eventName === 'uncaughtException') {
+ // don't patch uncaughtException of nodejs to prevent endless loop
+ return nativeListener.apply(this, arguments);
+ }
// don't create the bind delegate function for handleEvent
// case here to improve addEventListener performance
// we will create the bind delegate when invoke
@@ -1762,7 +1890,6 @@ function patchEventTarget(_global, apis, patchOptions) {
if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
return;
}
- var eventName = arguments[0];
var options = arguments[2];
if (blackListedEvents) {
// check black list
@@ -1792,8 +1919,8 @@ function patchEventTarget(_global, apis, patchOptions) {
var symbolEventName;
if (!symbolEventNames) {
// the code is duplicate, but I just want to get some better performance
- var falseEventName = eventName + FALSE_STR;
- var trueEventName = eventName + TRUE_STR;
+ var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
+ var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames$1[eventName] = {};
@@ -1828,7 +1955,8 @@ function patchEventTarget(_global, apis, patchOptions) {
source = targetSource[eventName];
}
if (!source) {
- source = constructorName + addSource + eventName;
+ source = constructorName + addSource +
+ (eventNameToString ? eventNameToString(eventName) : eventName);
}
// do not create a new object as task.data to pass those things
// just use the global shared one
@@ -1843,7 +1971,7 @@ function patchEventTarget(_global, apis, patchOptions) {
taskData.capture = capture;
taskData.eventName = eventName;
taskData.isExisting = isExisting;
- var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : null;
+ var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
// keep taskData into data to allow onScheduleEventTask to access the task information
if (data) {
data.taskData = taskData;
@@ -1861,7 +1989,11 @@ function patchEventTarget(_global, apis, patchOptions) {
if (once) {
options.once = true;
}
- task.options = options;
+ if (!(!passiveSupported && typeof task.options === 'boolean')) {
+ // if not support passive, and we pass an option object
+ // to addEventListener, we should save the options to task
+ task.options = options;
+ }
task.target = target;
task.capture = capture;
task.eventName = eventName;
@@ -1946,7 +2078,7 @@ function patchEventTarget(_global, apis, patchOptions) {
var target = this || _global;
var eventName = arguments[0];
var listeners = [];
- var tasks = findEventTasks(target, eventName);
+ var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
@@ -2102,9 +2234,9 @@ function patchTimer(window, setName, cancelName, nameSuffix) {
patchMethod(window, setName, function (delegate) { return function (self, args) {
if (typeof args[0] === 'function') {
var options = {
- handleId: null,
isPeriodic: nameSuffix === 'Interval',
- delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,
+ delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
+ undefined,
args: args
};
var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
@@ -2219,7 +2351,7 @@ function propertyPatch() {
};
Object.getOwnPropertyDescriptor = function (obj, prop) {
var desc = _getOwnPropertyDescriptor(obj, prop);
- if (isUnconfigurable(obj, prop)) {
+ if (desc && isUnconfigurable(obj, prop)) {
desc.configurable = false;
}
return desc;
@@ -2447,10 +2579,10 @@ var globalEventHandlersEventNames = [
'wheel'
];
var documentEventNames = [
- 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'fullscreenchange',
+ 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'freeze', 'fullscreenchange',
'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror',
'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange',
- 'visibilitychange'
+ 'visibilitychange', 'resume'
];
var windowEventNames = [
'absolutedeviceorientation',
@@ -2562,7 +2694,7 @@ var websocketEventNames = ['close', 'error', 'open', 'message'];
var workerEventNames = ['error', 'message'];
var eventNames = globalEventHandlersEventNames.concat(webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames, htmlElementEventNames, ieElementEventNames);
function filterProperties(target, onProperties, ignoreProperties) {
- if (!ignoreProperties) {
+ if (!ignoreProperties || ignoreProperties.length === 0) {
return onProperties;
}
var tip = ignoreProperties.filter(function (ip) { return ip.target === target; });
@@ -2587,13 +2719,14 @@ function propertyDescriptorPatch(api, _global) {
}
var supportsWebSocket = typeof WebSocket !== 'undefined';
if (canPatchViaPropertyDescriptor()) {
- var ignoreProperties = _global.__Zone_ignore_on_properties;
+ var ignoreProperties = _global['__Zone_ignore_on_properties'];
// for browsers that we can patch the descriptor: Chrome & Firefox
if (isBrowser) {
var internalWindow = window;
+ var ignoreErrorProperties = isIE ? [{ target: internalWindow, ignoreProperties: ['error'] }] : [];
// in IE/Edge, onProp not exist in window object, but in WindowPrototype
// so we need to pass WindowPrototype to check onProp exist or not
- patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties, ObjectGetPrototypeOf(internalWindow));
+ patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
patchFilteredProperties(Document.prototype, eventNames, ignoreProperties);
if (typeof internalWindow['SVGElement'] !== 'undefined') {
patchFilteredProperties(internalWindow['SVGElement'].prototype, eventNames, ignoreProperties);
@@ -2615,9 +2748,9 @@ function propertyDescriptorPatch(api, _global) {
}
}
patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties);
- var XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget'];
- if (XMLHttpRequestEventTarget) {
- patchFilteredProperties(XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames, ignoreProperties);
+ var XMLHttpRequestEventTarget_1 = _global['XMLHttpRequestEventTarget'];
+ if (XMLHttpRequestEventTarget_1) {
+ patchFilteredProperties(XMLHttpRequestEventTarget_1 && XMLHttpRequestEventTarget_1.prototype, XMLHttpRequestEventNames, ignoreProperties);
}
if (typeof IDBIndex !== 'undefined') {
patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties);
@@ -2832,16 +2965,16 @@ function patchEvent(global, api) {
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
-function registerElementPatch(_global) {
- if ((!isBrowser && !isMix) || !('registerElement' in _global.document)) {
+function patchCallbacks(target, targetName, method, callbacks) {
+ var symbol = Zone.__symbol__(method);
+ if (target[symbol]) {
return;
}
- var _registerElement = document.registerElement;
- var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
- document.registerElement = function (name, opts) {
+ var nativeDelegate = target[symbol] = target[method];
+ target[method] = function (name, opts, options) {
if (opts && opts.prototype) {
callbacks.forEach(function (callback) {
- var source = 'Document.registerElement::' + callback;
+ var source = targetName + "." + method + "::" + callback;
var prototype = opts.prototype;
if (prototype.hasOwnProperty(callback)) {
var descriptor = ObjectGetOwnPropertyDescriptor(prototype, callback);
@@ -2858,9 +2991,23 @@ function registerElementPatch(_global) {
}
});
}
- return _registerElement.call(document, name, opts);
+ return nativeDelegate.call(target, name, opts, options);
};
- attachOriginToPatched(document.registerElement, _registerElement);
+ attachOriginToPatched(target[method], nativeDelegate);
+}
+function registerElementPatch(_global) {
+ if ((!isBrowser && !isMix) || !('registerElement' in _global.document)) {
+ return;
+ }
+ var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
+ patchCallbacks(document, 'Document', 'registerElement', callbacks);
+}
+function patchCustomElements(_global) {
+ if ((!isBrowser && !isMix) || !('customElements' in _global)) {
+ return;
+ }
+ var callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
+ patchCallbacks(_global.customElements, 'customElements', 'define', callbacks);
}
/**
@@ -2923,7 +3070,10 @@ Zone.__load_patch('EventTarget', function (global, Zone, api) {
Zone.__load_patch('on_property', function (global, Zone, api) {
propertyDescriptorPatch(api, global);
propertyPatch();
+});
+Zone.__load_patch('customElements', function (global, Zone, api) {
registerElementPatch(global);
+ patchCustomElements(global);
});
Zone.__load_patch('canvas', function (global) {
var HTMLCanvasElement = global['HTMLCanvasElement'];
@@ -2942,6 +3092,7 @@ Zone.__load_patch('XHR', function (global, Zone) {
var XHR_LISTENER = zoneSymbol('xhrListener');
var XHR_SCHEDULED = zoneSymbol('xhrScheduled');
var XHR_URL = zoneSymbol('xhrURL');
+ var XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
function patchXHR(window) {
var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
function findPendingTask(target) {
@@ -2950,9 +3101,9 @@ Zone.__load_patch('XHR', function (global, Zone) {
var oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
var oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
if (!oriAddListener) {
- var XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
- if (XMLHttpRequestEventTarget) {
- var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
+ var XMLHttpRequestEventTarget_1 = window['XMLHttpRequestEventTarget'];
+ if (XMLHttpRequestEventTarget_1) {
+ var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget_1.prototype;
oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
}
@@ -2960,9 +3111,10 @@ Zone.__load_patch('XHR', function (global, Zone) {
var READY_STATE_CHANGE = 'readystatechange';
var SCHEDULED = 'scheduled';
function scheduleTask(task) {
- XMLHttpRequest[XHR_SCHEDULED] = false;
var data = task.data;
var target = data.target;
+ target[XHR_SCHEDULED] = false;
+ target[XHR_ERROR_BEFORE_SCHEDULED] = false;
// remove existing event listener
var listener = target[XHR_LISTENER];
if (!oriAddListener) {
@@ -2976,8 +3128,35 @@ Zone.__load_patch('XHR', function (global, Zone) {
if (target.readyState === target.DONE) {
// sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
// readyState=4 multiple times, so we need to check task state here
- if (!data.aborted && XMLHttpRequest[XHR_SCHEDULED] && task.state === SCHEDULED) {
- task.invoke();
+ if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
+ // check whether the xhr has registered onload listener
+ // if that is the case, the task should invoke after all
+ // onload listeners finish.
+ var loadTasks = target['__zone_symbol__loadfalse'];
+ if (loadTasks && loadTasks.length > 0) {
+ var oriInvoke_1 = task.invoke;
+ task.invoke = function () {
+ // need to load the tasks again, because in other
+ // load listener, they may remove themselves
+ var loadTasks = target['__zone_symbol__loadfalse'];
+ for (var i = 0; i < loadTasks.length; i++) {
+ if (loadTasks[i] === task) {
+ loadTasks.splice(i, 1);
+ }
+ }
+ if (!data.aborted && task.state === SCHEDULED) {
+ oriInvoke_1.call(task);
+ }
+ };
+ loadTasks.push(task);
+ }
+ else {
+ task.invoke();
+ }
+ }
+ else if (!data.aborted && target[XHR_SCHEDULED] === false) {
+ // error occurs when xhr.send()
+ target[XHR_ERROR_BEFORE_SCHEDULED] = true;
}
}
};
@@ -2987,7 +3166,7 @@ Zone.__load_patch('XHR', function (global, Zone) {
target[XHR_TASK] = task;
}
sendNative.apply(target, data.args);
- XMLHttpRequest[XHR_SCHEDULED] = true;
+ target[XHR_SCHEDULED] = true;
return task;
}
function placeholderCallback() { }
@@ -3004,24 +3183,32 @@ Zone.__load_patch('XHR', function (global, Zone) {
return openNative.apply(self, args);
}; });
var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
+ var fetchTaskAborting = zoneSymbol('fetchTaskAborting');
+ var fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
var sendNative = patchMethod(XMLHttpRequestPrototype, 'send', function () { return function (self, args) {
+ if (Zone.current[fetchTaskScheduling] === true) {
+ // a fetch is scheduling, so we are using xhr to polyfill fetch
+ // and because we already schedule macroTask for fetch, we should
+ // not schedule a macroTask for xhr again
+ return sendNative.apply(self, args);
+ }
if (self[XHR_SYNC]) {
// if the XHR is sync there is no task to schedule, just execute the code.
return sendNative.apply(self, args);
}
else {
- var options = {
- target: self,
- url: self[XHR_URL],
- isPeriodic: false,
- delay: null,
- args: args,
- aborted: false
- };
- return scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
+ var options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
+ var task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
+ if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
+ task.state === SCHEDULED) {
+ // xhr request throw error when send
+ // we should invoke task instead of leaving a scheduled
+ // pending macroTask
+ task.invoke();
+ }
}
}; });
- var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self) {
+ var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self, args) {
var task = findPendingTask(self);
if (task && typeof task.type == 'string') {
// If the XHR has already completed, do nothing.
@@ -3033,6 +3220,10 @@ Zone.__load_patch('XHR', function (global, Zone) {
}
task.zone.cancelTask(task);
}
+ else if (Zone.current[fetchTaskAborting] === true) {
+ // the abort is called from fetch polyfill, we need to call native abort of XHR.
+ return abortNative.apply(self, args);
+ }
// Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
// task
// to cancel. Do nothing.
@@ -3069,6 +3260,20 @@ Zone.__load_patch('PromiseRejectionEvent', function (global, Zone) {
}
});
+/**
+ * @license
+ * Copyright Google Inc. 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.io/license
+ */
+Zone.__load_patch('node_util', function (global, Zone, api) {
+ api.patchOnProperties = patchOnProperties;
+ api.patchMethod = patchMethod;
+ api.bindArguments = bindArguments;
+ setShouldCopySymbolProperties(true);
+});
+
/**
* @license
* Copyright Google Inc. All Rights Reserved.
@@ -3088,6 +3293,15 @@ Zone.__load_patch('EventEmitter', function (global) {
// same callback, same capture, same event name, just return
return task.callback === delegate || task.callback.listener === delegate;
};
+ var eventNameToString = function (eventName) {
+ if (typeof eventName === 'string') {
+ return eventName;
+ }
+ if (!eventName) {
+ return '';
+ }
+ return eventName.toString().replace('(', '_').replace(')', '_');
+ };
function patchEventEmitterMethods(obj) {
var result = patchEventTarget(global, [obj], {
useG: false,
@@ -3098,7 +3312,8 @@ Zone.__load_patch('EventEmitter', function (global) {
listeners: EE_LISTENERS,
chkDup: false,
rt: true,
- diff: compareTaskCallbackVsDelegate
+ diff: compareTaskCallbackVsDelegate,
+ eventNameToString: eventNameToString
});
if (result && result[0]) {
obj[EE_ON] = obj[EE_ADD_LISTENER];
@@ -3163,11 +3378,6 @@ Zone.__load_patch('fs', function () {
*/
var set = 'set';
var clear = 'clear';
-Zone.__load_patch('node_util', function (global, Zone, api) {
- api.patchOnProperties = patchOnProperties;
- api.patchMethod = patchMethod;
- api.bindArguments = bindArguments;
-});
Zone.__load_patch('node_timers', function (global, Zone) {
// Timers
var globalUseTimeoutFromTimer = false;
diff --git a/dist/zone-node.js b/dist/zone-node.js
index c857c893c..8bbe1e846 100644
--- a/dist/zone-node.js
+++ b/dist/zone-node.js
@@ -19,7 +19,6 @@
* found in the LICENSE file at https://angular.io/license
*/
var Zone$1 = (function (global) {
- var FUNCTION = 'function';
var performance = global['performance'];
function mark(name) {
performance && performance['mark'] && performance['mark'](name);
@@ -28,12 +27,26 @@ var Zone$1 = (function (global) {
performance && performance['measure'] && performance['measure'](name, label);
}
mark('Zone');
+ var checkDuplicate = global[('__zone_symbol__forceDuplicateZoneCheck')] === true;
if (global['Zone']) {
- throw new Error('Zone already loaded.');
+ // if global['Zone'] already exists (maybe zone.js was already loaded or
+ // some other lib also registered a global object named Zone), we may need
+ // to throw an error, but sometimes user may not want this error.
+ // For example,
+ // we have two web pages, page1 includes zone.js, page2 doesn't.
+ // and the 1st time user load page1 and page2, everything work fine,
+ // but when user load page2 again, error occurs because global['Zone'] already exists.
+ // so we add a flag to let user choose whether to throw this error or not.
+ // By default, if existing Zone is from zone.js, we will not throw the error.
+ if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
+ throw new Error('Zone already loaded.');
+ }
+ else {
+ return global['Zone'];
+ }
}
var Zone = /** @class */ (function () {
function Zone(parent, zoneSpec) {
- this._properties = null;
this._parent = parent;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '';
this._properties = zoneSpec && zoneSpec.properties || {};
@@ -76,7 +89,9 @@ var Zone$1 = (function (global) {
});
Zone.__load_patch = function (name, fn) {
if (patches.hasOwnProperty(name)) {
- throw Error('Already loaded patch: ' + name);
+ if (checkDuplicate) {
+ throw Error('Already loaded patch: ' + name);
+ }
}
else if (!global['__Zone_disable_' + name]) {
var perfName = 'Zone:' + name;
@@ -120,7 +135,7 @@ var Zone$1 = (function (global) {
return this._zoneDelegate.fork(this, zoneSpec);
};
Zone.prototype.wrap = function (callback, source) {
- if (typeof callback !== FUNCTION) {
+ if (typeof callback !== 'function') {
throw new Error('Expecting function got: ' + callback);
}
var _callback = this._zoneDelegate.intercept(this, callback, source);
@@ -130,9 +145,6 @@ var Zone$1 = (function (global) {
};
};
Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
- if (applyThis === void 0) { applyThis = undefined; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
@@ -143,8 +155,6 @@ var Zone$1 = (function (global) {
};
Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
try {
@@ -168,10 +178,7 @@ var Zone$1 = (function (global) {
// https://github.com/angular/zone.js/issues/778, sometimes eventTask
// will run in notScheduled(canceled) state, we should not try to
// run such kind of task but just return
- // we have to define an variable here, if not
- // typescript compiler will complain below
- var isNotScheduled = task.state === notScheduled;
- if (isNotScheduled && task.type === eventTask) {
+ if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
return;
}
var reEntryGuard = task.state != running;
@@ -182,7 +189,7 @@ var Zone$1 = (function (global) {
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
if (task.type == macroTask && task.data && !task.data.isPeriodic) {
- task.cancelFn = null;
+ task.cancelFn = undefined;
}
try {
return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
@@ -218,8 +225,7 @@ var Zone$1 = (function (global) {
var newZone = this;
while (newZone) {
if (newZone === task.zone) {
- throw Error("can not reschedule task to " + this
- .name + " which is descendants of the original zone " + task.zone.name);
+ throw Error("can not reschedule task to " + this.name + " which is descendants of the original zone " + task.zone.name);
}
newZone = newZone.parent;
}
@@ -249,7 +255,7 @@ var Zone$1 = (function (global) {
return task;
};
Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
- return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, null));
+ return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
};
Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
@@ -290,16 +296,14 @@ var Zone$1 = (function (global) {
}());
var DELEGATE_ZS = {
name: '',
- onHasTask: function (delegate, _, target, hasTaskState) {
- return delegate.hasTask(target, hasTaskState);
- },
+ onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
onScheduleTask: function (delegate, _, target, task) {
return delegate.scheduleTask(target, task);
},
- onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); },
- onCancelTask: function (delegate, _, target, task) {
- return delegate.cancelTask(target, task);
- }
+ onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) {
+ return delegate.invokeTask(target, task, applyThis, applyArgs);
+ },
+ onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
};
var ZoneDelegate = /** @class */ (function () {
function ZoneDelegate(zone, parentDelegate, zoneSpec) {
@@ -327,8 +331,8 @@ var Zone$1 = (function (global) {
zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);
this._scheduleTaskZS =
zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
- this._scheduleTaskDlgt =
- zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
+ this._scheduleTaskDlgt = zoneSpec &&
+ (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
this._scheduleTaskCurrZone =
zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);
this._invokeTaskZS =
@@ -383,8 +387,7 @@ var Zone$1 = (function (global) {
callback;
};
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
- return this._invokeZS ?
- this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
+ return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.handleError = function (targetZone, error) {
@@ -416,8 +419,7 @@ var Zone$1 = (function (global) {
return returnTask;
};
ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
- return this._invokeTaskZS ?
- this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
+ return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
task.callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
@@ -437,7 +439,7 @@ var Zone$1 = (function (global) {
// hasTask should not throw error so other ZoneDelegate
// can still trigger hasTask callback
try {
- return this._hasTaskZS &&
+ this._hasTaskZS &&
this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
}
catch (err) {
@@ -527,14 +529,12 @@ var Zone$1 = (function (global) {
}
}
else {
- throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ?
- ' or \'' + fromState2 + '\'' :
- '') + ", was '" + this._state + "'.");
+ throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ? ' or \'' + fromState2 + '\'' : '') + ", was '" + this._state + "'.");
}
};
ZoneTask.prototype.toString = function () {
if (this.data && typeof this.data.handleId !== 'undefined') {
- return this.data.handleId;
+ return this.data.handleId.toString();
}
else {
return Object.prototype.toString.call(this);
@@ -575,7 +575,13 @@ var Zone$1 = (function (global) {
}
}
if (nativeMicroTaskQueuePromise) {
- nativeMicroTaskQueuePromise[symbolThen](drainMicroTaskQueue);
+ var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
+ if (!nativeThen) {
+ // native Promise is not patchable, we need to use `then` directly
+ // issue 1078
+ nativeThen = nativeMicroTaskQueuePromise['then'];
+ }
+ nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
}
else {
global[symbolSetTimeout](drainMicroTaskQueue, 0);
@@ -622,12 +628,13 @@ var Zone$1 = (function (global) {
patchEventTarget: function () { return []; },
patchOnProperties: noop,
patchMethod: function () { return noop; },
- bindArguments: function () { return null; },
+ bindArguments: function () { return []; },
+ patchThen: function () { return noop; },
setNativePromise: function (NativePromise) {
// sometimes NativePromise.resolve static function
// is not ready yet, (such as core-js/es6.promise)
// so we need to check here.
- if (NativePromise && typeof NativePromise.resolve === FUNCTION) {
+ if (NativePromise && typeof NativePromise.resolve === 'function') {
nativeMicroTaskQueuePromise = NativePromise.resolve(0);
}
},
@@ -643,6 +650,16 @@ var Zone$1 = (function (global) {
return global['Zone'] = Zone;
})(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
+var __values = (undefined && undefined.__values) || function (o) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
+ if (m) return m.call(o);
+ return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+};
Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var ObjectDefineProperty = Object.defineProperty;
@@ -785,7 +802,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var queue = promise[symbolValue];
promise[symbolValue] = value;
if (promise[symbolFinally] === symbolFinally) {
- // the promise is generated by Promise.prototype.finally
+ // the promise is generated by Promise.prototype.finally
if (state === RESOLVED) {
// the state is resolved, should ignore the value
// and use parent promise value
@@ -869,7 +886,9 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
chainPromise[symbolParentPromiseState] = promiseState;
}
// should not pass value to finally callback
- var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ? [] : [parentPromiseValue]);
+ var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
+ [] :
+ [parentPromiseValue]);
resolvePromise(chainPromise, true, value);
}
catch (error) {
@@ -904,6 +923,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
return resolvePromise(new this(null), REJECTED, error);
};
ZoneAwarePromise.race = function (values) {
+ var e_1, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
@@ -916,40 +936,70 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
function onReject(error) {
promise && (promise = null || reject(error));
}
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- if (!isThenable(value)) {
- value = this.resolve(value);
+ try {
+ for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
+ var value = values_1_1.value;
+ if (!isThenable(value)) {
+ value = this.resolve(value);
+ }
+ value.then(onResolve, onReject);
}
- value.then(onResolve, onReject);
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
+ }
+ finally { if (e_1) throw e_1.error; }
}
return promise;
};
ZoneAwarePromise.all = function (values) {
+ var e_2, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
resolve = res;
reject = rej;
});
- var count = 0;
+ // Start at 2 to prevent prematurely resolving if .then is called immediately.
+ var unresolvedCount = 2;
+ var valueIndex = 0;
var resolvedValues = [];
- for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
- var value = values_2[_i];
+ var _loop_2 = function (value) {
if (!isThenable(value)) {
- value = this.resolve(value);
+ value = this_1.resolve(value);
}
- value.then((function (index) { return function (value) {
- resolvedValues[index] = value;
- count--;
- if (!count) {
+ var curValueIndex = valueIndex;
+ value.then(function (value) {
+ resolvedValues[curValueIndex] = value;
+ unresolvedCount--;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
}
- }; })(count), reject);
- count++;
+ }, reject);
+ unresolvedCount++;
+ valueIndex++;
+ };
+ var this_1 = this;
+ try {
+ for (var values_2 = __values(values), values_2_1 = values_2.next(); !values_2_1.done; values_2_1 = values_2.next()) {
+ var value = values_2_1.value;
+ _loop_2(value);
+ }
}
- if (!count)
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
+ finally {
+ try {
+ if (values_2_1 && !values_2_1.done && (_a = values_2.return)) _a.call(values_2);
+ }
+ finally { if (e_2) throw e_2.error; }
+ }
+ // Make the unresolvedCount zero-based again.
+ unresolvedCount -= 2;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
+ }
return promise;
};
ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
@@ -1045,25 +1095,9 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
};
Ctor[symbolThenPatched] = true;
}
- function zoneify(fn) {
- return function () {
- var resultPromise = fn.apply(this, arguments);
- if (resultPromise instanceof ZoneAwarePromise) {
- return resultPromise;
- }
- var ctor = resultPromise.constructor;
- if (!ctor[symbolThenPatched]) {
- patchThen(ctor);
- }
- return resultPromise;
- };
- }
+ api.patchThen = patchThen;
if (NativePromise) {
patchThen(NativePromise);
- var fetch_1 = global['fetch'];
- if (typeof fetch_1 == 'function') {
- global['fetch'] = zoneify(fetch_1);
- }
}
// This is not part of public API, but it is useful for tests, so we expose it.
Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
@@ -1163,9 +1197,23 @@ var wrapFn = function (event) {
}
var target = this || event.target || _global;
var listener = target[eventNameSymbol];
- var result = listener && listener.apply(this, arguments);
- if (result != undefined && !result) {
- event.preventDefault();
+ var result;
+ if (isBrowser && target === internalWindow && event.type === 'error') {
+ // window.onerror have different signiture
+ // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
+ // and onerror callback will prevent default when callback return true
+ var errorEvent = event;
+ result = listener &&
+ listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
+ if (result === true) {
+ event.preventDefault();
+ }
+ }
+ else {
+ result = listener && listener.apply(this, arguments);
+ if (result != undefined && !result) {
+ event.preventDefault();
+ }
}
return result;
};
@@ -1183,6 +1231,10 @@ function patchProperty(obj, prop, prototype) {
if (!desc || !desc.configurable) {
return;
}
+ var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
+ if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
+ return;
+ }
// A property descriptor cannot have getter/setter and be writable
// deleting the writable and value properties avoids this error:
//
@@ -1260,6 +1312,7 @@ function patchProperty(obj, prop, prototype) {
return null;
};
ObjectDefineProperty(obj, prop, desc);
+ obj[onPropPatchedSymbol] = true;
}
function patchOnProperties(obj, properties, prototype) {
if (properties) {
@@ -1282,6 +1335,33 @@ function patchOnProperties(obj, properties, prototype) {
var originalInstanceKey = zoneSymbol('originalInstance');
// wrap some native API on `window`
+function copySymbolProperties(src, dest) {
+ if (typeof Object.getOwnPropertySymbols !== 'function') {
+ return;
+ }
+ var symbols = Object.getOwnPropertySymbols(src);
+ symbols.forEach(function (symbol) {
+ var desc = Object.getOwnPropertyDescriptor(src, symbol);
+ Object.defineProperty(dest, symbol, {
+ get: function () {
+ return src[symbol];
+ },
+ set: function (value) {
+ if (desc && (!desc.writable || typeof desc.set !== 'function')) {
+ // if src[symbol] is not writable or not have a setter, just return
+ return;
+ }
+ src[symbol] = value;
+ },
+ enumerable: desc ? desc.enumerable : true,
+ configurable: desc ? desc.configurable : true
+ });
+ });
+}
+var shouldCopySymbolProperties = false;
+function setShouldCopySymbolProperties(flag) {
+ shouldCopySymbolProperties = flag;
+}
function patchMethod(target, name, patchFn) {
var proto = target;
while (proto && !proto.hasOwnProperty(name)) {
@@ -1292,7 +1372,7 @@ function patchMethod(target, name, patchFn) {
proto = target;
}
var delegateName = zoneSymbol(name);
- var delegate;
+ var delegate = null;
if (proto && !(delegate = proto[delegateName])) {
delegate = proto[delegateName] = proto[name];
// check whether proto[name] is writable
@@ -1304,6 +1384,9 @@ function patchMethod(target, name, patchFn) {
return patchDelegate_1(this, arguments);
};
attachOriginToPatched(proto[name], delegate);
+ if (shouldCopySymbolProperties) {
+ copySymbolProperties(delegate, proto[name]);
+ }
}
}
return delegate;
@@ -1322,7 +1405,7 @@ function patchMacroTask(obj, funcName, metaCreator) {
setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
var meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
- return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask, null);
+ return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
}
else {
// cause an error by calling it directly.
@@ -1409,6 +1492,20 @@ Zone.__load_patch('toString', function (global) {
};
});
+/**
+ * @license
+ * Copyright Google Inc. 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.io/license
+ */
+Zone.__load_patch('node_util', function (global, Zone, api) {
+ api.patchOnProperties = patchOnProperties;
+ api.patchMethod = patchMethod;
+ api.bindArguments = bindArguments;
+ setShouldCopySymbolProperties(true);
+});
+
/**
* @license
* Copyright Google Inc. All Rights Reserved.
@@ -1420,6 +1517,21 @@ Zone.__load_patch('toString', function (global) {
* @fileoverview
* @suppress {missingRequire}
*/
+var passiveSupported = false;
+if (typeof window !== 'undefined') {
+ try {
+ var options = Object.defineProperty({}, 'passive', {
+ get: function () {
+ passiveSupported = true;
+ }
+ });
+ window.addEventListener('test', options, options);
+ window.removeEventListener('test', options, options);
+ }
+ catch (err) {
+ passiveSupported = false;
+ }
+}
// an identifier to tell ZoneTask do not create a new invoke closure
var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
useG: true
@@ -1555,6 +1667,7 @@ function patchEventTarget(_global, apis, patchOptions) {
if (proto[zoneSymbolAddEventListener]) {
return false;
}
+ var eventNameToString = patchOptions && patchOptions.eventNameToString;
// a shared global taskData to pass data for scheduleEventTask
// so we do not need to create a new object just for pass some data
var taskData = {};
@@ -1570,12 +1683,24 @@ function patchEventTarget(_global, apis, patchOptions) {
nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
proto[patchOptions.prepend];
}
- var customScheduleGlobal = function () {
+ function checkIsPassive(task) {
+ if (!passiveSupported && typeof taskData.options !== 'boolean' &&
+ typeof taskData.options !== 'undefined' && taskData.options !== null) {
+ // options is a non-null non-undefined object
+ // passive is not supported
+ // don't pass options as object
+ // just pass capture as a boolean
+ task.options = !!taskData.options.capture;
+ taskData.options = task.options;
+ }
+ }
+ var customScheduleGlobal = function (task) {
// if there is already a task for the eventName + capture,
// just return, because we use the shared globalZoneAwareCallback here.
if (taskData.isExisting) {
return;
}
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
};
var customCancelGlobal = function (task) {
@@ -1616,6 +1741,7 @@ function patchEventTarget(_global, apis, patchOptions) {
return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
};
var customScheduleNonGlobal = function (task) {
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
};
var customSchedulePrepend = function (task) {
@@ -1638,10 +1764,15 @@ function patchEventTarget(_global, apis, patchOptions) {
if (prepend === void 0) { prepend = false; }
return function () {
var target = this || _global;
+ var eventName = arguments[0];
var delegate = arguments[1];
if (!delegate) {
return nativeListener.apply(this, arguments);
}
+ if (isNode && eventName === 'uncaughtException') {
+ // don't patch uncaughtException of nodejs to prevent endless loop
+ return nativeListener.apply(this, arguments);
+ }
// don't create the bind delegate function for handleEvent
// case here to improve addEventListener performance
// we will create the bind delegate when invoke
@@ -1655,7 +1786,6 @@ function patchEventTarget(_global, apis, patchOptions) {
if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
return;
}
- var eventName = arguments[0];
var options = arguments[2];
if (blackListedEvents) {
// check black list
@@ -1685,8 +1815,8 @@ function patchEventTarget(_global, apis, patchOptions) {
var symbolEventName;
if (!symbolEventNames) {
// the code is duplicate, but I just want to get some better performance
- var falseEventName = eventName + FALSE_STR;
- var trueEventName = eventName + TRUE_STR;
+ var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
+ var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames$1[eventName] = {};
@@ -1721,7 +1851,8 @@ function patchEventTarget(_global, apis, patchOptions) {
source = targetSource[eventName];
}
if (!source) {
- source = constructorName + addSource + eventName;
+ source = constructorName + addSource +
+ (eventNameToString ? eventNameToString(eventName) : eventName);
}
// do not create a new object as task.data to pass those things
// just use the global shared one
@@ -1736,7 +1867,7 @@ function patchEventTarget(_global, apis, patchOptions) {
taskData.capture = capture;
taskData.eventName = eventName;
taskData.isExisting = isExisting;
- var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : null;
+ var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
// keep taskData into data to allow onScheduleEventTask to access the task information
if (data) {
data.taskData = taskData;
@@ -1754,7 +1885,11 @@ function patchEventTarget(_global, apis, patchOptions) {
if (once) {
options.once = true;
}
- task.options = options;
+ if (!(!passiveSupported && typeof task.options === 'boolean')) {
+ // if not support passive, and we pass an option object
+ // to addEventListener, we should save the options to task
+ task.options = options;
+ }
task.target = target;
task.capture = capture;
task.eventName = eventName;
@@ -1839,7 +1974,7 @@ function patchEventTarget(_global, apis, patchOptions) {
var target = this || _global;
var eventName = arguments[0];
var listeners = [];
- var tasks = findEventTasks(target, eventName);
+ var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
@@ -1949,6 +2084,15 @@ Zone.__load_patch('EventEmitter', function (global) {
// same callback, same capture, same event name, just return
return task.callback === delegate || task.callback.listener === delegate;
};
+ var eventNameToString = function (eventName) {
+ if (typeof eventName === 'string') {
+ return eventName;
+ }
+ if (!eventName) {
+ return '';
+ }
+ return eventName.toString().replace('(', '_').replace(')', '_');
+ };
function patchEventEmitterMethods(obj) {
var result = patchEventTarget(global, [obj], {
useG: false,
@@ -1959,7 +2103,8 @@ Zone.__load_patch('EventEmitter', function (global) {
listeners: EE_LISTENERS,
chkDup: false,
rt: true,
- diff: compareTaskCallbackVsDelegate
+ diff: compareTaskCallbackVsDelegate,
+ eventNameToString: eventNameToString
});
if (result && result[0]) {
obj[EE_ON] = obj[EE_ADD_LISTENER];
@@ -2068,9 +2213,9 @@ function patchTimer(window, setName, cancelName, nameSuffix) {
patchMethod(window, setName, function (delegate) { return function (self, args) {
if (typeof args[0] === 'function') {
var options = {
- handleId: null,
isPeriodic: nameSuffix === 'Interval',
- delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,
+ delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
+ undefined,
args: args
};
var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
@@ -2151,11 +2296,6 @@ function patchTimer(window, setName, cancelName, nameSuffix) {
*/
var set = 'set';
var clear = 'clear';
-Zone.__load_patch('node_util', function (global, Zone, api) {
- api.patchOnProperties = patchOnProperties;
- api.patchMethod = patchMethod;
- api.bindArguments = bindArguments;
-});
Zone.__load_patch('node_timers', function (global, Zone) {
// Timers
var globalUseTimeoutFromTimer = false;
diff --git a/dist/zone-patch-jsonp.js b/dist/zone-patch-jsonp.js
index 4dcf57382..d7e75f2b8 100644
--- a/dist/zone-patch-jsonp.js
+++ b/dist/zone-patch-jsonp.js
@@ -71,9 +71,10 @@ Zone.__load_patch('jsonp', function (global, Zone, api) {
}
});
api.patchMethod(options.jsonp, options.sendFuncName, function (delegate) { return function (self, args) {
- global[api.symbol('jsonpTask')] = Zone.current.scheduleMacroTask('jsonp', noop, {}, function (task) {
- return delegate.apply(self, args);
- }, noop);
+ global[api.symbol('jsonpTask')] =
+ Zone.current.scheduleMacroTask('jsonp', noop, {}, function (task) {
+ return delegate.apply(self, args);
+ }, noop);
}; });
};
});
diff --git a/dist/zone-patch-resize-observer.js b/dist/zone-patch-resize-observer.js
index e80c32588..b85d7ee9f 100644
--- a/dist/zone-patch-resize-observer.js
+++ b/dist/zone-patch-resize-observer.js
@@ -39,6 +39,7 @@ Zone.__load_patch('ResizeObserver', function (global, Zone, api) {
if (callback) {
args[0] = function (entries, observer) {
var _this = this;
+ var e_1, _a;
var zones = {};
var currZone = Zone.current;
try {
@@ -71,7 +72,6 @@ Zone.__load_patch('ResizeObserver', function (global, Zone, api) {
callback.call(_this, zoneEntriesInfo.entries, observer);
}
});
- var e_1, _a;
};
}
return args.length > 0 ? new ResizeObserver(args[0]) : new ResizeObserver();
@@ -109,7 +109,9 @@ Zone.__load_patch('ResizeObserver', function (global, Zone, api) {
api.patchMethod(ResizeObserver.prototype, 'disconnect', function (delegate) { return function (self, args) {
var targets = self[resizeObserverSymbol];
if (targets) {
- targets.forEach(function (target) { target[resizeObserverSymbol] = undefined; });
+ targets.forEach(function (target) {
+ target[resizeObserverSymbol] = undefined;
+ });
self[resizeObserverSymbol] = undefined;
}
return delegate.apply(self, args);
diff --git a/dist/zone-patch-resize-observer.min.js b/dist/zone-patch-resize-observer.min.js
index 4e3ef0583..4762c8bc7 100644
--- a/dist/zone-patch-resize-observer.min.js
+++ b/dist/zone-patch-resize-observer.min.js
@@ -1 +1 @@
-!function(e,n){"object"==typeof exports&&"undefined"!=typeof module?n():"function"==typeof define&&define.amd?define(n):n()}(this,function(){"use strict";var e=function(e){var n="function"==typeof Symbol&&e[Symbol.iterator],r=0;return n?n.call(e):{next:function(){return e&&r>=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}};Zone.__load_patch("ResizeObserver",function(n,r,t){var o=n.ResizeObserver;if(o){var i=t.symbol("ResizeObserver");t.patchMethod(n,"ResizeObserver",function(n){return function(n,t){var u=t.length>0?t[0]:null;return u&&(t[0]=function(n,t){var o=this,a={},c=r.current;try{for(var f=e(n),l=f.next();!l.done;l=f.next()){var v=l.value,p=v.target[i];p||(p=c);var s=a[p.name];s||(a[p.name]=s={entries:[],zone:p}),s.entries.push(v)}}catch(h){d={error:h}}finally{try{l&&!l.done&&(y=f["return"])&&y.call(f)}finally{if(d)throw d.error}}Object.keys(a).forEach(function(e){var n=a[e];n.zone!==r.current?n.zone.run(u,o,[n.entries,t],"ResizeObserver"):u.call(o,n.entries,t)});var d,y}),t.length>0?new o(t[0]):new o}}),t.patchMethod(o.prototype,"observe",function(e){return function(n,t){var o=t.length>0?t[0]:null;if(!o)return e.apply(n,t);var u=n[i];return u||(u=n[i]=[]),u.push(o),o[i]=r.current,e.apply(n,t)}}),t.patchMethod(o.prototype,"unobserve",function(e){return function(n,r){var t=r.length>0?r[0]:null;if(!t)return e.apply(n,r);var o=n[i];if(o)for(var u=0;u=e.length&&(e=void 0),{value:e&&e[r++],done:!e}}}};Zone.__load_patch("ResizeObserver",function(n,r,t){var o=n.ResizeObserver;if(o){var i=t.symbol("ResizeObserver");t.patchMethod(n,"ResizeObserver",function(n){return function(n,t){var u=t.length>0?t[0]:null;return u&&(t[0]=function(n,t){var o,a,c=this,f={},l=r.current;try{for(var p=e(n),v=p.next();!v.done;v=p.next()){var s=v.value,h=s.target[i];h||(h=l);var d=f[h.name];d||(f[h.name]=d={entries:[],zone:h}),d.entries.push(s)}}catch(y){o={error:y}}finally{try{v&&!v.done&&(a=p["return"])&&a.call(p)}finally{if(o)throw o.error}}Object.keys(f).forEach(function(e){var n=f[e];n.zone!==r.current?n.zone.run(u,c,[n.entries,t],"ResizeObserver"):u.call(c,n.entries,t)})}),t.length>0?new o(t[0]):new o}}),t.patchMethod(o.prototype,"observe",function(e){return function(n,t){var o=t.length>0?t[0]:null;if(!o)return e.apply(n,t);var u=n[i];return u||(u=n[i]=[]),u.push(o),o[i]=r.current,e.apply(n,t)}}),t.patchMethod(o.prototype,"unobserve",function(e){return function(n,r){var t=r.length>0?r[0]:null;if(!t)return e.apply(n,r);var o=n[i];if(o)for(var u=0;u 0 ? args[0] : undefined;
- if (typeof subjectOrSubjectFactory !== 'function') {
- var originalFactory_1 = subjectOrSubjectFactory;
- subjectOrSubjectFactory = function () {
- return originalFactory_1;
- };
- }
- args[0] = function () {
- var subject;
- if (_zone && _zone !== Zone.current) {
- subject = _zone.run(subjectOrSubjectFactory, this, arguments);
- }
- else {
- subject = subjectOrSubjectFactory.apply(this, arguments);
- }
- if (subject && _zone) {
- subject._zone = _zone;
- }
- return subject;
- };
- var observable = factory.apply(this, args);
- patchObservableInstance(observable);
- return observable;
- };
- };
- var patchImmediate = function (asap$$1) {
- if (!asap$$1) {
- return;
- }
- var scheduleSymbol = symbol('scheduleSymbol');
- var zoneSymbol = symbol('zone');
- if (asap$$1[scheduleSymbol]) {
- return;
- }
- var schedule = asap$$1[scheduleSymbol] = asap$$1.schedule;
- asap$$1.schedule = function () {
- var args = Array.prototype.slice.call(arguments);
- var work = args.length > 0 ? args[0] : undefined;
- var delay = args.length > 1 ? args[1] : 0;
- var state = (args.length > 2 ? args[2] : undefined) || {};
- state[zoneSymbol] = Zone.current;
- var patchedWork = function () {
- var workArgs = Array.prototype.slice.call(arguments);
- var action = workArgs.length > 0 ? workArgs[0] : undefined;
- var scheduleZone = action && action[zoneSymbol];
- if (scheduleZone && scheduleZone !== Zone.current) {
- return scheduleZone.runGuarded(work, this, arguments);
- }
- else {
- return work.apply(this, arguments);
- }
- };
- return schedule.call(this, patchedWork, delay, state);
- };
- };
patchObservable();
patchSubscription();
patchSubscriber();
- patchObservableFactoryCreator(Observable.Observable, 'bindCallback');
- patchObservableFactoryCreator(Observable.Observable, 'bindNodeCallback');
- patchObservableFactory(Observable.Observable, 'defer');
- patchObservableFactory(Observable.Observable, 'forkJoin');
- patchObservableFactoryArgs(Observable.Observable, 'fromEventPattern');
- patchMulticast();
- patchImmediate(asap.asap);
});
})));
diff --git a/dist/zone-patch-rxjs.min.js b/dist/zone-patch-rxjs.min.js
index 8a509ada3..ead0815d5 100644
--- a/dist/zone-patch-rxjs.min.js
+++ b/dist/zone-patch-rxjs.min.js
@@ -1 +1 @@
-!function(r,e){"object"==typeof exports&&"undefined"!=typeof module?e(require("rxjs/add/observable/bindCallback"),require("rxjs/add/observable/bindNodeCallback"),require("rxjs/add/observable/defer"),require("rxjs/add/observable/forkJoin"),require("rxjs/add/observable/fromEventPattern"),require("rxjs/add/operator/multicast"),require("rxjs/Observable"),require("rxjs/scheduler/asap"),require("rxjs/Subscriber"),require("rxjs/Subscription"),require("rxjs/symbol/rxSubscriber")):"function"==typeof define&&define.amd?define(["rxjs/add/observable/bindCallback","rxjs/add/observable/bindNodeCallback","rxjs/add/observable/defer","rxjs/add/observable/forkJoin","rxjs/add/observable/fromEventPattern","rxjs/add/operator/multicast","rxjs/Observable","rxjs/scheduler/asap","rxjs/Subscriber","rxjs/Subscription","rxjs/symbol/rxSubscriber"],e):e(null,null,null,null,null,null,r.Rx,r.Rx.Scheduler,r.Rx,r.Rx,r.Rx.Symbol)}(this,function(r,e,t,n,i,u,o,s,b,c,a){"use strict";Zone.__load_patch("rxjs",function(r,e){function t(r,e,t){if(r){if(r instanceof b.Subscriber)return r;if(r[a.rxSubscriber])return r[a.rxSubscriber]()}return r||e||t?new b.Subscriber(r,e,t):new b.Subscriber(p)}var n=e.__symbol__,i="rxjs.Subscriber.next",u="rxjs.Subscriber.error",l="rxjs.Subscriber.complete",f=Object.defineProperties,p={closed:!0,next:function(r){},error:function(r){throw r},complete:function(){}},v=function(){var r=o.Observable.prototype,i=n("subscribe"),u=n("_subscribe"),s=r[u]=r._subscribe,b=r[i]=r.subscribe;f(o.Observable.prototype,{_zone:{value:null,writable:!0,configurable:!0},_zoneSource:{value:null,writable:!0,configurable:!0},_zoneSubscribe:{value:null,writable:!0,configurable:!0},source:{configurable:!0,get:function(){return this._zoneSource},set:function(r){this._zone=e.current,this._zoneSource=r}},_subscribe:{configurable:!0,get:function(){if(this._zoneSubscribe)return this._zoneSubscribe;if(this.constructor===o.Observable)return s;var r=Object.getPrototypeOf(this);return r&&r._subscribe},set:function(r){this._zone=e.current,this._zoneSubscribe=r}},subscribe:{writable:!0,configurable:!0,value:function(r,n,i){var u=this._zone;return u&&u!==e.current?u.run(b,this,[t(r,n,i)]):b.call(this,r,n,i)}}})},d=function(){var r=n("unsubscribe"),t=c.Subscription.prototype[r]=c.Subscription.prototype.unsubscribe;f(c.Subscription.prototype,{_zone:{value:null,writable:!0,configurable:!0},_zoneUnsubscribe:{value:null,writable:!0,configurable:!0},_unsubscribe:{get:function(){if(this._zoneUnsubscribe)return this._zoneUnsubscribe;var r=Object.getPrototypeOf(this);return r&&r._unsubscribe},set:function(r){this._zone=e.current,this._zoneUnsubscribe=r}},unsubscribe:{writable:!0,configurable:!0,value:function(){var r=this._zone;r&&r!==e.current?r.run(t,this):t.apply(this)}}})},h=function(){var r=b.Subscriber.prototype.next,t=b.Subscriber.prototype.error,n=b.Subscriber.prototype.complete;Object.defineProperty(b.Subscriber.prototype,"destination",{configurable:!0,get:function(){return this._zoneDestination},set:function(r){this._zone=e.current,this._zoneDestination=r}}),b.Subscriber.prototype.next=function(){var t=e.current,n=this._zone;return n&&n!==t?n.run(r,this,arguments,i):r.apply(this,arguments)},b.Subscriber.prototype.error=function(){var r=e.current,n=this._zone;return n&&n!==r?n.run(t,this,arguments,u):t.apply(this,arguments)},b.Subscriber.prototype.complete=function(){var r=e.current,t=this._zone;return t&&t!==r?t.run(n,this,arguments,l):n.apply(this,arguments)}},y=function(r){r._zone=e.current},x=function(r,e){var t=n(e);if(!r[t]){var i=r[t]=r[e];i&&(r[e]=function(){var r=i.apply(this,arguments);return function(){var e=r.apply(this,arguments);return y(e),e}})}},_=function(r,e){var t=n(e);if(!r[t]){var i=r[t]=r[e];i&&(r[e]=function(){var r=i.apply(this,arguments);return y(r),r})}},S=function(r,t){var i=n(t);if(!r[i]){var u=r[i]=r[t];u&&(r[t]=function(){for(var r=e.current,t=Array.prototype.slice.call(arguments),n=function(n){var i=t[n];"function"==typeof i&&(t[n]=function(){var t=Array.prototype.slice.call(arguments),n=e.current;return r&&n&&r!==n?r.run(i,this,t):i.apply(this,t)})},i=0;i0?t[0]:void 0;if("function"!=typeof n){var i=n;n=function(){return i}}t[0]=function(){var t;return t=r&&r!==e.current?r.run(n,this,arguments):n.apply(this,arguments),t&&r&&(t._zone=r),t};var o=u.apply(this,t);return y(o),o})}},z=function(r){if(r){var t=n("scheduleSymbol"),i=n("zone");if(!r[t]){var u=r[t]=r.schedule;r.schedule=function(){var r=Array.prototype.slice.call(arguments),t=r.length>0?r[0]:void 0,n=r.length>1?r[1]:0,o=(r.length>2?r[2]:void 0)||{};o[i]=e.current;var s=function(){var r=Array.prototype.slice.call(arguments),n=r.length>0?r[0]:void 0,u=n&&n[i];return u&&u!==e.current?u.runGuarded(t,this,arguments):t.apply(this,arguments)};return u.call(this,s,n,o)}}}};v(),d(),h(),x(o.Observable,"bindCallback"),x(o.Observable,"bindNodeCallback"),_(o.Observable,"defer"),_(o.Observable,"forkJoin"),S(o.Observable,"fromEventPattern"),j(),z(s.asap)})});
\ No newline at end of file
+!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(require("rxjs")):"function"==typeof define&&define.amd?define(["rxjs"],t):t(e.rxjs)}(this,function(e){"use strict";Zone.__load_patch("rxjs",function(t,r,n){var o=r.__symbol__,i="rxjs.Subscriber.next",u="rxjs.Subscriber.error",s="rxjs.Subscriber.complete",c=Object.defineProperties,b=function(){var t=e.Observable.prototype,n=o("_subscribe"),i=t[n]=t._subscribe;c(e.Observable.prototype,{_zone:{value:null,writable:!0,configurable:!0},_zoneSource:{value:null,writable:!0,configurable:!0},_zoneSubscribe:{value:null,writable:!0,configurable:!0},source:{configurable:!0,get:function(){return this._zoneSource},set:function(e){this._zone=r.current,this._zoneSource=e}},_subscribe:{configurable:!0,get:function(){if(this._zoneSubscribe)return this._zoneSubscribe;if(this.constructor===e.Observable)return i;var t=Object.getPrototypeOf(this);return t&&t._subscribe},set:function(e){this._zone=r.current,this._zoneSubscribe=function(){if(this._zone&&this._zone!==r.current){var t=this._zone.run(e,this,arguments);if(t&&"function"==typeof t){var n=this._zone;return function(){return n!==r.current?n.run(t,this,arguments):t.apply(this,arguments)}}return t}return e.apply(this,arguments)}}},subjectFactory:{get:function(){return this._zoneSubjectFactory},set:function(e){var t=this._zone;this._zoneSubjectFactory=function(){return t&&t!==r.current?t.run(e,this,arguments):e.apply(this,arguments)}}}})};n.patchMethod(e.Observable.prototype,"lift",function(e){return function(t,o){var i=e.apply(t,o);return i.operator&&(i.operator._zone=r.current,n.patchMethod(i.operator,"call",function(e){return function(t,n){return t._zone&&t._zone!==r.current?t._zone.run(e,t,n):e.apply(t,n)}})),i}});var a=function(){c(e.Subscription.prototype,{_zone:{value:null,writable:!0,configurable:!0},_zoneUnsubscribe:{value:null,writable:!0,configurable:!0},_unsubscribe:{get:function(){if(this._zoneUnsubscribe)return this._zoneUnsubscribe;var e=Object.getPrototypeOf(this);return e&&e._unsubscribe},set:function(e){this._zone=r.current,this._zoneUnsubscribe=function(){return this._zone&&this._zone!==r.current?this._zone.run(e,this,arguments):e.apply(this,arguments)}}}})},p=function(){var t=e.Subscriber.prototype.next,n=e.Subscriber.prototype.error,o=e.Subscriber.prototype.complete;Object.defineProperty(e.Subscriber.prototype,"destination",{configurable:!0,get:function(){return this._zoneDestination},set:function(e){this._zone=r.current,this._zoneDestination=e}}),e.Subscriber.prototype.next=function(){var e=r.current,n=this._zone;return n&&n!==e?n.run(t,this,arguments,i):t.apply(this,arguments)},e.Subscriber.prototype.error=function(){var e=r.current,t=this._zone;return t&&t!==e?t.run(n,this,arguments,u):n.apply(this,arguments)},e.Subscriber.prototype.complete=function(){var e=r.current,t=this._zone;return t&&t!==e?t.run(o,this,arguments,s):o.apply(this,arguments)}};b(),a(),p()})});
\ No newline at end of file
diff --git a/dist/zone-testing-bundle.js b/dist/zone-testing-bundle.js
index 7a8a81e5e..0f88dd882 100644
--- a/dist/zone-testing-bundle.js
+++ b/dist/zone-testing-bundle.js
@@ -19,7 +19,6 @@
* found in the LICENSE file at https://angular.io/license
*/
var Zone$1 = (function (global) {
- var FUNCTION = 'function';
var performance = global['performance'];
function mark(name) {
performance && performance['mark'] && performance['mark'](name);
@@ -28,12 +27,26 @@ var Zone$1 = (function (global) {
performance && performance['measure'] && performance['measure'](name, label);
}
mark('Zone');
+ var checkDuplicate = global[('__zone_symbol__forceDuplicateZoneCheck')] === true;
if (global['Zone']) {
- throw new Error('Zone already loaded.');
+ // if global['Zone'] already exists (maybe zone.js was already loaded or
+ // some other lib also registered a global object named Zone), we may need
+ // to throw an error, but sometimes user may not want this error.
+ // For example,
+ // we have two web pages, page1 includes zone.js, page2 doesn't.
+ // and the 1st time user load page1 and page2, everything work fine,
+ // but when user load page2 again, error occurs because global['Zone'] already exists.
+ // so we add a flag to let user choose whether to throw this error or not.
+ // By default, if existing Zone is from zone.js, we will not throw the error.
+ if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
+ throw new Error('Zone already loaded.');
+ }
+ else {
+ return global['Zone'];
+ }
}
var Zone = /** @class */ (function () {
function Zone(parent, zoneSpec) {
- this._properties = null;
this._parent = parent;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '';
this._properties = zoneSpec && zoneSpec.properties || {};
@@ -76,7 +89,9 @@ var Zone$1 = (function (global) {
});
Zone.__load_patch = function (name, fn) {
if (patches.hasOwnProperty(name)) {
- throw Error('Already loaded patch: ' + name);
+ if (checkDuplicate) {
+ throw Error('Already loaded patch: ' + name);
+ }
}
else if (!global['__Zone_disable_' + name]) {
var perfName = 'Zone:' + name;
@@ -120,7 +135,7 @@ var Zone$1 = (function (global) {
return this._zoneDelegate.fork(this, zoneSpec);
};
Zone.prototype.wrap = function (callback, source) {
- if (typeof callback !== FUNCTION) {
+ if (typeof callback !== 'function') {
throw new Error('Expecting function got: ' + callback);
}
var _callback = this._zoneDelegate.intercept(this, callback, source);
@@ -130,9 +145,6 @@ var Zone$1 = (function (global) {
};
};
Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
- if (applyThis === void 0) { applyThis = undefined; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
@@ -143,8 +155,6 @@ var Zone$1 = (function (global) {
};
Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
try {
@@ -168,10 +178,7 @@ var Zone$1 = (function (global) {
// https://github.com/angular/zone.js/issues/778, sometimes eventTask
// will run in notScheduled(canceled) state, we should not try to
// run such kind of task but just return
- // we have to define an variable here, if not
- // typescript compiler will complain below
- var isNotScheduled = task.state === notScheduled;
- if (isNotScheduled && task.type === eventTask) {
+ if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
return;
}
var reEntryGuard = task.state != running;
@@ -182,7 +189,7 @@ var Zone$1 = (function (global) {
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
if (task.type == macroTask && task.data && !task.data.isPeriodic) {
- task.cancelFn = null;
+ task.cancelFn = undefined;
}
try {
return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
@@ -218,8 +225,7 @@ var Zone$1 = (function (global) {
var newZone = this;
while (newZone) {
if (newZone === task.zone) {
- throw Error("can not reschedule task to " + this
- .name + " which is descendants of the original zone " + task.zone.name);
+ throw Error("can not reschedule task to " + this.name + " which is descendants of the original zone " + task.zone.name);
}
newZone = newZone.parent;
}
@@ -249,7 +255,7 @@ var Zone$1 = (function (global) {
return task;
};
Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
- return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, null));
+ return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
};
Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
@@ -290,16 +296,14 @@ var Zone$1 = (function (global) {
}());
var DELEGATE_ZS = {
name: '',
- onHasTask: function (delegate, _, target, hasTaskState) {
- return delegate.hasTask(target, hasTaskState);
- },
+ onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
onScheduleTask: function (delegate, _, target, task) {
return delegate.scheduleTask(target, task);
},
- onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); },
- onCancelTask: function (delegate, _, target, task) {
- return delegate.cancelTask(target, task);
- }
+ onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) {
+ return delegate.invokeTask(target, task, applyThis, applyArgs);
+ },
+ onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
};
var ZoneDelegate = /** @class */ (function () {
function ZoneDelegate(zone, parentDelegate, zoneSpec) {
@@ -327,8 +331,8 @@ var Zone$1 = (function (global) {
zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);
this._scheduleTaskZS =
zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
- this._scheduleTaskDlgt =
- zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
+ this._scheduleTaskDlgt = zoneSpec &&
+ (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
this._scheduleTaskCurrZone =
zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);
this._invokeTaskZS =
@@ -383,8 +387,7 @@ var Zone$1 = (function (global) {
callback;
};
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
- return this._invokeZS ?
- this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
+ return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.handleError = function (targetZone, error) {
@@ -416,8 +419,7 @@ var Zone$1 = (function (global) {
return returnTask;
};
ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
- return this._invokeTaskZS ?
- this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
+ return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
task.callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
@@ -437,7 +439,7 @@ var Zone$1 = (function (global) {
// hasTask should not throw error so other ZoneDelegate
// can still trigger hasTask callback
try {
- return this._hasTaskZS &&
+ this._hasTaskZS &&
this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
}
catch (err) {
@@ -527,14 +529,12 @@ var Zone$1 = (function (global) {
}
}
else {
- throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ?
- ' or \'' + fromState2 + '\'' :
- '') + ", was '" + this._state + "'.");
+ throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ? ' or \'' + fromState2 + '\'' : '') + ", was '" + this._state + "'.");
}
};
ZoneTask.prototype.toString = function () {
if (this.data && typeof this.data.handleId !== 'undefined') {
- return this.data.handleId;
+ return this.data.handleId.toString();
}
else {
return Object.prototype.toString.call(this);
@@ -575,7 +575,13 @@ var Zone$1 = (function (global) {
}
}
if (nativeMicroTaskQueuePromise) {
- nativeMicroTaskQueuePromise[symbolThen](drainMicroTaskQueue);
+ var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
+ if (!nativeThen) {
+ // native Promise is not patchable, we need to use `then` directly
+ // issue 1078
+ nativeThen = nativeMicroTaskQueuePromise['then'];
+ }
+ nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
}
else {
global[symbolSetTimeout](drainMicroTaskQueue, 0);
@@ -622,12 +628,13 @@ var Zone$1 = (function (global) {
patchEventTarget: function () { return []; },
patchOnProperties: noop,
patchMethod: function () { return noop; },
- bindArguments: function () { return null; },
+ bindArguments: function () { return []; },
+ patchThen: function () { return noop; },
setNativePromise: function (NativePromise) {
// sometimes NativePromise.resolve static function
// is not ready yet, (such as core-js/es6.promise)
// so we need to check here.
- if (NativePromise && typeof NativePromise.resolve === FUNCTION) {
+ if (NativePromise && typeof NativePromise.resolve === 'function') {
nativeMicroTaskQueuePromise = NativePromise.resolve(0);
}
},
@@ -643,6 +650,16 @@ var Zone$1 = (function (global) {
return global['Zone'] = Zone;
})(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
+var __values = (undefined && undefined.__values) || function (o) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
+ if (m) return m.call(o);
+ return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+};
Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var ObjectDefineProperty = Object.defineProperty;
@@ -785,7 +802,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var queue = promise[symbolValue];
promise[symbolValue] = value;
if (promise[symbolFinally] === symbolFinally) {
- // the promise is generated by Promise.prototype.finally
+ // the promise is generated by Promise.prototype.finally
if (state === RESOLVED) {
// the state is resolved, should ignore the value
// and use parent promise value
@@ -869,7 +886,9 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
chainPromise[symbolParentPromiseState] = promiseState;
}
// should not pass value to finally callback
- var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ? [] : [parentPromiseValue]);
+ var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
+ [] :
+ [parentPromiseValue]);
resolvePromise(chainPromise, true, value);
}
catch (error) {
@@ -904,6 +923,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
return resolvePromise(new this(null), REJECTED, error);
};
ZoneAwarePromise.race = function (values) {
+ var e_1, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
@@ -916,40 +936,70 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
function onReject(error) {
promise && (promise = null || reject(error));
}
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- if (!isThenable(value)) {
- value = this.resolve(value);
+ try {
+ for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
+ var value = values_1_1.value;
+ if (!isThenable(value)) {
+ value = this.resolve(value);
+ }
+ value.then(onResolve, onReject);
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
}
- value.then(onResolve, onReject);
+ finally { if (e_1) throw e_1.error; }
}
return promise;
};
ZoneAwarePromise.all = function (values) {
+ var e_2, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
resolve = res;
reject = rej;
});
- var count = 0;
+ // Start at 2 to prevent prematurely resolving if .then is called immediately.
+ var unresolvedCount = 2;
+ var valueIndex = 0;
var resolvedValues = [];
- for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
- var value = values_2[_i];
+ var _loop_2 = function (value) {
if (!isThenable(value)) {
- value = this.resolve(value);
+ value = this_1.resolve(value);
}
- value.then((function (index) { return function (value) {
- resolvedValues[index] = value;
- count--;
- if (!count) {
+ var curValueIndex = valueIndex;
+ value.then(function (value) {
+ resolvedValues[curValueIndex] = value;
+ unresolvedCount--;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
}
- }; })(count), reject);
- count++;
+ }, reject);
+ unresolvedCount++;
+ valueIndex++;
+ };
+ var this_1 = this;
+ try {
+ for (var values_2 = __values(values), values_2_1 = values_2.next(); !values_2_1.done; values_2_1 = values_2.next()) {
+ var value = values_2_1.value;
+ _loop_2(value);
+ }
+ }
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
+ finally {
+ try {
+ if (values_2_1 && !values_2_1.done && (_a = values_2.return)) _a.call(values_2);
+ }
+ finally { if (e_2) throw e_2.error; }
}
- if (!count)
+ // Make the unresolvedCount zero-based again.
+ unresolvedCount -= 2;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
+ }
return promise;
};
ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
@@ -1045,31 +1095,112 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
};
Ctor[symbolThenPatched] = true;
}
- function zoneify(fn) {
- return function () {
- var resultPromise = fn.apply(this, arguments);
- if (resultPromise instanceof ZoneAwarePromise) {
- return resultPromise;
- }
- var ctor = resultPromise.constructor;
- if (!ctor[symbolThenPatched]) {
- patchThen(ctor);
- }
- return resultPromise;
- };
- }
+ api.patchThen = patchThen;
if (NativePromise) {
patchThen(NativePromise);
- var fetch_1 = global['fetch'];
- if (typeof fetch_1 == 'function') {
- global['fetch'] = zoneify(fetch_1);
- }
}
// This is not part of public API, but it is useful for tests, so we expose it.
Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
return ZoneAwarePromise;
});
+/**
+ * @license
+ * Copyright Google Inc. 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.io/license
+ */
+Zone.__load_patch('fetch', function (global, Zone, api) {
+ var fetch = global['fetch'];
+ var ZoneAwarePromise = global.Promise;
+ var symbolThenPatched = api.symbol('thenPatched');
+ var fetchTaskScheduling = api.symbol('fetchTaskScheduling');
+ var fetchTaskAborting = api.symbol('fetchTaskAborting');
+ if (typeof fetch !== 'function') {
+ return;
+ }
+ var OriginalAbortController = global['AbortController'];
+ var supportAbort = typeof OriginalAbortController === 'function';
+ var abortNative = null;
+ if (supportAbort) {
+ global['AbortController'] = function () {
+ var abortController = new OriginalAbortController();
+ var signal = abortController.signal;
+ signal.abortController = abortController;
+ return abortController;
+ };
+ abortNative = api.patchMethod(OriginalAbortController.prototype, 'abort', function (delegate) { return function (self, args) {
+ if (self.task) {
+ return self.task.zone.cancelTask(self.task);
+ }
+ return delegate.apply(self, args);
+ }; });
+ }
+ var placeholder = function () { };
+ global['fetch'] = function () {
+ var _this = this;
+ var args = Array.prototype.slice.call(arguments);
+ var options = args.length > 1 ? args[1] : null;
+ var signal = options && options.signal;
+ return new Promise(function (res, rej) {
+ var task = Zone.current.scheduleMacroTask('fetch', placeholder, args, function () {
+ var fetchPromise;
+ var zone = Zone.current;
+ try {
+ zone[fetchTaskScheduling] = true;
+ fetchPromise = fetch.apply(_this, args);
+ }
+ catch (error) {
+ rej(error);
+ return;
+ }
+ finally {
+ zone[fetchTaskScheduling] = false;
+ }
+ if (!(fetchPromise instanceof ZoneAwarePromise)) {
+ var ctor = fetchPromise.constructor;
+ if (!ctor[symbolThenPatched]) {
+ api.patchThen(ctor);
+ }
+ }
+ fetchPromise.then(function (resource) {
+ if (task.state !== 'notScheduled') {
+ task.invoke();
+ }
+ res(resource);
+ }, function (error) {
+ if (task.state !== 'notScheduled') {
+ task.invoke();
+ }
+ rej(error);
+ });
+ }, function () {
+ if (!supportAbort) {
+ rej('No AbortController supported, can not cancel fetch');
+ return;
+ }
+ if (signal && signal.abortController && !signal.aborted &&
+ typeof signal.abortController.abort === 'function' && abortNative) {
+ try {
+ Zone.current[fetchTaskAborting] = true;
+ abortNative.call(signal.abortController);
+ }
+ finally {
+ Zone.current[fetchTaskAborting] = false;
+ }
+ }
+ else {
+ rej('cancel fetch need a AbortController.signal');
+ }
+ });
+ if (signal && signal.abortController) {
+ signal.abortController.task = task;
+ }
+ });
+ };
+});
+
/**
* @license
* Copyright Google Inc. All Rights Reserved.
@@ -1185,9 +1316,23 @@ var wrapFn = function (event) {
}
var target = this || event.target || _global;
var listener = target[eventNameSymbol];
- var result = listener && listener.apply(this, arguments);
- if (result != undefined && !result) {
- event.preventDefault();
+ var result;
+ if (isBrowser && target === internalWindow && event.type === 'error') {
+ // window.onerror have different signiture
+ // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
+ // and onerror callback will prevent default when callback return true
+ var errorEvent = event;
+ result = listener &&
+ listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
+ if (result === true) {
+ event.preventDefault();
+ }
+ }
+ else {
+ result = listener && listener.apply(this, arguments);
+ if (result != undefined && !result) {
+ event.preventDefault();
+ }
}
return result;
};
@@ -1205,6 +1350,10 @@ function patchProperty(obj, prop, prototype) {
if (!desc || !desc.configurable) {
return;
}
+ var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
+ if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
+ return;
+ }
// A property descriptor cannot have getter/setter and be writable
// deleting the writable and value properties avoids this error:
//
@@ -1282,6 +1431,7 @@ function patchProperty(obj, prop, prototype) {
return null;
};
ObjectDefineProperty(obj, prop, desc);
+ obj[onPropPatchedSymbol] = true;
}
function patchOnProperties(obj, properties, prototype) {
if (properties) {
@@ -1372,6 +1522,31 @@ function patchClass(className) {
}
}
}
+function copySymbolProperties(src, dest) {
+ if (typeof Object.getOwnPropertySymbols !== 'function') {
+ return;
+ }
+ var symbols = Object.getOwnPropertySymbols(src);
+ symbols.forEach(function (symbol) {
+ var desc = Object.getOwnPropertyDescriptor(src, symbol);
+ Object.defineProperty(dest, symbol, {
+ get: function () {
+ return src[symbol];
+ },
+ set: function (value) {
+ if (desc && (!desc.writable || typeof desc.set !== 'function')) {
+ // if src[symbol] is not writable or not have a setter, just return
+ return;
+ }
+ src[symbol] = value;
+ },
+ enumerable: desc ? desc.enumerable : true,
+ configurable: desc ? desc.configurable : true
+ });
+ });
+}
+var shouldCopySymbolProperties = false;
+
function patchMethod(target, name, patchFn) {
var proto = target;
while (proto && !proto.hasOwnProperty(name)) {
@@ -1382,7 +1557,7 @@ function patchMethod(target, name, patchFn) {
proto = target;
}
var delegateName = zoneSymbol(name);
- var delegate;
+ var delegate = null;
if (proto && !(delegate = proto[delegateName])) {
delegate = proto[delegateName] = proto[name];
// check whether proto[name] is writable
@@ -1394,6 +1569,9 @@ function patchMethod(target, name, patchFn) {
return patchDelegate_1(this, arguments);
};
attachOriginToPatched(proto[name], delegate);
+ if (shouldCopySymbolProperties) {
+ copySymbolProperties(delegate, proto[name]);
+ }
}
}
return delegate;
@@ -1412,7 +1590,7 @@ function patchMacroTask(obj, funcName, metaCreator) {
setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
var meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
- return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask, null);
+ return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
}
else {
// cause an error by calling it directly.
@@ -1426,6 +1604,17 @@ function attachOriginToPatched(patched, original) {
}
var isDetectedIEOrEdge = false;
var ieOrEdge = false;
+function isIE() {
+ try {
+ var ua = internalWindow.navigator.userAgent;
+ if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
+ return true;
+ }
+ }
+ catch (error) {
+ }
+ return false;
+}
function isIEOrEdge() {
if (isDetectedIEOrEdge) {
return ieOrEdge;
@@ -1507,6 +1696,21 @@ Zone.__load_patch('toString', function (global) {
* @fileoverview
* @suppress {missingRequire}
*/
+var passiveSupported = false;
+if (typeof window !== 'undefined') {
+ try {
+ var options = Object.defineProperty({}, 'passive', {
+ get: function () {
+ passiveSupported = true;
+ }
+ });
+ window.addEventListener('test', options, options);
+ window.removeEventListener('test', options, options);
+ }
+ catch (err) {
+ passiveSupported = false;
+ }
+}
// an identifier to tell ZoneTask do not create a new invoke closure
var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
useG: true
@@ -1642,6 +1846,7 @@ function patchEventTarget(_global, apis, patchOptions) {
if (proto[zoneSymbolAddEventListener]) {
return false;
}
+ var eventNameToString = patchOptions && patchOptions.eventNameToString;
// a shared global taskData to pass data for scheduleEventTask
// so we do not need to create a new object just for pass some data
var taskData = {};
@@ -1657,12 +1862,24 @@ function patchEventTarget(_global, apis, patchOptions) {
nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
proto[patchOptions.prepend];
}
- var customScheduleGlobal = function () {
+ function checkIsPassive(task) {
+ if (!passiveSupported && typeof taskData.options !== 'boolean' &&
+ typeof taskData.options !== 'undefined' && taskData.options !== null) {
+ // options is a non-null non-undefined object
+ // passive is not supported
+ // don't pass options as object
+ // just pass capture as a boolean
+ task.options = !!taskData.options.capture;
+ taskData.options = task.options;
+ }
+ }
+ var customScheduleGlobal = function (task) {
// if there is already a task for the eventName + capture,
// just return, because we use the shared globalZoneAwareCallback here.
if (taskData.isExisting) {
return;
}
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
};
var customCancelGlobal = function (task) {
@@ -1703,6 +1920,7 @@ function patchEventTarget(_global, apis, patchOptions) {
return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
};
var customScheduleNonGlobal = function (task) {
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
};
var customSchedulePrepend = function (task) {
@@ -1725,10 +1943,15 @@ function patchEventTarget(_global, apis, patchOptions) {
if (prepend === void 0) { prepend = false; }
return function () {
var target = this || _global;
+ var eventName = arguments[0];
var delegate = arguments[1];
if (!delegate) {
return nativeListener.apply(this, arguments);
}
+ if (isNode && eventName === 'uncaughtException') {
+ // don't patch uncaughtException of nodejs to prevent endless loop
+ return nativeListener.apply(this, arguments);
+ }
// don't create the bind delegate function for handleEvent
// case here to improve addEventListener performance
// we will create the bind delegate when invoke
@@ -1742,7 +1965,6 @@ function patchEventTarget(_global, apis, patchOptions) {
if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
return;
}
- var eventName = arguments[0];
var options = arguments[2];
if (blackListedEvents) {
// check black list
@@ -1772,8 +1994,8 @@ function patchEventTarget(_global, apis, patchOptions) {
var symbolEventName;
if (!symbolEventNames) {
// the code is duplicate, but I just want to get some better performance
- var falseEventName = eventName + FALSE_STR;
- var trueEventName = eventName + TRUE_STR;
+ var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
+ var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames$1[eventName] = {};
@@ -1808,7 +2030,8 @@ function patchEventTarget(_global, apis, patchOptions) {
source = targetSource[eventName];
}
if (!source) {
- source = constructorName + addSource + eventName;
+ source = constructorName + addSource +
+ (eventNameToString ? eventNameToString(eventName) : eventName);
}
// do not create a new object as task.data to pass those things
// just use the global shared one
@@ -1823,7 +2046,7 @@ function patchEventTarget(_global, apis, patchOptions) {
taskData.capture = capture;
taskData.eventName = eventName;
taskData.isExisting = isExisting;
- var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : null;
+ var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
// keep taskData into data to allow onScheduleEventTask to access the task information
if (data) {
data.taskData = taskData;
@@ -1841,7 +2064,11 @@ function patchEventTarget(_global, apis, patchOptions) {
if (once) {
options.once = true;
}
- task.options = options;
+ if (!(!passiveSupported && typeof task.options === 'boolean')) {
+ // if not support passive, and we pass an option object
+ // to addEventListener, we should save the options to task
+ task.options = options;
+ }
task.target = target;
task.capture = capture;
task.eventName = eventName;
@@ -1926,7 +2153,7 @@ function patchEventTarget(_global, apis, patchOptions) {
var target = this || _global;
var eventName = arguments[0];
var listeners = [];
- var tasks = findEventTasks(target, eventName);
+ var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
@@ -2082,9 +2309,9 @@ function patchTimer(window, setName, cancelName, nameSuffix) {
patchMethod(window, setName, function (delegate) { return function (self, args) {
if (typeof args[0] === 'function') {
var options = {
- handleId: null,
isPeriodic: nameSuffix === 'Interval',
- delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,
+ delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
+ undefined,
args: args
};
var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
@@ -2199,7 +2426,7 @@ function propertyPatch() {
};
Object.getOwnPropertyDescriptor = function (obj, prop) {
var desc = _getOwnPropertyDescriptor(obj, prop);
- if (isUnconfigurable(obj, prop)) {
+ if (desc && isUnconfigurable(obj, prop)) {
desc.configurable = false;
}
return desc;
@@ -2427,10 +2654,10 @@ var globalEventHandlersEventNames = [
'wheel'
];
var documentEventNames = [
- 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'fullscreenchange',
+ 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'freeze', 'fullscreenchange',
'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror',
'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange',
- 'visibilitychange'
+ 'visibilitychange', 'resume'
];
var windowEventNames = [
'absolutedeviceorientation',
@@ -2542,7 +2769,7 @@ var websocketEventNames = ['close', 'error', 'open', 'message'];
var workerEventNames = ['error', 'message'];
var eventNames = globalEventHandlersEventNames.concat(webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames, htmlElementEventNames, ieElementEventNames);
function filterProperties(target, onProperties, ignoreProperties) {
- if (!ignoreProperties) {
+ if (!ignoreProperties || ignoreProperties.length === 0) {
return onProperties;
}
var tip = ignoreProperties.filter(function (ip) { return ip.target === target; });
@@ -2567,13 +2794,14 @@ function propertyDescriptorPatch(api, _global) {
}
var supportsWebSocket = typeof WebSocket !== 'undefined';
if (canPatchViaPropertyDescriptor()) {
- var ignoreProperties = _global.__Zone_ignore_on_properties;
+ var ignoreProperties = _global['__Zone_ignore_on_properties'];
// for browsers that we can patch the descriptor: Chrome & Firefox
if (isBrowser) {
var internalWindow = window;
+ var ignoreErrorProperties = isIE ? [{ target: internalWindow, ignoreProperties: ['error'] }] : [];
// in IE/Edge, onProp not exist in window object, but in WindowPrototype
// so we need to pass WindowPrototype to check onProp exist or not
- patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties, ObjectGetPrototypeOf(internalWindow));
+ patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
patchFilteredProperties(Document.prototype, eventNames, ignoreProperties);
if (typeof internalWindow['SVGElement'] !== 'undefined') {
patchFilteredProperties(internalWindow['SVGElement'].prototype, eventNames, ignoreProperties);
@@ -2595,9 +2823,9 @@ function propertyDescriptorPatch(api, _global) {
}
}
patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties);
- var XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget'];
- if (XMLHttpRequestEventTarget) {
- patchFilteredProperties(XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames, ignoreProperties);
+ var XMLHttpRequestEventTarget_1 = _global['XMLHttpRequestEventTarget'];
+ if (XMLHttpRequestEventTarget_1) {
+ patchFilteredProperties(XMLHttpRequestEventTarget_1 && XMLHttpRequestEventTarget_1.prototype, XMLHttpRequestEventNames, ignoreProperties);
}
if (typeof IDBIndex !== 'undefined') {
patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties);
@@ -2812,16 +3040,16 @@ function patchEvent(global, api) {
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
-function registerElementPatch(_global) {
- if ((!isBrowser && !isMix) || !('registerElement' in _global.document)) {
+function patchCallbacks(target, targetName, method, callbacks) {
+ var symbol = Zone.__symbol__(method);
+ if (target[symbol]) {
return;
}
- var _registerElement = document.registerElement;
- var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
- document.registerElement = function (name, opts) {
+ var nativeDelegate = target[symbol] = target[method];
+ target[method] = function (name, opts, options) {
if (opts && opts.prototype) {
callbacks.forEach(function (callback) {
- var source = 'Document.registerElement::' + callback;
+ var source = targetName + "." + method + "::" + callback;
var prototype = opts.prototype;
if (prototype.hasOwnProperty(callback)) {
var descriptor = ObjectGetOwnPropertyDescriptor(prototype, callback);
@@ -2838,9 +3066,23 @@ function registerElementPatch(_global) {
}
});
}
- return _registerElement.call(document, name, opts);
+ return nativeDelegate.call(target, name, opts, options);
};
- attachOriginToPatched(document.registerElement, _registerElement);
+ attachOriginToPatched(target[method], nativeDelegate);
+}
+function registerElementPatch(_global) {
+ if ((!isBrowser && !isMix) || !('registerElement' in _global.document)) {
+ return;
+ }
+ var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
+ patchCallbacks(document, 'Document', 'registerElement', callbacks);
+}
+function patchCustomElements(_global) {
+ if ((!isBrowser && !isMix) || !('customElements' in _global)) {
+ return;
+ }
+ var callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
+ patchCallbacks(_global.customElements, 'customElements', 'define', callbacks);
}
/**
@@ -2903,7 +3145,10 @@ Zone.__load_patch('EventTarget', function (global, Zone, api) {
Zone.__load_patch('on_property', function (global, Zone, api) {
propertyDescriptorPatch(api, global);
propertyPatch();
+});
+Zone.__load_patch('customElements', function (global, Zone, api) {
registerElementPatch(global);
+ patchCustomElements(global);
});
Zone.__load_patch('canvas', function (global) {
var HTMLCanvasElement = global['HTMLCanvasElement'];
@@ -2922,6 +3167,7 @@ Zone.__load_patch('XHR', function (global, Zone) {
var XHR_LISTENER = zoneSymbol('xhrListener');
var XHR_SCHEDULED = zoneSymbol('xhrScheduled');
var XHR_URL = zoneSymbol('xhrURL');
+ var XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
function patchXHR(window) {
var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
function findPendingTask(target) {
@@ -2930,9 +3176,9 @@ Zone.__load_patch('XHR', function (global, Zone) {
var oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
var oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
if (!oriAddListener) {
- var XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
- if (XMLHttpRequestEventTarget) {
- var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
+ var XMLHttpRequestEventTarget_1 = window['XMLHttpRequestEventTarget'];
+ if (XMLHttpRequestEventTarget_1) {
+ var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget_1.prototype;
oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
}
@@ -2940,9 +3186,10 @@ Zone.__load_patch('XHR', function (global, Zone) {
var READY_STATE_CHANGE = 'readystatechange';
var SCHEDULED = 'scheduled';
function scheduleTask(task) {
- XMLHttpRequest[XHR_SCHEDULED] = false;
var data = task.data;
var target = data.target;
+ target[XHR_SCHEDULED] = false;
+ target[XHR_ERROR_BEFORE_SCHEDULED] = false;
// remove existing event listener
var listener = target[XHR_LISTENER];
if (!oriAddListener) {
@@ -2956,8 +3203,35 @@ Zone.__load_patch('XHR', function (global, Zone) {
if (target.readyState === target.DONE) {
// sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
// readyState=4 multiple times, so we need to check task state here
- if (!data.aborted && XMLHttpRequest[XHR_SCHEDULED] && task.state === SCHEDULED) {
- task.invoke();
+ if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
+ // check whether the xhr has registered onload listener
+ // if that is the case, the task should invoke after all
+ // onload listeners finish.
+ var loadTasks = target['__zone_symbol__loadfalse'];
+ if (loadTasks && loadTasks.length > 0) {
+ var oriInvoke_1 = task.invoke;
+ task.invoke = function () {
+ // need to load the tasks again, because in other
+ // load listener, they may remove themselves
+ var loadTasks = target['__zone_symbol__loadfalse'];
+ for (var i = 0; i < loadTasks.length; i++) {
+ if (loadTasks[i] === task) {
+ loadTasks.splice(i, 1);
+ }
+ }
+ if (!data.aborted && task.state === SCHEDULED) {
+ oriInvoke_1.call(task);
+ }
+ };
+ loadTasks.push(task);
+ }
+ else {
+ task.invoke();
+ }
+ }
+ else if (!data.aborted && target[XHR_SCHEDULED] === false) {
+ // error occurs when xhr.send()
+ target[XHR_ERROR_BEFORE_SCHEDULED] = true;
}
}
};
@@ -2967,7 +3241,7 @@ Zone.__load_patch('XHR', function (global, Zone) {
target[XHR_TASK] = task;
}
sendNative.apply(target, data.args);
- XMLHttpRequest[XHR_SCHEDULED] = true;
+ target[XHR_SCHEDULED] = true;
return task;
}
function placeholderCallback() { }
@@ -2984,24 +3258,32 @@ Zone.__load_patch('XHR', function (global, Zone) {
return openNative.apply(self, args);
}; });
var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
+ var fetchTaskAborting = zoneSymbol('fetchTaskAborting');
+ var fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
var sendNative = patchMethod(XMLHttpRequestPrototype, 'send', function () { return function (self, args) {
+ if (Zone.current[fetchTaskScheduling] === true) {
+ // a fetch is scheduling, so we are using xhr to polyfill fetch
+ // and because we already schedule macroTask for fetch, we should
+ // not schedule a macroTask for xhr again
+ return sendNative.apply(self, args);
+ }
if (self[XHR_SYNC]) {
// if the XHR is sync there is no task to schedule, just execute the code.
return sendNative.apply(self, args);
}
else {
- var options = {
- target: self,
- url: self[XHR_URL],
- isPeriodic: false,
- delay: null,
- args: args,
- aborted: false
- };
- return scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
+ var options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
+ var task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
+ if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
+ task.state === SCHEDULED) {
+ // xhr request throw error when send
+ // we should invoke task instead of leaving a scheduled
+ // pending macroTask
+ task.invoke();
+ }
}
}; });
- var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self) {
+ var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self, args) {
var task = findPendingTask(self);
if (task && typeof task.type == 'string') {
// If the XHR has already completed, do nothing.
@@ -3013,6 +3295,10 @@ Zone.__load_patch('XHR', function (global, Zone) {
}
task.zone.cancelTask(task);
}
+ else if (Zone.current[fetchTaskAborting] === true) {
+ // the abort is called from fetch polyfill, we need to call native abort of XHR.
+ return abortNative.apply(self, args);
+ }
// Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
// task
// to cancel. Do nothing.
@@ -3229,6 +3515,7 @@ var ProxyZoneSpec = /** @class */ (function () {
if (defaultSpecDelegate === void 0) { defaultSpecDelegate = null; }
this.defaultSpecDelegate = defaultSpecDelegate;
this.name = 'ProxyZone';
+ this._delegateSpec = null;
this.properties = { 'ProxyZoneSpec': this };
this.propertyKeys = null;
this.lastTaskState = null;
@@ -4031,7 +4318,11 @@ var __spread = (undefined && undefined.__spread) || function () {
}
}
}
+ lastCurrentTime = this._currentTime;
this._currentTime = finalTime;
+ if (doTick) {
+ doTick(this._currentTime - lastCurrentTime);
+ }
};
Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
if (limit === void 0) { limit = 20; }
@@ -4120,14 +4411,14 @@ var __spread = (undefined && undefined.__spread) || function () {
args[_i] = arguments[_i];
}
fn.apply(global, args);
- if (_this._lastError === null) {
+ if (_this._lastError === null) { // Success
if (completers.onSuccess != null) {
completers.onSuccess.apply(global);
}
// Flush microtasks only on success.
_this.flushMicrotasks();
}
- else {
+ else { // Failure
if (completers.onError != null) {
completers.onError.apply(global);
}
@@ -4426,23 +4717,23 @@ Zone.__load_patch('fakeasync', function (global, Zone, api) {
ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
}
/**
- * Wraps a function to be executed in the fakeAsync zone:
- * - microtasks are manually executed by calling `flushMicrotasks()`,
- * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
- *
- * If there are any pending timers at the end of the function, an exception will be thrown.
- *
- * Can be used to wrap inject() calls.
- *
- * ## Example
- *
- * {@example core/testing/ts/fake_async.ts region='basic'}
- *
- * @param fn
- * @returns The function wrapped to be executed in the fakeAsync zone
- *
- * @experimental
- */
+ * Wraps a function to be executed in the fakeAsync zone:
+ * - microtasks are manually executed by calling `flushMicrotasks()`,
+ * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
+ *
+ * If there are any pending timers at the end of the function, an exception will be thrown.
+ *
+ * Can be used to wrap inject() calls.
+ *
+ * ## Example
+ *
+ * {@example core/testing/ts/fake_async.ts region='basic'}
+ *
+ * @param fn
+ * @returns The function wrapped to be executed in the fakeAsync zone
+ *
+ * @experimental
+ */
function fakeAsync(fn) {
// Not using an arrow function to preserve context passed from call site
return function () {
diff --git a/dist/zone-testing-node-bundle.js b/dist/zone-testing-node-bundle.js
index a95fbf996..5347637e2 100644
--- a/dist/zone-testing-node-bundle.js
+++ b/dist/zone-testing-node-bundle.js
@@ -19,7 +19,6 @@
* found in the LICENSE file at https://angular.io/license
*/
var Zone$1 = (function (global) {
- var FUNCTION = 'function';
var performance = global['performance'];
function mark(name) {
performance && performance['mark'] && performance['mark'](name);
@@ -28,12 +27,26 @@ var Zone$1 = (function (global) {
performance && performance['measure'] && performance['measure'](name, label);
}
mark('Zone');
+ var checkDuplicate = global[('__zone_symbol__forceDuplicateZoneCheck')] === true;
if (global['Zone']) {
- throw new Error('Zone already loaded.');
+ // if global['Zone'] already exists (maybe zone.js was already loaded or
+ // some other lib also registered a global object named Zone), we may need
+ // to throw an error, but sometimes user may not want this error.
+ // For example,
+ // we have two web pages, page1 includes zone.js, page2 doesn't.
+ // and the 1st time user load page1 and page2, everything work fine,
+ // but when user load page2 again, error occurs because global['Zone'] already exists.
+ // so we add a flag to let user choose whether to throw this error or not.
+ // By default, if existing Zone is from zone.js, we will not throw the error.
+ if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
+ throw new Error('Zone already loaded.');
+ }
+ else {
+ return global['Zone'];
+ }
}
var Zone = /** @class */ (function () {
function Zone(parent, zoneSpec) {
- this._properties = null;
this._parent = parent;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '';
this._properties = zoneSpec && zoneSpec.properties || {};
@@ -76,7 +89,9 @@ var Zone$1 = (function (global) {
});
Zone.__load_patch = function (name, fn) {
if (patches.hasOwnProperty(name)) {
- throw Error('Already loaded patch: ' + name);
+ if (checkDuplicate) {
+ throw Error('Already loaded patch: ' + name);
+ }
}
else if (!global['__Zone_disable_' + name]) {
var perfName = 'Zone:' + name;
@@ -120,7 +135,7 @@ var Zone$1 = (function (global) {
return this._zoneDelegate.fork(this, zoneSpec);
};
Zone.prototype.wrap = function (callback, source) {
- if (typeof callback !== FUNCTION) {
+ if (typeof callback !== 'function') {
throw new Error('Expecting function got: ' + callback);
}
var _callback = this._zoneDelegate.intercept(this, callback, source);
@@ -130,9 +145,6 @@ var Zone$1 = (function (global) {
};
};
Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
- if (applyThis === void 0) { applyThis = undefined; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
@@ -143,8 +155,6 @@ var Zone$1 = (function (global) {
};
Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
try {
@@ -168,10 +178,7 @@ var Zone$1 = (function (global) {
// https://github.com/angular/zone.js/issues/778, sometimes eventTask
// will run in notScheduled(canceled) state, we should not try to
// run such kind of task but just return
- // we have to define an variable here, if not
- // typescript compiler will complain below
- var isNotScheduled = task.state === notScheduled;
- if (isNotScheduled && task.type === eventTask) {
+ if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
return;
}
var reEntryGuard = task.state != running;
@@ -182,7 +189,7 @@ var Zone$1 = (function (global) {
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
if (task.type == macroTask && task.data && !task.data.isPeriodic) {
- task.cancelFn = null;
+ task.cancelFn = undefined;
}
try {
return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
@@ -218,8 +225,7 @@ var Zone$1 = (function (global) {
var newZone = this;
while (newZone) {
if (newZone === task.zone) {
- throw Error("can not reschedule task to " + this
- .name + " which is descendants of the original zone " + task.zone.name);
+ throw Error("can not reschedule task to " + this.name + " which is descendants of the original zone " + task.zone.name);
}
newZone = newZone.parent;
}
@@ -249,7 +255,7 @@ var Zone$1 = (function (global) {
return task;
};
Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
- return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, null));
+ return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
};
Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
@@ -290,16 +296,14 @@ var Zone$1 = (function (global) {
}());
var DELEGATE_ZS = {
name: '',
- onHasTask: function (delegate, _, target, hasTaskState) {
- return delegate.hasTask(target, hasTaskState);
- },
+ onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
onScheduleTask: function (delegate, _, target, task) {
return delegate.scheduleTask(target, task);
},
- onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); },
- onCancelTask: function (delegate, _, target, task) {
- return delegate.cancelTask(target, task);
- }
+ onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) {
+ return delegate.invokeTask(target, task, applyThis, applyArgs);
+ },
+ onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
};
var ZoneDelegate = /** @class */ (function () {
function ZoneDelegate(zone, parentDelegate, zoneSpec) {
@@ -327,8 +331,8 @@ var Zone$1 = (function (global) {
zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);
this._scheduleTaskZS =
zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
- this._scheduleTaskDlgt =
- zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
+ this._scheduleTaskDlgt = zoneSpec &&
+ (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
this._scheduleTaskCurrZone =
zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);
this._invokeTaskZS =
@@ -383,8 +387,7 @@ var Zone$1 = (function (global) {
callback;
};
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
- return this._invokeZS ?
- this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
+ return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.handleError = function (targetZone, error) {
@@ -416,8 +419,7 @@ var Zone$1 = (function (global) {
return returnTask;
};
ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
- return this._invokeTaskZS ?
- this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
+ return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
task.callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
@@ -437,7 +439,7 @@ var Zone$1 = (function (global) {
// hasTask should not throw error so other ZoneDelegate
// can still trigger hasTask callback
try {
- return this._hasTaskZS &&
+ this._hasTaskZS &&
this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
}
catch (err) {
@@ -527,14 +529,12 @@ var Zone$1 = (function (global) {
}
}
else {
- throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ?
- ' or \'' + fromState2 + '\'' :
- '') + ", was '" + this._state + "'.");
+ throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ? ' or \'' + fromState2 + '\'' : '') + ", was '" + this._state + "'.");
}
};
ZoneTask.prototype.toString = function () {
if (this.data && typeof this.data.handleId !== 'undefined') {
- return this.data.handleId;
+ return this.data.handleId.toString();
}
else {
return Object.prototype.toString.call(this);
@@ -575,7 +575,13 @@ var Zone$1 = (function (global) {
}
}
if (nativeMicroTaskQueuePromise) {
- nativeMicroTaskQueuePromise[symbolThen](drainMicroTaskQueue);
+ var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
+ if (!nativeThen) {
+ // native Promise is not patchable, we need to use `then` directly
+ // issue 1078
+ nativeThen = nativeMicroTaskQueuePromise['then'];
+ }
+ nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
}
else {
global[symbolSetTimeout](drainMicroTaskQueue, 0);
@@ -622,12 +628,13 @@ var Zone$1 = (function (global) {
patchEventTarget: function () { return []; },
patchOnProperties: noop,
patchMethod: function () { return noop; },
- bindArguments: function () { return null; },
+ bindArguments: function () { return []; },
+ patchThen: function () { return noop; },
setNativePromise: function (NativePromise) {
// sometimes NativePromise.resolve static function
// is not ready yet, (such as core-js/es6.promise)
// so we need to check here.
- if (NativePromise && typeof NativePromise.resolve === FUNCTION) {
+ if (NativePromise && typeof NativePromise.resolve === 'function') {
nativeMicroTaskQueuePromise = NativePromise.resolve(0);
}
},
@@ -643,6 +650,16 @@ var Zone$1 = (function (global) {
return global['Zone'] = Zone;
})(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
+var __values = (undefined && undefined.__values) || function (o) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
+ if (m) return m.call(o);
+ return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+};
Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var ObjectDefineProperty = Object.defineProperty;
@@ -785,7 +802,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var queue = promise[symbolValue];
promise[symbolValue] = value;
if (promise[symbolFinally] === symbolFinally) {
- // the promise is generated by Promise.prototype.finally
+ // the promise is generated by Promise.prototype.finally
if (state === RESOLVED) {
// the state is resolved, should ignore the value
// and use parent promise value
@@ -869,7 +886,9 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
chainPromise[symbolParentPromiseState] = promiseState;
}
// should not pass value to finally callback
- var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ? [] : [parentPromiseValue]);
+ var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
+ [] :
+ [parentPromiseValue]);
resolvePromise(chainPromise, true, value);
}
catch (error) {
@@ -904,6 +923,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
return resolvePromise(new this(null), REJECTED, error);
};
ZoneAwarePromise.race = function (values) {
+ var e_1, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
@@ -916,40 +936,70 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
function onReject(error) {
promise && (promise = null || reject(error));
}
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- if (!isThenable(value)) {
- value = this.resolve(value);
+ try {
+ for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
+ var value = values_1_1.value;
+ if (!isThenable(value)) {
+ value = this.resolve(value);
+ }
+ value.then(onResolve, onReject);
}
- value.then(onResolve, onReject);
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
+ }
+ finally { if (e_1) throw e_1.error; }
}
return promise;
};
ZoneAwarePromise.all = function (values) {
+ var e_2, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
resolve = res;
reject = rej;
});
- var count = 0;
+ // Start at 2 to prevent prematurely resolving if .then is called immediately.
+ var unresolvedCount = 2;
+ var valueIndex = 0;
var resolvedValues = [];
- for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
- var value = values_2[_i];
+ var _loop_2 = function (value) {
if (!isThenable(value)) {
- value = this.resolve(value);
+ value = this_1.resolve(value);
}
- value.then((function (index) { return function (value) {
- resolvedValues[index] = value;
- count--;
- if (!count) {
+ var curValueIndex = valueIndex;
+ value.then(function (value) {
+ resolvedValues[curValueIndex] = value;
+ unresolvedCount--;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
}
- }; })(count), reject);
- count++;
+ }, reject);
+ unresolvedCount++;
+ valueIndex++;
+ };
+ var this_1 = this;
+ try {
+ for (var values_2 = __values(values), values_2_1 = values_2.next(); !values_2_1.done; values_2_1 = values_2.next()) {
+ var value = values_2_1.value;
+ _loop_2(value);
+ }
}
- if (!count)
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
+ finally {
+ try {
+ if (values_2_1 && !values_2_1.done && (_a = values_2.return)) _a.call(values_2);
+ }
+ finally { if (e_2) throw e_2.error; }
+ }
+ // Make the unresolvedCount zero-based again.
+ unresolvedCount -= 2;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
+ }
return promise;
};
ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
@@ -1045,25 +1095,9 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
};
Ctor[symbolThenPatched] = true;
}
- function zoneify(fn) {
- return function () {
- var resultPromise = fn.apply(this, arguments);
- if (resultPromise instanceof ZoneAwarePromise) {
- return resultPromise;
- }
- var ctor = resultPromise.constructor;
- if (!ctor[symbolThenPatched]) {
- patchThen(ctor);
- }
- return resultPromise;
- };
- }
+ api.patchThen = patchThen;
if (NativePromise) {
patchThen(NativePromise);
- var fetch_1 = global['fetch'];
- if (typeof fetch_1 == 'function') {
- global['fetch'] = zoneify(fetch_1);
- }
}
// This is not part of public API, but it is useful for tests, so we expose it.
Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
@@ -1163,9 +1197,23 @@ var wrapFn = function (event) {
}
var target = this || event.target || _global;
var listener = target[eventNameSymbol];
- var result = listener && listener.apply(this, arguments);
- if (result != undefined && !result) {
- event.preventDefault();
+ var result;
+ if (isBrowser && target === internalWindow && event.type === 'error') {
+ // window.onerror have different signiture
+ // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
+ // and onerror callback will prevent default when callback return true
+ var errorEvent = event;
+ result = listener &&
+ listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
+ if (result === true) {
+ event.preventDefault();
+ }
+ }
+ else {
+ result = listener && listener.apply(this, arguments);
+ if (result != undefined && !result) {
+ event.preventDefault();
+ }
}
return result;
};
@@ -1183,6 +1231,10 @@ function patchProperty(obj, prop, prototype) {
if (!desc || !desc.configurable) {
return;
}
+ var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
+ if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
+ return;
+ }
// A property descriptor cannot have getter/setter and be writable
// deleting the writable and value properties avoids this error:
//
@@ -1260,6 +1312,7 @@ function patchProperty(obj, prop, prototype) {
return null;
};
ObjectDefineProperty(obj, prop, desc);
+ obj[onPropPatchedSymbol] = true;
}
function patchOnProperties(obj, properties, prototype) {
if (properties) {
@@ -1282,6 +1335,33 @@ function patchOnProperties(obj, properties, prototype) {
var originalInstanceKey = zoneSymbol('originalInstance');
// wrap some native API on `window`
+function copySymbolProperties(src, dest) {
+ if (typeof Object.getOwnPropertySymbols !== 'function') {
+ return;
+ }
+ var symbols = Object.getOwnPropertySymbols(src);
+ symbols.forEach(function (symbol) {
+ var desc = Object.getOwnPropertyDescriptor(src, symbol);
+ Object.defineProperty(dest, symbol, {
+ get: function () {
+ return src[symbol];
+ },
+ set: function (value) {
+ if (desc && (!desc.writable || typeof desc.set !== 'function')) {
+ // if src[symbol] is not writable or not have a setter, just return
+ return;
+ }
+ src[symbol] = value;
+ },
+ enumerable: desc ? desc.enumerable : true,
+ configurable: desc ? desc.configurable : true
+ });
+ });
+}
+var shouldCopySymbolProperties = false;
+function setShouldCopySymbolProperties(flag) {
+ shouldCopySymbolProperties = flag;
+}
function patchMethod(target, name, patchFn) {
var proto = target;
while (proto && !proto.hasOwnProperty(name)) {
@@ -1292,7 +1372,7 @@ function patchMethod(target, name, patchFn) {
proto = target;
}
var delegateName = zoneSymbol(name);
- var delegate;
+ var delegate = null;
if (proto && !(delegate = proto[delegateName])) {
delegate = proto[delegateName] = proto[name];
// check whether proto[name] is writable
@@ -1304,6 +1384,9 @@ function patchMethod(target, name, patchFn) {
return patchDelegate_1(this, arguments);
};
attachOriginToPatched(proto[name], delegate);
+ if (shouldCopySymbolProperties) {
+ copySymbolProperties(delegate, proto[name]);
+ }
}
}
return delegate;
@@ -1322,7 +1405,7 @@ function patchMacroTask(obj, funcName, metaCreator) {
setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
var meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
- return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask, null);
+ return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
}
else {
// cause an error by calling it directly.
@@ -1409,6 +1492,20 @@ Zone.__load_patch('toString', function (global) {
};
});
+/**
+ * @license
+ * Copyright Google Inc. 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.io/license
+ */
+Zone.__load_patch('node_util', function (global, Zone, api) {
+ api.patchOnProperties = patchOnProperties;
+ api.patchMethod = patchMethod;
+ api.bindArguments = bindArguments;
+ setShouldCopySymbolProperties(true);
+});
+
/**
* @license
* Copyright Google Inc. All Rights Reserved.
@@ -1420,6 +1517,21 @@ Zone.__load_patch('toString', function (global) {
* @fileoverview
* @suppress {missingRequire}
*/
+var passiveSupported = false;
+if (typeof window !== 'undefined') {
+ try {
+ var options = Object.defineProperty({}, 'passive', {
+ get: function () {
+ passiveSupported = true;
+ }
+ });
+ window.addEventListener('test', options, options);
+ window.removeEventListener('test', options, options);
+ }
+ catch (err) {
+ passiveSupported = false;
+ }
+}
// an identifier to tell ZoneTask do not create a new invoke closure
var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
useG: true
@@ -1555,6 +1667,7 @@ function patchEventTarget(_global, apis, patchOptions) {
if (proto[zoneSymbolAddEventListener]) {
return false;
}
+ var eventNameToString = patchOptions && patchOptions.eventNameToString;
// a shared global taskData to pass data for scheduleEventTask
// so we do not need to create a new object just for pass some data
var taskData = {};
@@ -1570,12 +1683,24 @@ function patchEventTarget(_global, apis, patchOptions) {
nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
proto[patchOptions.prepend];
}
- var customScheduleGlobal = function () {
+ function checkIsPassive(task) {
+ if (!passiveSupported && typeof taskData.options !== 'boolean' &&
+ typeof taskData.options !== 'undefined' && taskData.options !== null) {
+ // options is a non-null non-undefined object
+ // passive is not supported
+ // don't pass options as object
+ // just pass capture as a boolean
+ task.options = !!taskData.options.capture;
+ taskData.options = task.options;
+ }
+ }
+ var customScheduleGlobal = function (task) {
// if there is already a task for the eventName + capture,
// just return, because we use the shared globalZoneAwareCallback here.
if (taskData.isExisting) {
return;
}
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
};
var customCancelGlobal = function (task) {
@@ -1616,6 +1741,7 @@ function patchEventTarget(_global, apis, patchOptions) {
return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
};
var customScheduleNonGlobal = function (task) {
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
};
var customSchedulePrepend = function (task) {
@@ -1638,10 +1764,15 @@ function patchEventTarget(_global, apis, patchOptions) {
if (prepend === void 0) { prepend = false; }
return function () {
var target = this || _global;
+ var eventName = arguments[0];
var delegate = arguments[1];
if (!delegate) {
return nativeListener.apply(this, arguments);
}
+ if (isNode && eventName === 'uncaughtException') {
+ // don't patch uncaughtException of nodejs to prevent endless loop
+ return nativeListener.apply(this, arguments);
+ }
// don't create the bind delegate function for handleEvent
// case here to improve addEventListener performance
// we will create the bind delegate when invoke
@@ -1655,7 +1786,6 @@ function patchEventTarget(_global, apis, patchOptions) {
if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
return;
}
- var eventName = arguments[0];
var options = arguments[2];
if (blackListedEvents) {
// check black list
@@ -1685,8 +1815,8 @@ function patchEventTarget(_global, apis, patchOptions) {
var symbolEventName;
if (!symbolEventNames) {
// the code is duplicate, but I just want to get some better performance
- var falseEventName = eventName + FALSE_STR;
- var trueEventName = eventName + TRUE_STR;
+ var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
+ var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames$1[eventName] = {};
@@ -1721,7 +1851,8 @@ function patchEventTarget(_global, apis, patchOptions) {
source = targetSource[eventName];
}
if (!source) {
- source = constructorName + addSource + eventName;
+ source = constructorName + addSource +
+ (eventNameToString ? eventNameToString(eventName) : eventName);
}
// do not create a new object as task.data to pass those things
// just use the global shared one
@@ -1736,7 +1867,7 @@ function patchEventTarget(_global, apis, patchOptions) {
taskData.capture = capture;
taskData.eventName = eventName;
taskData.isExisting = isExisting;
- var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : null;
+ var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
// keep taskData into data to allow onScheduleEventTask to access the task information
if (data) {
data.taskData = taskData;
@@ -1754,7 +1885,11 @@ function patchEventTarget(_global, apis, patchOptions) {
if (once) {
options.once = true;
}
- task.options = options;
+ if (!(!passiveSupported && typeof task.options === 'boolean')) {
+ // if not support passive, and we pass an option object
+ // to addEventListener, we should save the options to task
+ task.options = options;
+ }
task.target = target;
task.capture = capture;
task.eventName = eventName;
@@ -1839,7 +1974,7 @@ function patchEventTarget(_global, apis, patchOptions) {
var target = this || _global;
var eventName = arguments[0];
var listeners = [];
- var tasks = findEventTasks(target, eventName);
+ var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
@@ -1949,6 +2084,15 @@ Zone.__load_patch('EventEmitter', function (global) {
// same callback, same capture, same event name, just return
return task.callback === delegate || task.callback.listener === delegate;
};
+ var eventNameToString = function (eventName) {
+ if (typeof eventName === 'string') {
+ return eventName;
+ }
+ if (!eventName) {
+ return '';
+ }
+ return eventName.toString().replace('(', '_').replace(')', '_');
+ };
function patchEventEmitterMethods(obj) {
var result = patchEventTarget(global, [obj], {
useG: false,
@@ -1959,7 +2103,8 @@ Zone.__load_patch('EventEmitter', function (global) {
listeners: EE_LISTENERS,
chkDup: false,
rt: true,
- diff: compareTaskCallbackVsDelegate
+ diff: compareTaskCallbackVsDelegate,
+ eventNameToString: eventNameToString
});
if (result && result[0]) {
obj[EE_ON] = obj[EE_ADD_LISTENER];
@@ -2068,9 +2213,9 @@ function patchTimer(window, setName, cancelName, nameSuffix) {
patchMethod(window, setName, function (delegate) { return function (self, args) {
if (typeof args[0] === 'function') {
var options = {
- handleId: null,
isPeriodic: nameSuffix === 'Interval',
- delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,
+ delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
+ undefined,
args: args
};
var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
@@ -2151,11 +2296,6 @@ function patchTimer(window, setName, cancelName, nameSuffix) {
*/
var set = 'set';
var clear = 'clear';
-Zone.__load_patch('node_util', function (global, Zone, api) {
- api.patchOnProperties = patchOnProperties;
- api.patchMethod = patchMethod;
- api.bindArguments = bindArguments;
-});
Zone.__load_patch('node_timers', function (global, Zone) {
// Timers
var globalUseTimeoutFromTimer = false;
@@ -2467,6 +2607,7 @@ var ProxyZoneSpec = /** @class */ (function () {
if (defaultSpecDelegate === void 0) { defaultSpecDelegate = null; }
this.defaultSpecDelegate = defaultSpecDelegate;
this.name = 'ProxyZone';
+ this._delegateSpec = null;
this.properties = { 'ProxyZoneSpec': this };
this.propertyKeys = null;
this.lastTaskState = null;
@@ -3269,7 +3410,11 @@ var __spread = (undefined && undefined.__spread) || function () {
}
}
}
+ lastCurrentTime = this._currentTime;
this._currentTime = finalTime;
+ if (doTick) {
+ doTick(this._currentTime - lastCurrentTime);
+ }
};
Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
if (limit === void 0) { limit = 20; }
@@ -3358,14 +3503,14 @@ var __spread = (undefined && undefined.__spread) || function () {
args[_i] = arguments[_i];
}
fn.apply(global, args);
- if (_this._lastError === null) {
+ if (_this._lastError === null) { // Success
if (completers.onSuccess != null) {
completers.onSuccess.apply(global);
}
// Flush microtasks only on success.
_this.flushMicrotasks();
}
- else {
+ else { // Failure
if (completers.onError != null) {
completers.onError.apply(global);
}
@@ -3664,23 +3809,23 @@ Zone.__load_patch('fakeasync', function (global, Zone, api) {
ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
}
/**
- * Wraps a function to be executed in the fakeAsync zone:
- * - microtasks are manually executed by calling `flushMicrotasks()`,
- * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
- *
- * If there are any pending timers at the end of the function, an exception will be thrown.
- *
- * Can be used to wrap inject() calls.
- *
- * ## Example
- *
- * {@example core/testing/ts/fake_async.ts region='basic'}
- *
- * @param fn
- * @returns The function wrapped to be executed in the fakeAsync zone
- *
- * @experimental
- */
+ * Wraps a function to be executed in the fakeAsync zone:
+ * - microtasks are manually executed by calling `flushMicrotasks()`,
+ * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
+ *
+ * If there are any pending timers at the end of the function, an exception will be thrown.
+ *
+ * Can be used to wrap inject() calls.
+ *
+ * ## Example
+ *
+ * {@example core/testing/ts/fake_async.ts region='basic'}
+ *
+ * @param fn
+ * @returns The function wrapped to be executed in the fakeAsync zone
+ *
+ * @experimental
+ */
function fakeAsync(fn) {
// Not using an arrow function to preserve context passed from call site
return function () {
diff --git a/dist/zone-testing.js b/dist/zone-testing.js
index aa2bbb2f2..735a76d7c 100644
--- a/dist/zone-testing.js
+++ b/dist/zone-testing.js
@@ -183,6 +183,7 @@ var ProxyZoneSpec = /** @class */ (function () {
if (defaultSpecDelegate === void 0) { defaultSpecDelegate = null; }
this.defaultSpecDelegate = defaultSpecDelegate;
this.name = 'ProxyZone';
+ this._delegateSpec = null;
this.properties = { 'ProxyZoneSpec': this };
this.propertyKeys = null;
this.lastTaskState = null;
@@ -985,7 +986,11 @@ var __spread = (undefined && undefined.__spread) || function () {
}
}
}
+ lastCurrentTime = this._currentTime;
this._currentTime = finalTime;
+ if (doTick) {
+ doTick(this._currentTime - lastCurrentTime);
+ }
};
Scheduler.prototype.flush = function (limit, flushPeriodic, doTick) {
if (limit === void 0) { limit = 20; }
@@ -1074,14 +1079,14 @@ var __spread = (undefined && undefined.__spread) || function () {
args[_i] = arguments[_i];
}
fn.apply(global, args);
- if (_this._lastError === null) {
+ if (_this._lastError === null) { // Success
if (completers.onSuccess != null) {
completers.onSuccess.apply(global);
}
// Flush microtasks only on success.
_this.flushMicrotasks();
}
- else {
+ else { // Failure
if (completers.onError != null) {
completers.onError.apply(global);
}
@@ -1380,23 +1385,23 @@ Zone.__load_patch('fakeasync', function (global, Zone, api) {
ProxyZoneSpec && ProxyZoneSpec.assertPresent().resetDelegate();
}
/**
- * Wraps a function to be executed in the fakeAsync zone:
- * - microtasks are manually executed by calling `flushMicrotasks()`,
- * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
- *
- * If there are any pending timers at the end of the function, an exception will be thrown.
- *
- * Can be used to wrap inject() calls.
- *
- * ## Example
- *
- * {@example core/testing/ts/fake_async.ts region='basic'}
- *
- * @param fn
- * @returns The function wrapped to be executed in the fakeAsync zone
- *
- * @experimental
- */
+ * Wraps a function to be executed in the fakeAsync zone:
+ * - microtasks are manually executed by calling `flushMicrotasks()`,
+ * - timers are synchronous, `tick()` simulates the asynchronous passage of time.
+ *
+ * If there are any pending timers at the end of the function, an exception will be thrown.
+ *
+ * Can be used to wrap inject() calls.
+ *
+ * ## Example
+ *
+ * {@example core/testing/ts/fake_async.ts region='basic'}
+ *
+ * @param fn
+ * @returns The function wrapped to be executed in the fakeAsync zone
+ *
+ * @experimental
+ */
function fakeAsync(fn) {
// Not using an arrow function to preserve context passed from call site
return function () {
diff --git a/dist/zone.js b/dist/zone.js
index e15c127cf..fb3f4649b 100644
--- a/dist/zone.js
+++ b/dist/zone.js
@@ -19,7 +19,6 @@
* found in the LICENSE file at https://angular.io/license
*/
var Zone$1 = (function (global) {
- var FUNCTION = 'function';
var performance = global['performance'];
function mark(name) {
performance && performance['mark'] && performance['mark'](name);
@@ -28,12 +27,26 @@ var Zone$1 = (function (global) {
performance && performance['measure'] && performance['measure'](name, label);
}
mark('Zone');
+ var checkDuplicate = global[('__zone_symbol__forceDuplicateZoneCheck')] === true;
if (global['Zone']) {
- throw new Error('Zone already loaded.');
+ // if global['Zone'] already exists (maybe zone.js was already loaded or
+ // some other lib also registered a global object named Zone), we may need
+ // to throw an error, but sometimes user may not want this error.
+ // For example,
+ // we have two web pages, page1 includes zone.js, page2 doesn't.
+ // and the 1st time user load page1 and page2, everything work fine,
+ // but when user load page2 again, error occurs because global['Zone'] already exists.
+ // so we add a flag to let user choose whether to throw this error or not.
+ // By default, if existing Zone is from zone.js, we will not throw the error.
+ if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
+ throw new Error('Zone already loaded.');
+ }
+ else {
+ return global['Zone'];
+ }
}
var Zone = /** @class */ (function () {
function Zone(parent, zoneSpec) {
- this._properties = null;
this._parent = parent;
this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '';
this._properties = zoneSpec && zoneSpec.properties || {};
@@ -76,7 +89,9 @@ var Zone$1 = (function (global) {
});
Zone.__load_patch = function (name, fn) {
if (patches.hasOwnProperty(name)) {
- throw Error('Already loaded patch: ' + name);
+ if (checkDuplicate) {
+ throw Error('Already loaded patch: ' + name);
+ }
}
else if (!global['__Zone_disable_' + name]) {
var perfName = 'Zone:' + name;
@@ -120,7 +135,7 @@ var Zone$1 = (function (global) {
return this._zoneDelegate.fork(this, zoneSpec);
};
Zone.prototype.wrap = function (callback, source) {
- if (typeof callback !== FUNCTION) {
+ if (typeof callback !== 'function') {
throw new Error('Expecting function got: ' + callback);
}
var _callback = this._zoneDelegate.intercept(this, callback, source);
@@ -130,9 +145,6 @@ var Zone$1 = (function (global) {
};
};
Zone.prototype.run = function (callback, applyThis, applyArgs, source) {
- if (applyThis === void 0) { applyThis = undefined; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
@@ -143,8 +155,6 @@ var Zone$1 = (function (global) {
};
Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) {
if (applyThis === void 0) { applyThis = null; }
- if (applyArgs === void 0) { applyArgs = null; }
- if (source === void 0) { source = null; }
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
try {
@@ -168,10 +178,7 @@ var Zone$1 = (function (global) {
// https://github.com/angular/zone.js/issues/778, sometimes eventTask
// will run in notScheduled(canceled) state, we should not try to
// run such kind of task but just return
- // we have to define an variable here, if not
- // typescript compiler will complain below
- var isNotScheduled = task.state === notScheduled;
- if (isNotScheduled && task.type === eventTask) {
+ if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
return;
}
var reEntryGuard = task.state != running;
@@ -182,7 +189,7 @@ var Zone$1 = (function (global) {
_currentZoneFrame = { parent: _currentZoneFrame, zone: this };
try {
if (task.type == macroTask && task.data && !task.data.isPeriodic) {
- task.cancelFn = null;
+ task.cancelFn = undefined;
}
try {
return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
@@ -218,8 +225,7 @@ var Zone$1 = (function (global) {
var newZone = this;
while (newZone) {
if (newZone === task.zone) {
- throw Error("can not reschedule task to " + this
- .name + " which is descendants of the original zone " + task.zone.name);
+ throw Error("can not reschedule task to " + this.name + " which is descendants of the original zone " + task.zone.name);
}
newZone = newZone.parent;
}
@@ -249,7 +255,7 @@ var Zone$1 = (function (global) {
return task;
};
Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) {
- return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, null));
+ return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
};
Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) {
return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
@@ -290,16 +296,14 @@ var Zone$1 = (function (global) {
}());
var DELEGATE_ZS = {
name: '',
- onHasTask: function (delegate, _, target, hasTaskState) {
- return delegate.hasTask(target, hasTaskState);
- },
+ onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); },
onScheduleTask: function (delegate, _, target, task) {
return delegate.scheduleTask(target, task);
},
- onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); },
- onCancelTask: function (delegate, _, target, task) {
- return delegate.cancelTask(target, task);
- }
+ onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) {
+ return delegate.invokeTask(target, task, applyThis, applyArgs);
+ },
+ onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); }
};
var ZoneDelegate = /** @class */ (function () {
function ZoneDelegate(zone, parentDelegate, zoneSpec) {
@@ -327,8 +331,8 @@ var Zone$1 = (function (global) {
zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone);
this._scheduleTaskZS =
zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
- this._scheduleTaskDlgt =
- zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
+ this._scheduleTaskDlgt = zoneSpec &&
+ (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
this._scheduleTaskCurrZone =
zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone);
this._invokeTaskZS =
@@ -383,8 +387,7 @@ var Zone$1 = (function (global) {
callback;
};
ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) {
- return this._invokeZS ?
- this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
+ return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.handleError = function (targetZone, error) {
@@ -416,8 +419,7 @@ var Zone$1 = (function (global) {
return returnTask;
};
ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) {
- return this._invokeTaskZS ?
- this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
+ return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
task.callback.apply(applyThis, applyArgs);
};
ZoneDelegate.prototype.cancelTask = function (targetZone, task) {
@@ -437,7 +439,7 @@ var Zone$1 = (function (global) {
// hasTask should not throw error so other ZoneDelegate
// can still trigger hasTask callback
try {
- return this._hasTaskZS &&
+ this._hasTaskZS &&
this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
}
catch (err) {
@@ -527,14 +529,12 @@ var Zone$1 = (function (global) {
}
}
else {
- throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ?
- ' or \'' + fromState2 + '\'' :
- '') + ", was '" + this._state + "'.");
+ throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ? ' or \'' + fromState2 + '\'' : '') + ", was '" + this._state + "'.");
}
};
ZoneTask.prototype.toString = function () {
if (this.data && typeof this.data.handleId !== 'undefined') {
- return this.data.handleId;
+ return this.data.handleId.toString();
}
else {
return Object.prototype.toString.call(this);
@@ -575,7 +575,13 @@ var Zone$1 = (function (global) {
}
}
if (nativeMicroTaskQueuePromise) {
- nativeMicroTaskQueuePromise[symbolThen](drainMicroTaskQueue);
+ var nativeThen = nativeMicroTaskQueuePromise[symbolThen];
+ if (!nativeThen) {
+ // native Promise is not patchable, we need to use `then` directly
+ // issue 1078
+ nativeThen = nativeMicroTaskQueuePromise['then'];
+ }
+ nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
}
else {
global[symbolSetTimeout](drainMicroTaskQueue, 0);
@@ -622,12 +628,13 @@ var Zone$1 = (function (global) {
patchEventTarget: function () { return []; },
patchOnProperties: noop,
patchMethod: function () { return noop; },
- bindArguments: function () { return null; },
+ bindArguments: function () { return []; },
+ patchThen: function () { return noop; },
setNativePromise: function (NativePromise) {
// sometimes NativePromise.resolve static function
// is not ready yet, (such as core-js/es6.promise)
// so we need to check here.
- if (NativePromise && typeof NativePromise.resolve === FUNCTION) {
+ if (NativePromise && typeof NativePromise.resolve === 'function') {
nativeMicroTaskQueuePromise = NativePromise.resolve(0);
}
},
@@ -643,6 +650,16 @@ var Zone$1 = (function (global) {
return global['Zone'] = Zone;
})(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
+var __values = (undefined && undefined.__values) || function (o) {
+ var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0;
+ if (m) return m.call(o);
+ return {
+ next: function () {
+ if (o && i >= o.length) o = void 0;
+ return { value: o && o[i++], done: !o };
+ }
+ };
+};
Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
var ObjectDefineProperty = Object.defineProperty;
@@ -785,7 +802,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
var queue = promise[symbolValue];
promise[symbolValue] = value;
if (promise[symbolFinally] === symbolFinally) {
- // the promise is generated by Promise.prototype.finally
+ // the promise is generated by Promise.prototype.finally
if (state === RESOLVED) {
// the state is resolved, should ignore the value
// and use parent promise value
@@ -869,7 +886,9 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
chainPromise[symbolParentPromiseState] = promiseState;
}
// should not pass value to finally callback
- var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ? [] : [parentPromiseValue]);
+ var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
+ [] :
+ [parentPromiseValue]);
resolvePromise(chainPromise, true, value);
}
catch (error) {
@@ -904,6 +923,7 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
return resolvePromise(new this(null), REJECTED, error);
};
ZoneAwarePromise.race = function (values) {
+ var e_1, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
@@ -916,40 +936,70 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
function onReject(error) {
promise && (promise = null || reject(error));
}
- for (var _i = 0, values_1 = values; _i < values_1.length; _i++) {
- var value = values_1[_i];
- if (!isThenable(value)) {
- value = this.resolve(value);
+ try {
+ for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) {
+ var value = values_1_1.value;
+ if (!isThenable(value)) {
+ value = this.resolve(value);
+ }
+ value.then(onResolve, onReject);
+ }
+ }
+ catch (e_1_1) { e_1 = { error: e_1_1 }; }
+ finally {
+ try {
+ if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1);
}
- value.then(onResolve, onReject);
+ finally { if (e_1) throw e_1.error; }
}
return promise;
};
ZoneAwarePromise.all = function (values) {
+ var e_2, _a;
var resolve;
var reject;
var promise = new this(function (res, rej) {
resolve = res;
reject = rej;
});
- var count = 0;
+ // Start at 2 to prevent prematurely resolving if .then is called immediately.
+ var unresolvedCount = 2;
+ var valueIndex = 0;
var resolvedValues = [];
- for (var _i = 0, values_2 = values; _i < values_2.length; _i++) {
- var value = values_2[_i];
+ var _loop_2 = function (value) {
if (!isThenable(value)) {
- value = this.resolve(value);
+ value = this_1.resolve(value);
}
- value.then((function (index) { return function (value) {
- resolvedValues[index] = value;
- count--;
- if (!count) {
+ var curValueIndex = valueIndex;
+ value.then(function (value) {
+ resolvedValues[curValueIndex] = value;
+ unresolvedCount--;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
}
- }; })(count), reject);
- count++;
+ }, reject);
+ unresolvedCount++;
+ valueIndex++;
+ };
+ var this_1 = this;
+ try {
+ for (var values_2 = __values(values), values_2_1 = values_2.next(); !values_2_1.done; values_2_1 = values_2.next()) {
+ var value = values_2_1.value;
+ _loop_2(value);
+ }
}
- if (!count)
+ catch (e_2_1) { e_2 = { error: e_2_1 }; }
+ finally {
+ try {
+ if (values_2_1 && !values_2_1.done && (_a = values_2.return)) _a.call(values_2);
+ }
+ finally { if (e_2) throw e_2.error; }
+ }
+ // Make the unresolvedCount zero-based again.
+ unresolvedCount -= 2;
+ if (unresolvedCount === 0) {
resolve(resolvedValues);
+ }
return promise;
};
ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) {
@@ -1045,31 +1095,112 @@ Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) {
};
Ctor[symbolThenPatched] = true;
}
- function zoneify(fn) {
- return function () {
- var resultPromise = fn.apply(this, arguments);
- if (resultPromise instanceof ZoneAwarePromise) {
- return resultPromise;
- }
- var ctor = resultPromise.constructor;
- if (!ctor[symbolThenPatched]) {
- patchThen(ctor);
- }
- return resultPromise;
- };
- }
+ api.patchThen = patchThen;
if (NativePromise) {
patchThen(NativePromise);
- var fetch_1 = global['fetch'];
- if (typeof fetch_1 == 'function') {
- global['fetch'] = zoneify(fetch_1);
- }
}
// This is not part of public API, but it is useful for tests, so we expose it.
Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
return ZoneAwarePromise;
});
+/**
+ * @license
+ * Copyright Google Inc. 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.io/license
+ */
+Zone.__load_patch('fetch', function (global, Zone, api) {
+ var fetch = global['fetch'];
+ var ZoneAwarePromise = global.Promise;
+ var symbolThenPatched = api.symbol('thenPatched');
+ var fetchTaskScheduling = api.symbol('fetchTaskScheduling');
+ var fetchTaskAborting = api.symbol('fetchTaskAborting');
+ if (typeof fetch !== 'function') {
+ return;
+ }
+ var OriginalAbortController = global['AbortController'];
+ var supportAbort = typeof OriginalAbortController === 'function';
+ var abortNative = null;
+ if (supportAbort) {
+ global['AbortController'] = function () {
+ var abortController = new OriginalAbortController();
+ var signal = abortController.signal;
+ signal.abortController = abortController;
+ return abortController;
+ };
+ abortNative = api.patchMethod(OriginalAbortController.prototype, 'abort', function (delegate) { return function (self, args) {
+ if (self.task) {
+ return self.task.zone.cancelTask(self.task);
+ }
+ return delegate.apply(self, args);
+ }; });
+ }
+ var placeholder = function () { };
+ global['fetch'] = function () {
+ var _this = this;
+ var args = Array.prototype.slice.call(arguments);
+ var options = args.length > 1 ? args[1] : null;
+ var signal = options && options.signal;
+ return new Promise(function (res, rej) {
+ var task = Zone.current.scheduleMacroTask('fetch', placeholder, args, function () {
+ var fetchPromise;
+ var zone = Zone.current;
+ try {
+ zone[fetchTaskScheduling] = true;
+ fetchPromise = fetch.apply(_this, args);
+ }
+ catch (error) {
+ rej(error);
+ return;
+ }
+ finally {
+ zone[fetchTaskScheduling] = false;
+ }
+ if (!(fetchPromise instanceof ZoneAwarePromise)) {
+ var ctor = fetchPromise.constructor;
+ if (!ctor[symbolThenPatched]) {
+ api.patchThen(ctor);
+ }
+ }
+ fetchPromise.then(function (resource) {
+ if (task.state !== 'notScheduled') {
+ task.invoke();
+ }
+ res(resource);
+ }, function (error) {
+ if (task.state !== 'notScheduled') {
+ task.invoke();
+ }
+ rej(error);
+ });
+ }, function () {
+ if (!supportAbort) {
+ rej('No AbortController supported, can not cancel fetch');
+ return;
+ }
+ if (signal && signal.abortController && !signal.aborted &&
+ typeof signal.abortController.abort === 'function' && abortNative) {
+ try {
+ Zone.current[fetchTaskAborting] = true;
+ abortNative.call(signal.abortController);
+ }
+ finally {
+ Zone.current[fetchTaskAborting] = false;
+ }
+ }
+ else {
+ rej('cancel fetch need a AbortController.signal');
+ }
+ });
+ if (signal && signal.abortController) {
+ signal.abortController.task = task;
+ }
+ });
+ };
+});
+
/**
* @license
* Copyright Google Inc. All Rights Reserved.
@@ -1185,9 +1316,23 @@ var wrapFn = function (event) {
}
var target = this || event.target || _global;
var listener = target[eventNameSymbol];
- var result = listener && listener.apply(this, arguments);
- if (result != undefined && !result) {
- event.preventDefault();
+ var result;
+ if (isBrowser && target === internalWindow && event.type === 'error') {
+ // window.onerror have different signiture
+ // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
+ // and onerror callback will prevent default when callback return true
+ var errorEvent = event;
+ result = listener &&
+ listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
+ if (result === true) {
+ event.preventDefault();
+ }
+ }
+ else {
+ result = listener && listener.apply(this, arguments);
+ if (result != undefined && !result) {
+ event.preventDefault();
+ }
}
return result;
};
@@ -1205,6 +1350,10 @@ function patchProperty(obj, prop, prototype) {
if (!desc || !desc.configurable) {
return;
}
+ var onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
+ if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
+ return;
+ }
// A property descriptor cannot have getter/setter and be writable
// deleting the writable and value properties avoids this error:
//
@@ -1282,6 +1431,7 @@ function patchProperty(obj, prop, prototype) {
return null;
};
ObjectDefineProperty(obj, prop, desc);
+ obj[onPropPatchedSymbol] = true;
}
function patchOnProperties(obj, properties, prototype) {
if (properties) {
@@ -1372,6 +1522,31 @@ function patchClass(className) {
}
}
}
+function copySymbolProperties(src, dest) {
+ if (typeof Object.getOwnPropertySymbols !== 'function') {
+ return;
+ }
+ var symbols = Object.getOwnPropertySymbols(src);
+ symbols.forEach(function (symbol) {
+ var desc = Object.getOwnPropertyDescriptor(src, symbol);
+ Object.defineProperty(dest, symbol, {
+ get: function () {
+ return src[symbol];
+ },
+ set: function (value) {
+ if (desc && (!desc.writable || typeof desc.set !== 'function')) {
+ // if src[symbol] is not writable or not have a setter, just return
+ return;
+ }
+ src[symbol] = value;
+ },
+ enumerable: desc ? desc.enumerable : true,
+ configurable: desc ? desc.configurable : true
+ });
+ });
+}
+var shouldCopySymbolProperties = false;
+
function patchMethod(target, name, patchFn) {
var proto = target;
while (proto && !proto.hasOwnProperty(name)) {
@@ -1382,7 +1557,7 @@ function patchMethod(target, name, patchFn) {
proto = target;
}
var delegateName = zoneSymbol(name);
- var delegate;
+ var delegate = null;
if (proto && !(delegate = proto[delegateName])) {
delegate = proto[delegateName] = proto[name];
// check whether proto[name] is writable
@@ -1394,6 +1569,9 @@ function patchMethod(target, name, patchFn) {
return patchDelegate_1(this, arguments);
};
attachOriginToPatched(proto[name], delegate);
+ if (shouldCopySymbolProperties) {
+ copySymbolProperties(delegate, proto[name]);
+ }
}
}
return delegate;
@@ -1412,7 +1590,7 @@ function patchMacroTask(obj, funcName, metaCreator) {
setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) {
var meta = metaCreator(self, args);
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
- return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask, null);
+ return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
}
else {
// cause an error by calling it directly.
@@ -1426,6 +1604,17 @@ function attachOriginToPatched(patched, original) {
}
var isDetectedIEOrEdge = false;
var ieOrEdge = false;
+function isIE() {
+ try {
+ var ua = internalWindow.navigator.userAgent;
+ if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
+ return true;
+ }
+ }
+ catch (error) {
+ }
+ return false;
+}
function isIEOrEdge() {
if (isDetectedIEOrEdge) {
return ieOrEdge;
@@ -1507,6 +1696,21 @@ Zone.__load_patch('toString', function (global) {
* @fileoverview
* @suppress {missingRequire}
*/
+var passiveSupported = false;
+if (typeof window !== 'undefined') {
+ try {
+ var options = Object.defineProperty({}, 'passive', {
+ get: function () {
+ passiveSupported = true;
+ }
+ });
+ window.addEventListener('test', options, options);
+ window.removeEventListener('test', options, options);
+ }
+ catch (err) {
+ passiveSupported = false;
+ }
+}
// an identifier to tell ZoneTask do not create a new invoke closure
var OPTIMIZED_ZONE_EVENT_TASK_DATA = {
useG: true
@@ -1642,6 +1846,7 @@ function patchEventTarget(_global, apis, patchOptions) {
if (proto[zoneSymbolAddEventListener]) {
return false;
}
+ var eventNameToString = patchOptions && patchOptions.eventNameToString;
// a shared global taskData to pass data for scheduleEventTask
// so we do not need to create a new object just for pass some data
var taskData = {};
@@ -1657,12 +1862,24 @@ function patchEventTarget(_global, apis, patchOptions) {
nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
proto[patchOptions.prepend];
}
- var customScheduleGlobal = function () {
+ function checkIsPassive(task) {
+ if (!passiveSupported && typeof taskData.options !== 'boolean' &&
+ typeof taskData.options !== 'undefined' && taskData.options !== null) {
+ // options is a non-null non-undefined object
+ // passive is not supported
+ // don't pass options as object
+ // just pass capture as a boolean
+ task.options = !!taskData.options.capture;
+ taskData.options = task.options;
+ }
+ }
+ var customScheduleGlobal = function (task) {
// if there is already a task for the eventName + capture,
// just return, because we use the shared globalZoneAwareCallback here.
if (taskData.isExisting) {
return;
}
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
};
var customCancelGlobal = function (task) {
@@ -1703,6 +1920,7 @@ function patchEventTarget(_global, apis, patchOptions) {
return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
};
var customScheduleNonGlobal = function (task) {
+ checkIsPassive(task);
return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
};
var customSchedulePrepend = function (task) {
@@ -1725,10 +1943,15 @@ function patchEventTarget(_global, apis, patchOptions) {
if (prepend === void 0) { prepend = false; }
return function () {
var target = this || _global;
+ var eventName = arguments[0];
var delegate = arguments[1];
if (!delegate) {
return nativeListener.apply(this, arguments);
}
+ if (isNode && eventName === 'uncaughtException') {
+ // don't patch uncaughtException of nodejs to prevent endless loop
+ return nativeListener.apply(this, arguments);
+ }
// don't create the bind delegate function for handleEvent
// case here to improve addEventListener performance
// we will create the bind delegate when invoke
@@ -1742,7 +1965,6 @@ function patchEventTarget(_global, apis, patchOptions) {
if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
return;
}
- var eventName = arguments[0];
var options = arguments[2];
if (blackListedEvents) {
// check black list
@@ -1772,8 +1994,8 @@ function patchEventTarget(_global, apis, patchOptions) {
var symbolEventName;
if (!symbolEventNames) {
// the code is duplicate, but I just want to get some better performance
- var falseEventName = eventName + FALSE_STR;
- var trueEventName = eventName + TRUE_STR;
+ var falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
+ var trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
var symbol = ZONE_SYMBOL_PREFIX + falseEventName;
var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
zoneSymbolEventNames$1[eventName] = {};
@@ -1808,7 +2030,8 @@ function patchEventTarget(_global, apis, patchOptions) {
source = targetSource[eventName];
}
if (!source) {
- source = constructorName + addSource + eventName;
+ source = constructorName + addSource +
+ (eventNameToString ? eventNameToString(eventName) : eventName);
}
// do not create a new object as task.data to pass those things
// just use the global shared one
@@ -1823,7 +2046,7 @@ function patchEventTarget(_global, apis, patchOptions) {
taskData.capture = capture;
taskData.eventName = eventName;
taskData.isExisting = isExisting;
- var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : null;
+ var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
// keep taskData into data to allow onScheduleEventTask to access the task information
if (data) {
data.taskData = taskData;
@@ -1841,7 +2064,11 @@ function patchEventTarget(_global, apis, patchOptions) {
if (once) {
options.once = true;
}
- task.options = options;
+ if (!(!passiveSupported && typeof task.options === 'boolean')) {
+ // if not support passive, and we pass an option object
+ // to addEventListener, we should save the options to task
+ task.options = options;
+ }
task.target = target;
task.capture = capture;
task.eventName = eventName;
@@ -1926,7 +2153,7 @@ function patchEventTarget(_global, apis, patchOptions) {
var target = this || _global;
var eventName = arguments[0];
var listeners = [];
- var tasks = findEventTasks(target, eventName);
+ var tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
for (var i = 0; i < tasks.length; i++) {
var task = tasks[i];
var delegate = task.originalDelegate ? task.originalDelegate : task.callback;
@@ -2082,9 +2309,9 @@ function patchTimer(window, setName, cancelName, nameSuffix) {
patchMethod(window, setName, function (delegate) { return function (self, args) {
if (typeof args[0] === 'function') {
var options = {
- handleId: null,
isPeriodic: nameSuffix === 'Interval',
- delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null,
+ delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
+ undefined,
args: args
};
var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
@@ -2199,7 +2426,7 @@ function propertyPatch() {
};
Object.getOwnPropertyDescriptor = function (obj, prop) {
var desc = _getOwnPropertyDescriptor(obj, prop);
- if (isUnconfigurable(obj, prop)) {
+ if (desc && isUnconfigurable(obj, prop)) {
desc.configurable = false;
}
return desc;
@@ -2427,10 +2654,10 @@ var globalEventHandlersEventNames = [
'wheel'
];
var documentEventNames = [
- 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'fullscreenchange',
+ 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'freeze', 'fullscreenchange',
'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror',
'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange',
- 'visibilitychange'
+ 'visibilitychange', 'resume'
];
var windowEventNames = [
'absolutedeviceorientation',
@@ -2542,7 +2769,7 @@ var websocketEventNames = ['close', 'error', 'open', 'message'];
var workerEventNames = ['error', 'message'];
var eventNames = globalEventHandlersEventNames.concat(webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames, htmlElementEventNames, ieElementEventNames);
function filterProperties(target, onProperties, ignoreProperties) {
- if (!ignoreProperties) {
+ if (!ignoreProperties || ignoreProperties.length === 0) {
return onProperties;
}
var tip = ignoreProperties.filter(function (ip) { return ip.target === target; });
@@ -2567,13 +2794,14 @@ function propertyDescriptorPatch(api, _global) {
}
var supportsWebSocket = typeof WebSocket !== 'undefined';
if (canPatchViaPropertyDescriptor()) {
- var ignoreProperties = _global.__Zone_ignore_on_properties;
+ var ignoreProperties = _global['__Zone_ignore_on_properties'];
// for browsers that we can patch the descriptor: Chrome & Firefox
if (isBrowser) {
var internalWindow = window;
+ var ignoreErrorProperties = isIE ? [{ target: internalWindow, ignoreProperties: ['error'] }] : [];
// in IE/Edge, onProp not exist in window object, but in WindowPrototype
// so we need to pass WindowPrototype to check onProp exist or not
- patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties, ObjectGetPrototypeOf(internalWindow));
+ patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
patchFilteredProperties(Document.prototype, eventNames, ignoreProperties);
if (typeof internalWindow['SVGElement'] !== 'undefined') {
patchFilteredProperties(internalWindow['SVGElement'].prototype, eventNames, ignoreProperties);
@@ -2595,9 +2823,9 @@ function propertyDescriptorPatch(api, _global) {
}
}
patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties);
- var XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget'];
- if (XMLHttpRequestEventTarget) {
- patchFilteredProperties(XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames, ignoreProperties);
+ var XMLHttpRequestEventTarget_1 = _global['XMLHttpRequestEventTarget'];
+ if (XMLHttpRequestEventTarget_1) {
+ patchFilteredProperties(XMLHttpRequestEventTarget_1 && XMLHttpRequestEventTarget_1.prototype, XMLHttpRequestEventNames, ignoreProperties);
}
if (typeof IDBIndex !== 'undefined') {
patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties);
@@ -2812,16 +3040,16 @@ function patchEvent(global, api) {
* Use of this source code is governed by an MIT-style license that can be
* found in the LICENSE file at https://angular.io/license
*/
-function registerElementPatch(_global) {
- if ((!isBrowser && !isMix) || !('registerElement' in _global.document)) {
+function patchCallbacks(target, targetName, method, callbacks) {
+ var symbol = Zone.__symbol__(method);
+ if (target[symbol]) {
return;
}
- var _registerElement = document.registerElement;
- var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
- document.registerElement = function (name, opts) {
+ var nativeDelegate = target[symbol] = target[method];
+ target[method] = function (name, opts, options) {
if (opts && opts.prototype) {
callbacks.forEach(function (callback) {
- var source = 'Document.registerElement::' + callback;
+ var source = targetName + "." + method + "::" + callback;
var prototype = opts.prototype;
if (prototype.hasOwnProperty(callback)) {
var descriptor = ObjectGetOwnPropertyDescriptor(prototype, callback);
@@ -2838,9 +3066,23 @@ function registerElementPatch(_global) {
}
});
}
- return _registerElement.call(document, name, opts);
+ return nativeDelegate.call(target, name, opts, options);
};
- attachOriginToPatched(document.registerElement, _registerElement);
+ attachOriginToPatched(target[method], nativeDelegate);
+}
+function registerElementPatch(_global) {
+ if ((!isBrowser && !isMix) || !('registerElement' in _global.document)) {
+ return;
+ }
+ var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
+ patchCallbacks(document, 'Document', 'registerElement', callbacks);
+}
+function patchCustomElements(_global) {
+ if ((!isBrowser && !isMix) || !('customElements' in _global)) {
+ return;
+ }
+ var callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
+ patchCallbacks(_global.customElements, 'customElements', 'define', callbacks);
}
/**
@@ -2903,7 +3145,10 @@ Zone.__load_patch('EventTarget', function (global, Zone, api) {
Zone.__load_patch('on_property', function (global, Zone, api) {
propertyDescriptorPatch(api, global);
propertyPatch();
+});
+Zone.__load_patch('customElements', function (global, Zone, api) {
registerElementPatch(global);
+ patchCustomElements(global);
});
Zone.__load_patch('canvas', function (global) {
var HTMLCanvasElement = global['HTMLCanvasElement'];
@@ -2922,6 +3167,7 @@ Zone.__load_patch('XHR', function (global, Zone) {
var XHR_LISTENER = zoneSymbol('xhrListener');
var XHR_SCHEDULED = zoneSymbol('xhrScheduled');
var XHR_URL = zoneSymbol('xhrURL');
+ var XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
function patchXHR(window) {
var XMLHttpRequestPrototype = XMLHttpRequest.prototype;
function findPendingTask(target) {
@@ -2930,9 +3176,9 @@ Zone.__load_patch('XHR', function (global, Zone) {
var oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
var oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
if (!oriAddListener) {
- var XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
- if (XMLHttpRequestEventTarget) {
- var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
+ var XMLHttpRequestEventTarget_1 = window['XMLHttpRequestEventTarget'];
+ if (XMLHttpRequestEventTarget_1) {
+ var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget_1.prototype;
oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
}
@@ -2940,9 +3186,10 @@ Zone.__load_patch('XHR', function (global, Zone) {
var READY_STATE_CHANGE = 'readystatechange';
var SCHEDULED = 'scheduled';
function scheduleTask(task) {
- XMLHttpRequest[XHR_SCHEDULED] = false;
var data = task.data;
var target = data.target;
+ target[XHR_SCHEDULED] = false;
+ target[XHR_ERROR_BEFORE_SCHEDULED] = false;
// remove existing event listener
var listener = target[XHR_LISTENER];
if (!oriAddListener) {
@@ -2956,8 +3203,35 @@ Zone.__load_patch('XHR', function (global, Zone) {
if (target.readyState === target.DONE) {
// sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
// readyState=4 multiple times, so we need to check task state here
- if (!data.aborted && XMLHttpRequest[XHR_SCHEDULED] && task.state === SCHEDULED) {
- task.invoke();
+ if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
+ // check whether the xhr has registered onload listener
+ // if that is the case, the task should invoke after all
+ // onload listeners finish.
+ var loadTasks = target['__zone_symbol__loadfalse'];
+ if (loadTasks && loadTasks.length > 0) {
+ var oriInvoke_1 = task.invoke;
+ task.invoke = function () {
+ // need to load the tasks again, because in other
+ // load listener, they may remove themselves
+ var loadTasks = target['__zone_symbol__loadfalse'];
+ for (var i = 0; i < loadTasks.length; i++) {
+ if (loadTasks[i] === task) {
+ loadTasks.splice(i, 1);
+ }
+ }
+ if (!data.aborted && task.state === SCHEDULED) {
+ oriInvoke_1.call(task);
+ }
+ };
+ loadTasks.push(task);
+ }
+ else {
+ task.invoke();
+ }
+ }
+ else if (!data.aborted && target[XHR_SCHEDULED] === false) {
+ // error occurs when xhr.send()
+ target[XHR_ERROR_BEFORE_SCHEDULED] = true;
}
}
};
@@ -2967,7 +3241,7 @@ Zone.__load_patch('XHR', function (global, Zone) {
target[XHR_TASK] = task;
}
sendNative.apply(target, data.args);
- XMLHttpRequest[XHR_SCHEDULED] = true;
+ target[XHR_SCHEDULED] = true;
return task;
}
function placeholderCallback() { }
@@ -2984,24 +3258,32 @@ Zone.__load_patch('XHR', function (global, Zone) {
return openNative.apply(self, args);
}; });
var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
+ var fetchTaskAborting = zoneSymbol('fetchTaskAborting');
+ var fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
var sendNative = patchMethod(XMLHttpRequestPrototype, 'send', function () { return function (self, args) {
+ if (Zone.current[fetchTaskScheduling] === true) {
+ // a fetch is scheduling, so we are using xhr to polyfill fetch
+ // and because we already schedule macroTask for fetch, we should
+ // not schedule a macroTask for xhr again
+ return sendNative.apply(self, args);
+ }
if (self[XHR_SYNC]) {
// if the XHR is sync there is no task to schedule, just execute the code.
return sendNative.apply(self, args);
}
else {
- var options = {
- target: self,
- url: self[XHR_URL],
- isPeriodic: false,
- delay: null,
- args: args,
- aborted: false
- };
- return scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
+ var options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
+ var task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
+ if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
+ task.state === SCHEDULED) {
+ // xhr request throw error when send
+ // we should invoke task instead of leaving a scheduled
+ // pending macroTask
+ task.invoke();
+ }
}
}; });
- var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self) {
+ var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self, args) {
var task = findPendingTask(self);
if (task && typeof task.type == 'string') {
// If the XHR has already completed, do nothing.
@@ -3013,6 +3295,10 @@ Zone.__load_patch('XHR', function (global, Zone) {
}
task.zone.cancelTask(task);
}
+ else if (Zone.current[fetchTaskAborting] === true) {
+ // the abort is called from fetch polyfill, we need to call native abort of XHR.
+ return abortNative.apply(self, args);
+ }
// Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
// task
// to cancel. Do nothing.
diff --git a/dist/zone.js.d.ts b/dist/zone.js.d.ts
index ac7ddcdb4..5420fe1ba 100644
--- a/dist/zone.js.d.ts
+++ b/dist/zone.js.d.ts
@@ -136,7 +136,7 @@ interface Zone {
*
* @returns {Zone} The parent Zone.
*/
- parent: Zone;
+ parent: Zone | null;
/**
* @returns {string} The Zone name (useful for debugging)
*/
@@ -159,7 +159,7 @@ interface Zone {
* @param key The key to use for identification of the returned zone.
* @returns {Zone} The Zone which defines the `key`, `null` if not found.
*/
- getZoneWith(key: string): Zone;
+ getZoneWith(key: string): Zone | null;
/**
* Used to create a child zone.
*
@@ -235,7 +235,7 @@ interface Zone {
* @param customSchedule
* @param customCancel
*/
- scheduleMacroTask(source: string, callback: Function, data: TaskData, customSchedule: (task: Task) => void, customCancel: (task: Task) => void): MacroTask;
+ scheduleMacroTask(source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void, customCancel?: (task: Task) => void): MacroTask;
/**
* Schedule an EventTask.
*
@@ -245,7 +245,7 @@ interface Zone {
* @param customSchedule
* @param customCancel
*/
- scheduleEventTask(source: string, callback: Function, data: TaskData, customSchedule: (task: Task) => void, customCancel: (task: Task) => void): EventTask;
+ scheduleEventTask(source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void, customCancel?: (task: Task) => void): EventTask;
/**
* Schedule an existing Task.
*
@@ -275,7 +275,7 @@ interface ZoneType {
/**
* @returns {Task} The task associated with the current execution.
*/
- currentTask: Task;
+ currentTask: Task | null;
/**
* Verify that Zone has been correctly patched. Specifically that Promise is zone aware.
*/
@@ -339,7 +339,7 @@ interface ZoneSpec {
* @param applyArgs The argument passed into the `run` method.
* @param source The argument passed into the `run` method.
*/
- onInvoke?: (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function, applyThis: any, applyArgs: any[], source: string) => any;
+ onInvoke?: (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function, applyThis: any, applyArgs?: any[], source?: string) => any;
/**
* Allows interception of the error handling.
*
@@ -358,7 +358,7 @@ interface ZoneSpec {
* @param task The argument passed into the `scheduleTask` method.
*/
onScheduleTask?: (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task) => Task;
- onInvokeTask?: (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task, applyThis: any, applyArgs: any) => any;
+ onInvokeTask?: (parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task, applyThis: any, applyArgs?: any[]) => any;
/**
* Allows interception of task cancellation.
*
@@ -413,10 +413,10 @@ interface ZoneDelegate {
zone: Zone;
fork(targetZone: Zone, zoneSpec: ZoneSpec): Zone;
intercept(targetZone: Zone, callback: Function, source: string): Function;
- invoke(targetZone: Zone, callback: Function, applyThis: any, applyArgs: any[], source: string): any;
+ invoke(targetZone: Zone, callback: Function, applyThis?: any, applyArgs?: any[], source?: string): any;
handleError(targetZone: Zone, error: any): boolean;
scheduleTask(targetZone: Zone, task: Task): Task;
- invokeTask(targetZone: Zone, task: Task, applyThis: any, applyArgs: any): any;
+ invokeTask(targetZone: Zone, task: Task, applyThis?: any, applyArgs?: any[]): any;
cancelTask(targetZone: Zone, task: Task): any;
hasTask(targetZone: Zone, isEmpty: HasTaskState): void;
}
@@ -493,20 +493,20 @@ interface Task {
/**
* Task specific options associated with the current task. This is passed to the `scheduleFn`.
*/
- data: TaskData;
+ data?: TaskData;
/**
* Represents the default work which needs to be done to schedule the Task by the VM.
*
* A zone may choose to intercept this function and perform its own scheduling.
*/
- scheduleFn: (task: Task) => void;
+ scheduleFn?: (task: Task) => void;
/**
* Represents the default work which needs to be done to un-schedule the Task from the VM. Not all
* Tasks are cancelable, and therefore this method is optional.
*
* A zone may chose to intercept this function and perform its own un-scheduling.
*/
- cancelFn: (task: Task) => void;
+ cancelFn?: (task: Task) => void;
/**
* @type {Zone} The zone which will be used to invoke the `callback`. The Zone is captured
* at the time of Task creation.
diff --git a/dist/zone.min.js b/dist/zone.min.js
index b95e78412..2c5af2585 100644
--- a/dist/zone.min.js
+++ b/dist/zone.min.js
@@ -1,2 +1,2 @@
-!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t():"function"==typeof define&&define.amd?define(t):t()}(this,function(){"use strict";function e(e,t){return Zone.current.wrap(e,t)}function t(e,t,n,r,o){return Zone.current.scheduleMacroTask(e,t,n,r,o)}function n(t,n){for(var r=t.length-1;r>=0;r--)"function"==typeof t[r]&&(t[r]=e(t[r],n+"_"+r));return t}function r(e,t){for(var r=e.constructor.name,a=function(a){var i=t[a],s=e[i];if(s){var c=P(e,i);if(!o(c))return"continue";e[i]=function(e){var t=function(){return e.apply(this,n(arguments,r+"."+i))};return l(t,e),t}(s)}},i=0;i=0&&"function"==typeof a[i.cbIdx]?t(i.name,a[i.cbIdx],i,o,null):e.apply(n,a)}})}function l(e,t){e[B("OriginalDelegate")]=t}function f(){if(te)return ne;te=!0;try{var e=W.navigator.userAgent;return e.indexOf("MSIE ")===-1&&e.indexOf("Trident/")===-1&&e.indexOf("Edge/")===-1||(ne=!0),ne}catch(t){}}function p(e,t,n){function r(t,n){if(!t)return!1;var r=!0;n&&void 0!==n.useG&&(r=n.useG);var d=n&&n.vh,y=!0;n&&void 0!==n.chkDup&&(y=n.chkDup);var m=!1;n&&void 0!==n.rt&&(m=n.rt);for(var k=t;k&&!k.hasOwnProperty(o);)k=C(k);if(!k&&t[o]&&(k=t),!k)return!1;if(k[c])return!1;var _,b={},T=k[c]=k[o],w=k[B(a)]=k[a],E=k[B(i)]=k[i],S=k[B(s)]=k[s];n&&n.prepend&&(_=k[B(n.prepend)]=k[n.prepend]);var D=function(){if(!b.isExisting)return T.call(b.target,b.eventName,b.capture?g:v,b.options)},Z=function(e){if(!e.isRemoved){var t=oe[e.eventName],n=void 0;t&&(n=t[e.capture?F:q]);var r=n&&e.target[n];if(r)for(var o=0;o1?new n(e,t):new n(e),s=P(a,"onmessage");return s&&s.configurable===!1?(r=I(a),o=a,[M,R,"send","close"].forEach(function(e){r[e]=function(){var t=L.call(arguments);if(e===M||e===R){var n=t.length>0?t[0]:void 0;if(n){var o=Zone.__symbol__("ON_PROPERTY"+n);a[o]=r[o]}}return a[e].apply(a,t)}})):r=a,i(r,["close","error","message","open"],o),r};var r=t.WebSocket;for(var o in n)r[o]=n[o]}function T(e,t,n){if(!n)return t;var r=n.filter(function(t){return t.target===e});if(!r||0===r.length)return t;var o=r[0].ignoreProperties;return t.filter(function(e){return o.indexOf(e)===-1})}function w(e,t,n,r){if(e){var o=T(e,t,n);i(e,o,r)}}function E(e,t){if(!K||Y){var n="undefined"!=typeof WebSocket;if(S()){var r=t.__Zone_ignore_on_properties;if(J){var o=window;w(o,Oe.concat(["messageerror"]),r,C(o)),w(Document.prototype,Oe,r),"undefined"!=typeof o.SVGElement&&w(o.SVGElement.prototype,Oe,r),w(Element.prototype,Oe,r),w(HTMLElement.prototype,Oe,r),w(HTMLMediaElement.prototype,ye,r),w(HTMLFrameSetElement.prototype,ve.concat(we),r),w(HTMLBodyElement.prototype,ve.concat(we),r),w(HTMLFrameElement.prototype,Te,r),w(HTMLIFrameElement.prototype,Te,r);var a=o.HTMLMarqueeElement;a&&w(a.prototype,Ee,r);var i=o.Worker;i&&w(i.prototype,ze,r)}w(XMLHttpRequest.prototype,Se,r);var c=t.XMLHttpRequestEventTarget;c&&w(c&&c.prototype,Se,r),"undefined"!=typeof IDBIndex&&(w(IDBIndex.prototype,De,r),w(IDBRequest.prototype,De,r),w(IDBOpenDBRequest.prototype,De,r),w(IDBDatabase.prototype,De,r),w(IDBTransaction.prototype,De,r),w(IDBCursor.prototype,De,r)),n&&w(WebSocket.prototype,Ze,r)}else D(),s("XMLHttpRequest"),n&&b(e,t)}}function S(){if((J||Y)&&!P(HTMLElement.prototype,"onclick")&&"undefined"!=typeof Element){var e=P(Element.prototype,"onclick");if(e&&!e.configurable)return!1}var t="onreadystatechange",n=XMLHttpRequest.prototype,r=P(n,t);if(r){j(n,t,{enumerable:!0,configurable:!0,get:function(){return!0}});var o=new XMLHttpRequest,a=!!o.onreadystatechange;return j(n,t,r||{}),a}var i=B("fake");j(n,t,{enumerable:!0,configurable:!0,get:function(){return this[i]},set:function(e){this[i]=e}});var o=new XMLHttpRequest,s=function(){};o.onreadystatechange=s;var a=o[i]===s;return o.onreadystatechange=null,a}function D(){for(var t=function(t){var n=Oe[t],r="on"+n;self.addEventListener(n,function(t){var n,o,a=t.target;for(o=a?a.constructor.name+"."+r:"unknown."+r;a;)a[r]&&!a[r][Pe]&&(n=e(a[r],o),n[Pe]=a[r],a[r]=n),a=a.parentElement},!0)},n=0;n",this._properties=t&&t.properties||{},this._zoneDelegate=new p(this,this._parent&&this._parent._zoneDelegate,t)}return r.assertZonePatched=function(){if(e.Promise!==O.ZoneAwarePromise)throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten.\nMost likely cause is that a Promise polyfill has been loaded after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. If you must load one, do so before loading zone.js.)")},Object.defineProperty(r,"root",{get:function(){for(var e=r.current;e.parent;)e=e.parent;return e},enumerable:!0,configurable:!0}),Object.defineProperty(r,"current",{get:function(){return j.zone},enumerable:!0,configurable:!0}),Object.defineProperty(r,"currentTask",{get:function(){return C},enumerable:!0,configurable:!0}),r.__load_patch=function(o,a){if(O.hasOwnProperty(o))throw Error("Already loaded patch: "+o);if(!e["__Zone_disable_"+o]){var i="Zone:"+o;t(i),O[o]=a(e,r,P),n(i,i)}},Object.defineProperty(r.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"name",{get:function(){return this._name},enumerable:!0,configurable:!0}),r.prototype.get=function(e){var t=this.getZoneWith(e);if(t)return t._properties[e]},r.prototype.getZoneWith=function(e){for(var t=this;t;){if(t._properties.hasOwnProperty(e))return t;t=t._parent}return null},r.prototype.fork=function(e){if(!e)throw new Error("ZoneSpec required!");return this._zoneDelegate.fork(this,e)},r.prototype.wrap=function(e,t){if(typeof e!==s)throw new Error("Expecting function got: "+e);var n=this._zoneDelegate.intercept(this,e,t),r=this;return function(){return r.runGuarded(n,this,arguments,t)}},r.prototype.run=function(e,t,n,r){void 0===t&&(t=void 0),void 0===n&&(n=null),void 0===r&&(r=null),j={parent:j,zone:this};try{return this._zoneDelegate.invoke(this,e,t,n,r)}finally{j=j.parent}},r.prototype.runGuarded=function(e,t,n,r){void 0===t&&(t=null),void 0===n&&(n=null),void 0===r&&(r=null),j={parent:j,zone:this};try{try{return this._zoneDelegate.invoke(this,e,t,n,r)}catch(o){if(this._zoneDelegate.handleError(this,o))throw o}}finally{j=j.parent}},r.prototype.runTask=function(e,t,n){if(e.zone!=this)throw new Error("A task can only be run in the zone of creation! (Creation: "+(e.zone||k).name+"; Execution: "+this.name+")");var r=e.state===_;if(!r||e.type!==z){var o=e.state!=w;o&&e._transitionTo(w,T),e.runCount++;var a=C;C=e,j={parent:j,zone:this};try{e.type==Z&&e.data&&!e.data.isPeriodic&&(e.cancelFn=null);try{return this._zoneDelegate.invokeTask(this,e,t,n)}catch(i){if(this._zoneDelegate.handleError(this,i))throw i}}finally{e.state!==_&&e.state!==S&&(e.type==z||e.data&&e.data.isPeriodic?o&&e._transitionTo(T,w):(e.runCount=0,this._updateTaskCount(e,-1),o&&e._transitionTo(_,w,_))),j=j.parent,C=a}}},r.prototype.scheduleTask=function(e){if(e.zone&&e.zone!==this)for(var t=this;t;){if(t===e.zone)throw Error("can not reschedule task to "+this.name+" which is descendants of the original zone "+e.zone.name);t=t.parent}e._transitionTo(b,_);var n=[];e._zoneDelegates=n,e._zone=this;try{e=this._zoneDelegate.scheduleTask(this,e)}catch(r){throw e._transitionTo(S,b,_),this._zoneDelegate.handleError(this,r),r}return e._zoneDelegates===n&&this._updateTaskCount(e,1),e.state==b&&e._transitionTo(T,b),e},r.prototype.scheduleMicroTask=function(e,t,n,r){return this.scheduleTask(new h(D,e,t,n,r,null))},r.prototype.scheduleMacroTask=function(e,t,n,r,o){return this.scheduleTask(new h(Z,e,t,n,r,o))},r.prototype.scheduleEventTask=function(e,t,n,r,o){return this.scheduleTask(new h(z,e,t,n,r,o))},r.prototype.cancelTask=function(e){if(e.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(e.zone||k).name+"; Execution: "+this.name+")");e._transitionTo(E,T,w);try{this._zoneDelegate.cancelTask(this,e)}catch(t){throw e._transitionTo(S,E),this._zoneDelegate.handleError(this,t),t}return this._updateTaskCount(e,-1),e._transitionTo(_,E),e.runCount=0,e},r.prototype._updateTaskCount=function(e,t){var n=e._zoneDelegates;t==-1&&(e._zoneDelegates=null);for(var r=0;r0,macroTask:n.macroTask>0,eventTask:n.eventTask>0,change:e};this.hasTask(this.zone,a)}},e}(),h=function(){function t(n,r,o,a,i,s){this._zone=null,this.runCount=0,this._zoneDelegates=null,this._state="notScheduled",this.type=n,this.source=r,this.data=a,this.scheduleFn=i,this.cancelFn=s,this.callback=o;var c=this;n===z&&a&&a.useG?this.invoke=t.invokeTask:this.invoke=function(){return t.invokeTask.call(e,c,this,arguments)}}return t.invokeTask=function(e,t,n){e||(e=this),I++;try{return e.runCount++,e.zone.runTask(e,t,n)}finally{1==I&&o(),I--}},Object.defineProperty(t.prototype,"zone",{get:function(){return this._zone},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),t.prototype.cancelScheduleRequest=function(){this._transitionTo(_,b)},t.prototype._transitionTo=function(e,t,n){if(this._state!==t&&this._state!==n)throw new Error(this.type+" '"+this.source+"': can not transition to '"+e+"', expecting state '"+t+"'"+(n?" or '"+n+"'":"")+", was '"+this._state+"'.");this._state=e,e==_&&(this._zoneDelegates=null)},t.prototype.toString=function(){return this.data&&"undefined"!=typeof this.data.handleId?this.data.handleId:Object.prototype.toString.call(this)},t.prototype.toJSON=function(){return{type:this.type,state:this.state,source:this.source,zone:this.zone.name,runCount:this.runCount}},t}(),d=i("setTimeout"),v=i("Promise"),g=i("then"),y=[],m=!1,k={name:"NO ZONE"},_="notScheduled",b="scheduling",T="scheduled",w="running",E="canceling",S="unknown",D="microTask",Z="macroTask",z="eventTask",O={},P={symbol:i,currentZoneFrame:function(){return j},onUnhandledError:a,microtaskDrainDone:a,scheduleMicroTask:r,showUncaughtError:function(){return!l[i("ignoreConsoleErrorUncaughtError")]},patchEventTarget:function(){return[]},patchOnProperties:a,patchMethod:function(){return a},bindArguments:function(){return null},setNativePromise:function(e){e&&typeof e.resolve===s&&(u=e.resolve(0))}},j={parent:null,zone:new l(null,null)},C=null,I=0;return n("Zone","Zone"),e.Zone=l})("undefined"!=typeof window&&window||"undefined"!=typeof self&&self||global);Zone.__load_patch("ZoneAwarePromise",function(e,t,n){function r(e){if(e&&e.toString===Object.prototype.toString){var t=e.constructor&&e.constructor.name;return(t?t:"")+": "+JSON.stringify(e)}return e?e.toString():Object.prototype.toString.call(e)}function o(e){n.onUnhandledError(e);try{var r=t[b];r&&"function"==typeof r&&r.call(this,e)}catch(o){}}function a(e){return e&&e.then}function i(e){return e}function s(e){return H.reject(e)}function c(e,t){return function(n){try{u(e,t,n)}catch(r){u(e,!1,r)}}}function u(e,o,a){var i=C();if(e===a)throw new TypeError(I);if(e[T]===z){var s=null;try{"object"!=typeof a&&"function"!=typeof a||(s=a&&a.then)}catch(p){return i(function(){u(e,!1,p)})(),e}if(o!==P&&a instanceof H&&a.hasOwnProperty(T)&&a.hasOwnProperty(w)&&a[T]!==z)l(a),u(e,a[T],a[w]);else if(o!==P&&"function"==typeof s)try{s.call(a,i(c(e,o)),i(c(e,!1)))}catch(p){i(function(){u(e,!1,p)})()}else{e[T]=o;var h=e[w];if(e[w]=a,e[E]===E&&o===O&&(e[T]=e[D],e[w]=e[S]),o===P&&a instanceof Error){var d=t.currentTask&&t.currentTask.data&&t.currentTask.data[_];d&&v(a,L,{configurable:!0,enumerable:!1,writable:!0,value:d})}for(var g=0;g=0;r--)"function"==typeof t[r]&&(t[r]=e(t[r],n+"_"+r));return t}function r(e,t){for(var r=e.constructor.name,a=function(a){var i=t[a],s=e[i];if(s){var c=L(e,i);if(!o(c))return"continue";e[i]=function(e){var t=function(){return e.apply(this,n(arguments,r+"."+i))};return f(t,e),t}(s)}},i=0;i=0&&"function"==typeof a[i.cbIdx]?t(i.name,a[i.cbIdx],i,o):e.apply(n,a)}})}function f(e,t){e[U("OriginalDelegate")]=t}function p(){try{var e=K.navigator.userAgent;if(e.indexOf("MSIE ")!==-1||e.indexOf("Trident/")!==-1)return!0}catch(t){}return!1}function h(){if(se)return ce;se=!0;try{var e=K.navigator.userAgent;return e.indexOf("MSIE ")===-1&&e.indexOf("Trident/")===-1&&e.indexOf("Edge/")===-1||(ce=!0),ce}catch(t){}}function d(e,t,n){function r(t,n){function r(e){ue||"boolean"==typeof w.options||"undefined"==typeof w.options||null===w.options||(e.options=!!w.options.capture,w.options=e.options)}if(!t)return!1;var h=!0;n&&void 0!==n.useG&&(h=n.useG);var y=n&&n.vh,m=!0;n&&void 0!==n.chkDup&&(m=n.chkDup);var k=!1;n&&void 0!==n.rt&&(k=n.rt);for(var _=t;_&&!_.hasOwnProperty(o);)_=R(_);if(!_&&t[o]&&(_=t),!_)return!1;if(_[c])return!1;var b,T=n&&n.eventNameToString,w={},E=_[c]=_[o],S=_[U(a)]=_[a],D=_[U(i)]=_[i],Z=_[U(s)]=_[s];n&&n.prepend&&(b=_[U(n.prepend)]=_[n.prepend]);var z=function(e){if(!w.isExisting)return r(e),E.call(w.target,w.eventName,w.capture?g:d,w.options)},O=function(e){if(!e.isRemoved){var t=he[e.eventName],n=void 0;t&&(n=t[e.capture?W:X]);var r=n&&e.target[n];if(r)for(var o=0;o1?new n(e,t):new n(e),s=L(a,"onmessage");return s&&s.configurable===!1?(r=H(a),o=a,[A,B,"send","close"].forEach(function(e){r[e]=function(){var t=F.call(arguments);if(e===A||e===B){var n=t.length>0?t[0]:void 0;if(n){var o=Zone.__symbol__("ON_PROPERTY"+n);a[o]=r[o]}}return a[e].apply(a,t)}})):r=a,i(r,["close","error","message","open"],o),r};var r=t.WebSocket;for(var o in n)r[o]=n[o]}function E(e,t,n){if(!n||0===n.length)return t;var r=n.filter(function(t){return t.target===e});if(!r||0===r.length)return t;var o=r[0].ignoreProperties;return t.filter(function(e){return o.indexOf(e)===-1})}function S(e,t,n,r){if(e){var o=E(e,t,n);i(e,o,r)}}function D(e,t){if(!ee||ne){var n="undefined"!=typeof WebSocket;if(Z()){var r=t.__Zone_ignore_on_properties;if(te){var o=window,a=p?[{target:o,ignoreProperties:["error"]}]:[];S(o,He.concat(["messageerror"]),r?r.concat(a):r,R(o)),S(Document.prototype,He,r),"undefined"!=typeof o.SVGElement&&S(o.SVGElement.prototype,He,r),S(Element.prototype,He,r),S(HTMLElement.prototype,He,r),S(HTMLMediaElement.prototype,De,r),S(HTMLFrameSetElement.prototype,Ee.concat(je),r),S(HTMLBodyElement.prototype,Ee.concat(je),r),S(HTMLFrameElement.prototype,Ce,r),S(HTMLIFrameElement.prototype,Ce,r);var i=o.HTMLMarqueeElement;i&&S(i.prototype,Ie,r);var c=o.Worker;c&&S(c.prototype,Re,r)}S(XMLHttpRequest.prototype,Me,r);var u=t.XMLHttpRequestEventTarget;u&&S(u&&u.prototype,Me,r),"undefined"!=typeof IDBIndex&&(S(IDBIndex.prototype,Le,r),S(IDBRequest.prototype,Le,r),S(IDBOpenDBRequest.prototype,Le,r),S(IDBDatabase.prototype,Le,r),S(IDBTransaction.prototype,Le,r),S(IDBCursor.prototype,Le,r)),n&&S(WebSocket.prototype,xe,r)}else z(),s("XMLHttpRequest"),n&&w(e,t)}}function Z(){if((te||ne)&&!L(HTMLElement.prototype,"onclick")&&"undefined"!=typeof Element){var e=L(Element.prototype,"onclick");if(e&&!e.configurable)return!1}var t="onreadystatechange",n=XMLHttpRequest.prototype,r=L(n,t);if(r){x(n,t,{enumerable:!0,configurable:!0,get:function(){return!0}});var o=new XMLHttpRequest,a=!!o.onreadystatechange;return x(n,t,r||{}),a}var i=U("fake");x(n,t,{enumerable:!0,configurable:!0,get:function(){return this[i]},set:function(e){this[i]=e}});var o=new XMLHttpRequest,s=function(){};o.onreadystatechange=s;var a=o[i]===s;return o.onreadystatechange=null,a}function z(){for(var t=function(t){var n=He[t],r="on"+n;self.addEventListener(n,function(t){var n,o,a=t.target;for(o=a?a.constructor.name+"."+r:"unknown."+r;a;)a[r]&&!a[r][Fe]&&(n=e(a[r],o),n[Fe]=a[r],a[r]=n),a=a.parentElement},!0)},n=0;n",this._properties=t&&t.properties||{},this._zoneDelegate=new p(this,this._parent&&this._parent._zoneDelegate,t)}return r.assertZonePatched=function(){if(e.Promise!==O.ZoneAwarePromise)throw new Error("Zone.js has detected that ZoneAwarePromise `(window|global).Promise` has been overwritten.\nMost likely cause is that a Promise polyfill has been loaded after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. If you must load one, do so before loading zone.js.)")},Object.defineProperty(r,"root",{get:function(){for(var e=r.current;e.parent;)e=e.parent;return e},enumerable:!0,configurable:!0}),Object.defineProperty(r,"current",{get:function(){return C.zone},enumerable:!0,configurable:!0}),Object.defineProperty(r,"currentTask",{get:function(){return j},enumerable:!0,configurable:!0}),r.__load_patch=function(o,a){if(O.hasOwnProperty(o)){if(c)throw Error("Already loaded patch: "+o)}else if(!e["__Zone_disable_"+o]){var i="Zone:"+o;t(i),O[o]=a(e,r,P),n(i,i)}},Object.defineProperty(r.prototype,"parent",{get:function(){return this._parent},enumerable:!0,configurable:!0}),Object.defineProperty(r.prototype,"name",{get:function(){return this._name},enumerable:!0,configurable:!0}),r.prototype.get=function(e){var t=this.getZoneWith(e);if(t)return t._properties[e]},r.prototype.getZoneWith=function(e){for(var t=this;t;){if(t._properties.hasOwnProperty(e))return t;t=t._parent}return null},r.prototype.fork=function(e){if(!e)throw new Error("ZoneSpec required!");return this._zoneDelegate.fork(this,e)},r.prototype.wrap=function(e,t){if("function"!=typeof e)throw new Error("Expecting function got: "+e);var n=this._zoneDelegate.intercept(this,e,t),r=this;return function(){return r.runGuarded(n,this,arguments,t)}},r.prototype.run=function(e,t,n,r){C={parent:C,zone:this};try{return this._zoneDelegate.invoke(this,e,t,n,r)}finally{C=C.parent}},r.prototype.runGuarded=function(e,t,n,r){void 0===t&&(t=null),C={parent:C,zone:this};try{try{return this._zoneDelegate.invoke(this,e,t,n,r)}catch(o){if(this._zoneDelegate.handleError(this,o))throw o}}finally{C=C.parent}},r.prototype.runTask=function(e,t,n){if(e.zone!=this)throw new Error("A task can only be run in the zone of creation! (Creation: "+(e.zone||k).name+"; Execution: "+this.name+")");if(e.state!==_||e.type!==z&&e.type!==Z){var r=e.state!=w;r&&e._transitionTo(w,T),e.runCount++;var o=j;j=e,C={parent:C,zone:this};try{e.type==Z&&e.data&&!e.data.isPeriodic&&(e.cancelFn=void 0);try{return this._zoneDelegate.invokeTask(this,e,t,n)}catch(a){if(this._zoneDelegate.handleError(this,a))throw a}}finally{e.state!==_&&e.state!==S&&(e.type==z||e.data&&e.data.isPeriodic?r&&e._transitionTo(T,w):(e.runCount=0,this._updateTaskCount(e,-1),r&&e._transitionTo(_,w,_))),C=C.parent,j=o}}},r.prototype.scheduleTask=function(e){if(e.zone&&e.zone!==this)for(var t=this;t;){if(t===e.zone)throw Error("can not reschedule task to "+this.name+" which is descendants of the original zone "+e.zone.name);t=t.parent}e._transitionTo(b,_);var n=[];e._zoneDelegates=n,e._zone=this;try{e=this._zoneDelegate.scheduleTask(this,e)}catch(r){throw e._transitionTo(S,b,_),this._zoneDelegate.handleError(this,r),r}return e._zoneDelegates===n&&this._updateTaskCount(e,1),e.state==b&&e._transitionTo(T,b),e},r.prototype.scheduleMicroTask=function(e,t,n,r){return this.scheduleTask(new h(D,e,t,n,r,(void 0)))},r.prototype.scheduleMacroTask=function(e,t,n,r,o){return this.scheduleTask(new h(Z,e,t,n,r,o))},r.prototype.scheduleEventTask=function(e,t,n,r,o){return this.scheduleTask(new h(z,e,t,n,r,o))},r.prototype.cancelTask=function(e){if(e.zone!=this)throw new Error("A task can only be cancelled in the zone of creation! (Creation: "+(e.zone||k).name+"; Execution: "+this.name+")");e._transitionTo(E,T,w);try{this._zoneDelegate.cancelTask(this,e)}catch(t){throw e._transitionTo(S,E),this._zoneDelegate.handleError(this,t),t}return this._updateTaskCount(e,-1),e._transitionTo(_,E),e.runCount=0,e},r.prototype._updateTaskCount=function(e,t){var n=e._zoneDelegates;t==-1&&(e._zoneDelegates=null);for(var r=0;r0,macroTask:n.macroTask>0,eventTask:n.eventTask>0,change:e};this.hasTask(this.zone,a)}},e}(),h=function(){function t(n,r,o,a,i,s){this._zone=null,this.runCount=0,this._zoneDelegates=null,this._state="notScheduled",this.type=n,this.source=r,this.data=a,this.scheduleFn=i,this.cancelFn=s,this.callback=o;var c=this;n===z&&a&&a.useG?this.invoke=t.invokeTask:this.invoke=function(){return t.invokeTask.call(e,c,this,arguments)}}return t.invokeTask=function(e,t,n){e||(e=this),I++;try{return e.runCount++,e.zone.runTask(e,t,n)}finally{1==I&&o(),I--}},Object.defineProperty(t.prototype,"zone",{get:function(){return this._zone},enumerable:!0,configurable:!0}),Object.defineProperty(t.prototype,"state",{get:function(){return this._state},enumerable:!0,configurable:!0}),t.prototype.cancelScheduleRequest=function(){this._transitionTo(_,b)},t.prototype._transitionTo=function(e,t,n){if(this._state!==t&&this._state!==n)throw new Error(this.type+" '"+this.source+"': can not transition to '"+e+"', expecting state '"+t+"'"+(n?" or '"+n+"'":"")+", was '"+this._state+"'.");this._state=e,e==_&&(this._zoneDelegates=null)},t.prototype.toString=function(){return this.data&&"undefined"!=typeof this.data.handleId?this.data.handleId.toString():Object.prototype.toString.call(this)},t.prototype.toJSON=function(){return{type:this.type,state:this.state,source:this.source,zone:this.zone.name,runCount:this.runCount}},t}(),d=i("setTimeout"),v=i("Promise"),g=i("then"),y=[],m=!1,k={name:"NO ZONE"},_="notScheduled",b="scheduling",T="scheduled",w="running",E="canceling",S="unknown",D="microTask",Z="macroTask",z="eventTask",O={},P={symbol:i,currentZoneFrame:function(){return C},onUnhandledError:a,microtaskDrainDone:a,scheduleMicroTask:r,showUncaughtError:function(){return!l[i("ignoreConsoleErrorUncaughtError")]},patchEventTarget:function(){return[]},patchOnProperties:a,patchMethod:function(){return a},bindArguments:function(){return[]},patchThen:function(){return a},setNativePromise:function(e){e&&"function"==typeof e.resolve&&(u=e.resolve(0))}},C={parent:null,zone:new l(null,null)},j=null,I=0;return n("Zone","Zone"),e.Zone=l}("undefined"!=typeof window&&window||"undefined"!=typeof self&&self||global),function(e){var t="function"==typeof Symbol&&e[Symbol.iterator],n=0;return t?t.call(e):{next:function(){return e&&n>=e.length&&(e=void 0),{value:e&&e[n++],done:!e}}}});Zone.__load_patch("ZoneAwarePromise",function(e,t,n){function r(e){if(e&&e.toString===Object.prototype.toString){var t=e.constructor&&e.constructor.name;return(t?t:"")+": "+JSON.stringify(e)}return e?e.toString():Object.prototype.toString.call(e)}function o(e){n.onUnhandledError(e);try{var r=t[_];r&&"function"==typeof r&&r.call(this,e)}catch(o){}}function a(e){return e&&e.then}function i(e){return e}function s(e){return R.reject(e)}function c(e,t){return function(n){try{u(e,t,n)}catch(r){u(e,!1,r)}}}function u(e,o,a){var i=C();if(e===a)throw new TypeError(j);if(e[b]===Z){var s=null;try{"object"!=typeof a&&"function"!=typeof a||(s=a&&a.then)}catch(p){return i(function(){u(e,!1,p)})(),e}if(o!==O&&a instanceof R&&a.hasOwnProperty(b)&&a.hasOwnProperty(T)&&a[b]!==Z)l(a),u(e,a[b],a[T]);else if(o!==O&&"function"==typeof s)try{s.call(a,i(c(e,o)),i(c(e,!1)))}catch(p){i(function(){u(e,!1,p)})()}else{e[b]=o;var h=e[T];if(e[T]=a,e[w]===w&&o===z&&(e[b]=e[S],e[T]=e[E]),o===O&&a instanceof Error){var v=t.currentTask&&t.currentTask.data&&t.currentTask.data[k];v&&d(a,I,{configurable:!0,enumerable:!1,writable:!0,value:v})}for(var y=0;y1?c[1]:null,h=p&&p.signal;return new Promise(function(p,d){var v=t.current.scheduleMacroTask("fetch",f,c,function(){var s,u=t.current;try{u[i]=!0,s=r.apply(e,c)}catch(l){return void d(l)}finally{u[i]=!1}if(!(s instanceof o)){var f=s.constructor;f[a]||n.patchThen(f)}s.then(function(e){"notScheduled"!==v.state&&v.invoke(),p(e)},function(e){"notScheduled"!==v.state&&v.invoke(),d(e)})},function(){if(!u)return void d("No AbortController supported, can not cancel fetch");if(h&&h.abortController&&!h.aborted&&"function"==typeof h.abortController.abort&&l)try{t.current[s]=!0,l.call(h.abortController)}finally{t.current[s]=!1}else d("cancel fetch need a AbortController.signal")});h&&h.abortController&&(h.abortController.task=v)})}}});var L=Object.getOwnPropertyDescriptor,x=Object.defineProperty,R=Object.getPrototypeOf,H=Object.create,F=Array.prototype.slice,A="addEventListener",B="removeEventListener",q=Zone.__symbol__(A),N=Zone.__symbol__(B),W="true",X="false",G="__zone_symbol__",U=Zone.__symbol__,V="undefined"!=typeof window,K=V?window:void 0,J=V&&K||"object"==typeof self&&self||global,Y="removeAttribute",Q=[null],$="undefined"!=typeof WorkerGlobalScope&&self instanceof WorkerGlobalScope,ee=!("nw"in J)&&"undefined"!=typeof J.process&&"[object process]"==={}.toString.call(J.process),te=!ee&&!$&&!(!V||!K.HTMLElement),ne="undefined"!=typeof J.process&&"[object process]"==={}.toString.call(J.process)&&!$&&!(!V||!K.HTMLElement),re={},oe=function(e){if(e=e||J.event){var t=re[e.type];t||(t=re[e.type]=U("ON_PROPERTY"+e.type));var n,r=this||e.target||J,o=r[t];if(te&&r===K&&"error"===e.type){var a=e;n=o&&o.call(this,a.message,a.filename,a.lineno,a.colno,a.error),n===!0&&e.preventDefault()}else n=o&&o.apply(this,arguments),void 0==n||n||e.preventDefault();return n}},ae=U("originalInstance"),ie=!1,se=!1,ce=!1;Zone.__load_patch("toString",function(e){var t=Function.prototype.toString,n=U("OriginalDelegate"),r=U("Promise"),o=U("Error"),a=function(){if("function"==typeof this){var a=this[n];if(a)return"function"==typeof a?t.apply(this[n],arguments):Object.prototype.toString.call(a);if(this===Promise){var i=e[r];if(i)return t.apply(i,arguments)}if(this===Error){var s=e[o];if(s)return t.apply(s,arguments)}}return t.apply(this,arguments)};a[n]=t,Function.prototype.toString=a;var i=Object.prototype.toString,s="[object Promise]";Object.prototype.toString=function(){return this instanceof Promise?s:i.apply(this,arguments)}});var ue=!1;if("undefined"!=typeof window)try{var le=Object.defineProperty({},"passive",{get:function(){ue=!0}});window.addEventListener("test",le,le),window.removeEventListener("test",le,le)}catch(fe){ue=!1}var pe={useG:!0},he={},de={},ve=/^__zone_symbol__(\w+)(true|false)$/,ge="__zone_symbol__propagationStopped",ye=U("zoneTask"),me=Object[U("defineProperty")]=Object.defineProperty,ke=Object[U("getOwnPropertyDescriptor")]=Object.getOwnPropertyDescriptor,_e=Object.create,be=U("unconfigurables"),Te=["abort","animationcancel","animationend","animationiteration","auxclick","beforeinput","blur","cancel","canplay","canplaythrough","change","compositionstart","compositionupdate","compositionend","cuechange","click","close","contextmenu","curechange","dblclick","drag","dragend","dragenter","dragexit","dragleave","dragover","drop","durationchange","emptied","ended","error","focus","focusin","focusout","gotpointercapture","input","invalid","keydown","keypress","keyup","load","loadstart","loadeddata","loadedmetadata","lostpointercapture","mousedown","mouseenter","mouseleave","mousemove","mouseout","mouseover","mouseup","mousewheel","orientationchange","pause","play","playing","pointercancel","pointerdown","pointerenter","pointerleave","pointerlockchange","mozpointerlockchange","webkitpointerlockerchange","pointerlockerror","mozpointerlockerror","webkitpointerlockerror","pointermove","pointout","pointerover","pointerup","progress","ratechange","reset","resize","scroll","seeked","seeking","select","selectionchange","selectstart","show","sort","stalled","submit","suspend","timeupdate","volumechange","touchcancel","touchmove","touchstart","touchend","transitioncancel","transitionend","waiting","wheel"],we=["afterscriptexecute","beforescriptexecute","DOMContentLoaded","freeze","fullscreenchange","mozfullscreenchange","webkitfullscreenchange","msfullscreenchange","fullscreenerror","mozfullscreenerror","webkitfullscreenerror","msfullscreenerror","readystatechange","visibilitychange","resume"],Ee=["absolutedeviceorientation","afterinput","afterprint","appinstalled","beforeinstallprompt","beforeprint","beforeunload","devicelight","devicemotion","deviceorientation","deviceorientationabsolute","deviceproximity","hashchange","languagechange","message","mozbeforepaint","offline","online","paint","pageshow","pagehide","popstate","rejectionhandled","storage","unhandledrejection","unload","userproximity","vrdisplyconnected","vrdisplaydisconnected","vrdisplaypresentchange"],Se=["beforecopy","beforecut","beforepaste","copy","cut","paste","dragstart","loadend","animationstart","search","transitionrun","transitionstart","webkitanimationend","webkitanimationiteration","webkitanimationstart","webkittransitionend"],De=["encrypted","waitingforkey","msneedkey","mozinterruptbegin","mozinterruptend"],Ze=["activate","afterupdate","ariarequest","beforeactivate","beforedeactivate","beforeeditfocus","beforeupdate","cellchange","controlselect","dataavailable","datasetchanged","datasetcomplete","errorupdate","filterchange","layoutcomplete","losecapture","move","moveend","movestart","propertychange","resizeend","resizestart","rowenter","rowexit","rowsdelete","rowsinserted","command","compassneedscalibration","deactivate","help","mscontentzoom","msmanipulationstatechanged","msgesturechange","msgesturedoubletap","msgestureend","msgesturehold","msgesturestart","msgesturetap","msgotpointercapture","msinertiastart","mslostpointercapture","mspointercancel","mspointerdown","mspointerenter","mspointerhover","mspointerleave","mspointermove","mspointerout","mspointerover","mspointerup","pointerout","mssitemodejumplistitemremoved","msthumbnailclick","stop","storagecommit"],ze=["webglcontextrestored","webglcontextlost","webglcontextcreationerror"],Oe=["autocomplete","autocompleteerror"],Pe=["toggle"],Ce=["load"],je=["blur","error","focus","load","resize","scroll","messageerror"],Ie=["bounce","finish","start"],Me=["loadstart","progress","abort","error","load","progress","timeout","loadend","readystatechange"],Le=["upgradeneeded","complete","abort","success","error","blocked","versionchange","close"],xe=["close","error","open","message"],Re=["error","message"],He=Te.concat(ze,Oe,Pe,we,Ee,Se,Ze),Fe=U("unbound");Zone.__load_patch("util",function(e,t,r){r.patchOnProperties=i,r.patchMethod=u,r.bindArguments=n}),Zone.__load_patch("timers",function(e){var t="set",n="clear";y(e,t,n,"Timeout"),y(e,t,n,"Interval"),y(e,t,n,"Immediate")}),Zone.__load_patch("requestAnimationFrame",function(e){y(e,"request","cancel","AnimationFrame"),y(e,"mozRequest","mozCancel","AnimationFrame"),y(e,"webkitRequest","webkitCancel","AnimationFrame")}),Zone.__load_patch("blocking",function(e,t){for(var n=["alert","prompt","confirm"],r=0;r0){var o=e.invoke;e.invoke=function(){for(var r=n.__zone_symbol__loadfalse,a=0;a