
committed by
Kara Erickson

parent
7b3bcc23af
commit
5eb7426216
18
packages/zone.js/lib/BUILD.bazel
Normal file
18
packages/zone.js/lib/BUILD.bazel
Normal file
@ -0,0 +1,18 @@
|
||||
load("@npm_bazel_typescript//:defs.bzl", "ts_library")
|
||||
|
||||
package(default_visibility = ["//packages/zone.js:__pkg__"])
|
||||
|
||||
exports_files(glob([
|
||||
"**/*",
|
||||
]))
|
||||
|
||||
ts_library(
|
||||
name = "lib",
|
||||
srcs = glob(["**/*.ts"]),
|
||||
visibility = ["//packages/zone.js:__subpackages__"],
|
||||
deps = [
|
||||
"@npm//@types/jasmine",
|
||||
"@npm//@types/node",
|
||||
"@npm//rxjs",
|
||||
],
|
||||
)
|
52
packages/zone.js/lib/browser/api-util.ts
Normal file
52
packages/zone.js/lib/browser/api-util.ts
Normal file
@ -0,0 +1,52 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import {globalSources, patchEventPrototype, patchEventTarget, zoneSymbolEventNames} from '../common/events';
|
||||
import {ADD_EVENT_LISTENER_STR, ArraySlice, FALSE_STR, ObjectCreate, ObjectDefineProperty, ObjectGetOwnPropertyDescriptor, REMOVE_EVENT_LISTENER_STR, TRUE_STR, ZONE_SYMBOL_PREFIX, attachOriginToPatched, bindArguments, isBrowser, isIEOrEdge, isMix, isNode, patchClass, patchMacroTask, patchMethod, patchOnProperties, wrapWithCurrentZone} from '../common/utils';
|
||||
|
||||
import {patchCallbacks} from './browser-util';
|
||||
import {_redefineProperty} from './define-property';
|
||||
import {eventNames, filterProperties} from './property-descriptor';
|
||||
|
||||
Zone.__load_patch('util', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
api.patchOnProperties = patchOnProperties;
|
||||
api.patchMethod = patchMethod;
|
||||
api.bindArguments = bindArguments;
|
||||
api.patchMacroTask = patchMacroTask;
|
||||
// In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS` to
|
||||
// define which events will not be patched by `Zone.js`.
|
||||
// In newer version (>=0.9.0), we change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep
|
||||
// the name consistent with angular repo.
|
||||
// The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be supported for
|
||||
// backwards compatibility.
|
||||
const SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
|
||||
const SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
|
||||
if (global[SYMBOL_UNPATCHED_EVENTS]) {
|
||||
global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
|
||||
}
|
||||
if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
|
||||
(Zone as any)[SYMBOL_BLACK_LISTED_EVENTS] = (Zone as any)[SYMBOL_UNPATCHED_EVENTS] =
|
||||
global[SYMBOL_BLACK_LISTED_EVENTS];
|
||||
}
|
||||
api.patchEventPrototype = patchEventPrototype;
|
||||
api.patchEventTarget = patchEventTarget;
|
||||
api.isIEOrEdge = isIEOrEdge;
|
||||
api.ObjectDefineProperty = ObjectDefineProperty;
|
||||
api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
|
||||
api.ObjectCreate = ObjectCreate;
|
||||
api.ArraySlice = ArraySlice;
|
||||
api.patchClass = patchClass;
|
||||
api.wrapWithCurrentZone = wrapWithCurrentZone;
|
||||
api.filterProperties = filterProperties;
|
||||
api.attachOriginToPatched = attachOriginToPatched;
|
||||
api._redefineProperty = _redefineProperty;
|
||||
api.patchCallbacks = patchCallbacks;
|
||||
api.getGlobalObjects = () =>
|
||||
({globalSources, zoneSymbolEventNames, eventNames, isBrowser, isMix, isNode, TRUE_STR,
|
||||
FALSE_STR, ZONE_SYMBOL_PREFIX, ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR});
|
||||
});
|
31
packages/zone.js/lib/browser/browser-legacy.ts
Normal file
31
packages/zone.js/lib/browser/browser-legacy.ts
Normal file
@ -0,0 +1,31 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {missingRequire}
|
||||
*/
|
||||
|
||||
import {eventTargetLegacyPatch} from './event-target-legacy';
|
||||
import {propertyDescriptorLegacyPatch} from './property-descriptor-legacy';
|
||||
import {registerElementPatch} from './register-element';
|
||||
|
||||
(function(_global: any) {
|
||||
_global[Zone.__symbol__('legacyPatch')] = function() {
|
||||
const Zone = _global['Zone'];
|
||||
Zone.__load_patch('registerElement', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
registerElementPatch(global, api);
|
||||
});
|
||||
|
||||
Zone.__load_patch('EventTargetLegacy', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
eventTargetLegacyPatch(global, api);
|
||||
propertyDescriptorLegacyPatch(api, global);
|
||||
});
|
||||
};
|
||||
})(typeof window !== 'undefined' ?
|
||||
window :
|
||||
typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {});
|
38
packages/zone.js/lib/browser/browser-util.ts
Normal file
38
packages/zone.js/lib/browser/browser-util.ts
Normal file
@ -0,0 +1,38 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
export function patchCallbacks(
|
||||
api: _ZonePrivate, target: any, targetName: string, method: string, callbacks: string[]) {
|
||||
const symbol = Zone.__symbol__(method);
|
||||
if (target[symbol]) {
|
||||
return;
|
||||
}
|
||||
const nativeDelegate = target[symbol] = target[method];
|
||||
target[method] = function(name: any, opts: any, options?: any) {
|
||||
if (opts && opts.prototype) {
|
||||
callbacks.forEach(function(callback) {
|
||||
const source = `${targetName}.${method}::` + callback;
|
||||
const prototype = opts.prototype;
|
||||
if (prototype.hasOwnProperty(callback)) {
|
||||
const descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
|
||||
if (descriptor && descriptor.value) {
|
||||
descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
|
||||
api._redefineProperty(opts.prototype, callback, descriptor);
|
||||
} else if (prototype[callback]) {
|
||||
prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
|
||||
}
|
||||
} else if (prototype[callback]) {
|
||||
prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
return nativeDelegate.call(target, name, opts, options);
|
||||
};
|
||||
|
||||
api.attachOriginToPatched(target[method], nativeDelegate);
|
||||
}
|
280
packages/zone.js/lib/browser/browser.ts
Normal file
280
packages/zone.js/lib/browser/browser.ts
Normal file
@ -0,0 +1,280 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {missingRequire}
|
||||
*/
|
||||
|
||||
import {findEventTasks} from '../common/events';
|
||||
import {patchTimer} from '../common/timers';
|
||||
import {ZONE_SYMBOL_ADD_EVENT_LISTENER, ZONE_SYMBOL_REMOVE_EVENT_LISTENER, patchClass, patchMethod, patchPrototype, scheduleMacroTaskWithCurrentZone, zoneSymbol} from '../common/utils';
|
||||
|
||||
import {patchCustomElements} from './custom-elements';
|
||||
import {propertyPatch} from './define-property';
|
||||
import {eventTargetPatch, patchEvent} from './event-target';
|
||||
import {propertyDescriptorPatch} from './property-descriptor';
|
||||
|
||||
Zone.__load_patch('legacy', (global: any) => {
|
||||
const legacyPatch = global[Zone.__symbol__('legacyPatch')];
|
||||
if (legacyPatch) {
|
||||
legacyPatch();
|
||||
}
|
||||
});
|
||||
|
||||
Zone.__load_patch('timers', (global: any) => {
|
||||
const set = 'set';
|
||||
const clear = 'clear';
|
||||
patchTimer(global, set, clear, 'Timeout');
|
||||
patchTimer(global, set, clear, 'Interval');
|
||||
patchTimer(global, set, clear, 'Immediate');
|
||||
});
|
||||
|
||||
Zone.__load_patch('requestAnimationFrame', (global: any) => {
|
||||
patchTimer(global, 'request', 'cancel', 'AnimationFrame');
|
||||
patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
|
||||
patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
|
||||
});
|
||||
|
||||
Zone.__load_patch('blocking', (global: any, Zone: ZoneType) => {
|
||||
const blockingMethods = ['alert', 'prompt', 'confirm'];
|
||||
for (let i = 0; i < blockingMethods.length; i++) {
|
||||
const name = blockingMethods[i];
|
||||
patchMethod(global, name, (delegate, symbol, name) => {
|
||||
return function(s: any, args: any[]) {
|
||||
return Zone.current.run(delegate, global, args, name);
|
||||
};
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Zone.__load_patch('EventTarget', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
patchEvent(global, api);
|
||||
eventTargetPatch(global, api);
|
||||
// patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
|
||||
const XMLHttpRequestEventTarget = (global as any)['XMLHttpRequestEventTarget'];
|
||||
if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
|
||||
api.patchEventTarget(global, [XMLHttpRequestEventTarget.prototype]);
|
||||
}
|
||||
patchClass('MutationObserver');
|
||||
patchClass('WebKitMutationObserver');
|
||||
patchClass('IntersectionObserver');
|
||||
patchClass('FileReader');
|
||||
});
|
||||
|
||||
Zone.__load_patch('on_property', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
propertyDescriptorPatch(api, global);
|
||||
propertyPatch();
|
||||
});
|
||||
|
||||
Zone.__load_patch('customElements', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
patchCustomElements(global, api);
|
||||
});
|
||||
|
||||
Zone.__load_patch('XHR', (global: any, Zone: ZoneType) => {
|
||||
// Treat XMLHttpRequest as a macrotask.
|
||||
patchXHR(global);
|
||||
|
||||
const XHR_TASK = zoneSymbol('xhrTask');
|
||||
const XHR_SYNC = zoneSymbol('xhrSync');
|
||||
const XHR_LISTENER = zoneSymbol('xhrListener');
|
||||
const XHR_SCHEDULED = zoneSymbol('xhrScheduled');
|
||||
const XHR_URL = zoneSymbol('xhrURL');
|
||||
const XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
|
||||
|
||||
interface XHROptions extends TaskData {
|
||||
target: any;
|
||||
url: string;
|
||||
args: any[];
|
||||
aborted: boolean;
|
||||
}
|
||||
|
||||
function patchXHR(window: any) {
|
||||
const XMLHttpRequest = window['XMLHttpRequest'];
|
||||
if (!XMLHttpRequest) {
|
||||
// XMLHttpRequest is not available in service worker
|
||||
return;
|
||||
}
|
||||
const XMLHttpRequestPrototype: any = XMLHttpRequest.prototype;
|
||||
|
||||
function findPendingTask(target: any) { return target[XHR_TASK]; }
|
||||
|
||||
let oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
|
||||
let oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
|
||||
if (!oriAddListener) {
|
||||
const XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
|
||||
if (XMLHttpRequestEventTarget) {
|
||||
const XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
|
||||
oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
|
||||
oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
|
||||
}
|
||||
}
|
||||
|
||||
const READY_STATE_CHANGE = 'readystatechange';
|
||||
const SCHEDULED = 'scheduled';
|
||||
|
||||
function scheduleTask(task: Task) {
|
||||
const data = <XHROptions>task.data;
|
||||
const target = data.target;
|
||||
target[XHR_SCHEDULED] = false;
|
||||
target[XHR_ERROR_BEFORE_SCHEDULED] = false;
|
||||
// remove existing event listener
|
||||
const listener = target[XHR_LISTENER];
|
||||
if (!oriAddListener) {
|
||||
oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
|
||||
oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
|
||||
}
|
||||
|
||||
if (listener) {
|
||||
oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
|
||||
}
|
||||
const newListener = target[XHR_LISTENER] = () => {
|
||||
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 && 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.
|
||||
const loadTasks = target[Zone.__symbol__('loadfalse')];
|
||||
if (loadTasks && loadTasks.length > 0) {
|
||||
const oriInvoke = task.invoke;
|
||||
task.invoke = function() {
|
||||
// need to load the tasks again, because in other
|
||||
// load listener, they may remove themselves
|
||||
const loadTasks = target[Zone.__symbol__('loadfalse')];
|
||||
for (let i = 0; i < loadTasks.length; i++) {
|
||||
if (loadTasks[i] === task) {
|
||||
loadTasks.splice(i, 1);
|
||||
}
|
||||
}
|
||||
if (!data.aborted && task.state === SCHEDULED) {
|
||||
oriInvoke.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;
|
||||
}
|
||||
}
|
||||
};
|
||||
oriAddListener.call(target, READY_STATE_CHANGE, newListener);
|
||||
|
||||
const storedTask: Task = target[XHR_TASK];
|
||||
if (!storedTask) {
|
||||
target[XHR_TASK] = task;
|
||||
}
|
||||
sendNative !.apply(target, data.args);
|
||||
target[XHR_SCHEDULED] = true;
|
||||
return task;
|
||||
}
|
||||
|
||||
function placeholderCallback() {}
|
||||
|
||||
function clearTask(task: Task) {
|
||||
const data = <XHROptions>task.data;
|
||||
// Note - ideally, we would call data.target.removeEventListener here, but it's too late
|
||||
// to prevent it from firing. So instead, we store info for the event listener.
|
||||
data.aborted = true;
|
||||
return abortNative !.apply(data.target, data.args);
|
||||
}
|
||||
|
||||
const openNative =
|
||||
patchMethod(XMLHttpRequestPrototype, 'open', () => function(self: any, args: any[]) {
|
||||
self[XHR_SYNC] = args[2] == false;
|
||||
self[XHR_URL] = args[1];
|
||||
return openNative !.apply(self, args);
|
||||
});
|
||||
|
||||
const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
|
||||
const fetchTaskAborting = zoneSymbol('fetchTaskAborting');
|
||||
const fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
|
||||
const sendNative: Function|null =
|
||||
patchMethod(XMLHttpRequestPrototype, 'send', () => function(self: any, args: any[]) {
|
||||
if ((Zone.current as any)[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 {
|
||||
const options: XHROptions =
|
||||
{target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false};
|
||||
const 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();
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
const abortNative =
|
||||
patchMethod(XMLHttpRequestPrototype, 'abort', () => function(self: any, args: any[]) {
|
||||
const task: Task = findPendingTask(self);
|
||||
if (task && typeof task.type == 'string') {
|
||||
// If the XHR has already completed, do nothing.
|
||||
// If the XHR has already been aborted, do nothing.
|
||||
// Fix #569, call abort multiple times before done will cause
|
||||
// macroTask task count be negative number
|
||||
if (task.cancelFn == null || (task.data && (<XHROptions>task.data).aborted)) {
|
||||
return;
|
||||
}
|
||||
task.zone.cancelTask(task);
|
||||
} else if ((Zone.current as any)[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.
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Zone.__load_patch('geolocation', (global: any) => {
|
||||
/// GEO_LOCATION
|
||||
if (global['navigator'] && global['navigator'].geolocation) {
|
||||
patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
|
||||
}
|
||||
});
|
||||
|
||||
Zone.__load_patch('PromiseRejectionEvent', (global: any, Zone: ZoneType) => {
|
||||
// handle unhandled promise rejection
|
||||
function findPromiseRejectionHandler(evtName: string) {
|
||||
return function(e: any) {
|
||||
const eventTasks = findEventTasks(global, evtName);
|
||||
eventTasks.forEach(eventTask => {
|
||||
// windows has added unhandledrejection event listener
|
||||
// trigger the event listener
|
||||
const PromiseRejectionEvent = global['PromiseRejectionEvent'];
|
||||
if (PromiseRejectionEvent) {
|
||||
const evt = new PromiseRejectionEvent(evtName, {promise: e.promise, reason: e.rejection});
|
||||
eventTask.invoke(evt);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
|
||||
if (global['PromiseRejectionEvent']) {
|
||||
(Zone as any)[zoneSymbol('unhandledPromiseRejectionHandler')] =
|
||||
findPromiseRejectionHandler('unhandledrejection');
|
||||
|
||||
(Zone as any)[zoneSymbol('rejectionHandledHandler')] =
|
||||
findPromiseRejectionHandler('rejectionhandled');
|
||||
}
|
||||
});
|
16
packages/zone.js/lib/browser/canvas.ts
Normal file
16
packages/zone.js/lib/browser/canvas.ts
Normal file
@ -0,0 +1,16 @@
|
||||
/**
|
||||
* @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('canvas', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
const HTMLCanvasElement = global['HTMLCanvasElement'];
|
||||
if (typeof HTMLCanvasElement !== 'undefined' && HTMLCanvasElement.prototype &&
|
||||
HTMLCanvasElement.prototype.toBlob) {
|
||||
api.patchMacroTask(HTMLCanvasElement.prototype, 'toBlob', (self: any, args: any[]) => {
|
||||
return {name: 'HTMLCanvasElement.toBlob', target: self, cbIdx: 0, args: args};
|
||||
});
|
||||
}
|
||||
});
|
19
packages/zone.js/lib/browser/custom-elements.ts
Normal file
19
packages/zone.js/lib/browser/custom-elements.ts
Normal file
@ -0,0 +1,19 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
export function patchCustomElements(_global: any, api: _ZonePrivate) {
|
||||
const {isBrowser, isMix} = api.getGlobalObjects() !;
|
||||
if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const callbacks =
|
||||
['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
|
||||
|
||||
api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
|
||||
}
|
111
packages/zone.js/lib/browser/define-property.ts
Normal file
111
packages/zone.js/lib/browser/define-property.ts
Normal file
@ -0,0 +1,111 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
/*
|
||||
* This is necessary for Chrome and Chrome mobile, to enable
|
||||
* things like redefining `createdCallback` on an element.
|
||||
*/
|
||||
|
||||
const zoneSymbol = Zone.__symbol__;
|
||||
const _defineProperty = (Object as any)[zoneSymbol('defineProperty')] = Object.defineProperty;
|
||||
const _getOwnPropertyDescriptor = (Object as any)[zoneSymbol('getOwnPropertyDescriptor')] =
|
||||
Object.getOwnPropertyDescriptor;
|
||||
const _create = Object.create;
|
||||
const unconfigurablesKey = zoneSymbol('unconfigurables');
|
||||
|
||||
export function propertyPatch() {
|
||||
Object.defineProperty = function(obj: any, prop: string, desc: any) {
|
||||
if (isUnconfigurable(obj, prop)) {
|
||||
throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj);
|
||||
}
|
||||
const originalConfigurableFlag = desc.configurable;
|
||||
if (prop !== 'prototype') {
|
||||
desc = rewriteDescriptor(obj, prop, desc);
|
||||
}
|
||||
return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
|
||||
};
|
||||
|
||||
Object.defineProperties = function(obj, props) {
|
||||
Object.keys(props).forEach(function(prop) { Object.defineProperty(obj, prop, props[prop]); });
|
||||
return obj;
|
||||
};
|
||||
|
||||
Object.create = <any>function(obj: any, proto: any) {
|
||||
if (typeof proto === 'object' && !Object.isFrozen(proto)) {
|
||||
Object.keys(proto).forEach(function(prop) {
|
||||
proto[prop] = rewriteDescriptor(obj, prop, proto[prop]);
|
||||
});
|
||||
}
|
||||
return _create(obj, proto);
|
||||
};
|
||||
|
||||
Object.getOwnPropertyDescriptor = function(obj, prop) {
|
||||
const desc = _getOwnPropertyDescriptor(obj, prop);
|
||||
if (desc && isUnconfigurable(obj, prop)) {
|
||||
desc.configurable = false;
|
||||
}
|
||||
return desc;
|
||||
};
|
||||
}
|
||||
|
||||
export function _redefineProperty(obj: any, prop: string, desc: any) {
|
||||
const originalConfigurableFlag = desc.configurable;
|
||||
desc = rewriteDescriptor(obj, prop, desc);
|
||||
return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag);
|
||||
}
|
||||
|
||||
function isUnconfigurable(obj: any, prop: any) {
|
||||
return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop];
|
||||
}
|
||||
|
||||
function rewriteDescriptor(obj: any, prop: string, desc: any) {
|
||||
// issue-927, if the desc is frozen, don't try to change the desc
|
||||
if (!Object.isFrozen(desc)) {
|
||||
desc.configurable = true;
|
||||
}
|
||||
if (!desc.configurable) {
|
||||
// issue-927, if the obj is frozen, don't try to set the desc to obj
|
||||
if (!obj[unconfigurablesKey] && !Object.isFrozen(obj)) {
|
||||
_defineProperty(obj, unconfigurablesKey, {writable: true, value: {}});
|
||||
}
|
||||
if (obj[unconfigurablesKey]) {
|
||||
obj[unconfigurablesKey][prop] = true;
|
||||
}
|
||||
}
|
||||
return desc;
|
||||
}
|
||||
|
||||
function _tryDefineProperty(obj: any, prop: string, desc: any, originalConfigurableFlag: any) {
|
||||
try {
|
||||
return _defineProperty(obj, prop, desc);
|
||||
} catch (error) {
|
||||
if (desc.configurable) {
|
||||
// In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's
|
||||
// retry with the original flag value
|
||||
if (typeof originalConfigurableFlag == 'undefined') {
|
||||
delete desc.configurable;
|
||||
} else {
|
||||
desc.configurable = originalConfigurableFlag;
|
||||
}
|
||||
try {
|
||||
return _defineProperty(obj, prop, desc);
|
||||
} catch (error) {
|
||||
let descJson: string|null = null;
|
||||
try {
|
||||
descJson = JSON.stringify(desc);
|
||||
} catch (error) {
|
||||
descJson = desc.toString();
|
||||
}
|
||||
console.log(`Attempting to configure '${prop}' with descriptor '${descJson}' on object '${
|
||||
obj}' and got error, giving up: ${error}`);
|
||||
}
|
||||
} else {
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
110
packages/zone.js/lib/browser/event-target-legacy.ts
Normal file
110
packages/zone.js/lib/browser/event-target-legacy.ts
Normal file
@ -0,0 +1,110 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
export function eventTargetLegacyPatch(_global: any, api: _ZonePrivate) {
|
||||
const {eventNames, globalSources, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX} =
|
||||
api.getGlobalObjects() !;
|
||||
const WTF_ISSUE_555 =
|
||||
'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video';
|
||||
const NO_EVENT_TARGET =
|
||||
'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket'
|
||||
.split(',');
|
||||
const EVENT_TARGET = 'EventTarget';
|
||||
|
||||
let apis: any[] = [];
|
||||
const isWtf = _global['wtf'];
|
||||
const WTF_ISSUE_555_ARRAY = WTF_ISSUE_555.split(',');
|
||||
|
||||
if (isWtf) {
|
||||
// Workaround for: https://github.com/google/tracing-framework/issues/555
|
||||
apis = WTF_ISSUE_555_ARRAY.map((v) => 'HTML' + v + 'Element').concat(NO_EVENT_TARGET);
|
||||
} else if (_global[EVENT_TARGET]) {
|
||||
apis.push(EVENT_TARGET);
|
||||
} else {
|
||||
// Note: EventTarget is not available in all browsers,
|
||||
// if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget
|
||||
apis = NO_EVENT_TARGET;
|
||||
}
|
||||
|
||||
const isDisableIECheck = _global['__Zone_disable_IE_check'] || false;
|
||||
const isEnableCrossContextCheck = _global['__Zone_enable_cross_context_check'] || false;
|
||||
const ieOrEdge = api.isIEOrEdge();
|
||||
|
||||
const ADD_EVENT_LISTENER_SOURCE = '.addEventListener:';
|
||||
const FUNCTION_WRAPPER = '[object FunctionWrapper]';
|
||||
const BROWSER_TOOLS = 'function __BROWSERTOOLS_CONSOLE_SAFEFUNC() { [native code] }';
|
||||
|
||||
// predefine all __zone_symbol__ + eventName + true/false string
|
||||
for (let i = 0; i < eventNames.length; i++) {
|
||||
const eventName = eventNames[i];
|
||||
const falseEventName = eventName + FALSE_STR;
|
||||
const trueEventName = eventName + TRUE_STR;
|
||||
const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
|
||||
const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
|
||||
zoneSymbolEventNames[eventName] = {};
|
||||
zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
|
||||
zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
|
||||
}
|
||||
|
||||
// predefine all task.source string
|
||||
for (let i = 0; i < WTF_ISSUE_555.length; i++) {
|
||||
const target: any = WTF_ISSUE_555_ARRAY[i];
|
||||
const targets: any = globalSources[target] = {};
|
||||
for (let j = 0; j < eventNames.length; j++) {
|
||||
const eventName = eventNames[j];
|
||||
targets[eventName] = target + ADD_EVENT_LISTENER_SOURCE + eventName;
|
||||
}
|
||||
}
|
||||
|
||||
const checkIEAndCrossContext = function(
|
||||
nativeDelegate: any, delegate: any, target: any, args: any) {
|
||||
if (!isDisableIECheck && ieOrEdge) {
|
||||
if (isEnableCrossContextCheck) {
|
||||
try {
|
||||
const testString = delegate.toString();
|
||||
if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
|
||||
nativeDelegate.apply(target, args);
|
||||
return false;
|
||||
}
|
||||
} catch (error) {
|
||||
nativeDelegate.apply(target, args);
|
||||
return false;
|
||||
}
|
||||
} else {
|
||||
const testString = delegate.toString();
|
||||
if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) {
|
||||
nativeDelegate.apply(target, args);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
} else if (isEnableCrossContextCheck) {
|
||||
try {
|
||||
delegate.toString();
|
||||
} catch (error) {
|
||||
nativeDelegate.apply(target, args);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
return true;
|
||||
};
|
||||
|
||||
const apiTypes: any[] = [];
|
||||
for (let i = 0; i < apis.length; i++) {
|
||||
const type = _global[apis[i]];
|
||||
apiTypes.push(type && type.prototype);
|
||||
}
|
||||
// vh is validateHandler to check event handler
|
||||
// is valid or not(for security check)
|
||||
api.patchEventTarget(_global, apiTypes, {vh: checkIEAndCrossContext});
|
||||
(Zone as any)[api.symbol('patchEventTarget')] = !!_global[EVENT_TARGET];
|
||||
return true;
|
||||
}
|
||||
|
||||
export function patchEvent(global: any, api: _ZonePrivate) {
|
||||
api.patchEventPrototype(global, api);
|
||||
}
|
39
packages/zone.js/lib/browser/event-target.ts
Normal file
39
packages/zone.js/lib/browser/event-target.ts
Normal file
@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
export function eventTargetPatch(_global: any, api: _ZonePrivate) {
|
||||
if ((Zone as any)[api.symbol('patchEventTarget')]) {
|
||||
// EventTarget is already patched.
|
||||
return;
|
||||
}
|
||||
const {eventNames, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX} =
|
||||
api.getGlobalObjects() !;
|
||||
// predefine all __zone_symbol__ + eventName + true/false string
|
||||
for (let i = 0; i < eventNames.length; i++) {
|
||||
const eventName = eventNames[i];
|
||||
const falseEventName = eventName + FALSE_STR;
|
||||
const trueEventName = eventName + TRUE_STR;
|
||||
const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
|
||||
const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
|
||||
zoneSymbolEventNames[eventName] = {};
|
||||
zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
|
||||
zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
|
||||
}
|
||||
|
||||
const EVENT_TARGET = _global['EventTarget'];
|
||||
if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
|
||||
return;
|
||||
}
|
||||
api.patchEventTarget(_global, [EVENT_TARGET && EVENT_TARGET.prototype]);
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
export function patchEvent(global: any, api: _ZonePrivate) {
|
||||
api.patchEventPrototype(global, api);
|
||||
}
|
124
packages/zone.js/lib/browser/property-descriptor-legacy.ts
Normal file
124
packages/zone.js/lib/browser/property-descriptor-legacy.ts
Normal file
@ -0,0 +1,124 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {globalThis}
|
||||
*/
|
||||
|
||||
import * as webSocketPatch from './websocket';
|
||||
|
||||
export function propertyDescriptorLegacyPatch(api: _ZonePrivate, _global: any) {
|
||||
const {isNode, isMix} = api.getGlobalObjects() !;
|
||||
if (isNode && !isMix) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!canPatchViaPropertyDescriptor(api, _global)) {
|
||||
const supportsWebSocket = typeof WebSocket !== 'undefined';
|
||||
// Safari, Android browsers (Jelly Bean)
|
||||
patchViaCapturingAllTheEvents(api);
|
||||
api.patchClass('XMLHttpRequest');
|
||||
if (supportsWebSocket) {
|
||||
webSocketPatch.apply(api, _global);
|
||||
}
|
||||
(Zone as any)[api.symbol('patchEvents')] = true;
|
||||
}
|
||||
}
|
||||
|
||||
function canPatchViaPropertyDescriptor(api: _ZonePrivate, _global: any) {
|
||||
const {isBrowser, isMix} = api.getGlobalObjects() !;
|
||||
if ((isBrowser || isMix) &&
|
||||
!api.ObjectGetOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') &&
|
||||
typeof Element !== 'undefined') {
|
||||
// WebKit https://bugs.webkit.org/show_bug.cgi?id=134364
|
||||
// IDL interface attributes are not configurable
|
||||
const desc = api.ObjectGetOwnPropertyDescriptor(Element.prototype, 'onclick');
|
||||
if (desc && !desc.configurable) return false;
|
||||
// try to use onclick to detect whether we can patch via propertyDescriptor
|
||||
// because XMLHttpRequest is not available in service worker
|
||||
if (desc) {
|
||||
api.ObjectDefineProperty(
|
||||
Element.prototype, 'onclick',
|
||||
{enumerable: true, configurable: true, get: function() { return true; }});
|
||||
const div = document.createElement('div');
|
||||
const result = !!div.onclick;
|
||||
api.ObjectDefineProperty(Element.prototype, 'onclick', desc);
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
const XMLHttpRequest = _global['XMLHttpRequest'];
|
||||
if (!XMLHttpRequest) {
|
||||
// XMLHttpRequest is not available in service worker
|
||||
return false;
|
||||
}
|
||||
const ON_READY_STATE_CHANGE = 'onreadystatechange';
|
||||
const XMLHttpRequestPrototype = XMLHttpRequest.prototype;
|
||||
|
||||
const xhrDesc =
|
||||
api.ObjectGetOwnPropertyDescriptor(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE);
|
||||
|
||||
// add enumerable and configurable here because in opera
|
||||
// by default XMLHttpRequest.prototype.onreadystatechange is undefined
|
||||
// without adding enumerable and configurable will cause onreadystatechange
|
||||
// non-configurable
|
||||
// and if XMLHttpRequest.prototype.onreadystatechange is undefined,
|
||||
// we should set a real desc instead a fake one
|
||||
if (xhrDesc) {
|
||||
api.ObjectDefineProperty(
|
||||
XMLHttpRequestPrototype, ON_READY_STATE_CHANGE,
|
||||
{enumerable: true, configurable: true, get: function() { return true; }});
|
||||
const req = new XMLHttpRequest();
|
||||
const result = !!req.onreadystatechange;
|
||||
// restore original desc
|
||||
api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, xhrDesc || {});
|
||||
return result;
|
||||
} else {
|
||||
const SYMBOL_FAKE_ONREADYSTATECHANGE = api.symbol('fake');
|
||||
api.ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, {
|
||||
enumerable: true,
|
||||
configurable: true,
|
||||
get: function() { return this[SYMBOL_FAKE_ONREADYSTATECHANGE]; },
|
||||
set: function(value) { this[SYMBOL_FAKE_ONREADYSTATECHANGE] = value; }
|
||||
});
|
||||
const req = new XMLHttpRequest();
|
||||
const detectFunc = () => {};
|
||||
req.onreadystatechange = detectFunc;
|
||||
const result = (req as any)[SYMBOL_FAKE_ONREADYSTATECHANGE] === detectFunc;
|
||||
req.onreadystatechange = null as any;
|
||||
return result;
|
||||
}
|
||||
}
|
||||
|
||||
// Whenever any eventListener fires, we check the eventListener target and all parents
|
||||
// for `onwhatever` properties and replace them with zone-bound functions
|
||||
// - Chrome (for now)
|
||||
function patchViaCapturingAllTheEvents(api: _ZonePrivate) {
|
||||
const {eventNames} = api.getGlobalObjects() !;
|
||||
const unboundKey = api.symbol('unbound');
|
||||
for (let i = 0; i < eventNames.length; i++) {
|
||||
const property = eventNames[i];
|
||||
const onproperty = 'on' + property;
|
||||
self.addEventListener(property, function(event) {
|
||||
let elt: any = <Node>event.target, bound, source;
|
||||
if (elt) {
|
||||
source = elt.constructor['name'] + '.' + onproperty;
|
||||
} else {
|
||||
source = 'unknown.' + onproperty;
|
||||
}
|
||||
while (elt) {
|
||||
if (elt[onproperty] && !elt[onproperty][unboundKey]) {
|
||||
bound = api.wrapWithCurrentZone(elt[onproperty], source);
|
||||
bound[unboundKey] = elt[onproperty];
|
||||
elt[onproperty] = bound;
|
||||
}
|
||||
elt = elt.parentElement;
|
||||
}
|
||||
}, true);
|
||||
}
|
||||
}
|
334
packages/zone.js/lib/browser/property-descriptor.ts
Normal file
334
packages/zone.js/lib/browser/property-descriptor.ts
Normal file
@ -0,0 +1,334 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {globalThis}
|
||||
*/
|
||||
|
||||
import {ObjectGetPrototypeOf, isBrowser, isIE, isMix, isNode, patchOnProperties} from '../common/utils';
|
||||
|
||||
const globalEventHandlersEventNames = [
|
||||
'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'
|
||||
];
|
||||
const documentEventNames = [
|
||||
'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'freeze', 'fullscreenchange',
|
||||
'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror',
|
||||
'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange',
|
||||
'visibilitychange', 'resume'
|
||||
];
|
||||
const windowEventNames = [
|
||||
'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'
|
||||
];
|
||||
const htmlElementEventNames = [
|
||||
'beforecopy', 'beforecut', 'beforepaste', 'copy', 'cut', 'paste', 'dragstart', 'loadend',
|
||||
'animationstart', 'search', 'transitionrun', 'transitionstart', 'webkitanimationend',
|
||||
'webkitanimationiteration', 'webkitanimationstart', 'webkittransitionend'
|
||||
];
|
||||
const mediaElementEventNames =
|
||||
['encrypted', 'waitingforkey', 'msneedkey', 'mozinterruptbegin', 'mozinterruptend'];
|
||||
const ieElementEventNames = [
|
||||
'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'
|
||||
];
|
||||
const webglEventNames = ['webglcontextrestored', 'webglcontextlost', 'webglcontextcreationerror'];
|
||||
const formEventNames = ['autocomplete', 'autocompleteerror'];
|
||||
const detailEventNames = ['toggle'];
|
||||
const frameEventNames = ['load'];
|
||||
const frameSetEventNames = ['blur', 'error', 'focus', 'load', 'resize', 'scroll', 'messageerror'];
|
||||
const marqueeEventNames = ['bounce', 'finish', 'start'];
|
||||
|
||||
const XMLHttpRequestEventNames = [
|
||||
'loadstart', 'progress', 'abort', 'error', 'load', 'progress', 'timeout', 'loadend',
|
||||
'readystatechange'
|
||||
];
|
||||
const IDBIndexEventNames =
|
||||
['upgradeneeded', 'complete', 'abort', 'success', 'error', 'blocked', 'versionchange', 'close'];
|
||||
const websocketEventNames = ['close', 'error', 'open', 'message'];
|
||||
const workerEventNames = ['error', 'message'];
|
||||
|
||||
export const eventNames = globalEventHandlersEventNames.concat(
|
||||
webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames,
|
||||
htmlElementEventNames, ieElementEventNames);
|
||||
|
||||
export interface IgnoreProperty {
|
||||
target: any;
|
||||
ignoreProperties: string[];
|
||||
}
|
||||
|
||||
export function filterProperties(
|
||||
target: any, onProperties: string[], ignoreProperties: IgnoreProperty[]): string[] {
|
||||
if (!ignoreProperties || ignoreProperties.length === 0) {
|
||||
return onProperties;
|
||||
}
|
||||
|
||||
const tip: IgnoreProperty[] = ignoreProperties.filter(ip => ip.target === target);
|
||||
if (!tip || tip.length === 0) {
|
||||
return onProperties;
|
||||
}
|
||||
|
||||
const targetIgnoreProperties: string[] = tip[0].ignoreProperties;
|
||||
return onProperties.filter(op => targetIgnoreProperties.indexOf(op) === -1);
|
||||
}
|
||||
|
||||
export function patchFilteredProperties(
|
||||
target: any, onProperties: string[], ignoreProperties: IgnoreProperty[], prototype?: any) {
|
||||
// check whether target is available, sometimes target will be undefined
|
||||
// because different browser or some 3rd party plugin.
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
const filteredProperties: string[] = filterProperties(target, onProperties, ignoreProperties);
|
||||
patchOnProperties(target, filteredProperties, prototype);
|
||||
}
|
||||
|
||||
export function propertyDescriptorPatch(api: _ZonePrivate, _global: any) {
|
||||
if (isNode && !isMix) {
|
||||
return;
|
||||
}
|
||||
if ((Zone as any)[api.symbol('patchEvents')]) {
|
||||
// events are already been patched by legacy patch.
|
||||
return;
|
||||
}
|
||||
const supportsWebSocket = typeof WebSocket !== 'undefined';
|
||||
const ignoreProperties: IgnoreProperty[] = _global['__Zone_ignore_on_properties'];
|
||||
// for browsers that we can patch the descriptor: Chrome & Firefox
|
||||
if (isBrowser) {
|
||||
const internalWindow: any = window;
|
||||
const 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 ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties,
|
||||
ObjectGetPrototypeOf(internalWindow));
|
||||
patchFilteredProperties(Document.prototype, eventNames, ignoreProperties);
|
||||
|
||||
if (typeof internalWindow['SVGElement'] !== 'undefined') {
|
||||
patchFilteredProperties(internalWindow['SVGElement'].prototype, eventNames, ignoreProperties);
|
||||
}
|
||||
patchFilteredProperties(Element.prototype, eventNames, ignoreProperties);
|
||||
patchFilteredProperties(HTMLElement.prototype, eventNames, ignoreProperties);
|
||||
patchFilteredProperties(HTMLMediaElement.prototype, mediaElementEventNames, ignoreProperties);
|
||||
patchFilteredProperties(
|
||||
HTMLFrameSetElement.prototype, windowEventNames.concat(frameSetEventNames),
|
||||
ignoreProperties);
|
||||
patchFilteredProperties(
|
||||
HTMLBodyElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
|
||||
patchFilteredProperties(HTMLFrameElement.prototype, frameEventNames, ignoreProperties);
|
||||
patchFilteredProperties(HTMLIFrameElement.prototype, frameEventNames, ignoreProperties);
|
||||
|
||||
const HTMLMarqueeElement = internalWindow['HTMLMarqueeElement'];
|
||||
if (HTMLMarqueeElement) {
|
||||
patchFilteredProperties(HTMLMarqueeElement.prototype, marqueeEventNames, ignoreProperties);
|
||||
}
|
||||
const Worker = internalWindow['Worker'];
|
||||
if (Worker) {
|
||||
patchFilteredProperties(Worker.prototype, workerEventNames, ignoreProperties);
|
||||
}
|
||||
}
|
||||
const XMLHttpRequest = _global['XMLHttpRequest'];
|
||||
if (XMLHttpRequest) {
|
||||
// XMLHttpRequest is not available in ServiceWorker, so we need to check here
|
||||
patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties);
|
||||
}
|
||||
const XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget'];
|
||||
if (XMLHttpRequestEventTarget) {
|
||||
patchFilteredProperties(
|
||||
XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames,
|
||||
ignoreProperties);
|
||||
}
|
||||
if (typeof IDBIndex !== 'undefined') {
|
||||
patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties);
|
||||
patchFilteredProperties(IDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
|
||||
patchFilteredProperties(IDBOpenDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
|
||||
patchFilteredProperties(IDBDatabase.prototype, IDBIndexEventNames, ignoreProperties);
|
||||
patchFilteredProperties(IDBTransaction.prototype, IDBIndexEventNames, ignoreProperties);
|
||||
patchFilteredProperties(IDBCursor.prototype, IDBIndexEventNames, ignoreProperties);
|
||||
}
|
||||
if (supportsWebSocket) {
|
||||
patchFilteredProperties(WebSocket.prototype, websocketEventNames, ignoreProperties);
|
||||
}
|
||||
}
|
19
packages/zone.js/lib/browser/register-element.ts
Normal file
19
packages/zone.js/lib/browser/register-element.ts
Normal file
@ -0,0 +1,19 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
export function registerElementPatch(_global: any, api: _ZonePrivate) {
|
||||
const {isBrowser, isMix} = api.getGlobalObjects() !;
|
||||
if ((!isBrowser && !isMix) || !('registerElement' in (<any>_global).document)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const callbacks =
|
||||
['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback'];
|
||||
|
||||
api.patchCallbacks(api, document, 'Document', 'registerElement', callbacks);
|
||||
}
|
12
packages/zone.js/lib/browser/rollup-common.ts
Normal file
12
packages/zone.js/lib/browser/rollup-common.ts
Normal file
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import '../zone';
|
||||
import '../common/promise';
|
||||
import '../common/to-string';
|
||||
import './api-util';
|
11
packages/zone.js/lib/browser/rollup-legacy-main.ts
Normal file
11
packages/zone.js/lib/browser/rollup-legacy-main.ts
Normal file
@ -0,0 +1,11 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import './rollup-common';
|
||||
import './browser-legacy';
|
||||
import './browser';
|
12
packages/zone.js/lib/browser/rollup-legacy-test-main.ts
Normal file
12
packages/zone.js/lib/browser/rollup-legacy-test-main.ts
Normal file
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import './rollup-legacy-main';
|
||||
|
||||
// load test related files into bundle
|
||||
import '../testing/zone-testing';
|
10
packages/zone.js/lib/browser/rollup-main.ts
Normal file
10
packages/zone.js/lib/browser/rollup-main.ts
Normal file
@ -0,0 +1,10 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import './rollup-common';
|
||||
import './browser';
|
12
packages/zone.js/lib/browser/rollup-test-main.ts
Normal file
12
packages/zone.js/lib/browser/rollup-test-main.ts
Normal file
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import './rollup-main';
|
||||
|
||||
// load test related files into bundle
|
||||
import '../testing/zone-testing';
|
24
packages/zone.js/lib/browser/shadydom.ts
Normal file
24
packages/zone.js/lib/browser/shadydom.ts
Normal file
@ -0,0 +1,24 @@
|
||||
/**
|
||||
* @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('shadydom', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
// https://github.com/angular/zone.js/issues/782
|
||||
// in web components, shadydom will patch addEventListener/removeEventListener of
|
||||
// Node.prototype and WindowPrototype, this will have conflict with zone.js
|
||||
// so zone.js need to patch them again.
|
||||
const windowPrototype = Object.getPrototypeOf(window);
|
||||
if (windowPrototype && windowPrototype.hasOwnProperty('addEventListener')) {
|
||||
(windowPrototype as any)[Zone.__symbol__('addEventListener')] = null;
|
||||
(windowPrototype as any)[Zone.__symbol__('removeEventListener')] = null;
|
||||
api.patchEventTarget(global, [windowPrototype]);
|
||||
}
|
||||
if (Node.prototype.hasOwnProperty('addEventListener')) {
|
||||
(Node.prototype as any)[Zone.__symbol__('addEventListener')] = null;
|
||||
(Node.prototype as any)[Zone.__symbol__('removeEventListener')] = null;
|
||||
api.patchEventTarget(global, [Node.prototype]);
|
||||
}
|
||||
});
|
65
packages/zone.js/lib/browser/webapis-media-query.ts
Normal file
65
packages/zone.js/lib/browser/webapis-media-query.ts
Normal file
@ -0,0 +1,65 @@
|
||||
/**
|
||||
* @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('mediaQuery', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
function patchAddListener(proto: any) {
|
||||
api.patchMethod(proto, 'addListener', (delegate: Function) => (self: any, args: any[]) => {
|
||||
const callback = args.length > 0 ? args[0] : null;
|
||||
if (typeof callback === 'function') {
|
||||
const wrapperedCallback = Zone.current.wrap(callback, 'MediaQuery');
|
||||
callback[api.symbol('mediaQueryCallback')] = wrapperedCallback;
|
||||
return delegate.call(self, wrapperedCallback);
|
||||
} else {
|
||||
return delegate.apply(self, args);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
function patchRemoveListener(proto: any) {
|
||||
api.patchMethod(proto, 'removeListener', (delegate: Function) => (self: any, args: any[]) => {
|
||||
const callback = args.length > 0 ? args[0] : null;
|
||||
if (typeof callback === 'function') {
|
||||
const wrapperedCallback = callback[api.symbol('mediaQueryCallback')];
|
||||
if (wrapperedCallback) {
|
||||
return delegate.call(self, wrapperedCallback);
|
||||
} else {
|
||||
return delegate.apply(self, args);
|
||||
}
|
||||
} else {
|
||||
return delegate.apply(self, args);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (global['MediaQueryList']) {
|
||||
const proto = global['MediaQueryList'].prototype;
|
||||
patchAddListener(proto);
|
||||
patchRemoveListener(proto);
|
||||
} else if (global['matchMedia']) {
|
||||
api.patchMethod(global, 'matchMedia', (delegate: Function) => (self: any, args: any[]) => {
|
||||
const mql = delegate.apply(self, args);
|
||||
if (mql) {
|
||||
// try to patch MediaQueryList.prototype
|
||||
const proto = Object.getPrototypeOf(mql);
|
||||
if (proto && proto['addListener']) {
|
||||
// try to patch proto, don't need to worry about patch
|
||||
// multiple times, because, api.patchEventTarget will check it
|
||||
patchAddListener(proto);
|
||||
patchRemoveListener(proto);
|
||||
patchAddListener(mql);
|
||||
patchRemoveListener(mql);
|
||||
} else if (mql['addListener']) {
|
||||
// proto not exists, or proto has no addListener method
|
||||
// try to patch mql instance
|
||||
patchAddListener(mql);
|
||||
patchRemoveListener(mql);
|
||||
}
|
||||
}
|
||||
return mql;
|
||||
});
|
||||
}
|
||||
});
|
18
packages/zone.js/lib/browser/webapis-notification.ts
Normal file
18
packages/zone.js/lib/browser/webapis-notification.ts
Normal file
@ -0,0 +1,18 @@
|
||||
/**
|
||||
* @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('notification', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
const Notification = global['Notification'];
|
||||
if (!Notification || !Notification.prototype) {
|
||||
return;
|
||||
}
|
||||
const desc = Object.getOwnPropertyDescriptor(Notification.prototype, 'onerror');
|
||||
if (!desc || !desc.configurable) {
|
||||
return;
|
||||
}
|
||||
api.patchOnProperties(Notification.prototype, null);
|
||||
});
|
91
packages/zone.js/lib/browser/webapis-resize-observer.ts
Normal file
91
packages/zone.js/lib/browser/webapis-resize-observer.ts
Normal file
@ -0,0 +1,91 @@
|
||||
/**
|
||||
* @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('ResizeObserver', (global: any, Zone: any, api: _ZonePrivate) => {
|
||||
const ResizeObserver = global['ResizeObserver'];
|
||||
if (!ResizeObserver) {
|
||||
return;
|
||||
}
|
||||
|
||||
const resizeObserverSymbol = api.symbol('ResizeObserver');
|
||||
|
||||
api.patchMethod(global, 'ResizeObserver', (delegate: Function) => (self: any, args: any[]) => {
|
||||
const callback = args.length > 0 ? args[0] : null;
|
||||
if (callback) {
|
||||
args[0] = function(entries: any, observer: any) {
|
||||
const zones: {[zoneName: string]: any} = {};
|
||||
const currZone = Zone.current;
|
||||
for (let entry of entries) {
|
||||
let zone = entry.target[resizeObserverSymbol];
|
||||
if (!zone) {
|
||||
zone = currZone;
|
||||
}
|
||||
let zoneEntriesInfo = zones[zone.name];
|
||||
if (!zoneEntriesInfo) {
|
||||
zones[zone.name] = zoneEntriesInfo = {entries: [], zone: zone};
|
||||
}
|
||||
zoneEntriesInfo.entries.push(entry);
|
||||
}
|
||||
|
||||
Object.keys(zones).forEach(zoneName => {
|
||||
const zoneEntriesInfo = zones[zoneName];
|
||||
if (zoneEntriesInfo.zone !== Zone.current) {
|
||||
zoneEntriesInfo.zone.run(
|
||||
callback, this, [zoneEntriesInfo.entries, observer], 'ResizeObserver');
|
||||
} else {
|
||||
callback.call(this, zoneEntriesInfo.entries, observer);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
return args.length > 0 ? new ResizeObserver(args[0]) : new ResizeObserver();
|
||||
});
|
||||
|
||||
api.patchMethod(
|
||||
ResizeObserver.prototype, 'observe', (delegate: Function) => (self: any, args: any[]) => {
|
||||
const target = args.length > 0 ? args[0] : null;
|
||||
if (!target) {
|
||||
return delegate.apply(self, args);
|
||||
}
|
||||
let targets = self[resizeObserverSymbol];
|
||||
if (!targets) {
|
||||
targets = self[resizeObserverSymbol] = [];
|
||||
}
|
||||
targets.push(target);
|
||||
target[resizeObserverSymbol] = Zone.current;
|
||||
return delegate.apply(self, args);
|
||||
});
|
||||
|
||||
api.patchMethod(
|
||||
ResizeObserver.prototype, 'unobserve', (delegate: Function) => (self: any, args: any[]) => {
|
||||
const target = args.length > 0 ? args[0] : null;
|
||||
if (!target) {
|
||||
return delegate.apply(self, args);
|
||||
}
|
||||
let targets = self[resizeObserverSymbol];
|
||||
if (targets) {
|
||||
for (let i = 0; i < targets.length; i++) {
|
||||
if (targets[i] === target) {
|
||||
targets.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
target[resizeObserverSymbol] = undefined;
|
||||
return delegate.apply(self, args);
|
||||
});
|
||||
|
||||
api.patchMethod(
|
||||
ResizeObserver.prototype, 'disconnect', (delegate: Function) => (self: any, args: any[]) => {
|
||||
const targets = self[resizeObserverSymbol];
|
||||
if (targets) {
|
||||
targets.forEach((target: any) => { target[resizeObserverSymbol] = undefined; });
|
||||
self[resizeObserverSymbol] = undefined;
|
||||
}
|
||||
return delegate.apply(self, args);
|
||||
});
|
||||
});
|
26
packages/zone.js/lib/browser/webapis-rtc-peer-connection.ts
Normal file
26
packages/zone.js/lib/browser/webapis-rtc-peer-connection.ts
Normal file
@ -0,0 +1,26 @@
|
||||
/**
|
||||
* @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('RTCPeerConnection', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
const RTCPeerConnection = global['RTCPeerConnection'];
|
||||
if (!RTCPeerConnection) {
|
||||
return;
|
||||
}
|
||||
|
||||
const addSymbol = api.symbol('addEventListener');
|
||||
const removeSymbol = api.symbol('removeEventListener');
|
||||
|
||||
RTCPeerConnection.prototype.addEventListener = RTCPeerConnection.prototype[addSymbol];
|
||||
RTCPeerConnection.prototype.removeEventListener = RTCPeerConnection.prototype[removeSymbol];
|
||||
|
||||
// RTCPeerConnection extends EventTarget, so we must clear the symbol
|
||||
// to allow patch RTCPeerConnection.prototype.addEventListener again
|
||||
RTCPeerConnection.prototype[addSymbol] = null;
|
||||
RTCPeerConnection.prototype[removeSymbol] = null;
|
||||
|
||||
api.patchEventTarget(global, [RTCPeerConnection.prototype], {useG: false});
|
||||
});
|
20
packages/zone.js/lib/browser/webapis-user-media.ts
Normal file
20
packages/zone.js/lib/browser/webapis-user-media.ts
Normal file
@ -0,0 +1,20 @@
|
||||
/**
|
||||
* @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('getUserMedia', (global: any, Zone: any, api: _ZonePrivate) => {
|
||||
function wrapFunctionArgs(func: Function, source?: string): Function {
|
||||
return function() {
|
||||
const args = Array.prototype.slice.call(arguments);
|
||||
const wrappedArgs = api.bindArguments(args, source ? source : (func as any).name);
|
||||
return func.apply(this, wrappedArgs);
|
||||
};
|
||||
}
|
||||
let navigator = global['navigator'];
|
||||
if (navigator && navigator.getUserMedia) {
|
||||
navigator.getUserMedia = wrapFunctionArgs(navigator.getUserMedia);
|
||||
}
|
||||
});
|
59
packages/zone.js/lib/browser/websocket.ts
Normal file
59
packages/zone.js/lib/browser/websocket.ts
Normal file
@ -0,0 +1,59 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
// we have to patch the instance since the proto is non-configurable
|
||||
export function apply(api: _ZonePrivate, _global: any) {
|
||||
const {ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR} = api.getGlobalObjects() !;
|
||||
const WS = (<any>_global).WebSocket;
|
||||
// On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener
|
||||
// On older Chrome, no need since EventTarget was already patched
|
||||
if (!(<any>_global).EventTarget) {
|
||||
api.patchEventTarget(_global, [WS.prototype]);
|
||||
}
|
||||
(<any>_global).WebSocket = function(x: any, y: any) {
|
||||
const socket = arguments.length > 1 ? new WS(x, y) : new WS(x);
|
||||
let proxySocket: any;
|
||||
|
||||
let proxySocketProto: any;
|
||||
|
||||
// Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance
|
||||
const onmessageDesc = api.ObjectGetOwnPropertyDescriptor(socket, 'onmessage');
|
||||
if (onmessageDesc && onmessageDesc.configurable === false) {
|
||||
proxySocket = api.ObjectCreate(socket);
|
||||
// socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror'
|
||||
// but proxySocket not, so we will keep socket as prototype and pass it to
|
||||
// patchOnProperties method
|
||||
proxySocketProto = socket;
|
||||
[ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(function(
|
||||
propName) {
|
||||
proxySocket[propName] = function() {
|
||||
const args = api.ArraySlice.call(arguments);
|
||||
if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) {
|
||||
const eventName = args.length > 0 ? args[0] : undefined;
|
||||
if (eventName) {
|
||||
const propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName);
|
||||
socket[propertySymbol] = proxySocket[propertySymbol];
|
||||
}
|
||||
}
|
||||
return socket[propName].apply(socket, args);
|
||||
};
|
||||
});
|
||||
} else {
|
||||
// we can patch the real socket
|
||||
proxySocket = socket;
|
||||
}
|
||||
|
||||
api.patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto);
|
||||
return proxySocket;
|
||||
};
|
||||
|
||||
const globalWebSocket = _global['WebSocket'];
|
||||
for (const prop in WS) {
|
||||
globalWebSocket[prop] = WS[prop];
|
||||
}
|
||||
}
|
445
packages/zone.js/lib/closure/zone_externs.js
Normal file
445
packages/zone.js/lib/closure/zone_externs.js
Normal file
@ -0,0 +1,445 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
/**
|
||||
* @fileoverview Externs for zone.js
|
||||
* @see https://github.com/angular/zone.js
|
||||
* @externs
|
||||
*/
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
var Zone = function() {};
|
||||
/**
|
||||
* @type {!Zone} The parent Zone.
|
||||
*/
|
||||
Zone.prototype.parent;
|
||||
/**
|
||||
* @type {!string} The Zone name (useful for debugging)
|
||||
*/
|
||||
Zone.prototype.name;
|
||||
|
||||
Zone.assertZonePatched = function() {};
|
||||
|
||||
/**
|
||||
* @type {!Zone} Returns the current [Zone]. Returns the current zone. The only way to change
|
||||
* the current zone is by invoking a run() method, which will update the current zone for the
|
||||
* duration of the run method callback.
|
||||
*/
|
||||
Zone.current;
|
||||
|
||||
/**
|
||||
* @type {Task} The task associated with the current execution.
|
||||
*/
|
||||
Zone.currentTask;
|
||||
|
||||
/**
|
||||
* @type {!Zone} Return the root zone.
|
||||
*/
|
||||
Zone.root;
|
||||
|
||||
/**
|
||||
* Returns a value associated with the `key`.
|
||||
*
|
||||
* If the current zone does not have a key, the request is delegated to the parent zone. Use
|
||||
* [ZoneSpec.properties] to configure the set of properties associated with the current zone.
|
||||
*
|
||||
* @param {!string} key The key to retrieve.
|
||||
* @returns {?} The value for the key, or `undefined` if not found.
|
||||
*/
|
||||
Zone.prototype.get = function(key) {};
|
||||
|
||||
/**
|
||||
* Returns a Zone which defines a `key`.
|
||||
*
|
||||
* Recursively search the parent Zone until a Zone which has a property `key` is found.
|
||||
*
|
||||
* @param {!string} key The key to use for identification of the returned zone.
|
||||
* @returns {?Zone} The Zone which defines the `key`, `null` if not found.
|
||||
*/
|
||||
Zone.prototype.getZoneWith = function(key) {};
|
||||
|
||||
/**
|
||||
* Used to create a child zone.
|
||||
*
|
||||
* @param {!ZoneSpec} zoneSpec A set of rules which the child zone should follow.
|
||||
* @returns {!Zone} A new child zone.
|
||||
*/
|
||||
Zone.prototype.fork = function(zoneSpec) {};
|
||||
|
||||
/**
|
||||
* Wraps a callback function in a new function which will properly restore the current zone upon
|
||||
* invocation.
|
||||
*
|
||||
* The wrapped function will properly forward `this` as well as `arguments` to the `callback`.
|
||||
*
|
||||
* Before the function is wrapped the zone can intercept the `callback` by declaring
|
||||
* [ZoneSpec.onIntercept].
|
||||
*
|
||||
* @param {!Function} callback the function which will be wrapped in the zone.
|
||||
* @param {!string=} source A unique debug location of the API being wrapped.
|
||||
* @returns {!Function} A function which will invoke the `callback` through [Zone.runGuarded].
|
||||
*/
|
||||
Zone.prototype.wrap = function(callback, source) {};
|
||||
|
||||
/**
|
||||
* Invokes a function in a given zone.
|
||||
*
|
||||
* The invocation of `callback` can be intercepted be declaring [ZoneSpec.onInvoke].
|
||||
*
|
||||
* @param {!Function} callback The function to invoke.
|
||||
* @param {?Object=} applyThis
|
||||
* @param {?Array=} applyArgs
|
||||
* @param {?string=} source A unique debug location of the API being invoked.
|
||||
* @returns {*} Value from the `callback` function.
|
||||
*/
|
||||
Zone.prototype.run = function(callback, applyThis, applyArgs, source) {};
|
||||
|
||||
/**
|
||||
* Invokes a function in a given zone and catches any exceptions.
|
||||
*
|
||||
* Any exceptions thrown will be forwarded to [Zone.HandleError].
|
||||
*
|
||||
* The invocation of `callback` can be intercepted be declaring [ZoneSpec.onInvoke]. The
|
||||
* handling of exceptions can intercepted by declaring [ZoneSpec.handleError].
|
||||
*
|
||||
* @param {!Function} callback The function to invoke.
|
||||
* @param {?Object=} applyThis
|
||||
* @param {?Array=} applyArgs
|
||||
* @param {?string=} source A unique debug location of the API being invoked.
|
||||
* @returns {*} Value from the `callback` function.
|
||||
*/
|
||||
Zone.prototype.runGuarded = function(callback, applyThis, applyArgs, source) {};
|
||||
|
||||
/**
|
||||
* Execute the Task by restoring the [Zone.currentTask] in the Task's zone.
|
||||
*
|
||||
* @param {!Task} task
|
||||
* @param {?Object=} applyThis
|
||||
* @param {?Array=} applyArgs
|
||||
* @returns {*}
|
||||
*/
|
||||
Zone.prototype.runTask = function(task, applyThis, applyArgs) {};
|
||||
|
||||
/**
|
||||
* @param {string} source
|
||||
* @param {!Function} callback
|
||||
* @param {?TaskData=} data
|
||||
* @param {?function(!Task)=} customSchedule
|
||||
* @return {!MicroTask} microTask
|
||||
*/
|
||||
Zone.prototype.scheduleMicroTask = function(source, callback, data, customSchedule) {};
|
||||
|
||||
/**
|
||||
* @param {string} source
|
||||
* @param {!Function} callback
|
||||
* @param {?TaskData=} data
|
||||
* @param {?function(!Task)=} customSchedule
|
||||
* @param {?function(!Task)=} customCancel
|
||||
* @return {!MacroTask} macroTask
|
||||
*/
|
||||
Zone.prototype.scheduleMacroTask = function(source, callback, data, customSchedule, customCancel) {
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {string} source
|
||||
* @param {!Function} callback
|
||||
* @param {?TaskData=} data
|
||||
* @param {?function(!Task)=} customSchedule
|
||||
* @param {?function(!Task)=} customCancel
|
||||
* @return {!EventTask} eventTask
|
||||
*/
|
||||
Zone.prototype.scheduleEventTask = function(source, callback, data, customSchedule, customCancel) {
|
||||
};
|
||||
|
||||
/**
|
||||
* @param {!Task} task
|
||||
* @return {!Task} task
|
||||
*/
|
||||
Zone.prototype.scheduleTask = function(task) {};
|
||||
|
||||
/**
|
||||
* @param {!Task} task
|
||||
* @return {!Task} task
|
||||
*/
|
||||
Zone.prototype.cancelTask = function(task) {};
|
||||
|
||||
/**
|
||||
* @record
|
||||
*/
|
||||
var ZoneSpec = function() {};
|
||||
/**
|
||||
* @type {!string} The name of the zone. Usefull when debugging Zones.
|
||||
*/
|
||||
ZoneSpec.prototype.name;
|
||||
|
||||
/**
|
||||
* @type {Object<string, Object>|undefined} A set of properties to be associated with Zone. Use
|
||||
* [Zone.get] to retrieve them.
|
||||
*/
|
||||
ZoneSpec.prototype.properties;
|
||||
|
||||
/**
|
||||
* Allows the interception of zone forking.
|
||||
*
|
||||
* When the zone is being forked, the request is forwarded to this method for interception.
|
||||
*
|
||||
* @type {
|
||||
* undefined|?function(ZoneDelegate, Zone, Zone, ZoneSpec): Zone
|
||||
* }
|
||||
*/
|
||||
ZoneSpec.prototype.onFork;
|
||||
|
||||
/**
|
||||
* Allows the interception of the wrapping of the callback.
|
||||
*
|
||||
* When the zone is being forked, the request is forwarded to this method for interception.
|
||||
*
|
||||
* @type {
|
||||
* undefined|?function(ZoneDelegate, Zone, Zone, Function, string): Function
|
||||
* }
|
||||
*/
|
||||
ZoneSpec.prototype.onIntercept;
|
||||
|
||||
/**
|
||||
* Allows interception of the callback invocation.
|
||||
*
|
||||
* @type {
|
||||
* undefined|?function(ZoneDelegate, Zone, Zone, Function, Object, Array, string): *
|
||||
* }
|
||||
*/
|
||||
ZoneSpec.prototype.onInvoke;
|
||||
|
||||
/**
|
||||
* Allows interception of the error handling.
|
||||
*
|
||||
* @type {
|
||||
* undefined|?function(ZoneDelegate, Zone, Zone, Object): boolean
|
||||
* }
|
||||
*/
|
||||
ZoneSpec.prototype.onHandleError;
|
||||
|
||||
/**
|
||||
* Allows interception of task scheduling.
|
||||
*
|
||||
* @type {
|
||||
* undefined|?function(ZoneDelegate, Zone, Zone, Task): Task
|
||||
* }
|
||||
*/
|
||||
ZoneSpec.prototype.onScheduleTask;
|
||||
|
||||
/**
|
||||
* Allows interception of task invoke.
|
||||
*
|
||||
* @type {
|
||||
* undefined|?function(ZoneDelegate, Zone, Zone, Task, Object, Array): *
|
||||
* }
|
||||
*/
|
||||
ZoneSpec.prototype.onInvokeTask;
|
||||
|
||||
/**
|
||||
* Allows interception of task cancelation.
|
||||
*
|
||||
* @type {
|
||||
* undefined|?function(ZoneDelegate, Zone, Zone, Task): *
|
||||
* }
|
||||
*/
|
||||
ZoneSpec.prototype.onCancelTask;
|
||||
/**
|
||||
* Notifies of changes to the task queue empty status.
|
||||
*
|
||||
* @type {
|
||||
* undefined|?function(ZoneDelegate, Zone, Zone, HasTaskState)
|
||||
* }
|
||||
*/
|
||||
ZoneSpec.prototype.onHasTask;
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
var ZoneDelegate = function() {};
|
||||
/**
|
||||
* @type {!Zone} zone
|
||||
*/
|
||||
ZoneDelegate.prototype.zone;
|
||||
/**
|
||||
* @param {!Zone} targetZone the [Zone] which originally received the request.
|
||||
* @param {!ZoneSpec} zoneSpec the argument passed into the `fork` method.
|
||||
* @returns {!Zone} the new forked zone
|
||||
*/
|
||||
ZoneDelegate.prototype.fork = function(targetZone, zoneSpec) {};
|
||||
/**
|
||||
* @param {!Zone} targetZone the [Zone] which originally received the request.
|
||||
* @param {!Function} callback the callback function passed into `wrap` function
|
||||
* @param {string=} source the argument passed into the `wrap` method.
|
||||
* @returns {!Function}
|
||||
*/
|
||||
ZoneDelegate.prototype.intercept = function(targetZone, callback, source) {};
|
||||
|
||||
/**
|
||||
* @param {Zone} targetZone the [Zone] which originally received the request.
|
||||
* @param {!Function} callback the callback which will be invoked.
|
||||
* @param {?Object=} applyThis the argument passed into the `run` method.
|
||||
* @param {?Array=} applyArgs the argument passed into the `run` method.
|
||||
* @param {?string=} source the argument passed into the `run` method.
|
||||
* @returns {*}
|
||||
*/
|
||||
ZoneDelegate.prototype.invoke = function(targetZone, callback, applyThis, applyArgs, source) {};
|
||||
/**
|
||||
* @param {!Zone} targetZone the [Zone] which originally received the request.
|
||||
* @param {!Object} error the argument passed into the `handleError` method.
|
||||
* @returns {boolean}
|
||||
*/
|
||||
ZoneDelegate.prototype.handleError = function(targetZone, error) {};
|
||||
/**
|
||||
* @param {!Zone} targetZone the [Zone] which originally received the request.
|
||||
* @param {!Task} task the argument passed into the `scheduleTask` method.
|
||||
* @returns {!Task} task
|
||||
*/
|
||||
ZoneDelegate.prototype.scheduleTask = function(targetZone, task) {};
|
||||
/**
|
||||
* @param {!Zone} targetZone The [Zone] which originally received the request.
|
||||
* @param {!Task} task The argument passed into the `scheduleTask` method.
|
||||
* @param {?Object=} applyThis The argument passed into the `run` method.
|
||||
* @param {?Array=} applyArgs The argument passed into the `run` method.
|
||||
* @returns {*}
|
||||
*/
|
||||
ZoneDelegate.prototype.invokeTask = function(targetZone, task, applyThis, applyArgs) {};
|
||||
/**
|
||||
* @param {!Zone} targetZone The [Zone] which originally received the request.
|
||||
* @param {!Task} task The argument passed into the `cancelTask` method.
|
||||
* @returns {*}
|
||||
*/
|
||||
ZoneDelegate.prototype.cancelTask = function(targetZone, task) {};
|
||||
/**
|
||||
* @param {!Zone} targetZone The [Zone] which originally received the request.
|
||||
* @param {!HasTaskState} hasTaskState
|
||||
*/
|
||||
ZoneDelegate.prototype.hasTask = function(targetZone, hasTaskState) {};
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
var HasTaskState = function() {};
|
||||
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
HasTaskState.prototype.microTask;
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
HasTaskState.prototype.macroTask;
|
||||
/**
|
||||
* @type {boolean}
|
||||
*/
|
||||
HasTaskState.prototype.eventTask;
|
||||
/**
|
||||
* @type {TaskType}
|
||||
*/
|
||||
HasTaskState.prototype.change;
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
var TaskType = function() {};
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
var TaskState = function() {};
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
var TaskData = function() {};
|
||||
/**
|
||||
* @type {boolean|undefined}
|
||||
*/
|
||||
TaskData.prototype.isPeriodic;
|
||||
/**
|
||||
* @type {number|undefined}
|
||||
*/
|
||||
TaskData.prototype.delay;
|
||||
/**
|
||||
* @type {number|undefined}
|
||||
*/
|
||||
TaskData.prototype.handleId;
|
||||
|
||||
/**
|
||||
* @interface
|
||||
*/
|
||||
var Task = function() {};
|
||||
/**
|
||||
* @type {TaskType}
|
||||
*/
|
||||
Task.prototype.type;
|
||||
/**
|
||||
* @type {TaskState}
|
||||
*/
|
||||
Task.prototype.state;
|
||||
/**
|
||||
* @type {string}
|
||||
*/
|
||||
Task.prototype.source;
|
||||
/**
|
||||
* @type {Function}
|
||||
*/
|
||||
Task.prototype.invoke;
|
||||
/**
|
||||
* @type {Function}
|
||||
*/
|
||||
Task.prototype.callback;
|
||||
/**
|
||||
* @type {TaskData}
|
||||
*/
|
||||
Task.prototype.data;
|
||||
/**
|
||||
* @param {!Task} task
|
||||
*/
|
||||
Task.prototype.scheduleFn = function(task) {};
|
||||
/**
|
||||
* @param {!Task} task
|
||||
*/
|
||||
Task.prototype.cancelFn = function(task) {};
|
||||
/**
|
||||
* @type {Zone}
|
||||
*/
|
||||
Task.prototype.zone;
|
||||
/**
|
||||
* @type {number}
|
||||
*/
|
||||
Task.prototype.runCount;
|
||||
Task.prototype.cancelSchduleRequest = function() {};
|
||||
|
||||
/**
|
||||
* @interface
|
||||
* @extends {Task}
|
||||
*/
|
||||
var MicroTask = function() {};
|
||||
/**
|
||||
* @interface
|
||||
* @extends {Task}
|
||||
*/
|
||||
var MacroTask = function() {};
|
||||
/**
|
||||
* @interface
|
||||
* @extends {Task}
|
||||
*/
|
||||
var EventTask = function() {};
|
||||
|
||||
/**
|
||||
* @type {?string}
|
||||
*/
|
||||
Error.prototype.zoneAwareStack;
|
||||
|
||||
/**
|
||||
* @type {?string}
|
||||
*/
|
||||
Error.prototype.originalStack;
|
378
packages/zone.js/lib/common/error-rewrite.ts
Normal file
378
packages/zone.js/lib/common/error-rewrite.ts
Normal file
@ -0,0 +1,378 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {globalThis,undefinedVars}
|
||||
*/
|
||||
|
||||
/**
|
||||
* Extend the Error with additional fields for rewritten stack frames
|
||||
*/
|
||||
interface Error {
|
||||
/**
|
||||
* Stack trace where extra frames have been removed and zone names added.
|
||||
*/
|
||||
zoneAwareStack?: string;
|
||||
|
||||
/**
|
||||
* Original stack trace with no modifications
|
||||
*/
|
||||
originalStack?: string;
|
||||
}
|
||||
|
||||
Zone.__load_patch('Error', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
/*
|
||||
* This code patches Error so that:
|
||||
* - It ignores un-needed stack frames.
|
||||
* - It Shows the associated Zone for reach frame.
|
||||
*/
|
||||
|
||||
const enum FrameType {
|
||||
/// Skip this frame when printing out stack
|
||||
blackList,
|
||||
/// This frame marks zone transition
|
||||
transition
|
||||
}
|
||||
|
||||
const blacklistedStackFramesSymbol = api.symbol('blacklistedStackFrames');
|
||||
const NativeError = global[api.symbol('Error')] = global['Error'];
|
||||
// Store the frames which should be removed from the stack frames
|
||||
const blackListedStackFrames: {[frame: string]: FrameType} = {};
|
||||
// We must find the frame where Error was created, otherwise we assume we don't understand stack
|
||||
let zoneAwareFrame1: string;
|
||||
let zoneAwareFrame2: string;
|
||||
let zoneAwareFrame1WithoutNew: string;
|
||||
let zoneAwareFrame2WithoutNew: string;
|
||||
let zoneAwareFrame3WithoutNew: string;
|
||||
|
||||
global['Error'] = ZoneAwareError;
|
||||
const stackRewrite = 'stackRewrite';
|
||||
|
||||
type BlackListedStackFramesPolicy = 'default' | 'disable' | 'lazy';
|
||||
const blackListedStackFramesPolicy: BlackListedStackFramesPolicy =
|
||||
global['__Zone_Error_BlacklistedStackFrames_policy'] || 'default';
|
||||
|
||||
interface ZoneFrameName {
|
||||
zoneName: string;
|
||||
parent?: ZoneFrameName;
|
||||
}
|
||||
|
||||
function buildZoneFrameNames(zoneFrame: _ZoneFrame) {
|
||||
let zoneFrameName: ZoneFrameName = {zoneName: zoneFrame.zone.name};
|
||||
let result = zoneFrameName;
|
||||
while (zoneFrame.parent) {
|
||||
zoneFrame = zoneFrame.parent;
|
||||
const parentZoneFrameName = {zoneName: zoneFrame.zone.name};
|
||||
zoneFrameName.parent = parentZoneFrameName;
|
||||
zoneFrameName = parentZoneFrameName;
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
function buildZoneAwareStackFrames(
|
||||
originalStack: string, zoneFrame: _ZoneFrame | ZoneFrameName | null, isZoneFrame = true) {
|
||||
let frames: string[] = originalStack.split('\n');
|
||||
let i = 0;
|
||||
// Find the first frame
|
||||
while (!(frames[i] === zoneAwareFrame1 || frames[i] === zoneAwareFrame2 ||
|
||||
frames[i] === zoneAwareFrame1WithoutNew || frames[i] === zoneAwareFrame2WithoutNew ||
|
||||
frames[i] === zoneAwareFrame3WithoutNew) &&
|
||||
i < frames.length) {
|
||||
i++;
|
||||
}
|
||||
for (; i < frames.length && zoneFrame; i++) {
|
||||
let frame = frames[i];
|
||||
if (frame.trim()) {
|
||||
switch (blackListedStackFrames[frame]) {
|
||||
case FrameType.blackList:
|
||||
frames.splice(i, 1);
|
||||
i--;
|
||||
break;
|
||||
case FrameType.transition:
|
||||
if (zoneFrame.parent) {
|
||||
// This is the special frame where zone changed. Print and process it accordingly
|
||||
zoneFrame = zoneFrame.parent;
|
||||
} else {
|
||||
zoneFrame = null;
|
||||
}
|
||||
frames.splice(i, 1);
|
||||
i--;
|
||||
break;
|
||||
default:
|
||||
frames[i] += isZoneFrame ? ` [${(zoneFrame as _ZoneFrame).zone.name}]` :
|
||||
` [${(zoneFrame as ZoneFrameName).zoneName}]`;
|
||||
}
|
||||
}
|
||||
}
|
||||
return frames.join('\n');
|
||||
}
|
||||
/**
|
||||
* This is ZoneAwareError which processes the stack frame and cleans up extra frames as well as
|
||||
* adds zone information to it.
|
||||
*/
|
||||
function ZoneAwareError(): Error {
|
||||
// We always have to return native error otherwise the browser console will not work.
|
||||
let error: Error = NativeError.apply(this, arguments);
|
||||
// Save original stack trace
|
||||
const originalStack = (error as any)['originalStack'] = error.stack;
|
||||
|
||||
// Process the stack trace and rewrite the frames.
|
||||
if ((ZoneAwareError as any)[stackRewrite] && originalStack) {
|
||||
let zoneFrame = api.currentZoneFrame();
|
||||
if (blackListedStackFramesPolicy === 'lazy') {
|
||||
// don't handle stack trace now
|
||||
(error as any)[api.symbol('zoneFrameNames')] = buildZoneFrameNames(zoneFrame);
|
||||
} else if (blackListedStackFramesPolicy === 'default') {
|
||||
try {
|
||||
error.stack = error.zoneAwareStack = buildZoneAwareStackFrames(originalStack, zoneFrame);
|
||||
} catch (e) {
|
||||
// ignore as some browsers don't allow overriding of stack
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (this instanceof NativeError && this.constructor != NativeError) {
|
||||
// We got called with a `new` operator AND we are subclass of ZoneAwareError
|
||||
// in that case we have to copy all of our properties to `this`.
|
||||
Object.keys(error).concat('stack', 'message').forEach((key) => {
|
||||
const value = (error as any)[key];
|
||||
if (value !== undefined) {
|
||||
try {
|
||||
this[key] = value;
|
||||
} catch (e) {
|
||||
// ignore the assignment in case it is a setter and it throws.
|
||||
}
|
||||
}
|
||||
});
|
||||
return this;
|
||||
}
|
||||
return error;
|
||||
}
|
||||
|
||||
// Copy the prototype so that instanceof operator works as expected
|
||||
ZoneAwareError.prototype = NativeError.prototype;
|
||||
(ZoneAwareError as any)[blacklistedStackFramesSymbol] = blackListedStackFrames;
|
||||
(ZoneAwareError as any)[stackRewrite] = false;
|
||||
|
||||
const zoneAwareStackSymbol = api.symbol('zoneAwareStack');
|
||||
|
||||
// try to define zoneAwareStack property when blackListed
|
||||
// policy is delay
|
||||
if (blackListedStackFramesPolicy === 'lazy') {
|
||||
Object.defineProperty(ZoneAwareError.prototype, 'zoneAwareStack', {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
if (!this[zoneAwareStackSymbol]) {
|
||||
this[zoneAwareStackSymbol] = buildZoneAwareStackFrames(
|
||||
this.originalStack, this[api.symbol('zoneFrameNames')], false);
|
||||
}
|
||||
return this[zoneAwareStackSymbol];
|
||||
},
|
||||
set: function(newStack: string) {
|
||||
this.originalStack = newStack;
|
||||
this[zoneAwareStackSymbol] = buildZoneAwareStackFrames(
|
||||
this.originalStack, this[api.symbol('zoneFrameNames')], false);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// those properties need special handling
|
||||
const specialPropertyNames = ['stackTraceLimit', 'captureStackTrace', 'prepareStackTrace'];
|
||||
// those properties of NativeError should be set to ZoneAwareError
|
||||
const nativeErrorProperties = Object.keys(NativeError);
|
||||
if (nativeErrorProperties) {
|
||||
nativeErrorProperties.forEach(prop => {
|
||||
if (specialPropertyNames.filter(sp => sp === prop).length === 0) {
|
||||
Object.defineProperty(ZoneAwareError, prop, {
|
||||
get: function() { return NativeError[prop]; },
|
||||
set: function(value) { NativeError[prop] = value; }
|
||||
});
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
if (NativeError.hasOwnProperty('stackTraceLimit')) {
|
||||
// Extend default stack limit as we will be removing few frames.
|
||||
NativeError.stackTraceLimit = Math.max(NativeError.stackTraceLimit, 15);
|
||||
|
||||
// make sure that ZoneAwareError has the same property which forwards to NativeError.
|
||||
Object.defineProperty(ZoneAwareError, 'stackTraceLimit', {
|
||||
get: function() { return NativeError.stackTraceLimit; },
|
||||
set: function(value) { return NativeError.stackTraceLimit = value; }
|
||||
});
|
||||
}
|
||||
|
||||
if (NativeError.hasOwnProperty('captureStackTrace')) {
|
||||
Object.defineProperty(ZoneAwareError, 'captureStackTrace', {
|
||||
// add named function here because we need to remove this
|
||||
// stack frame when prepareStackTrace below
|
||||
value: function zoneCaptureStackTrace(targetObject: Object, constructorOpt?: Function) {
|
||||
NativeError.captureStackTrace(targetObject, constructorOpt);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
const ZONE_CAPTURESTACKTRACE = 'zoneCaptureStackTrace';
|
||||
Object.defineProperty(ZoneAwareError, 'prepareStackTrace', {
|
||||
get: function() { return NativeError.prepareStackTrace; },
|
||||
set: function(value) {
|
||||
if (!value || typeof value !== 'function') {
|
||||
return NativeError.prepareStackTrace = value;
|
||||
}
|
||||
return NativeError.prepareStackTrace = function(
|
||||
error: Error, structuredStackTrace: {getFunctionName: Function}[]) {
|
||||
// remove additional stack information from ZoneAwareError.captureStackTrace
|
||||
if (structuredStackTrace) {
|
||||
for (let i = 0; i < structuredStackTrace.length; i++) {
|
||||
const st = structuredStackTrace[i];
|
||||
// remove the first function which name is zoneCaptureStackTrace
|
||||
if (st.getFunctionName() === ZONE_CAPTURESTACKTRACE) {
|
||||
structuredStackTrace.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
return value.call(this, error, structuredStackTrace);
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
if (blackListedStackFramesPolicy === 'disable') {
|
||||
// don't need to run detectZone to populate
|
||||
// blacklisted stack frames
|
||||
return;
|
||||
}
|
||||
// Now we need to populate the `blacklistedStackFrames` as well as find the
|
||||
// run/runGuarded/runTask frames. This is done by creating a detect zone and then threading
|
||||
// the execution through all of the above methods so that we can look at the stack trace and
|
||||
// find the frames of interest.
|
||||
|
||||
let detectZone: Zone = Zone.current.fork({
|
||||
name: 'detect',
|
||||
onHandleError: function(
|
||||
parentZD: ZoneDelegate, current: Zone, target: Zone, error: any): boolean {
|
||||
if (error.originalStack && Error === ZoneAwareError) {
|
||||
let frames = error.originalStack.split(/\n/);
|
||||
let runFrame = false, runGuardedFrame = false, runTaskFrame = false;
|
||||
while (frames.length) {
|
||||
let frame = frames.shift();
|
||||
// On safari it is possible to have stack frame with no line number.
|
||||
// This check makes sure that we don't filter frames on name only (must have
|
||||
// line number or exact equals to `ZoneAwareError`)
|
||||
if (/:\d+:\d+/.test(frame) || frame === 'ZoneAwareError') {
|
||||
// Get rid of the path so that we don't accidentally find function name in path.
|
||||
// In chrome the separator is `(` and `@` in FF and safari
|
||||
// Chrome: at Zone.run (zone.js:100)
|
||||
// Chrome: at Zone.run (http://localhost:9876/base/build/lib/zone.js:100:24)
|
||||
// FireFox: Zone.prototype.run@http://localhost:9876/base/build/lib/zone.js:101:24
|
||||
// Safari: run@http://localhost:9876/base/build/lib/zone.js:101:24
|
||||
let fnName: string = frame.split('(')[0].split('@')[0];
|
||||
let frameType = FrameType.transition;
|
||||
if (fnName.indexOf('ZoneAwareError') !== -1) {
|
||||
if (fnName.indexOf('new ZoneAwareError') !== -1) {
|
||||
zoneAwareFrame1 = frame;
|
||||
zoneAwareFrame2 = frame.replace('new ZoneAwareError', 'new Error.ZoneAwareError');
|
||||
} else {
|
||||
zoneAwareFrame1WithoutNew = frame;
|
||||
zoneAwareFrame2WithoutNew = frame.replace('Error.', '');
|
||||
if (frame.indexOf('Error.ZoneAwareError') === -1) {
|
||||
zoneAwareFrame3WithoutNew =
|
||||
frame.replace('ZoneAwareError', 'Error.ZoneAwareError');
|
||||
}
|
||||
}
|
||||
blackListedStackFrames[zoneAwareFrame2] = FrameType.blackList;
|
||||
}
|
||||
if (fnName.indexOf('runGuarded') !== -1) {
|
||||
runGuardedFrame = true;
|
||||
} else if (fnName.indexOf('runTask') !== -1) {
|
||||
runTaskFrame = true;
|
||||
} else if (fnName.indexOf('run') !== -1) {
|
||||
runFrame = true;
|
||||
} else {
|
||||
frameType = FrameType.blackList;
|
||||
}
|
||||
blackListedStackFrames[frame] = frameType;
|
||||
// Once we find all of the frames we can stop looking.
|
||||
if (runFrame && runGuardedFrame && runTaskFrame) {
|
||||
(ZoneAwareError as any)[stackRewrite] = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
}) as Zone;
|
||||
// carefully constructor a stack frame which contains all of the frames of interest which
|
||||
// need to be detected and blacklisted.
|
||||
|
||||
const childDetectZone = detectZone.fork({
|
||||
name: 'child',
|
||||
onScheduleTask: function(delegate, curr, target, task) {
|
||||
return delegate.scheduleTask(target, task);
|
||||
},
|
||||
onInvokeTask: function(delegate, curr, target, task, applyThis, applyArgs) {
|
||||
return delegate.invokeTask(target, task, applyThis, applyArgs);
|
||||
},
|
||||
onCancelTask: function(delegate, curr, target, task) {
|
||||
return delegate.cancelTask(target, task);
|
||||
},
|
||||
onInvoke: function(delegate, curr, target, callback, applyThis, applyArgs, source) {
|
||||
return delegate.invoke(target, callback, applyThis, applyArgs, source);
|
||||
}
|
||||
});
|
||||
|
||||
// we need to detect all zone related frames, it will
|
||||
// exceed default stackTraceLimit, so we set it to
|
||||
// larger number here, and restore it after detect finish.
|
||||
const originalStackTraceLimit = Error.stackTraceLimit;
|
||||
Error.stackTraceLimit = 100;
|
||||
// we schedule event/micro/macro task, and invoke them
|
||||
// when onSchedule, so we can get all stack traces for
|
||||
// all kinds of tasks with one error thrown.
|
||||
childDetectZone.run(() => {
|
||||
childDetectZone.runGuarded(() => {
|
||||
const fakeTransitionTo = () => {};
|
||||
childDetectZone.scheduleEventTask(
|
||||
blacklistedStackFramesSymbol,
|
||||
() => {
|
||||
childDetectZone.scheduleMacroTask(
|
||||
blacklistedStackFramesSymbol,
|
||||
() => {
|
||||
childDetectZone.scheduleMicroTask(
|
||||
blacklistedStackFramesSymbol, () => { throw new Error(); }, undefined,
|
||||
(t: Task) => {
|
||||
(t as any)._transitionTo = fakeTransitionTo;
|
||||
t.invoke();
|
||||
});
|
||||
childDetectZone.scheduleMicroTask(
|
||||
blacklistedStackFramesSymbol, () => { throw Error(); }, undefined,
|
||||
(t: Task) => {
|
||||
(t as any)._transitionTo = fakeTransitionTo;
|
||||
t.invoke();
|
||||
});
|
||||
},
|
||||
undefined,
|
||||
(t) => {
|
||||
(t as any)._transitionTo = fakeTransitionTo;
|
||||
t.invoke();
|
||||
},
|
||||
() => {});
|
||||
},
|
||||
undefined,
|
||||
(t) => {
|
||||
(t as any)._transitionTo = fakeTransitionTo;
|
||||
t.invoke();
|
||||
},
|
||||
() => {});
|
||||
});
|
||||
});
|
||||
|
||||
Error.stackTraceLimit = originalStackTraceLimit;
|
||||
});
|
679
packages/zone.js/lib/common/events.ts
Normal file
679
packages/zone.js/lib/common/events.ts
Normal file
@ -0,0 +1,679 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {missingRequire}
|
||||
*/
|
||||
|
||||
import {ADD_EVENT_LISTENER_STR, FALSE_STR, ObjectGetPrototypeOf, REMOVE_EVENT_LISTENER_STR, TRUE_STR, ZONE_SYMBOL_PREFIX, attachOriginToPatched, isNode, zoneSymbol} from './utils';
|
||||
|
||||
|
||||
/** @internal **/
|
||||
interface EventTaskData extends TaskData {
|
||||
// use global callback or not
|
||||
readonly useG?: boolean;
|
||||
}
|
||||
|
||||
let passiveSupported = false;
|
||||
|
||||
if (typeof window !== 'undefined') {
|
||||
try {
|
||||
const 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
|
||||
const OPTIMIZED_ZONE_EVENT_TASK_DATA: EventTaskData = {
|
||||
useG: true
|
||||
};
|
||||
|
||||
export const zoneSymbolEventNames: any = {};
|
||||
export const globalSources: any = {};
|
||||
|
||||
const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
|
||||
const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
|
||||
|
||||
export interface PatchEventTargetOptions {
|
||||
// validateHandler
|
||||
vh?: (nativeDelegate: any, delegate: any, target: any, args: any) => boolean;
|
||||
// addEventListener function name
|
||||
add?: string;
|
||||
// removeEventListener function name
|
||||
rm?: string;
|
||||
// prependEventListener function name
|
||||
prepend?: string;
|
||||
// listeners function name
|
||||
listeners?: string;
|
||||
// removeAllListeners function name
|
||||
rmAll?: string;
|
||||
// useGlobalCallback flag
|
||||
useG?: boolean;
|
||||
// check duplicate flag when addEventListener
|
||||
chkDup?: boolean;
|
||||
// return target flag when addEventListener
|
||||
rt?: boolean;
|
||||
// event compare handler
|
||||
diff?: (task: any, delegate: any) => boolean;
|
||||
// support passive or not
|
||||
supportPassive?: boolean;
|
||||
// get string from eventName (in nodejs, eventName maybe Symbol)
|
||||
eventNameToString?: (eventName: any) => string;
|
||||
}
|
||||
|
||||
export function patchEventTarget(
|
||||
_global: any, apis: any[], patchOptions?: PatchEventTargetOptions) {
|
||||
const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
|
||||
const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
|
||||
|
||||
const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
|
||||
const REMOVE_ALL_LISTENERS_EVENT_LISTENER =
|
||||
(patchOptions && patchOptions.rmAll) || 'removeAllListeners';
|
||||
|
||||
const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
|
||||
|
||||
const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
|
||||
|
||||
const PREPEND_EVENT_LISTENER = 'prependListener';
|
||||
const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
|
||||
|
||||
const invokeTask = function(task: any, target: any, event: Event) {
|
||||
// for better performance, check isRemoved which is set
|
||||
// by removeEventListener
|
||||
if (task.isRemoved) {
|
||||
return;
|
||||
}
|
||||
const delegate = task.callback;
|
||||
if (typeof delegate === 'object' && delegate.handleEvent) {
|
||||
// create the bind version of handleEvent when invoke
|
||||
task.callback = (event: Event) => delegate.handleEvent(event);
|
||||
task.originalDelegate = delegate;
|
||||
}
|
||||
// invoke static task.invoke
|
||||
task.invoke(task, target, [event]);
|
||||
const options = task.options;
|
||||
if (options && typeof options === 'object' && options.once) {
|
||||
// if options.once is true, after invoke once remove listener here
|
||||
// only browser need to do this, nodejs eventEmitter will cal removeListener
|
||||
// inside EventEmitter.once
|
||||
const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
|
||||
target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
|
||||
}
|
||||
};
|
||||
|
||||
// global shared zoneAwareCallback to handle all event callback with capture = false
|
||||
const globalZoneAwareCallback = function(event: Event) {
|
||||
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
|
||||
// event will be undefined, so we need to use window.event
|
||||
event = event || _global.event;
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
// event.target is needed for Samsung TV and SourceBuffer
|
||||
// || global is needed https://github.com/angular/zone.js/issues/190
|
||||
const target: any = this || event.target || _global;
|
||||
const tasks = target[zoneSymbolEventNames[event.type][FALSE_STR]];
|
||||
if (tasks) {
|
||||
// invoke all tasks which attached to current target with given event.type and capture = false
|
||||
// for performance concern, if task.length === 1, just invoke
|
||||
if (tasks.length === 1) {
|
||||
invokeTask(tasks[0], target, event);
|
||||
} else {
|
||||
// https://github.com/angular/zone.js/issues/836
|
||||
// copy the tasks array before invoke, to avoid
|
||||
// the callback will remove itself or other listener
|
||||
const copyTasks = tasks.slice();
|
||||
for (let i = 0; i < copyTasks.length; i++) {
|
||||
if (event && (event as any)[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
|
||||
break;
|
||||
}
|
||||
invokeTask(copyTasks[i], target, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// global shared zoneAwareCallback to handle all event callback with capture = true
|
||||
const globalZoneAwareCaptureCallback = function(event: Event) {
|
||||
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
|
||||
// event will be undefined, so we need to use window.event
|
||||
event = event || _global.event;
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
// event.target is needed for Samsung TV and SourceBuffer
|
||||
// || global is needed https://github.com/angular/zone.js/issues/190
|
||||
const target: any = this || event.target || _global;
|
||||
const tasks = target[zoneSymbolEventNames[event.type][TRUE_STR]];
|
||||
if (tasks) {
|
||||
// invoke all tasks which attached to current target with given event.type and capture = false
|
||||
// for performance concern, if task.length === 1, just invoke
|
||||
if (tasks.length === 1) {
|
||||
invokeTask(tasks[0], target, event);
|
||||
} else {
|
||||
// https://github.com/angular/zone.js/issues/836
|
||||
// copy the tasks array before invoke, to avoid
|
||||
// the callback will remove itself or other listener
|
||||
const copyTasks = tasks.slice();
|
||||
for (let i = 0; i < copyTasks.length; i++) {
|
||||
if (event && (event as any)[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
|
||||
break;
|
||||
}
|
||||
invokeTask(copyTasks[i], target, event);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
function patchEventTargetMethods(obj: any, patchOptions?: PatchEventTargetOptions) {
|
||||
if (!obj) {
|
||||
return false;
|
||||
}
|
||||
|
||||
let useGlobalCallback = true;
|
||||
if (patchOptions && patchOptions.useG !== undefined) {
|
||||
useGlobalCallback = patchOptions.useG;
|
||||
}
|
||||
const validateHandler = patchOptions && patchOptions.vh;
|
||||
|
||||
let checkDuplicate = true;
|
||||
if (patchOptions && patchOptions.chkDup !== undefined) {
|
||||
checkDuplicate = patchOptions.chkDup;
|
||||
}
|
||||
|
||||
let returnTarget = false;
|
||||
if (patchOptions && patchOptions.rt !== undefined) {
|
||||
returnTarget = patchOptions.rt;
|
||||
}
|
||||
|
||||
let proto = obj;
|
||||
while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
|
||||
proto = ObjectGetPrototypeOf(proto);
|
||||
}
|
||||
if (!proto && obj[ADD_EVENT_LISTENER]) {
|
||||
// somehow we did not find it, but we can see it. This happens on IE for Window properties.
|
||||
proto = obj;
|
||||
}
|
||||
|
||||
if (!proto) {
|
||||
return false;
|
||||
}
|
||||
if (proto[zoneSymbolAddEventListener]) {
|
||||
return false;
|
||||
}
|
||||
|
||||
const 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
|
||||
const taskData: any = {};
|
||||
|
||||
const nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
|
||||
const nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
|
||||
proto[REMOVE_EVENT_LISTENER];
|
||||
|
||||
const nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
|
||||
proto[LISTENERS_EVENT_LISTENER];
|
||||
const nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
|
||||
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
|
||||
|
||||
let nativePrependEventListener: any;
|
||||
if (patchOptions && patchOptions.prepend) {
|
||||
nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
|
||||
proto[patchOptions.prepend];
|
||||
}
|
||||
|
||||
function checkIsPassive(task: 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 as any).options = !!taskData.options.capture;
|
||||
taskData.options = (task as any).options;
|
||||
}
|
||||
}
|
||||
|
||||
const customScheduleGlobal = function(task: 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);
|
||||
};
|
||||
|
||||
const customCancelGlobal = function(task: any) {
|
||||
// if task is not marked as isRemoved, this call is directly
|
||||
// from Zone.prototype.cancelTask, we should remove the task
|
||||
// from tasksList of target first
|
||||
if (!task.isRemoved) {
|
||||
const symbolEventNames = zoneSymbolEventNames[task.eventName];
|
||||
let symbolEventName;
|
||||
if (symbolEventNames) {
|
||||
symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
|
||||
}
|
||||
const existingTasks = symbolEventName && task.target[symbolEventName];
|
||||
if (existingTasks) {
|
||||
for (let i = 0; i < existingTasks.length; i++) {
|
||||
const existingTask = existingTasks[i];
|
||||
if (existingTask === task) {
|
||||
existingTasks.splice(i, 1);
|
||||
// set isRemoved to data for faster invokeTask check
|
||||
task.isRemoved = true;
|
||||
if (existingTasks.length === 0) {
|
||||
// all tasks for the eventName + capture have gone,
|
||||
// remove globalZoneAwareCallback and remove the task cache from target
|
||||
task.allRemoved = true;
|
||||
task.target[symbolEventName] = null;
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// if all tasks for the eventName + capture have gone,
|
||||
// we will really remove the global event callback,
|
||||
// if not, return
|
||||
if (!task.allRemoved) {
|
||||
return;
|
||||
}
|
||||
return nativeRemoveEventListener.call(
|
||||
task.target, task.eventName,
|
||||
task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
|
||||
};
|
||||
|
||||
const customScheduleNonGlobal = function(task: Task) {
|
||||
checkIsPassive(task);
|
||||
return nativeAddEventListener.call(
|
||||
taskData.target, taskData.eventName, task.invoke, taskData.options);
|
||||
};
|
||||
|
||||
const customSchedulePrepend = function(task: Task) {
|
||||
return nativePrependEventListener.call(
|
||||
taskData.target, taskData.eventName, task.invoke, taskData.options);
|
||||
};
|
||||
|
||||
const customCancelNonGlobal = function(task: any) {
|
||||
return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
|
||||
};
|
||||
|
||||
const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
|
||||
const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
|
||||
|
||||
const compareTaskCallbackVsDelegate = function(task: any, delegate: any) {
|
||||
const typeOfDelegate = typeof delegate;
|
||||
return (typeOfDelegate === 'function' && task.callback === delegate) ||
|
||||
(typeOfDelegate === 'object' && task.originalDelegate === delegate);
|
||||
};
|
||||
|
||||
const compare =
|
||||
(patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
|
||||
|
||||
const blackListedEvents: string[] = (Zone as any)[zoneSymbol('BLACK_LISTED_EVENTS')];
|
||||
|
||||
const makeAddListener = function(
|
||||
nativeListener: any, addSource: string, customScheduleFn: any, customCancelFn: any,
|
||||
returnTarget = false, prepend = false) {
|
||||
return function() {
|
||||
const target = this || _global;
|
||||
const eventName = arguments[0];
|
||||
let 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
|
||||
let isHandleEvent = false;
|
||||
if (typeof delegate !== 'function') {
|
||||
if (!delegate.handleEvent) {
|
||||
return nativeListener.apply(this, arguments);
|
||||
}
|
||||
isHandleEvent = true;
|
||||
}
|
||||
|
||||
if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const options = arguments[2];
|
||||
|
||||
if (blackListedEvents) {
|
||||
// check black list
|
||||
for (let i = 0; i < blackListedEvents.length; i++) {
|
||||
if (eventName === blackListedEvents[i]) {
|
||||
return nativeListener.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let capture;
|
||||
let once = false;
|
||||
if (options === undefined) {
|
||||
capture = false;
|
||||
} else if (options === true) {
|
||||
capture = true;
|
||||
} else if (options === false) {
|
||||
capture = false;
|
||||
} else {
|
||||
capture = options ? !!options.capture : false;
|
||||
once = options ? !!options.once : false;
|
||||
}
|
||||
|
||||
const zone = Zone.current;
|
||||
const symbolEventNames = zoneSymbolEventNames[eventName];
|
||||
let symbolEventName;
|
||||
if (!symbolEventNames) {
|
||||
// the code is duplicate, but I just want to get some better performance
|
||||
const falseEventName =
|
||||
(eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
|
||||
const trueEventName =
|
||||
(eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
|
||||
const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
|
||||
const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
|
||||
zoneSymbolEventNames[eventName] = {};
|
||||
zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
|
||||
zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
|
||||
symbolEventName = capture ? symbolCapture : symbol;
|
||||
} else {
|
||||
symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
|
||||
}
|
||||
let existingTasks = target[symbolEventName];
|
||||
let isExisting = false;
|
||||
if (existingTasks) {
|
||||
// already have task registered
|
||||
isExisting = true;
|
||||
if (checkDuplicate) {
|
||||
for (let i = 0; i < existingTasks.length; i++) {
|
||||
if (compare(existingTasks[i], delegate)) {
|
||||
// same callback, same capture, same event name, just return
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
} else {
|
||||
existingTasks = target[symbolEventName] = [];
|
||||
}
|
||||
let source;
|
||||
const constructorName = target.constructor['name'];
|
||||
const targetSource = globalSources[constructorName];
|
||||
if (targetSource) {
|
||||
source = targetSource[eventName];
|
||||
}
|
||||
if (!source) {
|
||||
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
|
||||
taskData.options = options;
|
||||
if (once) {
|
||||
// if addEventListener with once options, we don't pass it to
|
||||
// native addEventListener, instead we keep the once setting
|
||||
// and handle ourselves.
|
||||
taskData.options.once = false;
|
||||
}
|
||||
taskData.target = target;
|
||||
taskData.capture = capture;
|
||||
taskData.eventName = eventName;
|
||||
taskData.isExisting = isExisting;
|
||||
|
||||
const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
|
||||
|
||||
// keep taskData into data to allow onScheduleEventTask to access the task information
|
||||
if (data) {
|
||||
(data as any).taskData = taskData;
|
||||
}
|
||||
|
||||
const task: any =
|
||||
zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
|
||||
|
||||
// should clear taskData.target to avoid memory leak
|
||||
// issue, https://github.com/angular/angular/issues/20442
|
||||
taskData.target = null;
|
||||
|
||||
// need to clear up taskData because it is a global object
|
||||
if (data) {
|
||||
(data as any).taskData = null;
|
||||
}
|
||||
|
||||
// have to save those information to task in case
|
||||
// application may call task.zone.cancelTask() directly
|
||||
if (once) {
|
||||
options.once = true;
|
||||
}
|
||||
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;
|
||||
if (isHandleEvent) {
|
||||
// save original delegate for compare to check duplicate
|
||||
(task as any).originalDelegate = delegate;
|
||||
}
|
||||
if (!prepend) {
|
||||
existingTasks.push(task);
|
||||
} else {
|
||||
existingTasks.unshift(task);
|
||||
}
|
||||
|
||||
if (returnTarget) {
|
||||
return target;
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
proto[ADD_EVENT_LISTENER] = makeAddListener(
|
||||
nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel,
|
||||
returnTarget);
|
||||
if (nativePrependEventListener) {
|
||||
proto[PREPEND_EVENT_LISTENER] = makeAddListener(
|
||||
nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend,
|
||||
customCancel, returnTarget, true);
|
||||
}
|
||||
|
||||
proto[REMOVE_EVENT_LISTENER] = function() {
|
||||
const target = this || _global;
|
||||
const eventName = arguments[0];
|
||||
const options = arguments[2];
|
||||
|
||||
let capture;
|
||||
if (options === undefined) {
|
||||
capture = false;
|
||||
} else if (options === true) {
|
||||
capture = true;
|
||||
} else if (options === false) {
|
||||
capture = false;
|
||||
} else {
|
||||
capture = options ? !!options.capture : false;
|
||||
}
|
||||
|
||||
const delegate = arguments[1];
|
||||
if (!delegate) {
|
||||
return nativeRemoveEventListener.apply(this, arguments);
|
||||
}
|
||||
|
||||
if (validateHandler &&
|
||||
!validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
|
||||
return;
|
||||
}
|
||||
|
||||
const symbolEventNames = zoneSymbolEventNames[eventName];
|
||||
let symbolEventName;
|
||||
if (symbolEventNames) {
|
||||
symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
|
||||
}
|
||||
const existingTasks = symbolEventName && target[symbolEventName];
|
||||
if (existingTasks) {
|
||||
for (let i = 0; i < existingTasks.length; i++) {
|
||||
const existingTask = existingTasks[i];
|
||||
if (compare(existingTask, delegate)) {
|
||||
existingTasks.splice(i, 1);
|
||||
// set isRemoved to data for faster invokeTask check
|
||||
(existingTask as any).isRemoved = true;
|
||||
if (existingTasks.length === 0) {
|
||||
// all tasks for the eventName + capture have gone,
|
||||
// remove globalZoneAwareCallback and remove the task cache from target
|
||||
(existingTask as any).allRemoved = true;
|
||||
target[symbolEventName] = null;
|
||||
}
|
||||
existingTask.zone.cancelTask(existingTask);
|
||||
if (returnTarget) {
|
||||
return target;
|
||||
}
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
// issue 930, didn't find the event name or callback
|
||||
// from zone kept existingTasks, the callback maybe
|
||||
// added outside of zone, we need to call native removeEventListener
|
||||
// to try to remove it.
|
||||
return nativeRemoveEventListener.apply(this, arguments);
|
||||
};
|
||||
|
||||
proto[LISTENERS_EVENT_LISTENER] = function() {
|
||||
const target = this || _global;
|
||||
const eventName = arguments[0];
|
||||
|
||||
const listeners: any[] = [];
|
||||
const tasks =
|
||||
findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
|
||||
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
const task: any = tasks[i];
|
||||
let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
|
||||
listeners.push(delegate);
|
||||
}
|
||||
return listeners;
|
||||
};
|
||||
|
||||
proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function() {
|
||||
const target = this || _global;
|
||||
|
||||
const eventName = arguments[0];
|
||||
if (!eventName) {
|
||||
const keys = Object.keys(target);
|
||||
for (let i = 0; i < keys.length; i++) {
|
||||
const prop = keys[i];
|
||||
const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
|
||||
let evtName = match && match[1];
|
||||
// in nodejs EventEmitter, removeListener event is
|
||||
// used for monitoring the removeListener call,
|
||||
// so just keep removeListener eventListener until
|
||||
// all other eventListeners are removed
|
||||
if (evtName && evtName !== 'removeListener') {
|
||||
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
|
||||
}
|
||||
}
|
||||
// remove removeListener listener finally
|
||||
this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
|
||||
} else {
|
||||
const symbolEventNames = zoneSymbolEventNames[eventName];
|
||||
if (symbolEventNames) {
|
||||
const symbolEventName = symbolEventNames[FALSE_STR];
|
||||
const symbolCaptureEventName = symbolEventNames[TRUE_STR];
|
||||
|
||||
const tasks = target[symbolEventName];
|
||||
const captureTasks = target[symbolCaptureEventName];
|
||||
|
||||
if (tasks) {
|
||||
const removeTasks = tasks.slice();
|
||||
for (let i = 0; i < removeTasks.length; i++) {
|
||||
const task = removeTasks[i];
|
||||
let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
|
||||
this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
|
||||
}
|
||||
}
|
||||
|
||||
if (captureTasks) {
|
||||
const removeTasks = captureTasks.slice();
|
||||
for (let i = 0; i < removeTasks.length; i++) {
|
||||
const task = removeTasks[i];
|
||||
let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
|
||||
this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (returnTarget) {
|
||||
return this;
|
||||
}
|
||||
};
|
||||
|
||||
// for native toString patch
|
||||
attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
|
||||
attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
|
||||
if (nativeRemoveAllListeners) {
|
||||
attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
|
||||
}
|
||||
if (nativeListeners) {
|
||||
attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
let results: any[] = [];
|
||||
for (let i = 0; i < apis.length; i++) {
|
||||
results[i] = patchEventTargetMethods(apis[i], patchOptions);
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
export function findEventTasks(target: any, eventName: string): Task[] {
|
||||
const foundTasks: any[] = [];
|
||||
for (let prop in target) {
|
||||
const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
|
||||
let evtName = match && match[1];
|
||||
if (evtName && (!eventName || evtName === eventName)) {
|
||||
const tasks: any = target[prop];
|
||||
if (tasks) {
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
foundTasks.push(tasks[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
return foundTasks;
|
||||
}
|
||||
|
||||
export function patchEventPrototype(global: any, api: _ZonePrivate) {
|
||||
const Event = global['Event'];
|
||||
if (Event && Event.prototype) {
|
||||
api.patchMethod(
|
||||
Event.prototype, 'stopImmediatePropagation',
|
||||
(delegate: Function) => function(self: any, args: any[]) {
|
||||
self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
|
||||
// we need to call the native stopImmediatePropagation
|
||||
// in case in some hybrid application, some part of
|
||||
// application will be controlled by zone, some are not
|
||||
delegate && delegate.apply(self, args);
|
||||
});
|
||||
}
|
||||
}
|
112
packages/zone.js/lib/common/fetch.ts
Normal file
112
packages/zone.js/lib/common/fetch.ts
Normal file
@ -0,0 +1,112 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {missingRequire}
|
||||
*/
|
||||
|
||||
Zone.__load_patch('fetch', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
interface FetchTaskData extends TaskData {
|
||||
fetchArgs?: any[];
|
||||
}
|
||||
let fetch = global['fetch'];
|
||||
if (typeof fetch !== 'function') {
|
||||
return;
|
||||
}
|
||||
const originalFetch = global[api.symbol('fetch')];
|
||||
if (originalFetch) {
|
||||
// restore unpatched fetch first
|
||||
fetch = originalFetch;
|
||||
}
|
||||
const ZoneAwarePromise = global.Promise;
|
||||
const symbolThenPatched = api.symbol('thenPatched');
|
||||
const fetchTaskScheduling = api.symbol('fetchTaskScheduling');
|
||||
const fetchTaskAborting = api.symbol('fetchTaskAborting');
|
||||
const OriginalAbortController = global['AbortController'];
|
||||
const supportAbort = typeof OriginalAbortController === 'function';
|
||||
let abortNative: Function|null = null;
|
||||
if (supportAbort) {
|
||||
global['AbortController'] = function() {
|
||||
const abortController = new OriginalAbortController();
|
||||
const signal = abortController.signal;
|
||||
signal.abortController = abortController;
|
||||
return abortController;
|
||||
};
|
||||
abortNative = api.patchMethod(
|
||||
OriginalAbortController.prototype, 'abort',
|
||||
(delegate: Function) => (self: any, args: any) => {
|
||||
if (self.task) {
|
||||
return self.task.zone.cancelTask(self.task);
|
||||
}
|
||||
return delegate.apply(self, args);
|
||||
});
|
||||
}
|
||||
const placeholder = function() {};
|
||||
global['fetch'] = function() {
|
||||
const args = Array.prototype.slice.call(arguments);
|
||||
const options = args.length > 1 ? args[1] : null;
|
||||
const signal = options && options.signal;
|
||||
return new Promise((res, rej) => {
|
||||
const task = Zone.current.scheduleMacroTask(
|
||||
'fetch', placeholder, { fetchArgs: args } as FetchTaskData,
|
||||
() => {
|
||||
let fetchPromise;
|
||||
let zone = Zone.current;
|
||||
try {
|
||||
(zone as any)[fetchTaskScheduling] = true;
|
||||
fetchPromise = fetch.apply(this, args);
|
||||
} catch (error) {
|
||||
rej(error);
|
||||
return;
|
||||
} finally {
|
||||
(zone as any)[fetchTaskScheduling] = false;
|
||||
}
|
||||
|
||||
if (!(fetchPromise instanceof ZoneAwarePromise)) {
|
||||
let ctor = fetchPromise.constructor;
|
||||
if (!ctor[symbolThenPatched]) {
|
||||
api.patchThen(ctor);
|
||||
}
|
||||
}
|
||||
fetchPromise.then(
|
||||
(resource: any) => {
|
||||
if (task.state !== 'notScheduled') {
|
||||
task.invoke();
|
||||
}
|
||||
res(resource);
|
||||
},
|
||||
(error: any) => {
|
||||
if (task.state !== 'notScheduled') {
|
||||
task.invoke();
|
||||
}
|
||||
rej(error);
|
||||
});
|
||||
},
|
||||
() => {
|
||||
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 as any)[fetchTaskAborting] = true;
|
||||
abortNative.call(signal.abortController);
|
||||
} finally {
|
||||
(Zone.current as any)[fetchTaskAborting] = false;
|
||||
}
|
||||
} else {
|
||||
rej('cancel fetch need a AbortController.signal');
|
||||
}
|
||||
});
|
||||
if (signal && signal.abortController) {
|
||||
signal.abortController.task = task;
|
||||
}
|
||||
});
|
||||
};
|
||||
});
|
481
packages/zone.js/lib/common/promise.ts
Normal file
481
packages/zone.js/lib/common/promise.ts
Normal file
@ -0,0 +1,481 @@
|
||||
/**
|
||||
* @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('ZoneAwarePromise', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
|
||||
const ObjectDefineProperty = Object.defineProperty;
|
||||
|
||||
function readableObjectToString(obj: any) {
|
||||
if (obj && obj.toString === Object.prototype.toString) {
|
||||
const className = obj.constructor && obj.constructor.name;
|
||||
return (className ? className : '') + ': ' + JSON.stringify(obj);
|
||||
}
|
||||
|
||||
return obj ? obj.toString() : Object.prototype.toString.call(obj);
|
||||
}
|
||||
|
||||
const __symbol__ = api.symbol;
|
||||
const _uncaughtPromiseErrors: UncaughtPromiseError[] = [];
|
||||
const symbolPromise = __symbol__('Promise');
|
||||
const symbolThen = __symbol__('then');
|
||||
const creationTrace = '__creationTrace__';
|
||||
|
||||
api.onUnhandledError = (e: any) => {
|
||||
if (api.showUncaughtError()) {
|
||||
const rejection = e && e.rejection;
|
||||
if (rejection) {
|
||||
console.error(
|
||||
'Unhandled Promise rejection:',
|
||||
rejection instanceof Error ? rejection.message : rejection, '; Zone:',
|
||||
(<Zone>e.zone).name, '; Task:', e.task && (<Task>e.task).source, '; Value:', rejection,
|
||||
rejection instanceof Error ? rejection.stack : undefined);
|
||||
} else {
|
||||
console.error(e);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
api.microtaskDrainDone = () => {
|
||||
while (_uncaughtPromiseErrors.length) {
|
||||
while (_uncaughtPromiseErrors.length) {
|
||||
const uncaughtPromiseError: UncaughtPromiseError = _uncaughtPromiseErrors.shift() !;
|
||||
try {
|
||||
uncaughtPromiseError.zone.runGuarded(() => { throw uncaughtPromiseError; });
|
||||
} catch (error) {
|
||||
handleUnhandledRejection(error);
|
||||
}
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
|
||||
|
||||
function handleUnhandledRejection(e: any) {
|
||||
api.onUnhandledError(e);
|
||||
try {
|
||||
const handler = (Zone as any)[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
|
||||
if (handler && typeof handler === 'function') {
|
||||
handler.call(this, e);
|
||||
}
|
||||
} catch (err) {
|
||||
}
|
||||
}
|
||||
|
||||
function isThenable(value: any): boolean { return value && value.then; }
|
||||
|
||||
function forwardResolution(value: any): any { return value; }
|
||||
|
||||
function forwardRejection(rejection: any): any { return ZoneAwarePromise.reject(rejection); }
|
||||
|
||||
const symbolState: string = __symbol__('state');
|
||||
const symbolValue: string = __symbol__('value');
|
||||
const symbolFinally: string = __symbol__('finally');
|
||||
const symbolParentPromiseValue: string = __symbol__('parentPromiseValue');
|
||||
const symbolParentPromiseState: string = __symbol__('parentPromiseState');
|
||||
const source: string = 'Promise.then';
|
||||
const UNRESOLVED: null = null;
|
||||
const RESOLVED = true;
|
||||
const REJECTED = false;
|
||||
const REJECTED_NO_CATCH = 0;
|
||||
|
||||
function makeResolver(promise: ZoneAwarePromise<any>, state: boolean): (value: any) => void {
|
||||
return (v) => {
|
||||
try {
|
||||
resolvePromise(promise, state, v);
|
||||
} catch (err) {
|
||||
resolvePromise(promise, false, err);
|
||||
}
|
||||
// Do not return value or you will break the Promise spec.
|
||||
};
|
||||
}
|
||||
|
||||
const once = function() {
|
||||
let wasCalled = false;
|
||||
|
||||
return function wrapper(wrappedFunction: Function) {
|
||||
return function() {
|
||||
if (wasCalled) {
|
||||
return;
|
||||
}
|
||||
wasCalled = true;
|
||||
wrappedFunction.apply(null, arguments);
|
||||
};
|
||||
};
|
||||
};
|
||||
|
||||
const TYPE_ERROR = 'Promise resolved with itself';
|
||||
const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
|
||||
|
||||
// Promise Resolution
|
||||
function resolvePromise(
|
||||
promise: ZoneAwarePromise<any>, state: boolean, value: any): ZoneAwarePromise<any> {
|
||||
const onceWrapper = once();
|
||||
if (promise === value) {
|
||||
throw new TypeError(TYPE_ERROR);
|
||||
}
|
||||
if ((promise as any)[symbolState] === UNRESOLVED) {
|
||||
// should only get value.then once based on promise spec.
|
||||
let then: any = null;
|
||||
try {
|
||||
if (typeof value === 'object' || typeof value === 'function') {
|
||||
then = value && value.then;
|
||||
}
|
||||
} catch (err) {
|
||||
onceWrapper(() => { resolvePromise(promise, false, err); })();
|
||||
return promise;
|
||||
}
|
||||
// if (value instanceof ZoneAwarePromise) {
|
||||
if (state !== REJECTED && value instanceof ZoneAwarePromise &&
|
||||
value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
|
||||
(value as any)[symbolState] !== UNRESOLVED) {
|
||||
clearRejectedNoCatch(<Promise<any>>value as any);
|
||||
resolvePromise(promise, (value as any)[symbolState], (value as any)[symbolValue]);
|
||||
} else if (state !== REJECTED && typeof then === 'function') {
|
||||
try {
|
||||
then.call(
|
||||
value, onceWrapper(makeResolver(promise, state)),
|
||||
onceWrapper(makeResolver(promise, false)));
|
||||
} catch (err) {
|
||||
onceWrapper(() => { resolvePromise(promise, false, err); })();
|
||||
}
|
||||
} else {
|
||||
(promise as any)[symbolState] = state;
|
||||
const queue = (promise as any)[symbolValue];
|
||||
(promise as any)[symbolValue] = value;
|
||||
|
||||
if ((promise as any)[symbolFinally] === symbolFinally) {
|
||||
// the promise is generated by Promise.prototype.finally
|
||||
if (state === RESOLVED) {
|
||||
// the state is resolved, should ignore the value
|
||||
// and use parent promise value
|
||||
(promise as any)[symbolState] = (promise as any)[symbolParentPromiseState];
|
||||
(promise as any)[symbolValue] = (promise as any)[symbolParentPromiseValue];
|
||||
}
|
||||
}
|
||||
|
||||
// record task information in value when error occurs, so we can
|
||||
// do some additional work such as render longStackTrace
|
||||
if (state === REJECTED && value instanceof Error) {
|
||||
// check if longStackTraceZone is here
|
||||
const trace = Zone.currentTask && Zone.currentTask.data &&
|
||||
(Zone.currentTask.data as any)[creationTrace];
|
||||
if (trace) {
|
||||
// only keep the long stack trace into error when in longStackTraceZone
|
||||
ObjectDefineProperty(
|
||||
value, CURRENT_TASK_TRACE_SYMBOL,
|
||||
{configurable: true, enumerable: false, writable: true, value: trace});
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < queue.length;) {
|
||||
scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
|
||||
}
|
||||
if (queue.length == 0 && state == REJECTED) {
|
||||
(promise as any)[symbolState] = REJECTED_NO_CATCH;
|
||||
try {
|
||||
// try to print more readable error log
|
||||
throw new Error(
|
||||
'Uncaught (in promise): ' + readableObjectToString(value) +
|
||||
(value && value.stack ? '\n' + value.stack : ''));
|
||||
} catch (err) {
|
||||
const error: UncaughtPromiseError = err;
|
||||
error.rejection = value;
|
||||
error.promise = promise;
|
||||
error.zone = Zone.current;
|
||||
error.task = Zone.currentTask !;
|
||||
_uncaughtPromiseErrors.push(error);
|
||||
api.scheduleMicroTask(); // to make sure that it is running
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// Resolving an already resolved promise is a noop.
|
||||
return promise;
|
||||
}
|
||||
|
||||
const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
|
||||
function clearRejectedNoCatch(promise: ZoneAwarePromise<any>): void {
|
||||
if ((promise as any)[symbolState] === REJECTED_NO_CATCH) {
|
||||
// if the promise is rejected no catch status
|
||||
// and queue.length > 0, means there is a error handler
|
||||
// here to handle the rejected promise, we should trigger
|
||||
// windows.rejectionhandled eventHandler or nodejs rejectionHandled
|
||||
// eventHandler
|
||||
try {
|
||||
const handler = (Zone as any)[REJECTION_HANDLED_HANDLER];
|
||||
if (handler && typeof handler === 'function') {
|
||||
handler.call(this, {rejection: (promise as any)[symbolValue], promise: promise});
|
||||
}
|
||||
} catch (err) {
|
||||
}
|
||||
(promise as any)[symbolState] = REJECTED;
|
||||
for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
|
||||
if (promise === _uncaughtPromiseErrors[i].promise) {
|
||||
_uncaughtPromiseErrors.splice(i, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function scheduleResolveOrReject<R, U1, U2>(
|
||||
promise: ZoneAwarePromise<any>, zone: AmbientZone, chainPromise: ZoneAwarePromise<any>,
|
||||
onFulfilled?: ((value: R) => U1) | null | undefined,
|
||||
onRejected?: ((error: any) => U2) | null | undefined): void {
|
||||
clearRejectedNoCatch(promise);
|
||||
const promiseState = (promise as any)[symbolState];
|
||||
const delegate = promiseState ?
|
||||
(typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
|
||||
(typeof onRejected === 'function') ? onRejected : forwardRejection;
|
||||
zone.scheduleMicroTask(source, () => {
|
||||
try {
|
||||
const parentPromiseValue = (promise as any)[symbolValue];
|
||||
const isFinallyPromise =
|
||||
!!chainPromise && symbolFinally === (chainPromise as any)[symbolFinally];
|
||||
if (isFinallyPromise) {
|
||||
// if the promise is generated from finally call, keep parent promise's state and value
|
||||
(chainPromise as any)[symbolParentPromiseValue] = parentPromiseValue;
|
||||
(chainPromise as any)[symbolParentPromiseState] = promiseState;
|
||||
}
|
||||
// should not pass value to finally callback
|
||||
const value = zone.run(
|
||||
delegate, undefined,
|
||||
isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
|
||||
[] :
|
||||
[parentPromiseValue]);
|
||||
resolvePromise(chainPromise, true, value);
|
||||
} catch (error) {
|
||||
// if error occurs, should always return this error
|
||||
resolvePromise(chainPromise, false, error);
|
||||
}
|
||||
}, chainPromise as TaskData);
|
||||
}
|
||||
|
||||
const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
|
||||
|
||||
class ZoneAwarePromise<R> implements Promise<R> {
|
||||
static toString() { return ZONE_AWARE_PROMISE_TO_STRING; }
|
||||
|
||||
static resolve<R>(value: R): Promise<R> {
|
||||
return resolvePromise(<ZoneAwarePromise<R>>new this(null as any), RESOLVED, value);
|
||||
}
|
||||
|
||||
static reject<U>(error: U): Promise<U> {
|
||||
return resolvePromise(<ZoneAwarePromise<U>>new this(null as any), REJECTED, error);
|
||||
}
|
||||
|
||||
static race<R>(values: PromiseLike<any>[]): Promise<R> {
|
||||
let resolve: (v: any) => void;
|
||||
let reject: (v: any) => void;
|
||||
let promise: any = new this((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
function onResolve(value: any) { resolve(value); }
|
||||
function onReject(error: any) { reject(error); }
|
||||
|
||||
for (let value of values) {
|
||||
if (!isThenable(value)) {
|
||||
value = this.resolve(value);
|
||||
}
|
||||
value.then(onResolve, onReject);
|
||||
}
|
||||
return promise;
|
||||
}
|
||||
|
||||
static all<R>(values: any): Promise<R> {
|
||||
let resolve: (v: any) => void;
|
||||
let reject: (v: any) => void;
|
||||
let promise = new this<R>((res, rej) => {
|
||||
resolve = res;
|
||||
reject = rej;
|
||||
});
|
||||
|
||||
// Start at 2 to prevent prematurely resolving if .then is called immediately.
|
||||
let unresolvedCount = 2;
|
||||
let valueIndex = 0;
|
||||
|
||||
const resolvedValues: any[] = [];
|
||||
for (let value of values) {
|
||||
if (!isThenable(value)) {
|
||||
value = this.resolve(value);
|
||||
}
|
||||
|
||||
const curValueIndex = valueIndex;
|
||||
value.then((value: any) => {
|
||||
resolvedValues[curValueIndex] = value;
|
||||
unresolvedCount--;
|
||||
if (unresolvedCount === 0) {
|
||||
resolve !(resolvedValues);
|
||||
}
|
||||
}, reject !);
|
||||
|
||||
unresolvedCount++;
|
||||
valueIndex++;
|
||||
}
|
||||
|
||||
// Make the unresolvedCount zero-based again.
|
||||
unresolvedCount -= 2;
|
||||
|
||||
if (unresolvedCount === 0) {
|
||||
resolve !(resolvedValues);
|
||||
}
|
||||
|
||||
return promise;
|
||||
}
|
||||
|
||||
constructor(
|
||||
executor:
|
||||
(resolve: (value?: R|PromiseLike<R>) => void, reject: (error?: any) => void) => void) {
|
||||
const promise: ZoneAwarePromise<R> = this;
|
||||
if (!(promise instanceof ZoneAwarePromise)) {
|
||||
throw new Error('Must be an instanceof Promise.');
|
||||
}
|
||||
(promise as any)[symbolState] = UNRESOLVED;
|
||||
(promise as any)[symbolValue] = []; // queue;
|
||||
try {
|
||||
executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
|
||||
} catch (error) {
|
||||
resolvePromise(promise, false, error);
|
||||
}
|
||||
}
|
||||
|
||||
get[Symbol.toStringTag]() { return 'Promise' as any; }
|
||||
|
||||
then<TResult1 = R, TResult2 = never>(
|
||||
onFulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>)|undefined|null,
|
||||
onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>)|undefined|
|
||||
null): Promise<TResult1|TResult2> {
|
||||
const chainPromise: Promise<TResult1|TResult2> =
|
||||
new (this.constructor as typeof ZoneAwarePromise)(null as any);
|
||||
const zone = Zone.current;
|
||||
if ((this as any)[symbolState] == UNRESOLVED) {
|
||||
(<any[]>(this as any)[symbolValue]).push(zone, chainPromise, onFulfilled, onRejected);
|
||||
} else {
|
||||
scheduleResolveOrReject(this, zone, chainPromise as any, onFulfilled, onRejected);
|
||||
}
|
||||
return chainPromise;
|
||||
}
|
||||
|
||||
catch<TResult = never>(onRejected?: ((reason: any) => TResult | PromiseLike<TResult>)|undefined|
|
||||
null): Promise<R|TResult> {
|
||||
return this.then(null, onRejected);
|
||||
}
|
||||
|
||||
finally<U>(onFinally?: () => U | PromiseLike<U>): Promise<R> {
|
||||
const chainPromise: Promise<R|never> =
|
||||
new (this.constructor as typeof ZoneAwarePromise)(null as any);
|
||||
(chainPromise as any)[symbolFinally] = symbolFinally;
|
||||
const zone = Zone.current;
|
||||
if ((this as any)[symbolState] == UNRESOLVED) {
|
||||
(<any[]>(this as any)[symbolValue]).push(zone, chainPromise, onFinally, onFinally);
|
||||
} else {
|
||||
scheduleResolveOrReject(this, zone, chainPromise as any, onFinally, onFinally);
|
||||
}
|
||||
return chainPromise;
|
||||
}
|
||||
}
|
||||
// Protect against aggressive optimizers dropping seemingly unused properties.
|
||||
// E.g. Closure Compiler in advanced mode.
|
||||
ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
|
||||
ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
|
||||
ZoneAwarePromise['race'] = ZoneAwarePromise.race;
|
||||
ZoneAwarePromise['all'] = ZoneAwarePromise.all;
|
||||
|
||||
const NativePromise = global[symbolPromise] = global['Promise'];
|
||||
const ZONE_AWARE_PROMISE = Zone.__symbol__('ZoneAwarePromise');
|
||||
|
||||
let desc = ObjectGetOwnPropertyDescriptor(global, 'Promise');
|
||||
if (!desc || desc.configurable) {
|
||||
desc && delete desc.writable;
|
||||
desc && delete desc.value;
|
||||
if (!desc) {
|
||||
desc = {configurable: true, enumerable: true};
|
||||
}
|
||||
desc.get = function() {
|
||||
// if we already set ZoneAwarePromise, use patched one
|
||||
// otherwise return native one.
|
||||
return global[ZONE_AWARE_PROMISE] ? global[ZONE_AWARE_PROMISE] : global[symbolPromise];
|
||||
};
|
||||
desc.set = function(NewNativePromise) {
|
||||
if (NewNativePromise === ZoneAwarePromise) {
|
||||
// if the NewNativePromise is ZoneAwarePromise
|
||||
// save to global
|
||||
global[ZONE_AWARE_PROMISE] = NewNativePromise;
|
||||
} else {
|
||||
// if the NewNativePromise is not ZoneAwarePromise
|
||||
// for example: after load zone.js, some library just
|
||||
// set es6-promise to global, if we set it to global
|
||||
// directly, assertZonePatched will fail and angular
|
||||
// will not loaded, so we just set the NewNativePromise
|
||||
// to global[symbolPromise], so the result is just like
|
||||
// we load ES6 Promise before zone.js
|
||||
global[symbolPromise] = NewNativePromise;
|
||||
if (!NewNativePromise.prototype[symbolThen]) {
|
||||
patchThen(NewNativePromise);
|
||||
}
|
||||
api.setNativePromise(NewNativePromise);
|
||||
}
|
||||
};
|
||||
|
||||
ObjectDefineProperty(global, 'Promise', desc);
|
||||
}
|
||||
|
||||
global['Promise'] = ZoneAwarePromise;
|
||||
|
||||
const symbolThenPatched = __symbol__('thenPatched');
|
||||
|
||||
function patchThen(Ctor: Function) {
|
||||
const proto = Ctor.prototype;
|
||||
|
||||
const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
|
||||
if (prop && (prop.writable === false || !prop.configurable)) {
|
||||
// check Ctor.prototype.then propertyDescriptor is writable or not
|
||||
// in meteor env, writable is false, we should ignore such case
|
||||
return;
|
||||
}
|
||||
|
||||
const originalThen = proto.then;
|
||||
// Keep a reference to the original method.
|
||||
proto[symbolThen] = originalThen;
|
||||
|
||||
Ctor.prototype.then = function(onResolve: any, onReject: any) {
|
||||
const wrapped =
|
||||
new ZoneAwarePromise((resolve, reject) => { originalThen.call(this, resolve, reject); });
|
||||
return wrapped.then(onResolve, onReject);
|
||||
};
|
||||
(Ctor as any)[symbolThenPatched] = true;
|
||||
}
|
||||
|
||||
api.patchThen = patchThen;
|
||||
|
||||
function zoneify(fn: Function) {
|
||||
return function() {
|
||||
let resultPromise = fn.apply(this, arguments);
|
||||
if (resultPromise instanceof ZoneAwarePromise) {
|
||||
return resultPromise;
|
||||
}
|
||||
let ctor = resultPromise.constructor;
|
||||
if (!ctor[symbolThenPatched]) {
|
||||
patchThen(ctor);
|
||||
}
|
||||
return resultPromise;
|
||||
};
|
||||
}
|
||||
|
||||
if (NativePromise) {
|
||||
patchThen(NativePromise);
|
||||
const fetch = global['fetch'];
|
||||
if (typeof fetch == 'function') {
|
||||
global[api.symbol('fetch')] = fetch;
|
||||
global['fetch'] = zoneify(fetch);
|
||||
}
|
||||
}
|
||||
|
||||
// This is not part of public API, but it is useful for tests, so we expose it.
|
||||
(Promise as any)[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
|
||||
return ZoneAwarePromise;
|
||||
});
|
133
packages/zone.js/lib/common/timers.ts
Normal file
133
packages/zone.js/lib/common/timers.ts
Normal file
@ -0,0 +1,133 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {missingRequire}
|
||||
*/
|
||||
|
||||
import {patchMethod, scheduleMacroTaskWithCurrentZone, zoneSymbol} from './utils';
|
||||
|
||||
const taskSymbol = zoneSymbol('zoneTask');
|
||||
|
||||
interface TimerOptions extends TaskData {
|
||||
handleId?: number;
|
||||
args: any[];
|
||||
}
|
||||
|
||||
export function patchTimer(window: any, setName: string, cancelName: string, nameSuffix: string) {
|
||||
let setNative: Function|null = null;
|
||||
let clearNative: Function|null = null;
|
||||
setName += nameSuffix;
|
||||
cancelName += nameSuffix;
|
||||
|
||||
const tasksByHandleId: {[id: number]: Task} = {};
|
||||
|
||||
function scheduleTask(task: Task) {
|
||||
const data = <TimerOptions>task.data;
|
||||
function timer() {
|
||||
try {
|
||||
task.invoke.apply(this, arguments);
|
||||
} finally {
|
||||
// issue-934, task will be cancelled
|
||||
// even it is a periodic task such as
|
||||
// setInterval
|
||||
if (!(task.data && task.data.isPeriodic)) {
|
||||
if (typeof data.handleId === 'number') {
|
||||
// in non-nodejs env, we remove timerId
|
||||
// from local cache
|
||||
delete tasksByHandleId[data.handleId];
|
||||
} else if (data.handleId) {
|
||||
// Node returns complex objects as handleIds
|
||||
// we remove task reference from timer object
|
||||
(data.handleId as any)[taskSymbol] = null;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
data.args[0] = timer;
|
||||
data.handleId = setNative !.apply(window, data.args);
|
||||
return task;
|
||||
}
|
||||
|
||||
function clearTask(task: Task) { return clearNative !((<TimerOptions>task.data).handleId); }
|
||||
|
||||
setNative =
|
||||
patchMethod(window, setName, (delegate: Function) => function(self: any, args: any[]) {
|
||||
if (typeof args[0] === 'function') {
|
||||
const options: TimerOptions = {
|
||||
isPeriodic: nameSuffix === 'Interval',
|
||||
delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
|
||||
undefined,
|
||||
args: args
|
||||
};
|
||||
const task =
|
||||
scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
|
||||
if (!task) {
|
||||
return task;
|
||||
}
|
||||
// Node.js must additionally support the ref and unref functions.
|
||||
const handle: any = (<TimerOptions>task.data).handleId;
|
||||
if (typeof handle === 'number') {
|
||||
// for non nodejs env, we save handleId: task
|
||||
// mapping in local cache for clearTimeout
|
||||
tasksByHandleId[handle] = task;
|
||||
} else if (handle) {
|
||||
// for nodejs env, we save task
|
||||
// reference in timerId Object for clearTimeout
|
||||
handle[taskSymbol] = task;
|
||||
}
|
||||
|
||||
// check whether handle is null, because some polyfill or browser
|
||||
// may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
|
||||
if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
|
||||
typeof handle.unref === 'function') {
|
||||
(<any>task).ref = (<any>handle).ref.bind(handle);
|
||||
(<any>task).unref = (<any>handle).unref.bind(handle);
|
||||
}
|
||||
if (typeof handle === 'number' || handle) {
|
||||
return handle;
|
||||
}
|
||||
return task;
|
||||
} else {
|
||||
// cause an error by calling it directly.
|
||||
return delegate.apply(window, args);
|
||||
}
|
||||
});
|
||||
|
||||
clearNative =
|
||||
patchMethod(window, cancelName, (delegate: Function) => function(self: any, args: any[]) {
|
||||
const id = args[0];
|
||||
let task: Task;
|
||||
if (typeof id === 'number') {
|
||||
// non nodejs env.
|
||||
task = tasksByHandleId[id];
|
||||
} else {
|
||||
// nodejs env.
|
||||
task = id && id[taskSymbol];
|
||||
// other environments.
|
||||
if (!task) {
|
||||
task = id;
|
||||
}
|
||||
}
|
||||
if (task && typeof task.type === 'string') {
|
||||
if (task.state !== 'notScheduled' &&
|
||||
(task.cancelFn && task.data !.isPeriodic || task.runCount === 0)) {
|
||||
if (typeof id === 'number') {
|
||||
delete tasksByHandleId[id];
|
||||
} else if (id) {
|
||||
id[taskSymbol] = null;
|
||||
}
|
||||
// Do not cancel already canceled functions
|
||||
task.zone.cancelTask(task);
|
||||
}
|
||||
} else {
|
||||
// cause an error by calling it directly.
|
||||
delegate.apply(window, args);
|
||||
}
|
||||
});
|
||||
}
|
57
packages/zone.js/lib/common/to-string.ts
Normal file
57
packages/zone.js/lib/common/to-string.ts
Normal file
@ -0,0 +1,57 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
import {zoneSymbol} from './utils';
|
||||
|
||||
// override Function.prototype.toString to make zone.js patched function
|
||||
// look like native function
|
||||
Zone.__load_patch('toString', (global: any) => {
|
||||
// patch Func.prototype.toString to let them look like native
|
||||
const originalFunctionToString = Function.prototype.toString;
|
||||
|
||||
const ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
|
||||
const PROMISE_SYMBOL = zoneSymbol('Promise');
|
||||
const ERROR_SYMBOL = zoneSymbol('Error');
|
||||
const newFunctionToString = function toString() {
|
||||
if (typeof this === 'function') {
|
||||
const originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
|
||||
if (originalDelegate) {
|
||||
if (typeof originalDelegate === 'function') {
|
||||
return originalFunctionToString.call(originalDelegate);
|
||||
} else {
|
||||
return Object.prototype.toString.call(originalDelegate);
|
||||
}
|
||||
}
|
||||
if (this === Promise) {
|
||||
const nativePromise = global[PROMISE_SYMBOL];
|
||||
if (nativePromise) {
|
||||
return originalFunctionToString.call(nativePromise);
|
||||
}
|
||||
}
|
||||
if (this === Error) {
|
||||
const nativeError = global[ERROR_SYMBOL];
|
||||
if (nativeError) {
|
||||
return originalFunctionToString.call(nativeError);
|
||||
}
|
||||
}
|
||||
}
|
||||
return originalFunctionToString.call(this);
|
||||
};
|
||||
(newFunctionToString as any)[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
|
||||
Function.prototype.toString = newFunctionToString;
|
||||
|
||||
|
||||
// patch Object.prototype.toString to let them look like native
|
||||
const originalObjectToString = Object.prototype.toString;
|
||||
const PROMISE_OBJECT_TO_STRING = '[object Promise]';
|
||||
Object.prototype.toString = function() {
|
||||
if (this instanceof Promise) {
|
||||
return PROMISE_OBJECT_TO_STRING;
|
||||
}
|
||||
return originalObjectToString.call(this);
|
||||
};
|
||||
});
|
509
packages/zone.js/lib/common/utils.ts
Normal file
509
packages/zone.js/lib/common/utils.ts
Normal file
@ -0,0 +1,509 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* Suppress closure compiler errors about unknown 'Zone' variable
|
||||
* @fileoverview
|
||||
* @suppress {undefinedVars,globalThis,missingRequire}
|
||||
*/
|
||||
|
||||
/// <reference types="node"/>
|
||||
|
||||
// issue #989, to reduce bundle size, use short name
|
||||
/** Object.getOwnPropertyDescriptor */
|
||||
export const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
|
||||
/** Object.defineProperty */
|
||||
export const ObjectDefineProperty = Object.defineProperty;
|
||||
/** Object.getPrototypeOf */
|
||||
export const ObjectGetPrototypeOf = Object.getPrototypeOf;
|
||||
/** Object.create */
|
||||
export const ObjectCreate = Object.create;
|
||||
/** Array.prototype.slice */
|
||||
export const ArraySlice = Array.prototype.slice;
|
||||
/** addEventListener string const */
|
||||
export const ADD_EVENT_LISTENER_STR = 'addEventListener';
|
||||
/** removeEventListener string const */
|
||||
export const REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
|
||||
/** zoneSymbol addEventListener */
|
||||
export const ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR);
|
||||
/** zoneSymbol removeEventListener */
|
||||
export const ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
|
||||
/** true string const */
|
||||
export const TRUE_STR = 'true';
|
||||
/** false string const */
|
||||
export const FALSE_STR = 'false';
|
||||
/** Zone symbol prefix string const. */
|
||||
export const ZONE_SYMBOL_PREFIX = Zone.__symbol__('');
|
||||
|
||||
export function wrapWithCurrentZone<T extends Function>(callback: T, source: string): T {
|
||||
return Zone.current.wrap(callback, source);
|
||||
}
|
||||
|
||||
export function scheduleMacroTaskWithCurrentZone(
|
||||
source: string, callback: Function, data?: TaskData, customSchedule?: (task: Task) => void,
|
||||
customCancel?: (task: Task) => void): MacroTask {
|
||||
return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
|
||||
}
|
||||
|
||||
// Hack since TypeScript isn't compiling this for a worker.
|
||||
declare const WorkerGlobalScope: any;
|
||||
|
||||
export const zoneSymbol = Zone.__symbol__;
|
||||
const isWindowExists = typeof window !== 'undefined';
|
||||
const internalWindow: any = isWindowExists ? window : undefined;
|
||||
const _global: any = isWindowExists && internalWindow || typeof self === 'object' && self || global;
|
||||
|
||||
const REMOVE_ATTRIBUTE = 'removeAttribute';
|
||||
const NULL_ON_PROP_VALUE: [any] = [null];
|
||||
|
||||
export function bindArguments(args: any[], source: string): any[] {
|
||||
for (let i = args.length - 1; i >= 0; i--) {
|
||||
if (typeof args[i] === 'function') {
|
||||
args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
|
||||
}
|
||||
}
|
||||
return args;
|
||||
}
|
||||
|
||||
export function patchPrototype(prototype: any, fnNames: string[]) {
|
||||
const source = prototype.constructor['name'];
|
||||
for (let i = 0; i < fnNames.length; i++) {
|
||||
const name = fnNames[i];
|
||||
const delegate = prototype[name];
|
||||
if (delegate) {
|
||||
const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name);
|
||||
if (!isPropertyWritable(prototypeDesc)) {
|
||||
continue;
|
||||
}
|
||||
prototype[name] = ((delegate: Function) => {
|
||||
const patched: any = function() {
|
||||
return delegate.apply(this, bindArguments(<any>arguments, source + '.' + name));
|
||||
};
|
||||
attachOriginToPatched(patched, delegate);
|
||||
return patched;
|
||||
})(delegate);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function isPropertyWritable(propertyDesc: any) {
|
||||
if (!propertyDesc) {
|
||||
return true;
|
||||
}
|
||||
|
||||
if (propertyDesc.writable === false) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
|
||||
}
|
||||
|
||||
export const isWebWorker: boolean =
|
||||
(typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
|
||||
|
||||
// Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
|
||||
// this code.
|
||||
export const isNode: boolean =
|
||||
(!('nw' in _global) && typeof _global.process !== 'undefined' &&
|
||||
{}.toString.call(_global.process) === '[object process]');
|
||||
|
||||
export const isBrowser: boolean =
|
||||
!isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
|
||||
|
||||
// we are in electron of nw, so we are both browser and nodejs
|
||||
// Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
|
||||
// this code.
|
||||
export const isMix: boolean = typeof _global.process !== 'undefined' &&
|
||||
{}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
|
||||
!!(isWindowExists && internalWindow['HTMLElement']);
|
||||
|
||||
const zoneSymbolEventNames: {[eventName: string]: string} = {};
|
||||
|
||||
const wrapFn = function(event: Event) {
|
||||
// https://github.com/angular/zone.js/issues/911, in IE, sometimes
|
||||
// event will be undefined, so we need to use window.event
|
||||
event = event || _global.event;
|
||||
if (!event) {
|
||||
return;
|
||||
}
|
||||
let eventNameSymbol = zoneSymbolEventNames[event.type];
|
||||
if (!eventNameSymbol) {
|
||||
eventNameSymbol = zoneSymbolEventNames[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
|
||||
}
|
||||
const target = this || event.target || _global;
|
||||
const listener = target[eventNameSymbol];
|
||||
let 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
|
||||
const errorEvent: ErrorEvent = event as any;
|
||||
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;
|
||||
};
|
||||
|
||||
export function patchProperty(obj: any, prop: string, prototype?: any) {
|
||||
let desc = ObjectGetOwnPropertyDescriptor(obj, prop);
|
||||
if (!desc && prototype) {
|
||||
// when patch window object, use prototype to check prop exist or not
|
||||
const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
|
||||
if (prototypeDesc) {
|
||||
desc = {enumerable: true, configurable: true};
|
||||
}
|
||||
}
|
||||
// if the descriptor not exists or is not configurable
|
||||
// just return
|
||||
if (!desc || !desc.configurable) {
|
||||
return;
|
||||
}
|
||||
|
||||
const 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:
|
||||
//
|
||||
// TypeError: property descriptors must not specify a value or be writable when a
|
||||
// getter or setter has been specified
|
||||
delete desc.writable;
|
||||
delete desc.value;
|
||||
const originalDescGet = desc.get;
|
||||
const originalDescSet = desc.set;
|
||||
|
||||
// substr(2) cuz 'onclick' -> 'click', etc
|
||||
const eventName = prop.substr(2);
|
||||
|
||||
let eventNameSymbol = zoneSymbolEventNames[eventName];
|
||||
if (!eventNameSymbol) {
|
||||
eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
|
||||
}
|
||||
|
||||
desc.set = function(newValue) {
|
||||
// in some of windows's onproperty callback, this is undefined
|
||||
// so we need to check it
|
||||
let target = this;
|
||||
if (!target && obj === _global) {
|
||||
target = _global;
|
||||
}
|
||||
if (!target) {
|
||||
return;
|
||||
}
|
||||
let previousValue = target[eventNameSymbol];
|
||||
if (previousValue) {
|
||||
target.removeEventListener(eventName, wrapFn);
|
||||
}
|
||||
|
||||
// issue #978, when onload handler was added before loading zone.js
|
||||
// we should remove it with originalDescSet
|
||||
if (originalDescSet) {
|
||||
originalDescSet.apply(target, NULL_ON_PROP_VALUE);
|
||||
}
|
||||
|
||||
if (typeof newValue === 'function') {
|
||||
target[eventNameSymbol] = newValue;
|
||||
target.addEventListener(eventName, wrapFn, false);
|
||||
} else {
|
||||
target[eventNameSymbol] = null;
|
||||
}
|
||||
};
|
||||
|
||||
// The getter would return undefined for unassigned properties but the default value of an
|
||||
// unassigned property is null
|
||||
desc.get = function() {
|
||||
// in some of windows's onproperty callback, this is undefined
|
||||
// so we need to check it
|
||||
let target = this;
|
||||
if (!target && obj === _global) {
|
||||
target = _global;
|
||||
}
|
||||
if (!target) {
|
||||
return null;
|
||||
}
|
||||
const listener = target[eventNameSymbol];
|
||||
if (listener) {
|
||||
return listener;
|
||||
} else if (originalDescGet) {
|
||||
// result will be null when use inline event attribute,
|
||||
// such as <button onclick="func();">OK</button>
|
||||
// because the onclick function is internal raw uncompiled handler
|
||||
// the onclick will be evaluated when first time event was triggered or
|
||||
// the property is accessed, https://github.com/angular/zone.js/issues/525
|
||||
// so we should use original native get to retrieve the handler
|
||||
let value = originalDescGet && originalDescGet.call(this);
|
||||
if (value) {
|
||||
desc !.set !.call(this, value);
|
||||
if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
|
||||
target.removeAttribute(prop);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
|
||||
ObjectDefineProperty(obj, prop, desc);
|
||||
|
||||
obj[onPropPatchedSymbol] = true;
|
||||
}
|
||||
|
||||
export function patchOnProperties(obj: any, properties: string[] | null, prototype?: any) {
|
||||
if (properties) {
|
||||
for (let i = 0; i < properties.length; i++) {
|
||||
patchProperty(obj, 'on' + properties[i], prototype);
|
||||
}
|
||||
} else {
|
||||
const onProperties = [];
|
||||
for (const prop in obj) {
|
||||
if (prop.substr(0, 2) == 'on') {
|
||||
onProperties.push(prop);
|
||||
}
|
||||
}
|
||||
for (let j = 0; j < onProperties.length; j++) {
|
||||
patchProperty(obj, onProperties[j], prototype);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
const originalInstanceKey = zoneSymbol('originalInstance');
|
||||
|
||||
// wrap some native API on `window`
|
||||
export function patchClass(className: string) {
|
||||
const OriginalClass = _global[className];
|
||||
if (!OriginalClass) return;
|
||||
// keep original class in global
|
||||
_global[zoneSymbol(className)] = OriginalClass;
|
||||
|
||||
_global[className] = function() {
|
||||
const a = bindArguments(<any>arguments, className);
|
||||
switch (a.length) {
|
||||
case 0:
|
||||
this[originalInstanceKey] = new OriginalClass();
|
||||
break;
|
||||
case 1:
|
||||
this[originalInstanceKey] = new OriginalClass(a[0]);
|
||||
break;
|
||||
case 2:
|
||||
this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
|
||||
break;
|
||||
case 3:
|
||||
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
|
||||
break;
|
||||
case 4:
|
||||
this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
|
||||
break;
|
||||
default:
|
||||
throw new Error('Arg list too long.');
|
||||
}
|
||||
};
|
||||
|
||||
// attach original delegate to patched function
|
||||
attachOriginToPatched(_global[className], OriginalClass);
|
||||
|
||||
const instance = new OriginalClass(function() {});
|
||||
|
||||
let prop;
|
||||
for (prop in instance) {
|
||||
// https://bugs.webkit.org/show_bug.cgi?id=44721
|
||||
if (className === 'XMLHttpRequest' && prop === 'responseBlob') continue;
|
||||
(function(prop) {
|
||||
if (typeof instance[prop] === 'function') {
|
||||
_global[className].prototype[prop] = function() {
|
||||
return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
|
||||
};
|
||||
} else {
|
||||
ObjectDefineProperty(_global[className].prototype, prop, {
|
||||
set: function(fn) {
|
||||
if (typeof fn === 'function') {
|
||||
this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
|
||||
// keep callback in wrapped function so we can
|
||||
// use it in Function.prototype.toString to return
|
||||
// the native one.
|
||||
attachOriginToPatched(this[originalInstanceKey][prop], fn);
|
||||
} else {
|
||||
this[originalInstanceKey][prop] = fn;
|
||||
}
|
||||
},
|
||||
get: function() { return this[originalInstanceKey][prop]; }
|
||||
});
|
||||
}
|
||||
}(prop));
|
||||
}
|
||||
|
||||
for (prop in OriginalClass) {
|
||||
if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
|
||||
_global[className][prop] = OriginalClass[prop];
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export function copySymbolProperties(src: any, dest: any) {
|
||||
if (typeof(Object as any).getOwnPropertySymbols !== 'function') {
|
||||
return;
|
||||
}
|
||||
const symbols: any = (Object as any).getOwnPropertySymbols(src);
|
||||
symbols.forEach((symbol: any) => {
|
||||
const desc = Object.getOwnPropertyDescriptor(src, symbol);
|
||||
Object.defineProperty(dest, symbol, {
|
||||
get: function() { return src[symbol]; },
|
||||
set: function(value: any) {
|
||||
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
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
let shouldCopySymbolProperties = false;
|
||||
|
||||
export function setShouldCopySymbolProperties(flag: boolean) {
|
||||
shouldCopySymbolProperties = flag;
|
||||
}
|
||||
|
||||
export function patchMethod(
|
||||
target: any, name: string, patchFn: (delegate: Function, delegateName: string, name: string) =>
|
||||
(self: any, args: any[]) => any): Function|null {
|
||||
let proto = target;
|
||||
while (proto && !proto.hasOwnProperty(name)) {
|
||||
proto = ObjectGetPrototypeOf(proto);
|
||||
}
|
||||
if (!proto && target[name]) {
|
||||
// somehow we did not find it, but we can see it. This happens on IE for Window properties.
|
||||
proto = target;
|
||||
}
|
||||
|
||||
const delegateName = zoneSymbol(name);
|
||||
let delegate: Function|null = null;
|
||||
if (proto && !(delegate = proto[delegateName])) {
|
||||
delegate = proto[delegateName] = proto[name];
|
||||
// check whether proto[name] is writable
|
||||
// some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
|
||||
const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
|
||||
if (isPropertyWritable(desc)) {
|
||||
const patchDelegate = patchFn(delegate !, delegateName, name);
|
||||
proto[name] = function() { return patchDelegate(this, arguments as any); };
|
||||
attachOriginToPatched(proto[name], delegate);
|
||||
if (shouldCopySymbolProperties) {
|
||||
copySymbolProperties(delegate, proto[name]);
|
||||
}
|
||||
}
|
||||
}
|
||||
return delegate;
|
||||
}
|
||||
|
||||
export interface MacroTaskMeta extends TaskData {
|
||||
name: string;
|
||||
target: any;
|
||||
cbIdx: number;
|
||||
args: any[];
|
||||
}
|
||||
|
||||
// TODO: @JiaLiPassion, support cancel task later if necessary
|
||||
export function patchMacroTask(
|
||||
obj: any, funcName: string, metaCreator: (self: any, args: any[]) => MacroTaskMeta) {
|
||||
let setNative: Function|null = null;
|
||||
|
||||
function scheduleTask(task: Task) {
|
||||
const data = <MacroTaskMeta>task.data;
|
||||
data.args[data.cbIdx] = function() { task.invoke.apply(this, arguments); };
|
||||
setNative !.apply(data.target, data.args);
|
||||
return task;
|
||||
}
|
||||
|
||||
setNative = patchMethod(obj, funcName, (delegate: Function) => function(self: any, args: any[]) {
|
||||
const meta = metaCreator(self, args);
|
||||
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
|
||||
return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
|
||||
} else {
|
||||
// cause an error by calling it directly.
|
||||
return delegate.apply(self, args);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export interface MicroTaskMeta extends TaskData {
|
||||
name: string;
|
||||
target: any;
|
||||
cbIdx: number;
|
||||
args: any[];
|
||||
}
|
||||
|
||||
export function patchMicroTask(
|
||||
obj: any, funcName: string, metaCreator: (self: any, args: any[]) => MicroTaskMeta) {
|
||||
let setNative: Function|null = null;
|
||||
|
||||
function scheduleTask(task: Task) {
|
||||
const data = <MacroTaskMeta>task.data;
|
||||
data.args[data.cbIdx] = function() { task.invoke.apply(this, arguments); };
|
||||
setNative !.apply(data.target, data.args);
|
||||
return task;
|
||||
}
|
||||
|
||||
setNative = patchMethod(obj, funcName, (delegate: Function) => function(self: any, args: any[]) {
|
||||
const meta = metaCreator(self, args);
|
||||
if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
|
||||
return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
|
||||
} else {
|
||||
// cause an error by calling it directly.
|
||||
return delegate.apply(self, args);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function attachOriginToPatched(patched: Function, original: any) {
|
||||
(patched as any)[zoneSymbol('OriginalDelegate')] = original;
|
||||
}
|
||||
|
||||
let isDetectedIEOrEdge = false;
|
||||
let ieOrEdge = false;
|
||||
|
||||
export function isIE() {
|
||||
try {
|
||||
const ua = internalWindow.navigator.userAgent;
|
||||
if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
|
||||
return true;
|
||||
}
|
||||
} catch (error) {
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
export function isIEOrEdge() {
|
||||
if (isDetectedIEOrEdge) {
|
||||
return ieOrEdge;
|
||||
}
|
||||
|
||||
isDetectedIEOrEdge = true;
|
||||
|
||||
try {
|
||||
const ua = internalWindow.navigator.userAgent;
|
||||
if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
|
||||
ieOrEdge = true;
|
||||
}
|
||||
} catch (error) {
|
||||
}
|
||||
return ieOrEdge;
|
||||
}
|
55
packages/zone.js/lib/extra/bluebird.ts
Normal file
55
packages/zone.js/lib/extra/bluebird.ts
Normal file
@ -0,0 +1,55 @@
|
||||
/**
|
||||
* @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('bluebird', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
// TODO: @JiaLiPassion, we can automatically patch bluebird
|
||||
// if global.Promise = Bluebird, but sometimes in nodejs,
|
||||
// global.Promise is not Bluebird, and Bluebird is just be
|
||||
// used by other libraries such as sequelize, so I think it is
|
||||
// safe to just expose a method to patch Bluebird explicitly
|
||||
const BLUEBIRD = 'bluebird';
|
||||
(Zone as any)[Zone.__symbol__(BLUEBIRD)] = function patchBluebird(Bluebird: any) {
|
||||
// patch method of Bluebird.prototype which not using `then` internally
|
||||
const bluebirdApis: string[] = ['then', 'spread', 'finally'];
|
||||
bluebirdApis.forEach(bapi => {
|
||||
api.patchMethod(
|
||||
Bluebird.prototype, bapi, (delegate: Function) => (self: any, args: any[]) => {
|
||||
const zone = Zone.current;
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
const func = args[i];
|
||||
if (typeof func === 'function') {
|
||||
args[i] = function() {
|
||||
const argSelf: any = this;
|
||||
const argArgs: any = arguments;
|
||||
return new Bluebird((res: any, rej: any) => {
|
||||
zone.scheduleMicroTask('Promise.then', () => {
|
||||
try {
|
||||
res(func.apply(argSelf, argArgs));
|
||||
} catch (error) {
|
||||
rej(error);
|
||||
}
|
||||
});
|
||||
});
|
||||
};
|
||||
}
|
||||
}
|
||||
return delegate.apply(self, args);
|
||||
});
|
||||
});
|
||||
|
||||
Bluebird.onPossiblyUnhandledRejection(function(e: any, promise: any) {
|
||||
try {
|
||||
Zone.current.runGuarded(() => { throw e; });
|
||||
} catch (err) {
|
||||
api.onUnhandledError(err);
|
||||
}
|
||||
});
|
||||
|
||||
// override global promise
|
||||
global[api.symbol('ZoneAwarePromise')] = Bluebird;
|
||||
};
|
||||
});
|
39
packages/zone.js/lib/extra/cordova.ts
Normal file
39
packages/zone.js/lib/extra/cordova.ts
Normal file
@ -0,0 +1,39 @@
|
||||
/**
|
||||
* @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('cordova', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
if (global.cordova) {
|
||||
const SUCCESS_SOURCE = 'cordova.exec.success';
|
||||
const ERROR_SOURCE = 'cordova.exec.error';
|
||||
const FUNCTION = 'function';
|
||||
const nativeExec: Function|null =
|
||||
api.patchMethod(global.cordova, 'exec', () => function(self: any, args: any[]) {
|
||||
if (args.length > 0 && typeof args[0] === FUNCTION) {
|
||||
args[0] = Zone.current.wrap(args[0], SUCCESS_SOURCE);
|
||||
}
|
||||
if (args.length > 1 && typeof args[1] === FUNCTION) {
|
||||
args[1] = Zone.current.wrap(args[1], ERROR_SOURCE);
|
||||
}
|
||||
return nativeExec !.apply(self, args);
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Zone.__load_patch('cordova.FileReader', (global: any, Zone: ZoneType) => {
|
||||
if (global.cordova && typeof global['FileReader'] !== 'undefined') {
|
||||
document.addEventListener('deviceReady', () => {
|
||||
const FileReader = global['FileReader'];
|
||||
['abort', 'error', 'load', 'loadstart', 'loadend', 'progress'].forEach(prop => {
|
||||
const eventNameSymbol = Zone.__symbol__('ON_PROPERTY' + prop);
|
||||
Object.defineProperty(FileReader.prototype, eventNameSymbol, {
|
||||
configurable: true,
|
||||
get: function() { return this._realReader && this._realReader[eventNameSymbol]; }
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
31
packages/zone.js/lib/extra/electron.ts
Normal file
31
packages/zone.js/lib/extra/electron.ts
Normal file
@ -0,0 +1,31 @@
|
||||
/**
|
||||
* @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('electron', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
function patchArguments(target: any, name: string, source: string): Function|null {
|
||||
return api.patchMethod(target, name, (delegate: Function) => (self: any, args: any[]) => {
|
||||
return delegate && delegate.apply(self, api.bindArguments(args, source));
|
||||
});
|
||||
}
|
||||
const {desktopCapturer, shell, CallbacksRegistry} = require('electron');
|
||||
// patch api in renderer process directly
|
||||
// desktopCapturer
|
||||
if (desktopCapturer) {
|
||||
patchArguments(desktopCapturer, 'getSources', 'electron.desktopCapturer.getSources');
|
||||
}
|
||||
// shell
|
||||
if (shell) {
|
||||
patchArguments(shell, 'openExternal', 'electron.shell.openExternal');
|
||||
}
|
||||
|
||||
// patch api in main process through CallbackRegistry
|
||||
if (!CallbacksRegistry) {
|
||||
return;
|
||||
}
|
||||
|
||||
patchArguments(CallbacksRegistry.prototype, 'add', 'CallbackRegistry.add');
|
||||
});
|
77
packages/zone.js/lib/extra/jsonp.ts
Normal file
77
packages/zone.js/lib/extra/jsonp.ts
Normal file
@ -0,0 +1,77 @@
|
||||
/**
|
||||
* @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('jsonp', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
const noop = function() {};
|
||||
// because jsonp is not a standard api, there are a lot of
|
||||
// implementations, so zone.js just provide a helper util to
|
||||
// patch the jsonp send and onSuccess/onError callback
|
||||
// the options is an object which contains
|
||||
// - jsonp, the jsonp object which hold the send function
|
||||
// - sendFuncName, the name of the send function
|
||||
// - successFuncName, success func name
|
||||
// - failedFuncName, failed func name
|
||||
(Zone as any)[Zone.__symbol__('jsonp')] = function patchJsonp(options: any) {
|
||||
if (!options || !options.jsonp || !options.sendFuncName) {
|
||||
return;
|
||||
}
|
||||
const noop = function() {};
|
||||
|
||||
[options.successFuncName, options.failedFuncName].forEach(methodName => {
|
||||
if (!methodName) {
|
||||
return;
|
||||
}
|
||||
|
||||
const oriFunc = global[methodName];
|
||||
if (oriFunc) {
|
||||
api.patchMethod(global, methodName, (delegate: Function) => (self: any, args: any[]) => {
|
||||
const task = global[api.symbol('jsonTask')];
|
||||
if (task) {
|
||||
task.callback = delegate;
|
||||
return task.invoke.apply(self, args);
|
||||
} else {
|
||||
return delegate.apply(self, args);
|
||||
}
|
||||
});
|
||||
} else {
|
||||
Object.defineProperty(global, methodName, {
|
||||
configurable: true,
|
||||
enumerable: true,
|
||||
get: function() {
|
||||
return function() {
|
||||
const task = global[api.symbol('jsonpTask')];
|
||||
const target = this ? this : global;
|
||||
const delegate = global[api.symbol(`jsonp${methodName}callback`)];
|
||||
|
||||
if (task) {
|
||||
if (delegate) {
|
||||
task.callback = delegate;
|
||||
}
|
||||
global[api.symbol('jsonpTask')] = undefined;
|
||||
return task.invoke.apply(this, arguments);
|
||||
} else {
|
||||
if (delegate) {
|
||||
return delegate.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
return null;
|
||||
};
|
||||
},
|
||||
set: function(callback: Function) {
|
||||
this[api.symbol(`jsonp${methodName}callback`)] = callback;
|
||||
}
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
api.patchMethod(
|
||||
options.jsonp, options.sendFuncName, (delegate: Function) => (self: any, args: any[]) => {
|
||||
global[api.symbol('jsonpTask')] = Zone.current.scheduleMacroTask(
|
||||
'jsonp', noop, {}, (task: Task) => { return delegate.apply(self, args); }, noop);
|
||||
});
|
||||
};
|
||||
});
|
22
packages/zone.js/lib/extra/socket-io.ts
Normal file
22
packages/zone.js/lib/extra/socket-io.ts
Normal file
@ -0,0 +1,22 @@
|
||||
/**
|
||||
* @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('socketio', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
(Zone as any)[Zone.__symbol__('socketio')] = function patchSocketIO(io: any) {
|
||||
// patch io.Socket.prototype event listener related method
|
||||
api.patchEventTarget(global, [io.Socket.prototype], {
|
||||
useG: false,
|
||||
chkDup: false,
|
||||
rt: true,
|
||||
diff: (task: any, delegate: any) => { return task.callback === delegate; }
|
||||
});
|
||||
// also patch io.Socket.prototype.on/off/removeListener/removeAllListeners
|
||||
io.Socket.prototype.on = io.Socket.prototype.addEventListener;
|
||||
io.Socket.prototype.off = io.Socket.prototype.removeListener =
|
||||
io.Socket.prototype.removeAllListeners = io.Socket.prototype.removeEventListener;
|
||||
};
|
||||
});
|
302
packages/zone.js/lib/jasmine/jasmine.ts
Normal file
302
packages/zone.js/lib/jasmine/jasmine.ts
Normal file
@ -0,0 +1,302 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
/// <reference types="jasmine"/>
|
||||
|
||||
'use strict';
|
||||
((_global: any) => {
|
||||
const __extends = function(d: any, b: any) {
|
||||
for (const p in b)
|
||||
if (b.hasOwnProperty(p)) d[p] = b[p];
|
||||
function __() { this.constructor = d; }
|
||||
d.prototype = b === null ? Object.create(b) : ((__.prototype = b.prototype), new (__ as any)());
|
||||
};
|
||||
// Patch jasmine's describe/it/beforeEach/afterEach functions so test code always runs
|
||||
// in a testZone (ProxyZone). (See: angular/zone.js#91 & angular/angular#10503)
|
||||
if (!Zone) throw new Error('Missing: zone.js');
|
||||
if (typeof jasmine == 'undefined') throw new Error('Missing: jasmine.js');
|
||||
if ((jasmine as any)['__zone_patch__'])
|
||||
throw new Error(`'jasmine' has already been patched with 'Zone'.`);
|
||||
(jasmine as any)['__zone_patch__'] = true;
|
||||
|
||||
const SyncTestZoneSpec: {new (name: string): ZoneSpec} = (Zone as any)['SyncTestZoneSpec'];
|
||||
const ProxyZoneSpec: {new (): ZoneSpec} = (Zone as any)['ProxyZoneSpec'];
|
||||
if (!SyncTestZoneSpec) throw new Error('Missing: SyncTestZoneSpec');
|
||||
if (!ProxyZoneSpec) throw new Error('Missing: ProxyZoneSpec');
|
||||
|
||||
const ambientZone = Zone.current;
|
||||
// Create a synchronous-only zone in which to run `describe` blocks in order to raise an
|
||||
// error if any asynchronous operations are attempted inside of a `describe` but outside of
|
||||
// a `beforeEach` or `it`.
|
||||
const syncZone = ambientZone.fork(new SyncTestZoneSpec('jasmine.describe'));
|
||||
|
||||
const symbol = Zone.__symbol__;
|
||||
|
||||
// whether patch jasmine clock when in fakeAsync
|
||||
const disablePatchingJasmineClock = _global[symbol('fakeAsyncDisablePatchingClock')] === true;
|
||||
// the original variable name fakeAsyncPatchLock is not accurate, so the name will be
|
||||
// fakeAsyncAutoFakeAsyncWhenClockPatched and if this enablePatchingJasmineClock is false, we also
|
||||
// automatically disable the auto jump into fakeAsync feature
|
||||
const enableAutoFakeAsyncWhenClockPatched = !disablePatchingJasmineClock &&
|
||||
((_global[symbol('fakeAsyncPatchLock')] === true) ||
|
||||
(_global[symbol('fakeAsyncAutoFakeAsyncWhenClockPatched')] === true));
|
||||
|
||||
const ignoreUnhandledRejection = _global[symbol('ignoreUnhandledRejection')] === true;
|
||||
|
||||
if (!ignoreUnhandledRejection) {
|
||||
const globalErrors = (jasmine as any).GlobalErrors;
|
||||
if (globalErrors && !(jasmine as any)[symbol('GlobalErrors')]) {
|
||||
(jasmine as any)[symbol('GlobalErrors')] = globalErrors;
|
||||
(jasmine as any).GlobalErrors = function() {
|
||||
const instance = new globalErrors();
|
||||
const originalInstall = instance.install;
|
||||
if (originalInstall && !instance[symbol('install')]) {
|
||||
instance[symbol('install')] = originalInstall;
|
||||
instance.install = function() {
|
||||
const originalHandlers = process.listeners('unhandledRejection');
|
||||
const r = originalInstall.apply(this, arguments);
|
||||
process.removeAllListeners('unhandledRejection');
|
||||
if (originalHandlers) {
|
||||
originalHandlers.forEach(h => process.on('unhandledRejection', h));
|
||||
}
|
||||
return r;
|
||||
};
|
||||
}
|
||||
return instance;
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Monkey patch all of the jasmine DSL so that each function runs in appropriate zone.
|
||||
const jasmineEnv: any = jasmine.getEnv();
|
||||
['describe', 'xdescribe', 'fdescribe'].forEach(methodName => {
|
||||
let originalJasmineFn: Function = jasmineEnv[methodName];
|
||||
jasmineEnv[methodName] = function(description: string, specDefinitions: Function) {
|
||||
return originalJasmineFn.call(this, description, wrapDescribeInZone(specDefinitions));
|
||||
};
|
||||
});
|
||||
['it', 'xit', 'fit'].forEach(methodName => {
|
||||
let originalJasmineFn: Function = jasmineEnv[methodName];
|
||||
jasmineEnv[symbol(methodName)] = originalJasmineFn;
|
||||
jasmineEnv[methodName] = function(
|
||||
description: string, specDefinitions: Function, timeout: number) {
|
||||
arguments[1] = wrapTestInZone(specDefinitions);
|
||||
return originalJasmineFn.apply(this, arguments);
|
||||
};
|
||||
});
|
||||
['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach(methodName => {
|
||||
let originalJasmineFn: Function = jasmineEnv[methodName];
|
||||
jasmineEnv[symbol(methodName)] = originalJasmineFn;
|
||||
jasmineEnv[methodName] = function(specDefinitions: Function, timeout: number) {
|
||||
arguments[0] = wrapTestInZone(specDefinitions);
|
||||
return originalJasmineFn.apply(this, arguments);
|
||||
};
|
||||
});
|
||||
|
||||
if (!disablePatchingJasmineClock) {
|
||||
// need to patch jasmine.clock().mockDate and jasmine.clock().tick() so
|
||||
// they can work properly in FakeAsyncTest
|
||||
const originalClockFn: Function = ((jasmine as any)[symbol('clock')] = jasmine['clock']);
|
||||
(jasmine as any)['clock'] = function() {
|
||||
const clock = originalClockFn.apply(this, arguments);
|
||||
if (!clock[symbol('patched')]) {
|
||||
clock[symbol('patched')] = symbol('patched');
|
||||
const originalTick = (clock[symbol('tick')] = clock.tick);
|
||||
clock.tick = function() {
|
||||
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
|
||||
if (fakeAsyncZoneSpec) {
|
||||
return fakeAsyncZoneSpec.tick.apply(fakeAsyncZoneSpec, arguments);
|
||||
}
|
||||
return originalTick.apply(this, arguments);
|
||||
};
|
||||
const originalMockDate = (clock[symbol('mockDate')] = clock.mockDate);
|
||||
clock.mockDate = function() {
|
||||
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
|
||||
if (fakeAsyncZoneSpec) {
|
||||
const dateTime = arguments.length > 0 ? arguments[0] : new Date();
|
||||
return fakeAsyncZoneSpec.setCurrentRealTime.apply(
|
||||
fakeAsyncZoneSpec, dateTime && typeof dateTime.getTime === 'function' ?
|
||||
[dateTime.getTime()] :
|
||||
arguments);
|
||||
}
|
||||
return originalMockDate.apply(this, arguments);
|
||||
};
|
||||
// for auto go into fakeAsync feature, we need the flag to enable it
|
||||
if (enableAutoFakeAsyncWhenClockPatched) {
|
||||
['install', 'uninstall'].forEach(methodName => {
|
||||
const originalClockFn: Function = (clock[symbol(methodName)] = clock[methodName]);
|
||||
clock[methodName] = function() {
|
||||
const FakeAsyncTestZoneSpec = (Zone as any)['FakeAsyncTestZoneSpec'];
|
||||
if (FakeAsyncTestZoneSpec) {
|
||||
(jasmine as any)[symbol('clockInstalled')] = 'install' === methodName;
|
||||
return;
|
||||
}
|
||||
return originalClockFn.apply(this, arguments);
|
||||
};
|
||||
});
|
||||
}
|
||||
}
|
||||
return clock;
|
||||
};
|
||||
}
|
||||
/**
|
||||
* Gets a function wrapping the body of a Jasmine `describe` block to execute in a
|
||||
* synchronous-only zone.
|
||||
*/
|
||||
function wrapDescribeInZone(describeBody: Function): Function {
|
||||
return function() { return syncZone.run(describeBody, this, (arguments as any) as any[]); };
|
||||
}
|
||||
|
||||
function runInTestZone(testBody: Function, applyThis: any, queueRunner: any, done?: Function) {
|
||||
const isClockInstalled = !!(jasmine as any)[symbol('clockInstalled')];
|
||||
const testProxyZoneSpec = queueRunner.testProxyZoneSpec;
|
||||
const testProxyZone = queueRunner.testProxyZone;
|
||||
let lastDelegate;
|
||||
if (isClockInstalled && enableAutoFakeAsyncWhenClockPatched) {
|
||||
// auto run a fakeAsync
|
||||
const fakeAsyncModule = (Zone as any)[Zone.__symbol__('fakeAsyncTest')];
|
||||
if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
|
||||
testBody = fakeAsyncModule.fakeAsync(testBody);
|
||||
}
|
||||
}
|
||||
if (done) {
|
||||
return testProxyZone.run(testBody, applyThis, [done]);
|
||||
} else {
|
||||
return testProxyZone.run(testBody, applyThis);
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Gets a function wrapping the body of a Jasmine `it/beforeEach/afterEach` block to
|
||||
* execute in a ProxyZone zone.
|
||||
* This will run in `testProxyZone`. The `testProxyZone` will be reset by the `ZoneQueueRunner`
|
||||
*/
|
||||
function wrapTestInZone(testBody: Function): Function {
|
||||
// The `done` callback is only passed through if the function expects at least one argument.
|
||||
// Note we have to make a function with correct number of arguments, otherwise jasmine will
|
||||
// think that all functions are sync or async.
|
||||
return (testBody && (testBody.length ? function(done: Function) {
|
||||
return runInTestZone(testBody, this, this.queueRunner, done);
|
||||
} : function() { return runInTestZone(testBody, this, this.queueRunner); }));
|
||||
}
|
||||
interface QueueRunner {
|
||||
execute(): void;
|
||||
}
|
||||
interface QueueRunnerAttrs {
|
||||
queueableFns: {fn: Function}[];
|
||||
clearStack: (fn: any) => void;
|
||||
catchException: () => boolean;
|
||||
fail: () => void;
|
||||
onComplete: () => void;
|
||||
onException: (error: any) => void;
|
||||
userContext: any;
|
||||
timeout: {setTimeout: Function; clearTimeout: Function};
|
||||
}
|
||||
|
||||
const QueueRunner = (jasmine as any).QueueRunner as {
|
||||
new (attrs: QueueRunnerAttrs): QueueRunner;
|
||||
};
|
||||
(jasmine as any).QueueRunner = (function(_super) {
|
||||
__extends(ZoneQueueRunner, _super);
|
||||
function ZoneQueueRunner(attrs: QueueRunnerAttrs) {
|
||||
attrs.onComplete = (fn => () => {
|
||||
// All functions are done, clear the test zone.
|
||||
this.testProxyZone = null;
|
||||
this.testProxyZoneSpec = null;
|
||||
ambientZone.scheduleMicroTask('jasmine.onComplete', fn);
|
||||
})(attrs.onComplete);
|
||||
|
||||
const nativeSetTimeout = _global[Zone.__symbol__('setTimeout')];
|
||||
const nativeClearTimeout = _global[Zone.__symbol__('clearTimeout')];
|
||||
if (nativeSetTimeout) {
|
||||
// should run setTimeout inside jasmine outside of zone
|
||||
attrs.timeout = {
|
||||
setTimeout: nativeSetTimeout ? nativeSetTimeout : _global.setTimeout,
|
||||
clearTimeout: nativeClearTimeout ? nativeClearTimeout : _global.clearTimeout
|
||||
};
|
||||
}
|
||||
|
||||
// create a userContext to hold the queueRunner itself
|
||||
// so we can access the testProxy in it/xit/beforeEach ...
|
||||
if ((jasmine as any).UserContext) {
|
||||
if (!attrs.userContext) {
|
||||
attrs.userContext = new (jasmine as any).UserContext();
|
||||
}
|
||||
attrs.userContext.queueRunner = this;
|
||||
} else {
|
||||
if (!attrs.userContext) {
|
||||
attrs.userContext = {};
|
||||
}
|
||||
attrs.userContext.queueRunner = this;
|
||||
}
|
||||
|
||||
// patch attrs.onException
|
||||
const onException = attrs.onException;
|
||||
attrs.onException = function(error: any) {
|
||||
if (error &&
|
||||
error.message ===
|
||||
'Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.') {
|
||||
// jasmine timeout, we can make the error message more
|
||||
// reasonable to tell what tasks are pending
|
||||
const proxyZoneSpec: any = this && this.testProxyZoneSpec;
|
||||
if (proxyZoneSpec) {
|
||||
const pendingTasksInfo = proxyZoneSpec.getAndClearPendingTasksInfo();
|
||||
try {
|
||||
// try catch here in case error.message is not writable
|
||||
error.message += pendingTasksInfo;
|
||||
} catch (err) {
|
||||
}
|
||||
}
|
||||
}
|
||||
if (onException) {
|
||||
onException.call(this, error);
|
||||
}
|
||||
};
|
||||
|
||||
_super.call(this, attrs);
|
||||
}
|
||||
ZoneQueueRunner.prototype.execute = function() {
|
||||
let zone: Zone|null = Zone.current;
|
||||
let isChildOfAmbientZone = false;
|
||||
while (zone) {
|
||||
if (zone === ambientZone) {
|
||||
isChildOfAmbientZone = true;
|
||||
break;
|
||||
}
|
||||
zone = zone.parent;
|
||||
}
|
||||
|
||||
if (!isChildOfAmbientZone) throw new Error('Unexpected Zone: ' + Zone.current.name);
|
||||
|
||||
// This is the zone which will be used for running individual tests.
|
||||
// It will be a proxy zone, so that the tests function can retroactively install
|
||||
// different zones.
|
||||
// Example:
|
||||
// - In beforeEach() do childZone = Zone.current.fork(...);
|
||||
// - In it() try to do fakeAsync(). The issue is that because the beforeEach forked the
|
||||
// zone outside of fakeAsync it will be able to escape the fakeAsync rules.
|
||||
// - Because ProxyZone is parent fo `childZone` fakeAsync can retroactively add
|
||||
// fakeAsync behavior to the childZone.
|
||||
|
||||
this.testProxyZoneSpec = new ProxyZoneSpec();
|
||||
this.testProxyZone = ambientZone.fork(this.testProxyZoneSpec);
|
||||
if (!Zone.currentTask) {
|
||||
// if we are not running in a task then if someone would register a
|
||||
// element.addEventListener and then calling element.click() the
|
||||
// addEventListener callback would think that it is the top most task and would
|
||||
// drain the microtask queue on element.click() which would be incorrect.
|
||||
// For this reason we always force a task when running jasmine tests.
|
||||
Zone.current.scheduleMicroTask(
|
||||
'jasmine.execute().forceTask', () => QueueRunner.prototype.execute.call(this));
|
||||
} else {
|
||||
_super.prototype.execute.call(this);
|
||||
}
|
||||
};
|
||||
return ZoneQueueRunner;
|
||||
})(QueueRunner);
|
||||
})(global);
|
13
packages/zone.js/lib/mix/rollup-mix.ts
Normal file
13
packages/zone.js/lib/mix/rollup-mix.ts
Normal file
@ -0,0 +1,13 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import '../zone';
|
||||
import '../common/promise';
|
||||
import '../common/to-string';
|
||||
import '../browser/browser';
|
||||
import '../node/node';
|
161
packages/zone.js/lib/mocha/mocha.ts
Normal file
161
packages/zone.js/lib/mocha/mocha.ts
Normal file
@ -0,0 +1,161 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
'use strict';
|
||||
|
||||
((context: any) => {
|
||||
const Mocha = context.Mocha;
|
||||
|
||||
if (typeof Mocha === 'undefined') {
|
||||
throw new Error('Missing Mocha.js');
|
||||
}
|
||||
|
||||
if (typeof Zone === 'undefined') {
|
||||
throw new Error('Missing Zone.js');
|
||||
}
|
||||
|
||||
const ProxyZoneSpec = (Zone as any)['ProxyZoneSpec'];
|
||||
const SyncTestZoneSpec = (Zone as any)['SyncTestZoneSpec'];
|
||||
|
||||
if (!ProxyZoneSpec) {
|
||||
throw new Error('Missing ProxyZoneSpec');
|
||||
}
|
||||
|
||||
if (Mocha['__zone_patch__']) {
|
||||
throw new Error('"Mocha" has already been patched with "Zone".');
|
||||
}
|
||||
|
||||
Mocha['__zone_patch__'] = true;
|
||||
|
||||
const rootZone = Zone.current;
|
||||
const syncZone = rootZone.fork(new SyncTestZoneSpec('Mocha.describe'));
|
||||
let testZone: Zone|null = null;
|
||||
const suiteZone = rootZone.fork(new ProxyZoneSpec());
|
||||
|
||||
const mochaOriginal = {
|
||||
after: Mocha.after,
|
||||
afterEach: Mocha.afterEach,
|
||||
before: Mocha.before,
|
||||
beforeEach: Mocha.beforeEach,
|
||||
describe: Mocha.describe,
|
||||
it: Mocha.it
|
||||
};
|
||||
|
||||
function modifyArguments(args: IArguments, syncTest: Function, asyncTest?: Function): any[] {
|
||||
for (let i = 0; i < args.length; i++) {
|
||||
let arg = args[i];
|
||||
if (typeof arg === 'function') {
|
||||
// The `done` callback is only passed through if the function expects at
|
||||
// least one argument.
|
||||
// Note we have to make a function with correct number of arguments,
|
||||
// otherwise mocha will
|
||||
// think that all functions are sync or async.
|
||||
args[i] = (arg.length === 0) ? syncTest(arg) : asyncTest !(arg);
|
||||
// Mocha uses toString to view the test body in the result list, make sure we return the
|
||||
// correct function body
|
||||
args[i].toString = function() { return arg.toString(); };
|
||||
}
|
||||
}
|
||||
|
||||
return args as any;
|
||||
}
|
||||
|
||||
function wrapDescribeInZone(args: IArguments): any[] {
|
||||
const syncTest: any = function(fn: Function) {
|
||||
return function() { return syncZone.run(fn, this, arguments as any as any[]); };
|
||||
};
|
||||
|
||||
return modifyArguments(args, syncTest);
|
||||
}
|
||||
|
||||
function wrapTestInZone(args: IArguments): any[] {
|
||||
const asyncTest = function(fn: Function) {
|
||||
return function(done: Function) { return testZone !.run(fn, this, [done]); };
|
||||
};
|
||||
|
||||
const syncTest: any = function(fn: Function) {
|
||||
return function() { return testZone !.run(fn, this); };
|
||||
};
|
||||
|
||||
return modifyArguments(args, syncTest, asyncTest);
|
||||
}
|
||||
|
||||
function wrapSuiteInZone(args: IArguments): any[] {
|
||||
const asyncTest = function(fn: Function) {
|
||||
return function(done: Function) { return suiteZone.run(fn, this, [done]); };
|
||||
};
|
||||
|
||||
const syncTest: any = function(fn: Function) {
|
||||
return function() { return suiteZone.run(fn, this); };
|
||||
};
|
||||
|
||||
return modifyArguments(args, syncTest, asyncTest);
|
||||
}
|
||||
|
||||
context.describe = context.suite = Mocha.describe = function() {
|
||||
return mochaOriginal.describe.apply(this, wrapDescribeInZone(arguments));
|
||||
};
|
||||
|
||||
context.xdescribe = context.suite.skip = Mocha.describe.skip = function() {
|
||||
return mochaOriginal.describe.skip.apply(this, wrapDescribeInZone(arguments));
|
||||
};
|
||||
|
||||
context.describe.only = context.suite.only = Mocha.describe.only = function() {
|
||||
return mochaOriginal.describe.only.apply(this, wrapDescribeInZone(arguments));
|
||||
};
|
||||
|
||||
context.it = context.specify = context.test =
|
||||
Mocha.it = function() { return mochaOriginal.it.apply(this, wrapTestInZone(arguments)); };
|
||||
|
||||
context.xit = context.xspecify = Mocha.it.skip = function() {
|
||||
return mochaOriginal.it.skip.apply(this, wrapTestInZone(arguments));
|
||||
};
|
||||
|
||||
context.it.only = context.test.only = Mocha.it.only = function() {
|
||||
return mochaOriginal.it.only.apply(this, wrapTestInZone(arguments));
|
||||
};
|
||||
|
||||
context.after = context.suiteTeardown = Mocha.after = function() {
|
||||
return mochaOriginal.after.apply(this, wrapSuiteInZone(arguments));
|
||||
};
|
||||
|
||||
context.afterEach = context.teardown = Mocha.afterEach = function() {
|
||||
return mochaOriginal.afterEach.apply(this, wrapTestInZone(arguments));
|
||||
};
|
||||
|
||||
context.before = context.suiteSetup = Mocha.before = function() {
|
||||
return mochaOriginal.before.apply(this, wrapSuiteInZone(arguments));
|
||||
};
|
||||
|
||||
context.beforeEach = context.setup = Mocha.beforeEach = function() {
|
||||
return mochaOriginal.beforeEach.apply(this, wrapTestInZone(arguments));
|
||||
};
|
||||
|
||||
((originalRunTest, originalRun) => {
|
||||
Mocha.Runner.prototype.runTest = function(fn: Function) {
|
||||
Zone.current.scheduleMicroTask('mocha.forceTask', () => { originalRunTest.call(this, fn); });
|
||||
};
|
||||
|
||||
Mocha.Runner.prototype.run = function(fn: Function) {
|
||||
this.on('test', (e: any) => { testZone = rootZone.fork(new ProxyZoneSpec()); });
|
||||
|
||||
this.on('fail', (test: any, err: any) => {
|
||||
const proxyZoneSpec = testZone && testZone.get('ProxyZoneSpec');
|
||||
if (proxyZoneSpec && err) {
|
||||
try {
|
||||
// try catch here in case err.message is not writable
|
||||
err.message += proxyZoneSpec.getAndClearPendingTasksInfo();
|
||||
} catch (error) {
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return originalRun.call(this, fn);
|
||||
};
|
||||
})(Mocha.Runner.prototype.runTest, Mocha.Runner.prototype.run);
|
||||
})(global);
|
63
packages/zone.js/lib/node/events.ts
Normal file
63
packages/zone.js/lib/node/events.ts
Normal file
@ -0,0 +1,63 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import {patchEventTarget} from '../common/events';
|
||||
|
||||
Zone.__load_patch('EventEmitter', (global: any) => {
|
||||
// For EventEmitter
|
||||
const EE_ADD_LISTENER = 'addListener';
|
||||
const EE_PREPEND_LISTENER = 'prependListener';
|
||||
const EE_REMOVE_LISTENER = 'removeListener';
|
||||
const EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
|
||||
const EE_LISTENERS = 'listeners';
|
||||
const EE_ON = 'on';
|
||||
|
||||
const compareTaskCallbackVsDelegate = function(task: any, delegate: any) {
|
||||
// same callback, same capture, same event name, just return
|
||||
return task.callback === delegate || task.callback.listener === delegate;
|
||||
};
|
||||
|
||||
const eventNameToString = function(eventName: string|Symbol) {
|
||||
if (typeof eventName === 'string') {
|
||||
return eventName as string;
|
||||
}
|
||||
if (!eventName) {
|
||||
return '';
|
||||
}
|
||||
return eventName.toString().replace('(', '_').replace(')', '_');
|
||||
};
|
||||
|
||||
function patchEventEmitterMethods(obj: any) {
|
||||
const result = patchEventTarget(global, [obj], {
|
||||
useG: false,
|
||||
add: EE_ADD_LISTENER,
|
||||
rm: EE_REMOVE_LISTENER,
|
||||
prepend: EE_PREPEND_LISTENER,
|
||||
rmAll: EE_REMOVE_ALL_LISTENER,
|
||||
listeners: EE_LISTENERS,
|
||||
chkDup: false,
|
||||
rt: true,
|
||||
diff: compareTaskCallbackVsDelegate,
|
||||
eventNameToString: eventNameToString
|
||||
});
|
||||
if (result && result[0]) {
|
||||
obj[EE_ON] = obj[EE_ADD_LISTENER];
|
||||
}
|
||||
}
|
||||
|
||||
// EventEmitter
|
||||
let events;
|
||||
try {
|
||||
events = require('events');
|
||||
} catch (err) {
|
||||
}
|
||||
|
||||
if (events && events.EventEmitter) {
|
||||
patchEventEmitterMethods(events.EventEmitter.prototype);
|
||||
}
|
||||
});
|
41
packages/zone.js/lib/node/fs.ts
Normal file
41
packages/zone.js/lib/node/fs.ts
Normal file
@ -0,0 +1,41 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import {patchMacroTask} from '../common/utils';
|
||||
|
||||
Zone.__load_patch('fs', () => {
|
||||
let fs: any;
|
||||
try {
|
||||
fs = require('fs');
|
||||
} catch (err) {
|
||||
}
|
||||
|
||||
// watch, watchFile, unwatchFile has been patched
|
||||
// because EventEmitter has been patched
|
||||
const TO_PATCH_MACROTASK_METHODS = [
|
||||
'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod',
|
||||
'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod',
|
||||
'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read',
|
||||
'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat',
|
||||
'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile',
|
||||
];
|
||||
|
||||
if (fs) {
|
||||
TO_PATCH_MACROTASK_METHODS.filter(name => !!fs[name] && typeof fs[name] === 'function')
|
||||
.forEach(name => {
|
||||
patchMacroTask(fs, name, (self: any, args: any[]) => {
|
||||
return {
|
||||
name: 'fs.' + name,
|
||||
args: args,
|
||||
cbIdx: args.length > 0 ? args.length - 1 : -1,
|
||||
target: self
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
154
packages/zone.js/lib/node/node.ts
Normal file
154
packages/zone.js/lib/node/node.ts
Normal file
@ -0,0 +1,154 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import './node_util';
|
||||
import './events';
|
||||
import './fs';
|
||||
|
||||
import {findEventTasks} from '../common/events';
|
||||
import {patchTimer} from '../common/timers';
|
||||
import {ArraySlice, isMix, patchMacroTask, patchMicroTask} from '../common/utils';
|
||||
|
||||
const set = 'set';
|
||||
const clear = 'clear';
|
||||
|
||||
Zone.__load_patch('node_timers', (global: any, Zone: ZoneType) => {
|
||||
// Timers
|
||||
let globalUseTimeoutFromTimer = false;
|
||||
try {
|
||||
const timers = require('timers');
|
||||
let globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
|
||||
if (!globalEqualTimersTimeout && !isMix) {
|
||||
// 1. if isMix, then we are in mix environment such as Electron
|
||||
// we should only patch timers.setTimeout because global.setTimeout
|
||||
// have been patched
|
||||
// 2. if global.setTimeout not equal timers.setTimeout, check
|
||||
// whether global.setTimeout use timers.setTimeout or not
|
||||
const originSetTimeout = timers.setTimeout;
|
||||
timers.setTimeout = function() {
|
||||
globalUseTimeoutFromTimer = true;
|
||||
return originSetTimeout.apply(this, arguments);
|
||||
};
|
||||
const detectTimeout = global.setTimeout(() => {}, 100);
|
||||
clearTimeout(detectTimeout);
|
||||
timers.setTimeout = originSetTimeout;
|
||||
}
|
||||
patchTimer(timers, set, clear, 'Timeout');
|
||||
patchTimer(timers, set, clear, 'Interval');
|
||||
patchTimer(timers, set, clear, 'Immediate');
|
||||
} catch (error) {
|
||||
// timers module not exists, for example, when we using nativeScript
|
||||
// timers is not available
|
||||
}
|
||||
if (isMix) {
|
||||
// if we are in mix environment, such as Electron,
|
||||
// the global.setTimeout has already been patched,
|
||||
// so we just patch timers.setTimeout
|
||||
return;
|
||||
}
|
||||
if (!globalUseTimeoutFromTimer) {
|
||||
// 1. global setTimeout equals timers setTimeout
|
||||
// 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
|
||||
// 3. or load timers module error happens, we should patch global setTimeout
|
||||
patchTimer(global, set, clear, 'Timeout');
|
||||
patchTimer(global, set, clear, 'Interval');
|
||||
patchTimer(global, set, clear, 'Immediate');
|
||||
} else {
|
||||
// global use timers setTimeout, but not equals
|
||||
// this happens when use nodejs v0.10.x, global setTimeout will
|
||||
// use a lazy load version of timers setTimeout
|
||||
// we should not double patch timer's setTimeout
|
||||
// so we only store the __symbol__ for consistency
|
||||
global[Zone.__symbol__('setTimeout')] = global.setTimeout;
|
||||
global[Zone.__symbol__('setInterval')] = global.setInterval;
|
||||
global[Zone.__symbol__('setImmediate')] = global.setImmediate;
|
||||
}
|
||||
});
|
||||
|
||||
// patch process related methods
|
||||
Zone.__load_patch('nextTick', () => {
|
||||
// patch nextTick as microTask
|
||||
patchMicroTask(process, 'nextTick', (self: any, args: any[]) => {
|
||||
return {
|
||||
name: 'process.nextTick',
|
||||
args: args,
|
||||
cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1,
|
||||
target: process
|
||||
};
|
||||
});
|
||||
});
|
||||
|
||||
Zone.__load_patch(
|
||||
'handleUnhandledPromiseRejection', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
(Zone as any)[api.symbol('unhandledPromiseRejectionHandler')] =
|
||||
findProcessPromiseRejectionHandler('unhandledRejection');
|
||||
|
||||
(Zone as any)[api.symbol('rejectionHandledHandler')] =
|
||||
findProcessPromiseRejectionHandler('rejectionHandled');
|
||||
|
||||
// handle unhandled promise rejection
|
||||
function findProcessPromiseRejectionHandler(evtName: string) {
|
||||
return function(e: any) {
|
||||
const eventTasks = findEventTasks(process, evtName);
|
||||
eventTasks.forEach(eventTask => {
|
||||
// process has added unhandledrejection event listener
|
||||
// trigger the event listener
|
||||
if (evtName === 'unhandledRejection') {
|
||||
eventTask.invoke(e.rejection, e.promise);
|
||||
} else if (evtName === 'rejectionHandled') {
|
||||
eventTask.invoke(e.promise);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
|
||||
// Crypto
|
||||
Zone.__load_patch('crypto', () => {
|
||||
let crypto: any;
|
||||
try {
|
||||
crypto = require('crypto');
|
||||
} catch (err) {
|
||||
}
|
||||
|
||||
// use the generic patchMacroTask to patch crypto
|
||||
if (crypto) {
|
||||
const methodNames = ['randomBytes', 'pbkdf2'];
|
||||
methodNames.forEach(name => {
|
||||
patchMacroTask(crypto, name, (self: any, args: any[]) => {
|
||||
return {
|
||||
name: 'crypto.' + name,
|
||||
args: args,
|
||||
cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ?
|
||||
args.length - 1 :
|
||||
-1,
|
||||
target: crypto
|
||||
};
|
||||
});
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
Zone.__load_patch('console', (global: any, Zone: ZoneType) => {
|
||||
const consoleMethods =
|
||||
['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace'];
|
||||
consoleMethods.forEach((m: string) => {
|
||||
const originalMethod = (console as any)[Zone.__symbol__(m)] = (console as any)[m];
|
||||
if (originalMethod) {
|
||||
(console as any)[m] = function() {
|
||||
const args = ArraySlice.call(arguments);
|
||||
if (Zone.current === Zone.root) {
|
||||
return originalMethod.apply(this, args);
|
||||
} else {
|
||||
return Zone.root.run(originalMethod, this, args);
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
});
|
17
packages/zone.js/lib/node/node_util.ts
Normal file
17
packages/zone.js/lib/node/node_util.ts
Normal file
@ -0,0 +1,17 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import {bindArguments, patchMacroTask, patchMethod, patchOnProperties, setShouldCopySymbolProperties} from '../common/utils';
|
||||
|
||||
Zone.__load_patch('node_util', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
api.patchOnProperties = patchOnProperties;
|
||||
api.patchMethod = patchMethod;
|
||||
api.bindArguments = bindArguments;
|
||||
api.patchMacroTask = patchMacroTask;
|
||||
setShouldCopySymbolProperties(true);
|
||||
});
|
12
packages/zone.js/lib/node/rollup-main.ts
Normal file
12
packages/zone.js/lib/node/rollup-main.ts
Normal file
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import '../zone';
|
||||
import '../common/promise';
|
||||
import '../common/to-string';
|
||||
import './node';
|
12
packages/zone.js/lib/node/rollup-test-main.ts
Normal file
12
packages/zone.js/lib/node/rollup-test-main.ts
Normal file
@ -0,0 +1,12 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import './rollup-main';
|
||||
|
||||
// load test related files into bundle
|
||||
import '../testing/zone-testing';
|
21
packages/zone.js/lib/rxjs/rxjs-fake-async.ts
Normal file
21
packages/zone.js/lib/rxjs/rxjs-fake-async.ts
Normal file
@ -0,0 +1,21 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import {Scheduler, asapScheduler, asyncScheduler} from 'rxjs';
|
||||
|
||||
Zone.__load_patch('rxjs.Scheduler.now', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
api.patchMethod(Scheduler, 'now', (delegate: Function) => (self: any, args: any[]) => {
|
||||
return Date.now.call(self);
|
||||
});
|
||||
api.patchMethod(asyncScheduler, 'now', (delegate: Function) => (self: any, args: any[]) => {
|
||||
return Date.now.call(self);
|
||||
});
|
||||
api.patchMethod(asapScheduler, 'now', (delegate: Function) => (self: any, args: any[]) => {
|
||||
return Date.now.call(self);
|
||||
});
|
||||
});
|
182
packages/zone.js/lib/rxjs/rxjs.ts
Normal file
182
packages/zone.js/lib/rxjs/rxjs.ts
Normal file
@ -0,0 +1,182 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
import {Observable, Subscriber, Subscription} from 'rxjs';
|
||||
|
||||
(Zone as any).__load_patch('rxjs', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
const symbol: (symbolString: string) => string = (Zone as any).__symbol__;
|
||||
const nextSource = 'rxjs.Subscriber.next';
|
||||
const errorSource = 'rxjs.Subscriber.error';
|
||||
const completeSource = 'rxjs.Subscriber.complete';
|
||||
|
||||
const ObjectDefineProperties = Object.defineProperties;
|
||||
|
||||
const patchObservable = function() {
|
||||
const ObservablePrototype: any = Observable.prototype;
|
||||
const _symbolSubscribe = symbol('_subscribe');
|
||||
const _subscribe = ObservablePrototype[_symbolSubscribe] = ObservablePrototype._subscribe;
|
||||
|
||||
ObjectDefineProperties(Observable.prototype, {
|
||||
_zone: {value: null, writable: true, configurable: true},
|
||||
_zoneSource: {value: null, writable: true, configurable: true},
|
||||
_zoneSubscribe: {value: null, writable: true, configurable: true},
|
||||
source: {
|
||||
configurable: true,
|
||||
get: function(this: Observable<any>) { return (this as any)._zoneSource; },
|
||||
set: function(this: Observable<any>, source: any) {
|
||||
(this as any)._zone = Zone.current;
|
||||
(this as any)._zoneSource = source;
|
||||
}
|
||||
},
|
||||
_subscribe: {
|
||||
configurable: true,
|
||||
get: function(this: Observable<any>) {
|
||||
if ((this as any)._zoneSubscribe) {
|
||||
return (this as any)._zoneSubscribe;
|
||||
} else if (this.constructor === Observable) {
|
||||
return _subscribe;
|
||||
}
|
||||
const proto = Object.getPrototypeOf(this);
|
||||
return proto && proto._subscribe;
|
||||
},
|
||||
set: function(this: Observable<any>, subscribe: any) {
|
||||
(this as any)._zone = Zone.current;
|
||||
(this as any)._zoneSubscribe = function() {
|
||||
if (this._zone && this._zone !== Zone.current) {
|
||||
const tearDown = this._zone.run(subscribe, this, arguments);
|
||||
if (tearDown && typeof tearDown === 'function') {
|
||||
const zone = this._zone;
|
||||
return function() {
|
||||
if (zone !== Zone.current) {
|
||||
return zone.run(tearDown, this, arguments);
|
||||
}
|
||||
return tearDown.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
return tearDown;
|
||||
}
|
||||
return subscribe.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
},
|
||||
subjectFactory: {
|
||||
get: function() { return (this as any)._zoneSubjectFactory; },
|
||||
set: function(factory: any) {
|
||||
const zone = this._zone;
|
||||
this._zoneSubjectFactory = function() {
|
||||
if (zone && zone !== Zone.current) {
|
||||
return zone.run(factory, this, arguments);
|
||||
}
|
||||
return factory.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
api.patchMethod(Observable.prototype, 'lift', (delegate: any) => (self: any, args: any[]) => {
|
||||
const observable: any = delegate.apply(self, args);
|
||||
if (observable.operator) {
|
||||
observable.operator._zone = Zone.current;
|
||||
api.patchMethod(
|
||||
observable.operator, 'call',
|
||||
(operatorDelegate: any) => (operatorSelf: any, operatorArgs: any[]) => {
|
||||
if (operatorSelf._zone && operatorSelf._zone !== Zone.current) {
|
||||
return operatorSelf._zone.run(operatorDelegate, operatorSelf, operatorArgs);
|
||||
}
|
||||
return operatorDelegate.apply(operatorSelf, operatorArgs);
|
||||
});
|
||||
}
|
||||
return observable;
|
||||
});
|
||||
|
||||
const patchSubscription = function() {
|
||||
ObjectDefineProperties(Subscription.prototype, {
|
||||
_zone: {value: null, writable: true, configurable: true},
|
||||
_zoneUnsubscribe: {value: null, writable: true, configurable: true},
|
||||
_unsubscribe: {
|
||||
get: function(this: Subscription) {
|
||||
if ((this as any)._zoneUnsubscribe) {
|
||||
return (this as any)._zoneUnsubscribe;
|
||||
}
|
||||
const proto = Object.getPrototypeOf(this);
|
||||
return proto && proto._unsubscribe;
|
||||
},
|
||||
set: function(this: Subscription, unsubscribe: any) {
|
||||
(this as any)._zone = Zone.current;
|
||||
(this as any)._zoneUnsubscribe = function() {
|
||||
if (this._zone && this._zone !== Zone.current) {
|
||||
return this._zone.run(unsubscribe, this, arguments);
|
||||
}
|
||||
return unsubscribe.apply(this, arguments);
|
||||
};
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
const patchSubscriber = function() {
|
||||
const next = Subscriber.prototype.next;
|
||||
const error = Subscriber.prototype.error;
|
||||
const complete = Subscriber.prototype.complete;
|
||||
|
||||
Object.defineProperty(Subscriber.prototype, 'destination', {
|
||||
configurable: true,
|
||||
get: function(this: Subscriber<any>) { return (this as any)._zoneDestination; },
|
||||
set: function(this: Subscriber<any>, destination: any) {
|
||||
(this as any)._zone = Zone.current;
|
||||
(this as any)._zoneDestination = destination;
|
||||
}
|
||||
});
|
||||
|
||||
// patch Subscriber.next to make sure it run
|
||||
// into SubscriptionZone
|
||||
Subscriber.prototype.next = function() {
|
||||
const currentZone = Zone.current;
|
||||
const subscriptionZone = this._zone;
|
||||
|
||||
// for performance concern, check Zone.current
|
||||
// equal with this._zone(SubscriptionZone) or not
|
||||
if (subscriptionZone && subscriptionZone !== currentZone) {
|
||||
return subscriptionZone.run(next, this, arguments, nextSource);
|
||||
} else {
|
||||
return next.apply(this, arguments as any);
|
||||
}
|
||||
};
|
||||
|
||||
Subscriber.prototype.error = function() {
|
||||
const currentZone = Zone.current;
|
||||
const subscriptionZone = this._zone;
|
||||
|
||||
// for performance concern, check Zone.current
|
||||
// equal with this._zone(SubscriptionZone) or not
|
||||
if (subscriptionZone && subscriptionZone !== currentZone) {
|
||||
return subscriptionZone.run(error, this, arguments, errorSource);
|
||||
} else {
|
||||
return error.apply(this, arguments as any);
|
||||
}
|
||||
};
|
||||
|
||||
Subscriber.prototype.complete = function() {
|
||||
const currentZone = Zone.current;
|
||||
const subscriptionZone = this._zone;
|
||||
|
||||
// for performance concern, check Zone.current
|
||||
// equal with this._zone(SubscriptionZone) or not
|
||||
if (subscriptionZone && subscriptionZone !== currentZone) {
|
||||
return subscriptionZone.run(complete, this, arguments, completeSource);
|
||||
} else {
|
||||
return complete.call(this);
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
patchObservable();
|
||||
patchSubscription();
|
||||
patchSubscriber();
|
||||
});
|
99
packages/zone.js/lib/testing/async-testing.ts
Normal file
99
packages/zone.js/lib/testing/async-testing.ts
Normal file
@ -0,0 +1,99 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
import '../zone-spec/async-test';
|
||||
|
||||
Zone.__load_patch('asynctest', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
/**
|
||||
* Wraps a test function in an asynchronous test zone. The test will automatically
|
||||
* complete when all asynchronous calls within this zone are done.
|
||||
*/
|
||||
(Zone as any)[api.symbol('asyncTest')] = function asyncTest(fn: Function): (done: any) => any {
|
||||
// If we're running using the Jasmine test framework, adapt to call the 'done'
|
||||
// function when asynchronous activity is finished.
|
||||
if (global.jasmine) {
|
||||
// Not using an arrow function to preserve context passed from call site
|
||||
return function(done: any) {
|
||||
if (!done) {
|
||||
// if we run beforeEach in @angular/core/testing/testing_internal then we get no done
|
||||
// fake it here and assume sync.
|
||||
done = function() {};
|
||||
done.fail = function(e: any) { throw e; };
|
||||
}
|
||||
runInTestZone(fn, this, done, (err: any) => {
|
||||
if (typeof err === 'string') {
|
||||
return done.fail(new Error(<string>err));
|
||||
} else {
|
||||
done.fail(err);
|
||||
}
|
||||
});
|
||||
};
|
||||
}
|
||||
// Otherwise, return a promise which will resolve when asynchronous activity
|
||||
// is finished. This will be correctly consumed by the Mocha framework with
|
||||
// it('...', async(myFn)); or can be used in a custom framework.
|
||||
// Not using an arrow function to preserve context passed from call site
|
||||
return function() {
|
||||
return new Promise<void>((finishCallback, failCallback) => {
|
||||
runInTestZone(fn, this, finishCallback, failCallback);
|
||||
});
|
||||
};
|
||||
};
|
||||
|
||||
function runInTestZone(
|
||||
fn: Function, context: any, finishCallback: Function, failCallback: Function) {
|
||||
const currentZone = Zone.current;
|
||||
const AsyncTestZoneSpec = (Zone as any)['AsyncTestZoneSpec'];
|
||||
if (AsyncTestZoneSpec === undefined) {
|
||||
throw new Error(
|
||||
'AsyncTestZoneSpec is needed for the async() test helper but could not be found. ' +
|
||||
'Please make sure that your environment includes zone.js/dist/async-test.js');
|
||||
}
|
||||
const ProxyZoneSpec = (Zone as any)['ProxyZoneSpec'] as {
|
||||
get(): {setDelegate(spec: ZoneSpec): void; getDelegate(): ZoneSpec;};
|
||||
assertPresent: () => void;
|
||||
};
|
||||
if (ProxyZoneSpec === undefined) {
|
||||
throw new Error(
|
||||
'ProxyZoneSpec is needed for the async() test helper but could not be found. ' +
|
||||
'Please make sure that your environment includes zone.js/dist/proxy.js');
|
||||
}
|
||||
const proxyZoneSpec = ProxyZoneSpec.get();
|
||||
ProxyZoneSpec.assertPresent();
|
||||
// We need to create the AsyncTestZoneSpec outside the ProxyZone.
|
||||
// If we do it in ProxyZone then we will get to infinite recursion.
|
||||
const proxyZone = Zone.current.getZoneWith('ProxyZoneSpec');
|
||||
const previousDelegate = proxyZoneSpec.getDelegate();
|
||||
proxyZone !.parent !.run(() => {
|
||||
const testZoneSpec: ZoneSpec = new AsyncTestZoneSpec(
|
||||
() => {
|
||||
// Need to restore the original zone.
|
||||
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
|
||||
// Only reset the zone spec if it's
|
||||
// sill this one. Otherwise, assume
|
||||
// it's OK.
|
||||
proxyZoneSpec.setDelegate(previousDelegate);
|
||||
}
|
||||
(testZoneSpec as any).unPatchPromiseForTest();
|
||||
currentZone.run(() => { finishCallback(); });
|
||||
},
|
||||
(error: any) => {
|
||||
// Need to restore the original zone.
|
||||
if (proxyZoneSpec.getDelegate() == testZoneSpec) {
|
||||
// Only reset the zone spec if it's sill this one. Otherwise, assume it's OK.
|
||||
proxyZoneSpec.setDelegate(previousDelegate);
|
||||
}
|
||||
(testZoneSpec as any).unPatchPromiseForTest();
|
||||
currentZone.run(() => { failCallback(error); });
|
||||
},
|
||||
'test');
|
||||
proxyZoneSpec.setDelegate(testZoneSpec);
|
||||
(testZoneSpec as any).patchPromiseForTest();
|
||||
});
|
||||
return Zone.current.runGuarded(fn, context);
|
||||
}
|
||||
});
|
153
packages/zone.js/lib/testing/fake-async.ts
Normal file
153
packages/zone.js/lib/testing/fake-async.ts
Normal file
@ -0,0 +1,153 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
import '../zone-spec/fake-async-test';
|
||||
|
||||
Zone.__load_patch('fakeasync', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
const FakeAsyncTestZoneSpec = Zone && (Zone as any)['FakeAsyncTestZoneSpec'];
|
||||
type ProxyZoneSpec = {
|
||||
setDelegate(delegateSpec: ZoneSpec): void; getDelegate(): ZoneSpec; resetDelegate(): void;
|
||||
};
|
||||
const ProxyZoneSpec: {get(): ProxyZoneSpec; assertPresent: () => ProxyZoneSpec} =
|
||||
Zone && (Zone as any)['ProxyZoneSpec'];
|
||||
|
||||
let _fakeAsyncTestZoneSpec: any = null;
|
||||
|
||||
/**
|
||||
* Clears out the shared fake async zone for a test.
|
||||
* To be called in a global `beforeEach`.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
function resetFakeAsyncZone() {
|
||||
if (_fakeAsyncTestZoneSpec) {
|
||||
_fakeAsyncTestZoneSpec.unlockDatePatch();
|
||||
}
|
||||
_fakeAsyncTestZoneSpec = null;
|
||||
// in node.js testing we may not have ProxyZoneSpec in which case there is nothing to reset.
|
||||
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
|
||||
*/
|
||||
function fakeAsync(fn: Function): (...args: any[]) => any {
|
||||
// Not using an arrow function to preserve context passed from call site
|
||||
return function(...args: any[]) {
|
||||
const proxyZoneSpec = ProxyZoneSpec.assertPresent();
|
||||
if (Zone.current.get('FakeAsyncTestZoneSpec')) {
|
||||
throw new Error('fakeAsync() calls can not be nested');
|
||||
}
|
||||
try {
|
||||
// in case jasmine.clock init a fakeAsyncTestZoneSpec
|
||||
if (!_fakeAsyncTestZoneSpec) {
|
||||
if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
|
||||
throw new Error('fakeAsync() calls can not be nested');
|
||||
}
|
||||
|
||||
_fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec();
|
||||
}
|
||||
|
||||
let res: any;
|
||||
const lastProxyZoneSpec = proxyZoneSpec.getDelegate();
|
||||
proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
|
||||
_fakeAsyncTestZoneSpec.lockDatePatch();
|
||||
try {
|
||||
res = fn.apply(this, args);
|
||||
flushMicrotasks();
|
||||
} finally {
|
||||
proxyZoneSpec.setDelegate(lastProxyZoneSpec);
|
||||
}
|
||||
|
||||
if (_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length > 0) {
|
||||
throw new Error(
|
||||
`${_fakeAsyncTestZoneSpec.pendingPeriodicTimers.length} ` +
|
||||
`periodic timer(s) still in the queue.`);
|
||||
}
|
||||
|
||||
if (_fakeAsyncTestZoneSpec.pendingTimers.length > 0) {
|
||||
throw new Error(
|
||||
`${_fakeAsyncTestZoneSpec.pendingTimers.length} timer(s) still in the queue.`);
|
||||
}
|
||||
return res;
|
||||
} finally {
|
||||
resetFakeAsyncZone();
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
function _getFakeAsyncZoneSpec(): any {
|
||||
if (_fakeAsyncTestZoneSpec == null) {
|
||||
_fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
|
||||
if (_fakeAsyncTestZoneSpec == null) {
|
||||
throw new Error('The code should be running in the fakeAsync zone to call this function');
|
||||
}
|
||||
}
|
||||
return _fakeAsyncTestZoneSpec;
|
||||
}
|
||||
|
||||
/**
|
||||
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone.
|
||||
*
|
||||
* The microtasks queue is drained at the very start of this function and after any timer callback
|
||||
* has been executed.
|
||||
*
|
||||
* ## Example
|
||||
*
|
||||
* {@example core/testing/ts/fake_async.ts region='basic'}
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
function tick(millis: number = 0): void { _getFakeAsyncZoneSpec().tick(millis); }
|
||||
|
||||
/**
|
||||
* Simulates the asynchronous passage of time for the timers in the fakeAsync zone by
|
||||
* draining the macrotask queue until it is empty. The returned value is the milliseconds
|
||||
* of time that would have been elapsed.
|
||||
*
|
||||
* @param maxTurns
|
||||
* @returns The simulated time elapsed, in millis.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
function flush(maxTurns?: number): number { return _getFakeAsyncZoneSpec().flush(maxTurns); }
|
||||
|
||||
/**
|
||||
* Discard all remaining periodic tasks.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
function discardPeriodicTasks(): void {
|
||||
const zoneSpec = _getFakeAsyncZoneSpec();
|
||||
const pendingTimers = zoneSpec.pendingPeriodicTimers;
|
||||
zoneSpec.pendingPeriodicTimers.length = 0;
|
||||
}
|
||||
|
||||
/**
|
||||
* Flush any pending microtasks.
|
||||
*
|
||||
* @experimental
|
||||
*/
|
||||
function flushMicrotasks(): void { _getFakeAsyncZoneSpec().flushMicrotasks(); }
|
||||
(Zone as any)[api.symbol('fakeAsyncTest')] = {
|
||||
resetFakeAsyncZone, flushMicrotasks, discardPeriodicTasks, tick, flush, fakeAsync};
|
||||
});
|
68
packages/zone.js/lib/testing/promise-testing.ts
Normal file
68
packages/zone.js/lib/testing/promise-testing.ts
Normal file
@ -0,0 +1,68 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
/**
|
||||
* Promise for async/fakeAsync zoneSpec test
|
||||
* can support async operation which not supported by zone.js
|
||||
* such as
|
||||
* it ('test jsonp in AsyncZone', async() => {
|
||||
* new Promise(res => {
|
||||
* jsonp(url, (data) => {
|
||||
* // success callback
|
||||
* res(data);
|
||||
* });
|
||||
* }).then((jsonpResult) => {
|
||||
* // get jsonp result.
|
||||
*
|
||||
* // user will expect AsyncZoneSpec wait for
|
||||
* // then, but because jsonp is not zone aware
|
||||
* // AsyncZone will finish before then is called.
|
||||
* });
|
||||
* });
|
||||
*/
|
||||
Zone.__load_patch('promisefortest', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
|
||||
const symbolState: string = api.symbol('state');
|
||||
const UNRESOLVED: null = null;
|
||||
const symbolParentUnresolved = api.symbol('parentUnresolved');
|
||||
|
||||
// patch Promise.prototype.then to keep an internal
|
||||
// number for tracking unresolved chained promise
|
||||
// we will decrease this number when the parent promise
|
||||
// being resolved/rejected and chained promise was
|
||||
// scheduled as a microTask.
|
||||
// so we can know such kind of chained promise still
|
||||
// not resolved in AsyncTestZone
|
||||
(Promise as any)[api.symbol('patchPromiseForTest')] = function patchPromiseForTest() {
|
||||
let oriThen = (Promise as any)[Zone.__symbol__('ZonePromiseThen')];
|
||||
if (oriThen) {
|
||||
return;
|
||||
}
|
||||
oriThen = (Promise as any)[Zone.__symbol__('ZonePromiseThen')] = Promise.prototype.then;
|
||||
Promise.prototype.then = function() {
|
||||
const chained = oriThen.apply(this, arguments);
|
||||
if (this[symbolState] === UNRESOLVED) {
|
||||
// parent promise is unresolved.
|
||||
const asyncTestZoneSpec = Zone.current.get('AsyncTestZoneSpec');
|
||||
if (asyncTestZoneSpec) {
|
||||
asyncTestZoneSpec.unresolvedChainedPromiseCount++;
|
||||
chained[symbolParentUnresolved] = true;
|
||||
}
|
||||
}
|
||||
return chained;
|
||||
};
|
||||
};
|
||||
|
||||
(Promise as any)[api.symbol('unPatchPromiseForTest')] = function unpatchPromiseForTest() {
|
||||
// restore origin then
|
||||
const oriThen = (Promise as any)[Zone.__symbol__('ZonePromiseThen')];
|
||||
if (oriThen) {
|
||||
Promise.prototype.then = oriThen;
|
||||
(Promise as any)[Zone.__symbol__('ZonePromiseThen')] = undefined;
|
||||
}
|
||||
};
|
||||
});
|
16
packages/zone.js/lib/testing/zone-testing.ts
Normal file
16
packages/zone.js/lib/testing/zone-testing.ts
Normal file
@ -0,0 +1,16 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
// load test related files into bundle in correct order
|
||||
import '../zone-spec/long-stack-trace';
|
||||
import '../zone-spec/proxy';
|
||||
import '../zone-spec/sync-test';
|
||||
import '../jasmine/jasmine';
|
||||
import './async-testing';
|
||||
import './fake-async';
|
||||
import './promise-testing';
|
149
packages/zone.js/lib/zone-spec/async-test.ts
Normal file
149
packages/zone.js/lib/zone-spec/async-test.ts
Normal file
@ -0,0 +1,149 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
(function(_global: any) {
|
||||
class AsyncTestZoneSpec implements ZoneSpec {
|
||||
static symbolParentUnresolved = Zone.__symbol__('parentUnresolved');
|
||||
|
||||
_pendingMicroTasks: boolean = false;
|
||||
_pendingMacroTasks: boolean = false;
|
||||
_alreadyErrored: boolean = false;
|
||||
_isSync: boolean = false;
|
||||
runZone = Zone.current;
|
||||
unresolvedChainedPromiseCount = 0;
|
||||
|
||||
supportWaitUnresolvedChainedPromise = false;
|
||||
|
||||
constructor(
|
||||
private finishCallback: Function, private failCallback: Function, namePrefix: string) {
|
||||
this.name = 'asyncTestZone for ' + namePrefix;
|
||||
this.properties = {'AsyncTestZoneSpec': this};
|
||||
this.supportWaitUnresolvedChainedPromise =
|
||||
_global[Zone.__symbol__('supportWaitUnResolvedChainedPromise')] === true;
|
||||
}
|
||||
|
||||
isUnresolvedChainedPromisePending() { return this.unresolvedChainedPromiseCount > 0; }
|
||||
|
||||
_finishCallbackIfDone() {
|
||||
if (!(this._pendingMicroTasks || this._pendingMacroTasks ||
|
||||
(this.supportWaitUnresolvedChainedPromise &&
|
||||
this.isUnresolvedChainedPromisePending()))) {
|
||||
// We do this because we would like to catch unhandled rejected promises.
|
||||
this.runZone.run(() => {
|
||||
setTimeout(() => {
|
||||
if (!this._alreadyErrored && !(this._pendingMicroTasks || this._pendingMacroTasks)) {
|
||||
this.finishCallback();
|
||||
}
|
||||
}, 0);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
patchPromiseForTest() {
|
||||
if (!this.supportWaitUnresolvedChainedPromise) {
|
||||
return;
|
||||
}
|
||||
const patchPromiseForTest = (Promise as any)[Zone.__symbol__('patchPromiseForTest')];
|
||||
if (patchPromiseForTest) {
|
||||
patchPromiseForTest();
|
||||
}
|
||||
}
|
||||
|
||||
unPatchPromiseForTest() {
|
||||
if (!this.supportWaitUnresolvedChainedPromise) {
|
||||
return;
|
||||
}
|
||||
const unPatchPromiseForTest = (Promise as any)[Zone.__symbol__('unPatchPromiseForTest')];
|
||||
if (unPatchPromiseForTest) {
|
||||
unPatchPromiseForTest();
|
||||
}
|
||||
}
|
||||
|
||||
// ZoneSpec implementation below.
|
||||
|
||||
name: string;
|
||||
|
||||
properties: {[key: string]: any};
|
||||
|
||||
onScheduleTask(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): Task {
|
||||
if (task.type !== 'eventTask') {
|
||||
this._isSync = false;
|
||||
}
|
||||
if (task.type === 'microTask' && task.data && task.data instanceof Promise) {
|
||||
// check whether the promise is a chained promise
|
||||
if ((task.data as any)[AsyncTestZoneSpec.symbolParentUnresolved] === true) {
|
||||
// chained promise is being scheduled
|
||||
this.unresolvedChainedPromiseCount--;
|
||||
}
|
||||
}
|
||||
return delegate.scheduleTask(target, task);
|
||||
}
|
||||
|
||||
onInvokeTask(
|
||||
delegate: ZoneDelegate, current: Zone, target: Zone, task: Task, applyThis: any,
|
||||
applyArgs: any) {
|
||||
if (task.type !== 'eventTask') {
|
||||
this._isSync = false;
|
||||
}
|
||||
return delegate.invokeTask(target, task, applyThis, applyArgs);
|
||||
}
|
||||
|
||||
onCancelTask(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task) {
|
||||
if (task.type !== 'eventTask') {
|
||||
this._isSync = false;
|
||||
}
|
||||
return delegate.cancelTask(target, task);
|
||||
}
|
||||
|
||||
// Note - we need to use onInvoke at the moment to call finish when a test is
|
||||
// fully synchronous. TODO(juliemr): remove this when the logic for
|
||||
// onHasTask changes and it calls whenever the task queues are dirty.
|
||||
// updated by(JiaLiPassion), only call finish callback when no task
|
||||
// was scheduled/invoked/canceled.
|
||||
onInvoke(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
|
||||
applyThis: any, applyArgs?: any[], source?: string): any {
|
||||
let previousTaskCounts: any = null;
|
||||
try {
|
||||
this._isSync = true;
|
||||
return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
|
||||
} finally {
|
||||
const afterTaskCounts: any = (parentZoneDelegate as any)._taskCounts;
|
||||
if (this._isSync) {
|
||||
this._finishCallbackIfDone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onHandleError(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
|
||||
error: any): boolean {
|
||||
// Let the parent try to handle the error.
|
||||
const result = parentZoneDelegate.handleError(targetZone, error);
|
||||
if (result) {
|
||||
this.failCallback(error);
|
||||
this._alreadyErrored = true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
onHasTask(delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState) {
|
||||
delegate.hasTask(target, hasTaskState);
|
||||
if (hasTaskState.change == 'microTask') {
|
||||
this._pendingMicroTasks = hasTaskState.microTask;
|
||||
this._finishCallbackIfDone();
|
||||
} else if (hasTaskState.change == 'macroTask') {
|
||||
this._pendingMacroTasks = hasTaskState.macroTask;
|
||||
this._finishCallbackIfDone();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export the class so that new instances can be created with proper
|
||||
// constructor params.
|
||||
(Zone as any)['AsyncTestZoneSpec'] = AsyncTestZoneSpec;
|
||||
})(global);
|
560
packages/zone.js/lib/zone-spec/fake-async-test.ts
Normal file
560
packages/zone.js/lib/zone-spec/fake-async-test.ts
Normal file
@ -0,0 +1,560 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
(function(global: any) {
|
||||
interface ScheduledFunction {
|
||||
endTime: number;
|
||||
id: number;
|
||||
func: Function;
|
||||
args: any[];
|
||||
delay: number;
|
||||
isPeriodic: boolean;
|
||||
isRequestAnimationFrame: boolean;
|
||||
}
|
||||
|
||||
interface MicroTaskScheduledFunction {
|
||||
func: Function;
|
||||
args?: any[];
|
||||
target: any;
|
||||
}
|
||||
|
||||
interface MacroTaskOptions {
|
||||
source: string;
|
||||
isPeriodic?: boolean;
|
||||
callbackArgs?: any;
|
||||
}
|
||||
|
||||
const OriginalDate = global.Date;
|
||||
class FakeDate {
|
||||
constructor() {
|
||||
if (arguments.length === 0) {
|
||||
const d = new OriginalDate();
|
||||
d.setTime(FakeDate.now());
|
||||
return d;
|
||||
} else {
|
||||
const args = Array.prototype.slice.call(arguments);
|
||||
return new OriginalDate(...args);
|
||||
}
|
||||
}
|
||||
|
||||
static now() {
|
||||
const fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
|
||||
if (fakeAsyncTestZoneSpec) {
|
||||
return fakeAsyncTestZoneSpec.getCurrentRealTime() + fakeAsyncTestZoneSpec.getCurrentTime();
|
||||
}
|
||||
return OriginalDate.now.apply(this, arguments);
|
||||
}
|
||||
}
|
||||
|
||||
(FakeDate as any).UTC = OriginalDate.UTC;
|
||||
(FakeDate as any).parse = OriginalDate.parse;
|
||||
|
||||
// keep a reference for zone patched timer function
|
||||
const timers = {
|
||||
setTimeout: global.setTimeout,
|
||||
setInterval: global.setInterval,
|
||||
clearTimeout: global.clearTimeout,
|
||||
clearInterval: global.clearInterval
|
||||
};
|
||||
|
||||
class Scheduler {
|
||||
// Next scheduler id.
|
||||
public static nextId: number = 1;
|
||||
|
||||
// Scheduler queue with the tuple of end time and callback function - sorted by end time.
|
||||
private _schedulerQueue: ScheduledFunction[] = [];
|
||||
// Current simulated time in millis.
|
||||
private _currentTime: number = 0;
|
||||
// Current real time in millis.
|
||||
private _currentRealTime: number = OriginalDate.now();
|
||||
|
||||
constructor() {}
|
||||
|
||||
getCurrentTime() { return this._currentTime; }
|
||||
|
||||
getCurrentRealTime() { return this._currentRealTime; }
|
||||
|
||||
setCurrentRealTime(realTime: number) { this._currentRealTime = realTime; }
|
||||
|
||||
scheduleFunction(
|
||||
cb: Function, delay: number, args: any[] = [], isPeriodic: boolean = false,
|
||||
isRequestAnimationFrame: boolean = false, id: number = -1): number {
|
||||
let currentId: number = id < 0 ? Scheduler.nextId++ : id;
|
||||
let endTime = this._currentTime + delay;
|
||||
|
||||
// Insert so that scheduler queue remains sorted by end time.
|
||||
let newEntry: ScheduledFunction = {
|
||||
endTime: endTime,
|
||||
id: currentId,
|
||||
func: cb,
|
||||
args: args,
|
||||
delay: delay,
|
||||
isPeriodic: isPeriodic,
|
||||
isRequestAnimationFrame: isRequestAnimationFrame
|
||||
};
|
||||
let i = 0;
|
||||
for (; i < this._schedulerQueue.length; i++) {
|
||||
let currentEntry = this._schedulerQueue[i];
|
||||
if (newEntry.endTime < currentEntry.endTime) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
this._schedulerQueue.splice(i, 0, newEntry);
|
||||
return currentId;
|
||||
}
|
||||
|
||||
removeScheduledFunctionWithId(id: number): void {
|
||||
for (let i = 0; i < this._schedulerQueue.length; i++) {
|
||||
if (this._schedulerQueue[i].id == id) {
|
||||
this._schedulerQueue.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
tick(millis: number = 0, doTick?: (elapsed: number) => void): void {
|
||||
let finalTime = this._currentTime + millis;
|
||||
let lastCurrentTime = 0;
|
||||
if (this._schedulerQueue.length === 0 && doTick) {
|
||||
doTick(millis);
|
||||
return;
|
||||
}
|
||||
while (this._schedulerQueue.length > 0) {
|
||||
let current = this._schedulerQueue[0];
|
||||
if (finalTime < current.endTime) {
|
||||
// Done processing the queue since it's sorted by endTime.
|
||||
break;
|
||||
} else {
|
||||
// Time to run scheduled function. Remove it from the head of queue.
|
||||
let current = this._schedulerQueue.shift() !;
|
||||
lastCurrentTime = this._currentTime;
|
||||
this._currentTime = current.endTime;
|
||||
if (doTick) {
|
||||
doTick(this._currentTime - lastCurrentTime);
|
||||
}
|
||||
let retval = current.func.apply(
|
||||
global, current.isRequestAnimationFrame ? [this._currentTime] : current.args);
|
||||
if (!retval) {
|
||||
// Uncaught exception in the current scheduled function. Stop processing the queue.
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
lastCurrentTime = this._currentTime;
|
||||
this._currentTime = finalTime;
|
||||
if (doTick) {
|
||||
doTick(this._currentTime - lastCurrentTime);
|
||||
}
|
||||
}
|
||||
|
||||
flush(limit = 20, flushPeriodic = false, doTick?: (elapsed: number) => void): number {
|
||||
if (flushPeriodic) {
|
||||
return this.flushPeriodic(doTick);
|
||||
} else {
|
||||
return this.flushNonPeriodic(limit, doTick);
|
||||
}
|
||||
}
|
||||
|
||||
private flushPeriodic(doTick?: (elapsed: number) => void): number {
|
||||
if (this._schedulerQueue.length === 0) {
|
||||
return 0;
|
||||
}
|
||||
// Find the last task currently queued in the scheduler queue and tick
|
||||
// till that time.
|
||||
const startTime = this._currentTime;
|
||||
const lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
|
||||
this.tick(lastTask.endTime - startTime, doTick);
|
||||
return this._currentTime - startTime;
|
||||
}
|
||||
|
||||
private flushNonPeriodic(limit: number, doTick?: (elapsed: number) => void): number {
|
||||
const startTime = this._currentTime;
|
||||
let lastCurrentTime = 0;
|
||||
let count = 0;
|
||||
while (this._schedulerQueue.length > 0) {
|
||||
count++;
|
||||
if (count > limit) {
|
||||
throw new Error(
|
||||
'flush failed after reaching the limit of ' + limit +
|
||||
' tasks. Does your code use a polling timeout?');
|
||||
}
|
||||
|
||||
// flush only non-periodic timers.
|
||||
// If the only remaining tasks are periodic(or requestAnimationFrame), finish flushing.
|
||||
if (this._schedulerQueue.filter(task => !task.isPeriodic && !task.isRequestAnimationFrame)
|
||||
.length === 0) {
|
||||
break;
|
||||
}
|
||||
|
||||
const current = this._schedulerQueue.shift() !;
|
||||
lastCurrentTime = this._currentTime;
|
||||
this._currentTime = current.endTime;
|
||||
if (doTick) {
|
||||
// Update any secondary schedulers like Jasmine mock Date.
|
||||
doTick(this._currentTime - lastCurrentTime);
|
||||
}
|
||||
const retval = current.func.apply(global, current.args);
|
||||
if (!retval) {
|
||||
// Uncaught exception in the current scheduled function. Stop processing the queue.
|
||||
break;
|
||||
}
|
||||
}
|
||||
return this._currentTime - startTime;
|
||||
}
|
||||
}
|
||||
|
||||
class FakeAsyncTestZoneSpec implements ZoneSpec {
|
||||
static assertInZone(): void {
|
||||
if (Zone.current.get('FakeAsyncTestZoneSpec') == null) {
|
||||
throw new Error('The code should be running in the fakeAsync zone to call this function');
|
||||
}
|
||||
}
|
||||
|
||||
private _scheduler: Scheduler = new Scheduler();
|
||||
private _microtasks: MicroTaskScheduledFunction[] = [];
|
||||
private _lastError: Error|null = null;
|
||||
private _uncaughtPromiseErrors: {rejection: any}[] =
|
||||
(Promise as any)[(Zone as any).__symbol__('uncaughtPromiseErrors')];
|
||||
|
||||
pendingPeriodicTimers: number[] = [];
|
||||
pendingTimers: number[] = [];
|
||||
|
||||
private patchDateLocked = false;
|
||||
|
||||
constructor(
|
||||
namePrefix: string, private trackPendingRequestAnimationFrame = false,
|
||||
private macroTaskOptions?: MacroTaskOptions[]) {
|
||||
this.name = 'fakeAsyncTestZone for ' + namePrefix;
|
||||
// in case user can't access the construction of FakeAsyncTestSpec
|
||||
// user can also define macroTaskOptions by define a global variable.
|
||||
if (!this.macroTaskOptions) {
|
||||
this.macroTaskOptions = global[Zone.__symbol__('FakeAsyncTestMacroTask')];
|
||||
}
|
||||
}
|
||||
|
||||
private _fnAndFlush(fn: Function, completers: {onSuccess?: Function, onError?: Function}):
|
||||
Function {
|
||||
return (...args: any[]): boolean => {
|
||||
fn.apply(global, args);
|
||||
|
||||
if (this._lastError === null) { // Success
|
||||
if (completers.onSuccess != null) {
|
||||
completers.onSuccess.apply(global);
|
||||
}
|
||||
// Flush microtasks only on success.
|
||||
this.flushMicrotasks();
|
||||
} else { // Failure
|
||||
if (completers.onError != null) {
|
||||
completers.onError.apply(global);
|
||||
}
|
||||
}
|
||||
// Return true if there were no errors, false otherwise.
|
||||
return this._lastError === null;
|
||||
};
|
||||
}
|
||||
|
||||
private static _removeTimer(timers: number[], id: number): void {
|
||||
let index = timers.indexOf(id);
|
||||
if (index > -1) {
|
||||
timers.splice(index, 1);
|
||||
}
|
||||
}
|
||||
|
||||
private _dequeueTimer(id: number): Function {
|
||||
return () => { FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id); };
|
||||
}
|
||||
|
||||
private _requeuePeriodicTimer(fn: Function, interval: number, args: any[], id: number):
|
||||
Function {
|
||||
return () => {
|
||||
// Requeue the timer callback if it's not been canceled.
|
||||
if (this.pendingPeriodicTimers.indexOf(id) !== -1) {
|
||||
this._scheduler.scheduleFunction(fn, interval, args, true, false, id);
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
private _dequeuePeriodicTimer(id: number): Function {
|
||||
return () => { FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id); };
|
||||
}
|
||||
|
||||
private _setTimeout(fn: Function, delay: number, args: any[], isTimer = true): number {
|
||||
let removeTimerFn = this._dequeueTimer(Scheduler.nextId);
|
||||
// Queue the callback and dequeue the timer on success and error.
|
||||
let cb = this._fnAndFlush(fn, {onSuccess: removeTimerFn, onError: removeTimerFn});
|
||||
let id = this._scheduler.scheduleFunction(cb, delay, args, false, !isTimer);
|
||||
if (isTimer) {
|
||||
this.pendingTimers.push(id);
|
||||
}
|
||||
return id;
|
||||
}
|
||||
|
||||
private _clearTimeout(id: number): void {
|
||||
FakeAsyncTestZoneSpec._removeTimer(this.pendingTimers, id);
|
||||
this._scheduler.removeScheduledFunctionWithId(id);
|
||||
}
|
||||
|
||||
private _setInterval(fn: Function, interval: number, args: any[]): number {
|
||||
let id = Scheduler.nextId;
|
||||
let completers = {onSuccess: null as any, onError: this._dequeuePeriodicTimer(id)};
|
||||
let cb = this._fnAndFlush(fn, completers);
|
||||
|
||||
// Use the callback created above to requeue on success.
|
||||
completers.onSuccess = this._requeuePeriodicTimer(cb, interval, args, id);
|
||||
|
||||
// Queue the callback and dequeue the periodic timer only on error.
|
||||
this._scheduler.scheduleFunction(cb, interval, args, true);
|
||||
this.pendingPeriodicTimers.push(id);
|
||||
return id;
|
||||
}
|
||||
|
||||
private _clearInterval(id: number): void {
|
||||
FakeAsyncTestZoneSpec._removeTimer(this.pendingPeriodicTimers, id);
|
||||
this._scheduler.removeScheduledFunctionWithId(id);
|
||||
}
|
||||
|
||||
private _resetLastErrorAndThrow(): void {
|
||||
let error = this._lastError || this._uncaughtPromiseErrors[0];
|
||||
this._uncaughtPromiseErrors.length = 0;
|
||||
this._lastError = null;
|
||||
throw error;
|
||||
}
|
||||
|
||||
getCurrentTime() { return this._scheduler.getCurrentTime(); }
|
||||
|
||||
getCurrentRealTime() { return this._scheduler.getCurrentRealTime(); }
|
||||
|
||||
setCurrentRealTime(realTime: number) { this._scheduler.setCurrentRealTime(realTime); }
|
||||
|
||||
static patchDate() {
|
||||
if (!!global[Zone.__symbol__('disableDatePatching')]) {
|
||||
// we don't want to patch global Date
|
||||
// because in some case, global Date
|
||||
// is already being patched, we need to provide
|
||||
// an option to let user still use their
|
||||
// own version of Date.
|
||||
return;
|
||||
}
|
||||
|
||||
if (global['Date'] === FakeDate) {
|
||||
// already patched
|
||||
return;
|
||||
}
|
||||
global['Date'] = FakeDate;
|
||||
FakeDate.prototype = OriginalDate.prototype;
|
||||
|
||||
// try check and reset timers
|
||||
// because jasmine.clock().install() may
|
||||
// have replaced the global timer
|
||||
FakeAsyncTestZoneSpec.checkTimerPatch();
|
||||
}
|
||||
|
||||
static resetDate() {
|
||||
if (global['Date'] === FakeDate) {
|
||||
global['Date'] = OriginalDate;
|
||||
}
|
||||
}
|
||||
|
||||
static checkTimerPatch() {
|
||||
if (global.setTimeout !== timers.setTimeout) {
|
||||
global.setTimeout = timers.setTimeout;
|
||||
global.clearTimeout = timers.clearTimeout;
|
||||
}
|
||||
if (global.setInterval !== timers.setInterval) {
|
||||
global.setInterval = timers.setInterval;
|
||||
global.clearInterval = timers.clearInterval;
|
||||
}
|
||||
}
|
||||
|
||||
lockDatePatch() {
|
||||
this.patchDateLocked = true;
|
||||
FakeAsyncTestZoneSpec.patchDate();
|
||||
}
|
||||
unlockDatePatch() {
|
||||
this.patchDateLocked = false;
|
||||
FakeAsyncTestZoneSpec.resetDate();
|
||||
}
|
||||
|
||||
tick(millis: number = 0, doTick?: (elapsed: number) => void): void {
|
||||
FakeAsyncTestZoneSpec.assertInZone();
|
||||
this.flushMicrotasks();
|
||||
this._scheduler.tick(millis, doTick);
|
||||
if (this._lastError !== null) {
|
||||
this._resetLastErrorAndThrow();
|
||||
}
|
||||
}
|
||||
|
||||
flushMicrotasks(): void {
|
||||
FakeAsyncTestZoneSpec.assertInZone();
|
||||
const flushErrors = () => {
|
||||
if (this._lastError !== null || this._uncaughtPromiseErrors.length) {
|
||||
// If there is an error stop processing the microtask queue and rethrow the error.
|
||||
this._resetLastErrorAndThrow();
|
||||
}
|
||||
};
|
||||
while (this._microtasks.length > 0) {
|
||||
let microtask = this._microtasks.shift() !;
|
||||
microtask.func.apply(microtask.target, microtask.args);
|
||||
}
|
||||
flushErrors();
|
||||
}
|
||||
|
||||
flush(limit?: number, flushPeriodic?: boolean, doTick?: (elapsed: number) => void): number {
|
||||
FakeAsyncTestZoneSpec.assertInZone();
|
||||
this.flushMicrotasks();
|
||||
const elapsed = this._scheduler.flush(limit, flushPeriodic, doTick);
|
||||
if (this._lastError !== null) {
|
||||
this._resetLastErrorAndThrow();
|
||||
}
|
||||
return elapsed;
|
||||
}
|
||||
|
||||
// ZoneSpec implementation below.
|
||||
|
||||
name: string;
|
||||
|
||||
properties: {[key: string]: any} = {'FakeAsyncTestZoneSpec': this};
|
||||
|
||||
onScheduleTask(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): Task {
|
||||
switch (task.type) {
|
||||
case 'microTask':
|
||||
let args = task.data && (task.data as any).args;
|
||||
// should pass additional arguments to callback if have any
|
||||
// currently we know process.nextTick will have such additional
|
||||
// arguments
|
||||
let additionalArgs: any[]|undefined;
|
||||
if (args) {
|
||||
let callbackIndex = (task.data as any).cbIdx;
|
||||
if (typeof args.length === 'number' && args.length > callbackIndex + 1) {
|
||||
additionalArgs = Array.prototype.slice.call(args, callbackIndex + 1);
|
||||
}
|
||||
}
|
||||
this._microtasks.push({
|
||||
func: task.invoke,
|
||||
args: additionalArgs,
|
||||
target: task.data && (task.data as any).target
|
||||
});
|
||||
break;
|
||||
case 'macroTask':
|
||||
switch (task.source) {
|
||||
case 'setTimeout':
|
||||
task.data !['handleId'] = this._setTimeout(
|
||||
task.invoke, task.data !['delay'] !,
|
||||
Array.prototype.slice.call((task.data as any)['args'], 2));
|
||||
break;
|
||||
case 'setImmediate':
|
||||
task.data !['handleId'] = this._setTimeout(
|
||||
task.invoke, 0, Array.prototype.slice.call((task.data as any)['args'], 1));
|
||||
break;
|
||||
case 'setInterval':
|
||||
task.data !['handleId'] = this._setInterval(
|
||||
task.invoke, task.data !['delay'] !,
|
||||
Array.prototype.slice.call((task.data as any)['args'], 2));
|
||||
break;
|
||||
case 'XMLHttpRequest.send':
|
||||
throw new Error(
|
||||
'Cannot make XHRs from within a fake async test. Request URL: ' +
|
||||
(task.data as any)['url']);
|
||||
case 'requestAnimationFrame':
|
||||
case 'webkitRequestAnimationFrame':
|
||||
case 'mozRequestAnimationFrame':
|
||||
// Simulate a requestAnimationFrame by using a setTimeout with 16 ms.
|
||||
// (60 frames per second)
|
||||
task.data !['handleId'] = this._setTimeout(
|
||||
task.invoke, 16, (task.data as any)['args'],
|
||||
this.trackPendingRequestAnimationFrame);
|
||||
break;
|
||||
default:
|
||||
// user can define which macroTask they want to support by passing
|
||||
// macroTaskOptions
|
||||
const macroTaskOption = this.findMacroTaskOption(task);
|
||||
if (macroTaskOption) {
|
||||
const args = task.data && (task.data as any)['args'];
|
||||
const delay = args && args.length > 1 ? args[1] : 0;
|
||||
let callbackArgs =
|
||||
macroTaskOption.callbackArgs ? macroTaskOption.callbackArgs : args;
|
||||
if (!!macroTaskOption.isPeriodic) {
|
||||
// periodic macroTask, use setInterval to simulate
|
||||
task.data !['handleId'] = this._setInterval(task.invoke, delay, callbackArgs);
|
||||
task.data !.isPeriodic = true;
|
||||
} else {
|
||||
// not periodic, use setTimeout to simulate
|
||||
task.data !['handleId'] = this._setTimeout(task.invoke, delay, callbackArgs);
|
||||
}
|
||||
break;
|
||||
}
|
||||
throw new Error('Unknown macroTask scheduled in fake async test: ' + task.source);
|
||||
}
|
||||
break;
|
||||
case 'eventTask':
|
||||
task = delegate.scheduleTask(target, task);
|
||||
break;
|
||||
}
|
||||
return task;
|
||||
}
|
||||
|
||||
onCancelTask(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): any {
|
||||
switch (task.source) {
|
||||
case 'setTimeout':
|
||||
case 'requestAnimationFrame':
|
||||
case 'webkitRequestAnimationFrame':
|
||||
case 'mozRequestAnimationFrame':
|
||||
return this._clearTimeout(<number>task.data !['handleId']);
|
||||
case 'setInterval':
|
||||
return this._clearInterval(<number>task.data !['handleId']);
|
||||
default:
|
||||
// user can define which macroTask they want to support by passing
|
||||
// macroTaskOptions
|
||||
const macroTaskOption = this.findMacroTaskOption(task);
|
||||
if (macroTaskOption) {
|
||||
const handleId: number = <number>task.data !['handleId'];
|
||||
return macroTaskOption.isPeriodic ? this._clearInterval(handleId) :
|
||||
this._clearTimeout(handleId);
|
||||
}
|
||||
return delegate.cancelTask(target, task);
|
||||
}
|
||||
}
|
||||
|
||||
onInvoke(
|
||||
delegate: ZoneDelegate, current: Zone, target: Zone, callback: Function, applyThis: any,
|
||||
applyArgs?: any[], source?: string): any {
|
||||
try {
|
||||
FakeAsyncTestZoneSpec.patchDate();
|
||||
return delegate.invoke(target, callback, applyThis, applyArgs, source);
|
||||
} finally {
|
||||
if (!this.patchDateLocked) {
|
||||
FakeAsyncTestZoneSpec.resetDate();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
findMacroTaskOption(task: Task) {
|
||||
if (!this.macroTaskOptions) {
|
||||
return null;
|
||||
}
|
||||
for (let i = 0; i < this.macroTaskOptions.length; i++) {
|
||||
const macroTaskOption = this.macroTaskOptions[i];
|
||||
if (macroTaskOption.source === task.source) {
|
||||
return macroTaskOption;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
onHandleError(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
|
||||
error: any): boolean {
|
||||
this._lastError = error;
|
||||
return false; // Don't propagate error to parent zone.
|
||||
}
|
||||
}
|
||||
|
||||
// Export the class so that new instances can be created with proper
|
||||
// constructor params.
|
||||
(Zone as any)['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
|
||||
})(global);
|
183
packages/zone.js/lib/zone-spec/long-stack-trace.ts
Normal file
183
packages/zone.js/lib/zone-spec/long-stack-trace.ts
Normal file
@ -0,0 +1,183 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {globalThis}
|
||||
*/
|
||||
|
||||
const NEWLINE = '\n';
|
||||
const IGNORE_FRAMES: {[k: string]: true} = {};
|
||||
const creationTrace = '__creationTrace__';
|
||||
const ERROR_TAG = 'STACKTRACE TRACKING';
|
||||
const SEP_TAG = '__SEP_TAG__';
|
||||
let sepTemplate: string = SEP_TAG + '@[native]';
|
||||
|
||||
class LongStackTrace {
|
||||
error: Error = getStacktrace();
|
||||
timestamp: Date = new Date();
|
||||
}
|
||||
|
||||
function getStacktraceWithUncaughtError(): Error {
|
||||
return new Error(ERROR_TAG);
|
||||
}
|
||||
|
||||
function getStacktraceWithCaughtError(): Error {
|
||||
try {
|
||||
throw getStacktraceWithUncaughtError();
|
||||
} catch (err) {
|
||||
return err;
|
||||
}
|
||||
}
|
||||
|
||||
// Some implementations of exception handling don't create a stack trace if the exception
|
||||
// isn't thrown, however it's faster not to actually throw the exception.
|
||||
const error = getStacktraceWithUncaughtError();
|
||||
const caughtError = getStacktraceWithCaughtError();
|
||||
const getStacktrace = error.stack ?
|
||||
getStacktraceWithUncaughtError :
|
||||
(caughtError.stack ? getStacktraceWithCaughtError : getStacktraceWithUncaughtError);
|
||||
|
||||
function getFrames(error: Error): string[] {
|
||||
return error.stack ? error.stack.split(NEWLINE) : [];
|
||||
}
|
||||
|
||||
function addErrorStack(lines: string[], error: Error): void {
|
||||
let trace: string[] = getFrames(error);
|
||||
for (let i = 0; i < trace.length; i++) {
|
||||
const frame = trace[i];
|
||||
// Filter out the Frames which are part of stack capturing.
|
||||
if (!IGNORE_FRAMES.hasOwnProperty(frame)) {
|
||||
lines.push(trace[i]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
function renderLongStackTrace(frames: LongStackTrace[], stack?: string): string {
|
||||
const longTrace: string[] = [stack ? stack.trim() : ''];
|
||||
|
||||
if (frames) {
|
||||
let timestamp = new Date().getTime();
|
||||
for (let i = 0; i < frames.length; i++) {
|
||||
const traceFrames: LongStackTrace = frames[i];
|
||||
const lastTime = traceFrames.timestamp;
|
||||
let separator =
|
||||
`____________________Elapsed ${timestamp - lastTime.getTime()} ms; At: ${lastTime}`;
|
||||
separator = separator.replace(/[^\w\d]/g, '_');
|
||||
longTrace.push(sepTemplate.replace(SEP_TAG, separator));
|
||||
addErrorStack(longTrace, traceFrames.error);
|
||||
|
||||
timestamp = lastTime.getTime();
|
||||
}
|
||||
}
|
||||
|
||||
return longTrace.join(NEWLINE);
|
||||
}
|
||||
|
||||
(Zone as any)['longStackTraceZoneSpec'] = <ZoneSpec>{
|
||||
name: 'long-stack-trace',
|
||||
longStackTraceLimit: 10, // Max number of task to keep the stack trace for.
|
||||
// add a getLongStackTrace method in spec to
|
||||
// handle handled reject promise error.
|
||||
getLongStackTrace: function(error: Error): string |
|
||||
undefined {
|
||||
if (!error) {
|
||||
return undefined;
|
||||
}
|
||||
const trace = (error as any)[(Zone as any).__symbol__('currentTaskTrace')];
|
||||
if (!trace) {
|
||||
return error.stack;
|
||||
}
|
||||
return renderLongStackTrace(trace, error.stack);
|
||||
},
|
||||
|
||||
onScheduleTask: function(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any {
|
||||
if (Error.stackTraceLimit > 0) {
|
||||
// if Error.stackTraceLimit is 0, means stack trace
|
||||
// is disabled, so we don't need to generate long stack trace
|
||||
// this will improve performance in some test(some test will
|
||||
// set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
|
||||
const currentTask = Zone.currentTask;
|
||||
let trace = currentTask && currentTask.data && (currentTask.data as any)[creationTrace] || [];
|
||||
trace = [new LongStackTrace()].concat(trace);
|
||||
if (trace.length > this.longStackTraceLimit) {
|
||||
trace.length = this.longStackTraceLimit;
|
||||
}
|
||||
if (!task.data) task.data = {};
|
||||
if (task.type === 'eventTask') {
|
||||
// Fix issue https://github.com/angular/zone.js/issues/1195,
|
||||
// For event task of browser, by default, all task will share a
|
||||
// singleton instance of data object, we should create a new one here
|
||||
|
||||
// The cast to `any` is required to workaround a closure bug which wrongly applies
|
||||
// URL sanitization rules to .data access.
|
||||
(task.data as any) = {...(task.data as any)};
|
||||
}
|
||||
(task.data as any)[creationTrace] = trace;
|
||||
}
|
||||
return parentZoneDelegate.scheduleTask(targetZone, task);
|
||||
},
|
||||
|
||||
onHandleError: function(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any): boolean {
|
||||
if (Error.stackTraceLimit > 0) {
|
||||
// if Error.stackTraceLimit is 0, means stack trace
|
||||
// is disabled, so we don't need to generate long stack trace
|
||||
// this will improve performance in some test(some test will
|
||||
// set stackTraceLimit to 0, https://github.com/angular/zone.js/issues/698
|
||||
const parentTask = Zone.currentTask || error.task;
|
||||
if (error instanceof Error && parentTask) {
|
||||
const longStack =
|
||||
renderLongStackTrace(parentTask.data && parentTask.data[creationTrace], error.stack);
|
||||
try {
|
||||
error.stack = (error as any).longStack = longStack;
|
||||
} catch (err) {
|
||||
}
|
||||
}
|
||||
}
|
||||
return parentZoneDelegate.handleError(targetZone, error);
|
||||
}
|
||||
};
|
||||
|
||||
function captureStackTraces(stackTraces: string[][], count: number): void {
|
||||
if (count > 0) {
|
||||
stackTraces.push(getFrames((new LongStackTrace()).error));
|
||||
captureStackTraces(stackTraces, count - 1);
|
||||
}
|
||||
}
|
||||
|
||||
function computeIgnoreFrames() {
|
||||
if (Error.stackTraceLimit <= 0) {
|
||||
return;
|
||||
}
|
||||
const frames: string[][] = [];
|
||||
captureStackTraces(frames, 2);
|
||||
const frames1 = frames[0];
|
||||
const frames2 = frames[1];
|
||||
for (let i = 0; i < frames1.length; i++) {
|
||||
const frame1 = frames1[i];
|
||||
if (frame1.indexOf(ERROR_TAG) == -1) {
|
||||
let match = frame1.match(/^\s*at\s+/);
|
||||
if (match) {
|
||||
sepTemplate = match[0] + SEP_TAG + ' (http://localhost)';
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
for (let i = 0; i < frames1.length; i++) {
|
||||
const frame1 = frames1[i];
|
||||
const frame2 = frames2[i];
|
||||
if (frame1 === frame2) {
|
||||
IGNORE_FRAMES[frame1] = true;
|
||||
} else {
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
computeIgnoreFrames();
|
195
packages/zone.js/lib/zone-spec/proxy.ts
Normal file
195
packages/zone.js/lib/zone-spec/proxy.ts
Normal file
@ -0,0 +1,195 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
class ProxyZoneSpec implements ZoneSpec {
|
||||
name: string = 'ProxyZone';
|
||||
|
||||
private _delegateSpec: ZoneSpec|null = null;
|
||||
|
||||
properties: {[k: string]: any} = {'ProxyZoneSpec': this};
|
||||
propertyKeys: string[]|null = null;
|
||||
|
||||
lastTaskState: HasTaskState|null = null;
|
||||
isNeedToTriggerHasTask = false;
|
||||
|
||||
private tasks: Task[] = [];
|
||||
|
||||
static get(): ProxyZoneSpec { return Zone.current.get('ProxyZoneSpec'); }
|
||||
|
||||
static isLoaded(): boolean { return ProxyZoneSpec.get() instanceof ProxyZoneSpec; }
|
||||
|
||||
static assertPresent(): ProxyZoneSpec {
|
||||
if (!ProxyZoneSpec.isLoaded()) {
|
||||
throw new Error(`Expected to be running in 'ProxyZone', but it was not found.`);
|
||||
}
|
||||
return ProxyZoneSpec.get();
|
||||
}
|
||||
|
||||
constructor(private defaultSpecDelegate: ZoneSpec|null = null) {
|
||||
this.setDelegate(defaultSpecDelegate);
|
||||
}
|
||||
|
||||
setDelegate(delegateSpec: ZoneSpec|null) {
|
||||
const isNewDelegate = this._delegateSpec !== delegateSpec;
|
||||
this._delegateSpec = delegateSpec;
|
||||
this.propertyKeys && this.propertyKeys.forEach((key) => delete this.properties[key]);
|
||||
this.propertyKeys = null;
|
||||
if (delegateSpec && delegateSpec.properties) {
|
||||
this.propertyKeys = Object.keys(delegateSpec.properties);
|
||||
this.propertyKeys.forEach((k) => this.properties[k] = delegateSpec.properties ![k]);
|
||||
}
|
||||
// if set a new delegateSpec, shoulde check whether need to
|
||||
// trigger hasTask or not
|
||||
if (isNewDelegate && this.lastTaskState &&
|
||||
(this.lastTaskState.macroTask || this.lastTaskState.microTask)) {
|
||||
this.isNeedToTriggerHasTask = true;
|
||||
}
|
||||
}
|
||||
|
||||
getDelegate() { return this._delegateSpec; }
|
||||
|
||||
|
||||
resetDelegate() {
|
||||
const delegateSpec = this.getDelegate();
|
||||
this.setDelegate(this.defaultSpecDelegate);
|
||||
}
|
||||
|
||||
tryTriggerHasTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone) {
|
||||
if (this.isNeedToTriggerHasTask && this.lastTaskState) {
|
||||
// last delegateSpec has microTask or macroTask
|
||||
// should call onHasTask in current delegateSpec
|
||||
this.isNeedToTriggerHasTask = false;
|
||||
this.onHasTask(parentZoneDelegate, currentZone, targetZone, this.lastTaskState);
|
||||
}
|
||||
}
|
||||
|
||||
removeFromTasks(task: Task) {
|
||||
if (!this.tasks) {
|
||||
return;
|
||||
}
|
||||
for (let i = 0; i < this.tasks.length; i++) {
|
||||
if (this.tasks[i] === task) {
|
||||
this.tasks.splice(i, 1);
|
||||
return;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
getAndClearPendingTasksInfo() {
|
||||
if (this.tasks.length === 0) {
|
||||
return '';
|
||||
}
|
||||
const taskInfo = this.tasks.map((task: Task) => {
|
||||
const dataInfo = task.data &&
|
||||
Object.keys(task.data)
|
||||
.map((key: string) => { return key + ':' + (task.data as any)[key]; })
|
||||
.join(',');
|
||||
return `type: ${task.type}, source: ${task.source}, args: {${dataInfo}}`;
|
||||
});
|
||||
const pendingTasksInfo = '--Pendng async tasks are: [' + taskInfo + ']';
|
||||
// clear tasks
|
||||
this.tasks = [];
|
||||
|
||||
return pendingTasksInfo;
|
||||
}
|
||||
|
||||
onFork(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, zoneSpec: ZoneSpec):
|
||||
Zone {
|
||||
if (this._delegateSpec && this._delegateSpec.onFork) {
|
||||
return this._delegateSpec.onFork(parentZoneDelegate, currentZone, targetZone, zoneSpec);
|
||||
} else {
|
||||
return parentZoneDelegate.fork(targetZone, zoneSpec);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
onIntercept(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
|
||||
source: string): Function {
|
||||
if (this._delegateSpec && this._delegateSpec.onIntercept) {
|
||||
return this._delegateSpec.onIntercept(
|
||||
parentZoneDelegate, currentZone, targetZone, delegate, source);
|
||||
} else {
|
||||
return parentZoneDelegate.intercept(targetZone, delegate, source);
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
onInvoke(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
|
||||
applyThis: any, applyArgs?: any[], source?: string): any {
|
||||
this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
|
||||
if (this._delegateSpec && this._delegateSpec.onInvoke) {
|
||||
return this._delegateSpec.onInvoke(
|
||||
parentZoneDelegate, currentZone, targetZone, delegate, applyThis, applyArgs, source);
|
||||
} else {
|
||||
return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
|
||||
}
|
||||
}
|
||||
|
||||
onHandleError(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, error: any):
|
||||
boolean {
|
||||
if (this._delegateSpec && this._delegateSpec.onHandleError) {
|
||||
return this._delegateSpec.onHandleError(parentZoneDelegate, currentZone, targetZone, error);
|
||||
} else {
|
||||
return parentZoneDelegate.handleError(targetZone, error);
|
||||
}
|
||||
}
|
||||
|
||||
onScheduleTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
|
||||
Task {
|
||||
if (task.type !== 'eventTask') {
|
||||
this.tasks.push(task);
|
||||
}
|
||||
if (this._delegateSpec && this._delegateSpec.onScheduleTask) {
|
||||
return this._delegateSpec.onScheduleTask(parentZoneDelegate, currentZone, targetZone, task);
|
||||
} else {
|
||||
return parentZoneDelegate.scheduleTask(targetZone, task);
|
||||
}
|
||||
}
|
||||
|
||||
onInvokeTask(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
|
||||
applyThis: any, applyArgs: any): any {
|
||||
if (task.type !== 'eventTask') {
|
||||
this.removeFromTasks(task);
|
||||
}
|
||||
this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
|
||||
if (this._delegateSpec && this._delegateSpec.onInvokeTask) {
|
||||
return this._delegateSpec.onInvokeTask(
|
||||
parentZoneDelegate, currentZone, targetZone, task, applyThis, applyArgs);
|
||||
} else {
|
||||
return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
|
||||
}
|
||||
}
|
||||
|
||||
onCancelTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
|
||||
any {
|
||||
if (task.type !== 'eventTask') {
|
||||
this.removeFromTasks(task);
|
||||
}
|
||||
this.tryTriggerHasTask(parentZoneDelegate, currentZone, targetZone);
|
||||
if (this._delegateSpec && this._delegateSpec.onCancelTask) {
|
||||
return this._delegateSpec.onCancelTask(parentZoneDelegate, currentZone, targetZone, task);
|
||||
} else {
|
||||
return parentZoneDelegate.cancelTask(targetZone, task);
|
||||
}
|
||||
}
|
||||
|
||||
onHasTask(delegate: ZoneDelegate, current: Zone, target: Zone, hasTaskState: HasTaskState): void {
|
||||
this.lastTaskState = hasTaskState;
|
||||
if (this._delegateSpec && this._delegateSpec.onHasTask) {
|
||||
this._delegateSpec.onHasTask(delegate, current, target, hasTaskState);
|
||||
} else {
|
||||
delegate.hasTask(target, hasTaskState);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export the class so that new instances can be created with proper
|
||||
// constructor params.
|
||||
(Zone as any)['ProxyZoneSpec'] = ProxyZoneSpec;
|
33
packages/zone.js/lib/zone-spec/sync-test.ts
Normal file
33
packages/zone.js/lib/zone-spec/sync-test.ts
Normal file
@ -0,0 +1,33 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
class SyncTestZoneSpec implements ZoneSpec {
|
||||
runZone = Zone.current;
|
||||
|
||||
constructor(namePrefix: string) { this.name = 'syncTestZone for ' + namePrefix; }
|
||||
|
||||
// ZoneSpec implementation below.
|
||||
|
||||
name: string;
|
||||
|
||||
onScheduleTask(delegate: ZoneDelegate, current: Zone, target: Zone, task: Task): Task {
|
||||
switch (task.type) {
|
||||
case 'microTask':
|
||||
case 'macroTask':
|
||||
throw new Error(`Cannot call ${task.source} from within a sync test.`);
|
||||
case 'eventTask':
|
||||
task = delegate.scheduleTask(target, task);
|
||||
break;
|
||||
}
|
||||
return task;
|
||||
}
|
||||
}
|
||||
|
||||
// Export the class so that new instances can be created with proper
|
||||
// constructor params.
|
||||
(Zone as any)['SyncTestZoneSpec'] = SyncTestZoneSpec;
|
80
packages/zone.js/lib/zone-spec/task-tracking.ts
Normal file
80
packages/zone.js/lib/zone-spec/task-tracking.ts
Normal file
@ -0,0 +1,80 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
|
||||
/**
|
||||
* A `TaskTrackingZoneSpec` allows one to track all outstanding Tasks.
|
||||
*
|
||||
* This is useful in tests. For example to see which tasks are preventing a test from completing
|
||||
* or an automated way of releasing all of the event listeners at the end of the test.
|
||||
*/
|
||||
class TaskTrackingZoneSpec implements ZoneSpec {
|
||||
name = 'TaskTrackingZone';
|
||||
microTasks: Task[] = [];
|
||||
macroTasks: Task[] = [];
|
||||
eventTasks: Task[] = [];
|
||||
properties: {[key: string]: any} = {'TaskTrackingZone': this};
|
||||
|
||||
static get() { return Zone.current.get('TaskTrackingZone'); }
|
||||
|
||||
private getTasksFor(type: string): Task[] {
|
||||
switch (type) {
|
||||
case 'microTask':
|
||||
return this.microTasks;
|
||||
case 'macroTask':
|
||||
return this.macroTasks;
|
||||
case 'eventTask':
|
||||
return this.eventTasks;
|
||||
}
|
||||
throw new Error('Unknown task format: ' + type);
|
||||
}
|
||||
|
||||
onScheduleTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
|
||||
Task {
|
||||
(task as any)['creationLocation'] = new Error(`Task '${task.type}' from '${task.source}'.`);
|
||||
const tasks = this.getTasksFor(task.type);
|
||||
tasks.push(task);
|
||||
return parentZoneDelegate.scheduleTask(targetZone, task);
|
||||
}
|
||||
|
||||
onCancelTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
|
||||
any {
|
||||
const tasks = this.getTasksFor(task.type);
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
if (tasks[i] == task) {
|
||||
tasks.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return parentZoneDelegate.cancelTask(targetZone, task);
|
||||
}
|
||||
|
||||
onInvokeTask(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
|
||||
applyThis: any, applyArgs: any): any {
|
||||
if (task.type === 'eventTask')
|
||||
return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
|
||||
const tasks = this.getTasksFor(task.type);
|
||||
for (let i = 0; i < tasks.length; i++) {
|
||||
if (tasks[i] == task) {
|
||||
tasks.splice(i, 1);
|
||||
break;
|
||||
}
|
||||
}
|
||||
return parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs);
|
||||
}
|
||||
|
||||
clearEvents() {
|
||||
while (this.eventTasks.length) {
|
||||
Zone.current.cancelTask(this.eventTasks[0]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Export the class so that new instances can be created with proper
|
||||
// constructor params.
|
||||
(Zone as any)['TaskTrackingZoneSpec'] = TaskTrackingZoneSpec;
|
161
packages/zone.js/lib/zone-spec/wtf.ts
Normal file
161
packages/zone.js/lib/zone-spec/wtf.ts
Normal file
@ -0,0 +1,161 @@
|
||||
/**
|
||||
* @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
|
||||
*/
|
||||
/**
|
||||
* @fileoverview
|
||||
* @suppress {missingRequire}
|
||||
*/
|
||||
|
||||
(function(global: any) {
|
||||
interface Wtf {
|
||||
trace: WtfTrace;
|
||||
}
|
||||
interface WtfScope {}
|
||||
interface WtfRange {}
|
||||
interface WtfTrace {
|
||||
events: WtfEvents;
|
||||
leaveScope(scope: WtfScope, returnValue?: any): void;
|
||||
beginTimeRange(rangeType: string, action: string): WtfRange;
|
||||
endTimeRange(range: WtfRange): void;
|
||||
}
|
||||
interface WtfEvents {
|
||||
createScope(signature: string, flags?: any): WtfScopeFn;
|
||||
createInstance(signature: string, flags?: any): WtfEventFn;
|
||||
}
|
||||
|
||||
type WtfScopeFn = (...args: any[]) => WtfScope;
|
||||
type WtfEventFn = (...args: any[]) => any;
|
||||
|
||||
// Detect and setup WTF.
|
||||
let wtfTrace: WtfTrace|null = null;
|
||||
let wtfEvents: WtfEvents|null = null;
|
||||
const wtfEnabled: boolean = (function(): boolean {
|
||||
const wtf: Wtf = global['wtf'];
|
||||
if (wtf) {
|
||||
wtfTrace = wtf.trace;
|
||||
if (wtfTrace) {
|
||||
wtfEvents = wtfTrace.events;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
})();
|
||||
|
||||
class WtfZoneSpec implements ZoneSpec {
|
||||
name: string = 'WTF';
|
||||
|
||||
static forkInstance =
|
||||
wtfEnabled? wtfEvents !.createInstance('Zone:fork(ascii zone, ascii newZone)'): null;
|
||||
static scheduleInstance: {[key: string]: WtfEventFn} = {};
|
||||
static cancelInstance: {[key: string]: WtfEventFn} = {};
|
||||
static invokeScope: {[key: string]: WtfEventFn} = {};
|
||||
static invokeTaskScope: {[key: string]: WtfEventFn} = {};
|
||||
|
||||
onFork(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
|
||||
zoneSpec: ZoneSpec): Zone {
|
||||
const retValue = parentZoneDelegate.fork(targetZone, zoneSpec);
|
||||
WtfZoneSpec.forkInstance !(zonePathName(targetZone), retValue.name);
|
||||
return retValue;
|
||||
}
|
||||
|
||||
onInvoke(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, delegate: Function,
|
||||
applyThis: any, applyArgs?: any[], source?: string): any {
|
||||
const src = source || 'unknown';
|
||||
let scope = WtfZoneSpec.invokeScope[src];
|
||||
if (!scope) {
|
||||
scope = WtfZoneSpec.invokeScope[src] =
|
||||
wtfEvents !.createScope(`Zone:invoke:${source}(ascii zone)`);
|
||||
}
|
||||
return wtfTrace !.leaveScope(
|
||||
scope(zonePathName(targetZone)),
|
||||
parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source));
|
||||
}
|
||||
|
||||
|
||||
onHandleError(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone,
|
||||
error: any): boolean {
|
||||
return parentZoneDelegate.handleError(targetZone, error);
|
||||
}
|
||||
|
||||
onScheduleTask(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task): any {
|
||||
const key = task.type + ':' + task.source;
|
||||
let instance = WtfZoneSpec.scheduleInstance[key];
|
||||
if (!instance) {
|
||||
instance = WtfZoneSpec.scheduleInstance[key] =
|
||||
wtfEvents !.createInstance(`Zone:schedule:${key}(ascii zone, any data)`);
|
||||
}
|
||||
const retValue = parentZoneDelegate.scheduleTask(targetZone, task);
|
||||
instance(zonePathName(targetZone), shallowObj(task.data, 2));
|
||||
return retValue;
|
||||
}
|
||||
|
||||
|
||||
onInvokeTask(
|
||||
parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task,
|
||||
applyThis?: any, applyArgs?: any[]): any {
|
||||
const source = task.source;
|
||||
let scope = WtfZoneSpec.invokeTaskScope[source];
|
||||
if (!scope) {
|
||||
scope = WtfZoneSpec.invokeTaskScope[source] =
|
||||
wtfEvents !.createScope(`Zone:invokeTask:${source}(ascii zone)`);
|
||||
}
|
||||
return wtfTrace !.leaveScope(
|
||||
scope(zonePathName(targetZone)),
|
||||
parentZoneDelegate.invokeTask(targetZone, task, applyThis, applyArgs));
|
||||
}
|
||||
|
||||
onCancelTask(parentZoneDelegate: ZoneDelegate, currentZone: Zone, targetZone: Zone, task: Task):
|
||||
any {
|
||||
const key = task.source;
|
||||
let instance = WtfZoneSpec.cancelInstance[key];
|
||||
if (!instance) {
|
||||
instance = WtfZoneSpec.cancelInstance[key] =
|
||||
wtfEvents !.createInstance(`Zone:cancel:${key}(ascii zone, any options)`);
|
||||
}
|
||||
const retValue = parentZoneDelegate.cancelTask(targetZone, task);
|
||||
instance(zonePathName(targetZone), shallowObj(task.data, 2));
|
||||
return retValue;
|
||||
}
|
||||
}
|
||||
|
||||
function shallowObj(obj: {[k: string]: any} | undefined, depth: number): any {
|
||||
if (!obj || !depth) return null;
|
||||
const out: {[k: string]: any} = {};
|
||||
for (const key in obj) {
|
||||
if (obj.hasOwnProperty(key)) {
|
||||
let value = obj[key];
|
||||
switch (typeof value) {
|
||||
case 'object':
|
||||
const name = value && value.constructor && (<any>value.constructor).name;
|
||||
value = name == (<any>Object).name ? shallowObj(value, depth - 1) : name;
|
||||
break;
|
||||
case 'function':
|
||||
value = value.name || undefined;
|
||||
break;
|
||||
}
|
||||
out[key] = value;
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
function zonePathName(zone: Zone) {
|
||||
let name: string = zone.name;
|
||||
let localZone = zone.parent;
|
||||
while (localZone != null) {
|
||||
name = localZone.name + '::' + name;
|
||||
localZone = localZone.parent;
|
||||
}
|
||||
return name;
|
||||
}
|
||||
|
||||
(Zone as any)['wtfZoneSpec'] = !wtfEnabled ? null : new WtfZoneSpec();
|
||||
})(global);
|
1404
packages/zone.js/lib/zone.ts
Normal file
1404
packages/zone.js/lib/zone.ts
Normal file
File diff suppressed because it is too large
Load Diff
Reference in New Issue
Block a user