build: move zone.js to angular repo (#30962)

PR Close #30962
This commit is contained in:
JiaLiPassion
2019-06-01 00:56:07 +09:00
committed by Kara Erickson
parent 7b3bcc23af
commit 5eb7426216
271 changed files with 30890 additions and 19 deletions

View 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;
});

View 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);
});
}
}

View 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;
}
});
};
});

View 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;
});

View 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);
}
});
}

View 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);
};
});

View 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;
}