_id stringlengths 21 254 | text stringlengths 1 93.7k | metadata dict |
|---|---|---|
angular/packages/zone.js/lib/browser/rollup-common.ts_0_500 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchPromise} from '../common/promise';
import {patchToString} from '../common/to-string';
import {ZoneType} from '../zone-impl';
import {patchUtil} from './api-util';
export function patchCommon(Zone: ZoneType): void {
patchPromise(Zone);
patchToString(Zone);
patchUtil(Zone);
}
| {
"end_byte": 500,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-common.ts"
} |
angular/packages/zone.js/lib/browser/rollup-webapis-resize-observer.ts_0_295 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchResizeObserver} from './webapis-resize-observer';
patchResizeObserver(Zone);
| {
"end_byte": 295,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-webapis-resize-observer.ts"
} |
angular/packages/zone.js/lib/browser/property-descriptor.ts_0_3600 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {globalThis}
*/
import {
isBrowser,
isIE,
isMix,
isNode,
ObjectGetPrototypeOf,
patchOnProperties,
} from '../common/utils';
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);
}
/**
* Get all event name properties which the event name startsWith `on`
* from the target object itself, inherited properties are not considered.
*/
export function getOnEventNames(target: Object) {
return Object.getOwnPropertyNames(target)
.filter((name) => name.startsWith('on') && name.length > 2)
.map((name) => name.substring(2));
}
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 ignoreProperties: IgnoreProperty[] = _global['__Zone_ignore_on_properties'];
// for browsers that we can patch the descriptor: Chrome & Firefox
let patchTargets: string[] = [];
if (isBrowser) {
const internalWindow: any = window;
patchTargets = patchTargets.concat([
'Document',
'SVGElement',
'Element',
'HTMLElement',
'HTMLBodyElement',
'HTMLMediaElement',
'HTMLFrameSetElement',
'HTMLFrameElement',
'HTMLIFrameElement',
'HTMLMarqueeElement',
'Worker',
]);
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,
getOnEventNames(internalWindow),
ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties,
ObjectGetPrototypeOf(internalWindow),
);
}
patchTargets = patchTargets.concat([
'XMLHttpRequest',
'XMLHttpRequestEventTarget',
'IDBIndex',
'IDBRequest',
'IDBOpenDBRequest',
'IDBDatabase',
'IDBTransaction',
'IDBCursor',
'WebSocket',
]);
for (let i = 0; i < patchTargets.length; i++) {
const target = _global[patchTargets[i]];
target &&
target.prototype &&
patchFilteredProperties(
target.prototype,
getOnEventNames(target.prototype),
ignoreProperties,
);
}
}
| {
"end_byte": 3600,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/property-descriptor.ts"
} |
angular/packages/zone.js/lib/browser/rollup-legacy-main.ts_0_464 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {loadZone} from '../zone';
import {patchBrowser} from './browser';
import {patchBrowserLegacy} from './browser-legacy';
import {patchCommon} from './rollup-common';
const Zone = loadZone();
patchCommon(Zone);
patchBrowserLegacy();
patchBrowser(Zone);
| {
"end_byte": 464,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-legacy-main.ts"
} |
angular/packages/zone.js/lib/browser/rollup-canvas.ts_0_262 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchCanvas} from './canvas';
patchCanvas(Zone);
| {
"end_byte": 262,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-canvas.ts"
} |
angular/packages/zone.js/lib/browser/rollup-shadydom.ts_0_268 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchShadyDom} from './shadydom';
patchShadyDom(Zone);
| {
"end_byte": 268,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-shadydom.ts"
} |
angular/packages/zone.js/lib/browser/define-property.ts_0_5548 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/*
* This is necessary for Chrome and Chrome mobile, to enable
* things like redefining `createdCallback` on an element.
*/
let zoneSymbol: any;
let _defineProperty: any;
let _getOwnPropertyDescriptor: any;
let _create: any;
let unconfigurablesKey: any;
export function propertyPatch() {
zoneSymbol = Zone.__symbol__;
_defineProperty = (Object as any)[zoneSymbol('defineProperty')] = Object.defineProperty;
_getOwnPropertyDescriptor = (Object as any)[zoneSymbol('getOwnPropertyDescriptor')] =
Object.getOwnPropertyDescriptor;
_create = Object.create;
unconfigurablesKey = zoneSymbol('unconfigurables');
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 <T>(
obj: T,
props: PropertyDescriptorMap &
ThisType<any> & {
[s: symbol]: PropertyDescriptor;
},
): T {
Object.keys(props).forEach(function (prop) {
Object.defineProperty(obj, prop, props[prop]);
});
for (const sym of Object.getOwnPropertySymbols(props)) {
const desc = Object.getOwnPropertyDescriptor(props, sym);
// Since `Object.getOwnPropertySymbols` returns *all* symbols,
// including non-enumerable ones, retrieve property descriptor and check
// enumerability there. Proceed with the rewrite only when a property is
// enumerable to make the logic consistent with the way regular
// properties are retrieved (via `Object.keys`, which respects
// `enumerable: false` flag). More information:
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties#retrieval
if (desc?.enumerable) {
Object.defineProperty(obj, sym, props[sym]);
}
}
return obj;
};
Object.create = <any>function (proto: any, propertiesObject: any) {
if (typeof propertiesObject === 'object' && !Object.isFrozen(propertiesObject)) {
Object.keys(propertiesObject).forEach(function (prop) {
propertiesObject[prop] = rewriteDescriptor(proto, prop, propertiesObject[prop]);
});
}
return _create(proto, propertiesObject);
};
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 swallowError = false;
if (
prop === 'createdCallback' ||
prop === 'attachedCallback' ||
prop === 'detachedCallback' ||
prop === 'attributeChangedCallback'
) {
// We only swallow the error in registerElement patch
// this is the work around since some applications
// fail if we throw the error
swallowError = true;
}
if (!swallowError) {
throw error;
}
// TODO: @JiaLiPassion, Some application such as `registerElement` patch
// still need to swallow the error, in the future after these applications
// are updated, the following logic can be removed.
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;
}
}
}
| {
"end_byte": 5548,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/define-property.ts"
} |
angular/packages/zone.js/lib/browser/webapis-rtc-peer-connection.ts_0_1162 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchRtcPeerConnection(Zone: ZoneType): void {
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, api, [RTCPeerConnection.prototype], {useG: false});
});
}
| {
"end_byte": 1162,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/webapis-rtc-peer-connection.ts"
} |
angular/packages/zone.js/lib/browser/property-descriptor-legacy.ts_0_6693 | /**
* @license
* Copyright Google LLC 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.dev/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;
}
}
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',
'vrdisplayconnected',
'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',
]; | {
"end_byte": 6693,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/property-descriptor-legacy.ts"
} |
angular/packages/zone.js/lib/browser/property-descriptor-legacy.ts_6694_9230 | 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 eventNames = [
...globalEventHandlersEventNames,
...webglEventNames,
...formEventNames,
...detailEventNames,
...documentEventNames,
...windowEventNames,
...htmlElementEventNames,
...ieElementEventNames,
];
// 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 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,
);
}
} | {
"end_byte": 9230,
"start_byte": 6694,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/property-descriptor-legacy.ts"
} |
angular/packages/zone.js/lib/browser/rollup-legacy-test-main.ts_0_309 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import './rollup-legacy-main';
// load test related files into bundle
import '../testing/zone-testing';
| {
"end_byte": 309,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-legacy-test-main.ts"
} |
angular/packages/zone.js/lib/browser/api-util.ts_0_3133 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {
globalSources,
patchEventPrototype,
patchEventTarget,
zoneSymbolEventNames,
} from '../common/events';
import {
ADD_EVENT_LISTENER_STR,
ArraySlice,
attachOriginToPatched,
bindArguments,
FALSE_STR,
isBrowser,
isIEOrEdge,
isMix,
isNode,
ObjectCreate,
ObjectDefineProperty,
ObjectGetOwnPropertyDescriptor,
patchClass,
patchMacroTask,
patchMethod,
patchOnProperties,
REMOVE_EVENT_LISTENER_STR,
TRUE_STR,
wrapWithCurrentZone,
ZONE_SYMBOL_PREFIX,
} from '../common/utils';
import {ZoneType} from '../zone-impl';
import {patchCallbacks} from './browser-util';
import {filterProperties, getOnEventNames} from './property-descriptor';
export function patchUtil(Zone: ZoneType): void {
Zone.__load_patch('util', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
// Collect native event names by looking at properties
// on the global namespace, e.g. 'onclick'.
const eventNames: string[] = getOnEventNames(global);
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 = Object.defineProperty;
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,
});
});
}
| {
"end_byte": 3133,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/api-util.ts"
} |
angular/packages/zone.js/lib/browser/webapis-notification.ts_0_723 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchNotifications(Zone: ZoneType): void {
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);
});
}
| {
"end_byte": 723,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/webapis-notification.ts"
} |
angular/packages/zone.js/lib/browser/register-element.ts_0_642 | /**
* @license
* Copyright Google LLC 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.dev/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);
}
| {
"end_byte": 642,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/register-element.ts"
} |
angular/packages/zone.js/lib/browser/browser.ts_0_3226 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
import {findEventTasks} from '../common/events';
import {patchQueueMicrotask} from '../common/queue-microtask';
import {patchTimer} from '../common/timers';
import {
patchClass,
patchMethod,
patchPrototype,
scheduleMacroTaskWithCurrentZone,
ZONE_SYMBOL_ADD_EVENT_LISTENER,
ZONE_SYMBOL_REMOVE_EVENT_LISTENER,
zoneSymbol,
} from '../common/utils';
import {ZoneType} from '../zone-impl';
import {patchCustomElements} from './custom-elements';
import {eventTargetPatch, patchEvent} from './event-target';
import {propertyDescriptorPatch} from './property-descriptor';
export function patchBrowser(Zone: ZoneType): void {
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, api, [XMLHttpRequestEventTarget.prototype]);
}
});
Zone.__load_patch('MutationObserver', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
patchClass('MutationObserver');
patchClass('WebKitMutationObserver');
});
Zone.__load_patch('IntersectionObserver', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
patchClass('IntersectionObserver');
});
Zone.__load_patch('FileReader', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
patchClass('FileReader');
});
Zone.__load_patch('on_property', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
propertyDescriptorPatch(api, global);
});
Zone.__load_patch('customElements', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
patchCustomElements(global, api);
}); | {
"end_byte": 3226,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/browser.ts"
} |
angular/packages/zone.js/lib/browser/browser.ts_3230_12731 | 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.
// Also if the request failed without response (status = 0), the load event handler
// will not be triggered, in that case, we should also invoke the placeholder callback
// to close the XMLHttpRequest::send macroTask.
// https://github.com/angular/angular/issues/38795
const loadTasks = target[Zone.__symbol__('loadfalse')];
if (target.status !== 0 && 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');
}
}); | {
"end_byte": 12731,
"start_byte": 3230,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/browser.ts"
} |
angular/packages/zone.js/lib/browser/browser.ts_12735_12870 | Zone.__load_patch('queueMicrotask', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
patchQueueMicrotask(global, api);
});
} | {
"end_byte": 12870,
"start_byte": 12735,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/browser.ts"
} |
angular/packages/zone.js/lib/browser/rollup-browser-legacy.ts_0_280 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchBrowserLegacy} from './browser-legacy';
patchBrowserLegacy();
| {
"end_byte": 280,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-browser-legacy.ts"
} |
angular/packages/zone.js/lib/browser/event-target.ts_0_1348 | /**
* @license
* Copyright Google LLC 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.dev/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, api, [EVENT_TARGET && EVENT_TARGET.prototype]);
return true;
}
export function patchEvent(global: any, api: _ZonePrivate) {
api.patchEventPrototype(global, api);
}
| {
"end_byte": 1348,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/event-target.ts"
} |
angular/packages/zone.js/lib/browser/shadydom.ts_0_1280 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchShadyDom(Zone: ZoneType): void {
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 HTMLSlotElement = global.HTMLSlotElement;
const prototypes = [
Object.getPrototypeOf(window),
Node.prototype,
Text.prototype,
Element.prototype,
HTMLElement.prototype,
HTMLSlotElement && HTMLSlotElement.prototype,
DocumentFragment.prototype,
Document.prototype,
];
prototypes.forEach(function (proto) {
if (proto && proto.hasOwnProperty('addEventListener')) {
proto[Zone.__symbol__('addEventListener')] = null;
proto[Zone.__symbol__('removeEventListener')] = null;
api.patchEventTarget(global, api, [proto]);
}
});
});
}
| {
"end_byte": 1280,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/shadydom.ts"
} |
angular/packages/zone.js/lib/browser/rollup-webapis-user-media.ts_0_280 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchUserMedia} from './webapis-user-media';
patchUserMedia(Zone);
| {
"end_byte": 280,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-webapis-user-media.ts"
} |
angular/packages/zone.js/lib/browser/webapis-media-query.ts_0_2622 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchMediaQuery(Zone: ZoneType): void {
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;
});
}
});
}
| {
"end_byte": 2622,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/webapis-media-query.ts"
} |
angular/packages/zone.js/lib/browser/browser-legacy.ts_0_1528 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
import {_redefineProperty, propertyPatch} from './define-property';
import {eventTargetLegacyPatch} from './event-target-legacy';
import {propertyDescriptorLegacyPatch} from './property-descriptor-legacy';
import {registerElementPatch} from './register-element';
export function patchBrowserLegacy(): void {
const _global: any =
typeof window !== 'undefined'
? window
: typeof global !== 'undefined'
? global
: typeof self !== 'undefined'
? self
: {};
const symbolPrefix = _global['__Zone_symbol_prefix'] || '__zone_symbol__';
function __symbol__(name: string) {
return symbolPrefix + name;
}
_global[__symbol__('legacyPatch')] = function () {
const Zone = _global['Zone'];
Zone.__load_patch('defineProperty', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
api._redefineProperty = _redefineProperty;
propertyPatch();
});
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);
});
};
}
| {
"end_byte": 1528,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/browser-legacy.ts"
} |
angular/packages/zone.js/lib/browser/rollup-main.ts_0_389 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {loadZone} from '../zone';
import {patchBrowser} from './browser';
import {patchCommon} from './rollup-common';
const Zone = loadZone();
patchCommon(Zone);
patchBrowser(Zone);
| {
"end_byte": 389,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-main.ts"
} |
angular/packages/zone.js/lib/browser/webapis-resize-observer.ts_0_3515 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchResizeObserver(Zone: ZoneType): void {
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);
},
);
});
}
| {
"end_byte": 3515,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/webapis-resize-observer.ts"
} |
angular/packages/zone.js/lib/browser/message-port.ts_0_783 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchMessagePort(Zone: ZoneType): void {
/**
* Monkey patch `MessagePort.prototype.onmessage` and `MessagePort.prototype.onmessageerror`
* properties to make the callback in the zone when the value are set.
*/
Zone.__load_patch('MessagePort', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
const MessagePort = global['MessagePort'];
if (typeof MessagePort !== 'undefined' && MessagePort.prototype) {
api.patchOnProperties(MessagePort.prototype, ['message', 'messageerror']);
}
});
}
| {
"end_byte": 783,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/message-port.ts"
} |
angular/packages/zone.js/lib/browser/browser-util.ts_0_2440 | /**
* @license
* Copyright Google LLC 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.dev/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;
// Note: the `patchCallbacks` is used for patching the `document.registerElement` and
// `customElements.define`. We explicitly wrap the patching code into try-catch since
// callbacks may be already patched by other web components frameworks (e.g. LWC), and they
// make those properties non-writable. This means that patching callback will throw an error
// `cannot assign to read-only property`. See this code as an example:
// https://github.com/salesforce/lwc/blob/master/packages/@lwc/engine-core/src/framework/base-bridge-element.ts#L180-L186
// We don't want to stop the application rendering if we couldn't patch some
// callback, e.g. `attributeChangedCallback`.
try {
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);
}
} catch {
// Note: we leave the catch block empty since there's no way to handle the error related
// to non-writable property.
}
});
}
return nativeDelegate.call(target, name, opts, options);
};
api.attachOriginToPatched(target[method], nativeDelegate);
}
| {
"end_byte": 2440,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/browser-util.ts"
} |
angular/packages/zone.js/lib/browser/rollup-message-port.ts_0_278 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchMessagePort} from './message-port';
patchMessagePort(Zone);
| {
"end_byte": 278,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-message-port.ts"
} |
angular/packages/zone.js/lib/browser/rollup-webapis-rtc-peer-connection.ts_0_305 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchRtcPeerConnection} from './webapis-rtc-peer-connection';
patchRtcPeerConnection(Zone);
| {
"end_byte": 305,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-webapis-rtc-peer-connection.ts"
} |
angular/packages/zone.js/lib/browser/custom-elements.ts_0_904 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
export function patchCustomElements(_global: any, api: _ZonePrivate) {
const {isBrowser, isMix} = api.getGlobalObjects()!;
if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
return;
}
// https://html.spec.whatwg.org/multipage/custom-elements.html#concept-custom-element-definition-lifecycle-callbacks
const callbacks = [
'connectedCallback',
'disconnectedCallback',
'adoptedCallback',
'attributeChangedCallback',
'formAssociatedCallback',
'formDisabledCallback',
'formResetCallback',
'formStateRestoreCallback',
];
api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
}
| {
"end_byte": 904,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/custom-elements.ts"
} |
angular/packages/zone.js/lib/browser/rollup-webapis-media-query.ts_0_283 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchMediaQuery} from './webapis-media-query';
patchMediaQuery(Zone);
| {
"end_byte": 283,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/browser/rollup-webapis-media-query.ts"
} |
angular/packages/zone.js/lib/common/timers.ts_0_5655 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
import {
isFunction,
isNumber,
patchMethod,
scheduleMacroTaskWithCurrentZone,
zoneSymbol,
} from './utils';
export 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;
data.args[0] = function () {
return task.invoke.apply(this, arguments);
};
const handleOrId = setNative!.apply(window, data.args);
// Whlist on Node.js when get can the ID by using `[Symbol.toPrimitive]()` we do
// to this so that we do not cause potentally leaks when using `setTimeout`
// since this can be periodic when using `.refresh`.
if (isNumber(handleOrId)) {
data.handleId = handleOrId;
} else {
data.handle = handleOrId;
// On Node.js a timeout and interval can be restarted over and over again by using the `.refresh` method.
data.isRefreshable = isFunction(handleOrId.refresh);
}
return task;
}
function clearTask(task: Task) {
const {handle, handleId} = task.data!;
return clearNative!.call(window, handle ?? handleId);
}
setNative = patchMethod(
window,
setName,
(delegate: Function) =>
function (self: any, args: any[]) {
if (isFunction(args[0])) {
const options: TimerOptions = {
isRefreshable: false,
isPeriodic: nameSuffix === 'Interval',
delay: nameSuffix === 'Timeout' || nameSuffix === 'Interval' ? args[1] || 0 : undefined,
args: args,
};
const callback = args[0];
args[0] = function timer(this: unknown) {
try {
return callback.apply(this, arguments);
} finally {
// issue-934, task will be cancelled
// even it is a periodic task such as
// setInterval
// https://github.com/angular/angular/issues/40387
// Cleanup tasksByHandleId should be handled before scheduleTask
// Since some zoneSpec may intercept and doesn't trigger
// scheduleFn(scheduleTask) provided here.
const {handle, handleId, isPeriodic, isRefreshable} = options;
if (!isPeriodic && !isRefreshable) {
if (handleId) {
// in non-nodejs env, we remove timerId
// from local cache
delete tasksByHandleId[handleId];
} else if (handle) {
// Node returns complex objects as handleIds
// we remove task reference from timer object
handle[taskSymbol] = null;
}
}
}
};
const task = scheduleMacroTaskWithCurrentZone(
setName,
args[0],
options,
scheduleTask,
clearTask,
);
if (!task) {
return task;
}
// Node.js must additionally support the ref and unref functions.
const {handleId, handle, isRefreshable, isPeriodic} = <TimerOptions>task.data;
if (handleId) {
// for non nodejs env, we save handleId: task
// mapping in local cache for clearTimeout
tasksByHandleId[handleId] = task;
} else if (handle) {
// for nodejs env, we save task
// reference in timerId Object for clearTimeout
handle[taskSymbol] = task;
if (isRefreshable && !isPeriodic) {
const originalRefresh = handle.refresh;
handle.refresh = function () {
const {zone, state} = task as any;
if (state === 'notScheduled') {
(task as any)._state = 'scheduled';
zone._updateTaskCount(task, 1);
} else if (state === 'running') {
(task as any)._state = 'scheduling';
}
return originalRefresh.call(this);
};
}
}
return handle ?? handleId ?? 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 (isNumber(id)) {
// non nodejs env.
task = tasksByHandleId[id];
delete tasksByHandleId[id];
} else {
// nodejs env ?? other environments.
task = id?.[taskSymbol];
if (task) {
id[taskSymbol] = null;
} else {
task = id;
}
}
if (task?.type) {
if (task.cancelFn) {
// Do not cancel already canceled functions
task.zone.cancelTask(task);
}
} else {
// cause an error by calling it directly.
delegate.apply(window, args);
}
},
);
}
| {
"end_byte": 5655,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/timers.ts"
} |
angular/packages/zone.js/lib/common/queue-microtask.ts_0_516 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
export function patchQueueMicrotask(global: any, api: _ZonePrivate) {
api.patchMethod(global, 'queueMicrotask', (delegate) => {
return function (self: any, args: any[]) {
Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
};
});
}
| {
"end_byte": 516,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/queue-microtask.ts"
} |
angular/packages/zone.js/lib/common/to-string.ts_0_2262 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
import {zoneSymbol} from './utils';
export function patchToString(Zone: ZoneType): void {
// 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(this: unknown) {
if (typeof this === 'function') {
const originalDelegate = (this as any)[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 (typeof Promise === 'function' && this instanceof Promise) {
return PROMISE_OBJECT_TO_STRING;
}
return originalObjectToString.call(this);
};
});
}
| {
"end_byte": 2262,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/to-string.ts"
} |
angular/packages/zone.js/lib/common/utils.ts_0_7036 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* Suppress closure compiler errors about unknown 'Zone' variable
* @fileoverview
* @suppress {undefinedVars,globalThis,missingRequire}
*/
/// <reference types="node"/>
import {__symbol__} from '../zone-impl';
// 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 = __symbol__(ADD_EVENT_LISTENER_STR);
/** zoneSymbol removeEventListener */
export const ZONE_SYMBOL_REMOVE_EVENT_LISTENER = __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 = __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 = __symbol__;
const isWindowExists = typeof window !== 'undefined';
const internalWindow: any = isWindowExists ? window : undefined;
const _global: any = (isWindowExists && internalWindow) || globalThis;
const REMOVE_ATTRIBUTE = 'removeAttribute';
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 (this: unknown) {
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' &&
_global.process.toString() === '[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' &&
_global.process.toString() === '[object process]' &&
!isWebWorker &&
!!(isWindowExists && internalWindow['HTMLElement']);
const zoneSymbolEventNames: {[eventName: string]: string} = {};
const enableBeforeunloadSymbol = zoneSymbol('enable_beforeunload');
const wrapFn = function (this: unknown, 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 signature
// 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 (
// https://github.com/angular/angular/issues/47579
// https://www.w3.org/TR/2011/WD-html5-20110525/history.html#beforeunloadevent
// This is the only specific case we should check for. The spec defines that the
// `returnValue` attribute represents the message to show the user. When the event
// is created, this attribute must be set to the empty string.
event.type === 'beforeunload' &&
// To prevent any breaking changes resulting from this change, given that
// it was already causing a significant number of failures in G3, we have hidden
// that behavior behind a global configuration flag. Consumers can enable this
// flag explicitly if they want the `beforeunload` event to be handled as defined
// in the specification.
_global[enableBeforeunloadSymbol] &&
// The IDL event definition is `attribute DOMString returnValue`, so we check whether
// `typeof result` is a string.
typeof result === 'string'
) {
(event as BeforeUnloadEvent).returnValue = result;
} else if (result != undefined && !result) {
event.preventDefault();
}
}
return result;
}; | {
"end_byte": 7036,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/utils.ts"
} |
angular/packages/zone.js/lib/common/utils.ts_7038_14321 | 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;
// slice(2) cuz 'onclick' -> 'click', etc
const eventName = prop.slice(2);
let eventNameSymbol = zoneSymbolEventNames[eventName];
if (!eventNameSymbol) {
eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
}
desc.set = function (this: EventSource, 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;
}
const previousValue = (target as any)[eventNameSymbol];
if (typeof previousValue === 'function') {
target.removeEventListener(eventName, wrapFn);
}
// issue #978, when onload handler was added before loading zone.js
// we should remove it with originalDescSet
originalDescSet && originalDescSet.call(target, null);
(target as any)[eventNameSymbol] = newValue;
if (typeof newValue === 'function') {
target.addEventListener(eventName, wrapFn, false);
}
};
// 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: any = this;
if (!target && obj === _global) {
target = _global;
}
if (!target) {
return null;
}
const listener = (target as any)[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.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.slice(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;
} | {
"end_byte": 14321,
"start_byte": 7038,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/utils.ts"
} |
angular/packages/zone.js/lib/common/utils.ts_14323_18640 | 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]) || !proto.hasOwnProperty(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;
}
export function isFunction(value: unknown): value is Function {
return typeof value === 'function';
}
export function isNumber(value: unknown): value is number {
return typeof value === 'number';
} | {
"end_byte": 18640,
"start_byte": 14323,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/utils.ts"
} |
angular/packages/zone.js/lib/common/rollup-fetch.ts_0_259 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchFetch} from './fetch';
patchFetch(Zone);
| {
"end_byte": 259,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/rollup-fetch.ts"
} |
angular/packages/zone.js/lib/common/rollup-error-rewrite.ts_0_267 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchError} from './error-rewrite';
patchError(Zone);
| {
"end_byte": 267,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/rollup-error-rewrite.ts"
} |
angular/packages/zone.js/lib/common/events.ts_0_5030 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
import {
ADD_EVENT_LISTENER_STR,
attachOriginToPatched,
FALSE_STR,
isNode,
ObjectGetPrototypeOf,
REMOVE_EVENT_LISTENER_STR,
TRUE_STR,
ZONE_SYMBOL_PREFIX,
zoneSymbol,
} from './utils';
/** @internal **/
interface EventTaskData extends TaskData {
// use global callback or not
readonly useG?: boolean;
taskData?: any;
}
/** @internal **/
interface InternalGlobalTaskData {
// This is used internally to avoid duplicating event listeners on
// the same target when the event name is the same, such as when
// `addEventListener` is called multiple times on the `document`
// for the `keydown` event.
isExisting?: boolean;
// `target` is the actual event target on which `addEventListener`
// is being called.
target?: any;
eventName?: string;
capture?: boolean;
// Not changing the type to avoid any regressions.
options?: any; // boolean | AddEventListenerOptions
}
/**
* The `scheduleEventTask` function returns an `EventTask` object.
* However, we also store some task-related information on the task
* itself, such as the task target, for easy access when the task is
* manually canceled or for other purposes. This internal storage is
* used solely for enhancing our understanding of which properties are
* being assigned to the task.
*
* @internal
*/
interface InternalEventTask extends EventTask {
removeAbortListener?: VoidFunction | null;
// `target` is the actual event target on which `addEventListener`
// is being called for this specific task.
target?: any;
eventName?: string;
capture?: boolean;
// Not changing the type to avoid any regressions.
options?: any; // boolean | AddEventListenerOptions
// `isRemoved` is associated with a specific task and indicates whether
// that task was canceled and removed from the event target to prevent
// its invocation if dispatched later.
isRemoved?: boolean;
allRemoved?: boolean;
}
// Note that passive event listeners are now supported by most modern browsers,
// including Chrome, Firefox, Safari, and Edge. There's a pending change that
// would remove support for legacy browsers by zone.js. Removing `passiveSupported`
// from the codebase will reduce the final code size for existing apps that still use zone.js.
let passiveSupported = false;
if (typeof window !== 'undefined') {
try {
const options = Object.defineProperty({}, 'passive', {
get: function () {
passiveSupported = true;
},
});
// Note: We pass the `options` object as the event handler too. This is not compatible with the
// signature of `addEventListener` or `removeEventListener` but enables us to remove the handler
// without an actual handler.
window.addEventListener('test', options as any, options);
window.removeEventListener('test', options as any, 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');
function prepareEventNames(eventName: string, eventNameToString?: (eventName: string) => string) {
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;
}
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;
// transfer eventName
transferEventName?: (eventName: string) => string;
} | {
"end_byte": 5030,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/events.ts"
} |
angular/packages/zone.js/lib/common/events.ts_5032_9419 | export function patchEventTarget(
_global: any,
api: _ZonePrivate,
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): Error | undefined {
// 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
// need to try/catch error here, otherwise, the error in one event listener
// will break the executions of the other event listeners. Also error will
// not remove the event listener when `once` options is true.
let error;
try {
task.invoke(task, target, [event]);
} catch (err: any) {
error = err;
}
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);
}
return error;
};
function globalCallback(context: unknown, event: Event, isCapture: boolean) {
// 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 = context || event.target || _global;
const tasks = target[zoneSymbolEventNames[event.type][isCapture ? TRUE_STR : FALSE_STR]];
if (tasks) {
const errors = [];
// 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) {
const err = invokeTask(tasks[0], target, event);
err && errors.push(err);
} 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;
}
const err = invokeTask(copyTasks[i], target, event);
err && errors.push(err);
}
}
// Since there is only one error, we don't need to schedule microTask
// to throw the error.
if (errors.length === 1) {
throw errors[0];
} else {
for (let i = 0; i < errors.length; i++) {
const err = errors[i];
api.nativeScheduleMicroTask(() => {
throw err;
});
}
}
}
}
// global shared zoneAwareCallback to handle all event callback with capture = false
const globalZoneAwareCallback = function (this: unknown, event: Event) {
return globalCallback(this, event, false);
};
// global shared zoneAwareCallback to handle all event callback with capture = true
const globalZoneAwareCaptureCallback = function (this: unknown, event: Event) {
return globalCallback(this, event, true);
}; | {
"end_byte": 9419,
"start_byte": 5032,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/events.ts"
} |
angular/packages/zone.js/lib/common/events.ts_9423_17936 | 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;
// We use a shared global `taskData` to pass data for `scheduleEventTask`,
// eliminating the need to create a new object solely for passing data.
// WARNING: This object has a static lifetime, meaning it is not created
// each time `addEventListener` is called. It is instantiated only once
// and captured by reference inside the `addEventListener` and
// `removeEventListener` functions. Do not add any new properties to this
// object, as doing so would necessitate maintaining the information
// between `addEventListener` calls.
const taskData: InternalGlobalTaskData = {};
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];
}
/**
* This util function will build an option object with passive option
* to handle all possible input from the user.
*/
function buildEventListenerOptions(options: any, passive: boolean) {
if (!passiveSupported && typeof options === 'object' && options) {
// doesn't support passive but user want to pass an object as options.
// this will not work on some old browser, so we just pass a boolean
// as useCapture parameter
return !!options.capture;
}
if (!passiveSupported || !passive) {
return options;
}
if (typeof options === 'boolean') {
return {capture: options, passive: true};
}
if (!options) {
return {passive: true};
}
if (typeof options === 'object' && options.passive !== false) {
return {...options, passive: true};
}
return 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;
}
return nativeAddEventListener.call(
taskData.target,
taskData.eventName,
taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback,
taskData.options,
);
};
/**
* In the context of events and listeners, this function will be
* called at the end by `cancelTask`, which, in turn, calls `task.cancelFn`.
* Cancelling a task is primarily used to remove event listeners from
* the task target.
*/
const customCancelGlobal = function (task: InternalEventTask) {
// 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 (task.removeAbortListener) {
task.removeAbortListener();
task.removeAbortListener = null;
}
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) {
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 unpatchedEvents: string[] = (Zone as any)[zoneSymbol('UNPATCHED_EVENTS')];
const passiveEvents: string[] = _global[zoneSymbol('PASSIVE_EVENTS')];
function copyEventListenerOptions(options: any) {
if (typeof options === 'object' && options !== null) {
// We need to destructure the target `options` object since it may
// be frozen or sealed (possibly provided implicitly by a third-party
// library), or its properties may be readonly.
const newOptions: any = {...options};
// The `signal` option was recently introduced, which caused regressions in
// third-party scenarios where `AbortController` was directly provided to
// `addEventListener` as options. For instance, in cases like
// `document.addEventListener('keydown', callback, abortControllerInstance)`,
// which is valid because `AbortController` includes a `signal` getter, spreading
// `{...options}` wouldn't copy the `signal`. Additionally, using `Object.create`
// isn't feasible since `AbortController` is a built-in object type, and attempting
// to create a new object directly with it as the prototype might result in
// unexpected behavior.
if (options.signal) {
newOptions.signal = options.signal;
}
return newOptions;
}
return options;
} | {
"end_byte": 17936,
"start_byte": 9423,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/events.ts"
} |
angular/packages/zone.js/lib/common/events.ts_17942_26215 | const makeAddListener = function (
nativeListener: any,
addSource: string,
customScheduleFn: any,
customCancelFn: any,
returnTarget = false,
prepend = false,
) {
return function (this: unknown) {
const target = this || _global;
let eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
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 passive =
passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
const options = copyEventListenerOptions(buildEventListenerOptions(arguments[2], passive));
const signal: AbortSignal | undefined = options?.signal;
if (signal?.aborted) {
// the signal is an aborted one, just return without attaching the event listener.
return;
}
if (unpatchedEvents) {
// check unpatched list
for (let i = 0; i < unpatchedEvents.length; i++) {
if (eventName === unpatchedEvents[i]) {
if (passive) {
return nativeListener.call(target, eventName, delegate, options);
} else {
return nativeListener.apply(this, arguments);
}
}
}
}
const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
const once = options && typeof options === 'object' ? options.once : false;
const zone = Zone.current;
let symbolEventNames = zoneSymbolEventNames[eventName];
if (!symbolEventNames) {
prepareEventNames(eventName, eventNameToString);
symbolEventNames = zoneSymbolEventNames[eventName];
}
const 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);
}
// In the code below, `options` should no longer be reassigned; instead, it
// should only be mutated. This is because we pass that object to the native
// `addEventListener`.
// It's generally recommended to use the same object reference for options.
// This ensures consistency and avoids potential issues.
taskData.options = options;
if (once) {
// When using `addEventListener` with the `once` option, we don't pass
// the `once` option directly to the native `addEventListener` method.
// Instead, we keep the `once` setting and handle it 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.taskData = taskData;
}
if (signal) {
// When using `addEventListener` with the `signal` option, we don't pass
// the `signal` option directly to the native `addEventListener` method.
// Instead, we keep the `signal` setting and handle it ourselves.
taskData.options.signal = undefined;
}
// The `scheduleEventTask` function will ultimately call `customScheduleGlobal`,
// which in turn calls the native `addEventListener`. This is why `taskData.options`
// is updated before scheduling the task, as `customScheduleGlobal` uses
// `taskData.options` to pass it to the native `addEventListener`.
const task: InternalEventTask = zone.scheduleEventTask(
source,
delegate,
data,
customScheduleFn,
customCancelFn,
);
if (signal) {
// after task is scheduled, we need to store the signal back to task.options
taskData.options.signal = signal;
// Wrapping `task` in a weak reference would not prevent memory leaks. Weak references are
// primarily used for preventing strong references cycles. `onAbort` is always reachable
// as it's an event listener, so its closure retains a strong reference to the `task`.
const onAbort = () => task.zone.cancelTask(task);
nativeListener.call(signal, 'abort', onAbort, {once: true});
// We need to remove the `abort` listener when the event listener is going to be removed,
// as it creates a closure that captures `task`. This closure retains a reference to the
// `task` object even after it goes out of scope, preventing `task` from being garbage
// collected.
task.removeAbortListener = () => signal.removeEventListener('abort', onAbort);
}
// 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.taskData = null;
}
// have to save those information to task in case
// application may call task.zone.cancelTask() directly
if (once) {
taskData.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,
);
} | {
"end_byte": 26215,
"start_byte": 17942,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/events.ts"
} |
angular/packages/zone.js/lib/common/events.ts_26221_35011 | proto[REMOVE_EVENT_LISTENER] = function () {
const target = this || _global;
let eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
const options = arguments[2];
const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
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: InternalEventTask[] = symbolEventName && target[symbolEventName];
// `existingTasks` may not exist if the `addEventListener` was called before
// it was patched by zone.js. Please refer to the attached issue for
// clarification, particularly after the `if` condition, before calling
// the native `removeEventListener`.
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.isRemoved = true;
if (existingTasks.length === 0) {
// all tasks for the eventName + capture have gone,
// remove globalZoneAwareCallback and remove the task cache from target
existingTask.allRemoved = true;
target[symbolEventName] = null;
// in the target, we have an event listener which is added by on_property
// such as target.onclick = function() {}, so we need to clear this internal
// property too if all delegates with capture=false were removed
// https:// github.com/angular/angular/issues/31643
// https://github.com/angular/angular/issues/54581
if (!capture && typeof eventName === 'string') {
const onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
target[onPropertySymbol] = null;
}
}
// In all other conditions, when `addEventListener` is called after being
// patched by zone.js, we would always find an event task on the `EventTarget`.
// This will trigger `cancelFn` on the `existingTask`, leading to `customCancelGlobal`,
// which ultimately removes an event listener and cleans up the abort listener
// (if an `AbortSignal` was provided when scheduling a task).
existingTask.zone.cancelTask(existingTask);
if (returnTarget) {
return target;
}
return;
}
}
}
// https://github.com/angular/zone.js/issues/930
// We may encounter a situation where the `addEventListener` was
// called on the event target before zone.js is loaded, resulting
// in no task being stored on the event target due to its invocation
// of the native implementation. In this scenario, we simply need to
// invoke the native `removeEventListener`.
return nativeRemoveEventListener.apply(this, arguments);
};
proto[LISTENERS_EVENT_LISTENER] = function () {
const target = this || _global;
let eventName = arguments[0];
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
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;
let 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 {
if (patchOptions && patchOptions.transferEventName) {
eventName = patchOptions.transferEventName(eventName);
}
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[] {
if (!eventName) {
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;
}
let symbolEventName = zoneSymbolEventNames[eventName];
if (!symbolEventName) {
prepareEventNames(eventName);
symbolEventName = zoneSymbolEventNames[eventName];
}
const captureFalseTasks = target[symbolEventName[FALSE_STR]];
const captureTrueTasks = target[symbolEventName[TRUE_STR]];
if (!captureFalseTasks) {
return captureTrueTasks ? captureTrueTasks.slice() : [];
} else {
return captureTrueTasks
? captureFalseTasks.concat(captureTrueTasks)
: captureFalseTasks.slice();
}
}
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);
},
);
}
} | {
"end_byte": 35011,
"start_byte": 26221,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/events.ts"
} |
angular/packages/zone.js/lib/common/error-rewrite.ts_0_440 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {globalThis,undefinedVars}
*/
import {ZoneType} from '../zone-impl';
export function patchError(Zone: ZoneType): void {
Zone.__load_patch('Error', (global: any, Zone: ZoneType, api: _ZonePrivate) => | {
"end_byte": 440,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/error-rewrite.ts"
} |
angular/packages/zone.js/lib/common/error-rewrite.ts_441_9704 | {
/*
* 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
zoneJsInternal,
/// This frame marks zone transition
transition,
}
const zoneJsInternalStackFramesSymbol = api.symbol('zoneJsInternalStackFrames');
const NativeError = (global[api.symbol('Error')] = global['Error']);
// Store the frames which should be removed from the stack frames
const zoneJsInternalStackFrames: {[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 ZoneJsInternalStackFramesPolicy = 'default' | 'disable' | 'lazy';
const zoneJsInternalStackFramesPolicy: ZoneJsInternalStackFramesPolicy =
global['__Zone_Error_BlacklistedStackFrames_policy'] ||
global['__Zone_Error_ZoneJsInternalStackFrames_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 (zoneJsInternalStackFrames[frame]) {
case FrameType.zoneJsInternal:
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(this: unknown | typeof NativeError): 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 (zoneJsInternalStackFramesPolicy === 'lazy') {
// don't handle stack trace now
(error as any)[api.symbol('zoneFrameNames')] = buildZoneFrameNames(zoneFrame);
} else if (zoneJsInternalStackFramesPolicy === '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)[zoneJsInternalStackFramesSymbol] = zoneJsInternalStackFrames;
(ZoneAwareError as any)[stackRewrite] = false;
const zoneAwareStackSymbol = api.symbol('zoneAwareStack');
// try to define zoneAwareStack property when zoneJsInternal frames policy is delay
if (zoneJsInternalStackFramesPolicy === '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);
});
},
}); | {
"end_byte": 9704,
"start_byte": 441,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/error-rewrite.ts"
} |
angular/packages/zone.js/lib/common/error-rewrite.ts_9710_16106 | if (zoneJsInternalStackFramesPolicy === 'disable') {
// don't need to run detectZone to populate zoneJs internal stack frames
return;
}
// Now we need to populate the `zoneJsInternalStackFrames` 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',
);
}
}
zoneJsInternalStackFrames[zoneAwareFrame2] = FrameType.zoneJsInternal;
}
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.zoneJsInternal;
}
zoneJsInternalStackFrames[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 marked as an internal zoneJs frame.
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.
// We cast through any so we don't need to depend on nodejs typings.
const originalStackTraceLimit = (Error as any).stackTraceLimit;
(Error as any).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(
zoneJsInternalStackFramesSymbol,
() => {
childDetectZone.scheduleMacroTask(
zoneJsInternalStackFramesSymbol,
() => {
childDetectZone.scheduleMicroTask(
zoneJsInternalStackFramesSymbol,
() => {
throw new Error();
},
undefined,
(t: Task) => {
(t as any)._transitionTo = fakeTransitionTo;
t.invoke();
},
);
childDetectZone.scheduleMicroTask(
zoneJsInternalStackFramesSymbol,
() => {
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 as any).stackTraceLimit = originalStackTraceLimit;
});
} | {
"end_byte": 16106,
"start_byte": 9710,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/error-rewrite.ts"
} |
angular/packages/zone.js/lib/common/promise.ts_0_9037 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
import {patchMethod} from './utils';
export function patchPromise(Zone: ZoneType): void {
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 isDisableWrappingUncaughtPromiseRejection =
global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] !== false;
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) {
const uncaughtPromiseError: UncaughtPromiseError = _uncaughtPromiseErrors.shift()!;
try {
uncaughtPromiseError.zone.runGuarded(() => {
if (uncaughtPromiseError.throwOriginal) {
throw uncaughtPromiseError.rejection;
}
throw uncaughtPromiseError;
});
} catch (error) {
handleUnhandledRejection(error);
}
}
};
const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__(
'unhandledPromiseRejectionHandler',
);
function handleUnhandledRejection(this: unknown, e: any) {
api.onUnhandledError(e);
try {
const handler = (Zone as any)[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
if (typeof handler === 'function') {
handler.call(this, e);
}
} catch (err) {}
}
function isThenable(value: any): boolean {
return value && typeof value.then === 'function';
}
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: any) => {
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(value);
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;
let uncaughtPromiseError = value;
try {
// Here we throws a new Error to print more readable error log
// and if the value is not an error, zone.js builds an `Error`
// Object here to attach the stack information.
throw new Error(
'Uncaught (in promise): ' +
readableObjectToString(value) +
(value && value.stack ? '\n' + value.stack : ''),
);
} catch (err) {
uncaughtPromiseError = err;
}
if (isDisableWrappingUncaughtPromiseRejection) {
// If disable wrapping uncaught promise reject
// use the value instead of wrapping it.
uncaughtPromiseError.throwOriginal = true;
}
uncaughtPromiseError.rejection = value;
uncaughtPromiseError.promise = promise;
uncaughtPromiseError.zone = Zone.current;
uncaughtPromiseError.task = Zone.currentTask!;
_uncaughtPromiseErrors.push(uncaughtPromiseError);
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'); | {
"end_byte": 9037,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/promise.ts"
} |
angular/packages/zone.js/lib/common/promise.ts_9042_11971 | function clearRejectedNoCatch(this: unknown, 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: Zone,
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] }';
const noop = function () {};
const AggregateError = global.AggregateError; | {
"end_byte": 11971,
"start_byte": 9042,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/promise.ts"
} |
angular/packages/zone.js/lib/common/promise.ts_11977_20992 | class ZoneAwarePromise<R> implements Promise<R> {
static toString() {
return ZONE_AWARE_PROMISE_TO_STRING;
}
static resolve<R>(value: R): Promise<R> {
if (value instanceof ZoneAwarePromise) {
return value;
}
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 withResolvers<T>(): {
promise: Promise<T>;
resolve: (value?: T | PromiseLike<T>) => void;
reject: (error?: any) => void;
} {
const result: any = {};
result.promise = new ZoneAwarePromise((res, rej) => {
result.resolve = res;
result.reject = rej;
});
return result;
}
static any<T>(values: Iterable<PromiseLike<T>>): Promise<T> {
if (!values || typeof values[Symbol.iterator] !== 'function') {
return Promise.reject(new AggregateError([], 'All promises were rejected'));
}
const promises: Promise<PromiseLike<T>>[] = [];
let count = 0;
try {
for (let v of values) {
count++;
promises.push(ZoneAwarePromise.resolve(v));
}
} catch (err) {
return Promise.reject(new AggregateError([], 'All promises were rejected'));
}
if (count === 0) {
return Promise.reject(new AggregateError([], 'All promises were rejected'));
}
let finished = false;
const errors: any[] = [];
return new ZoneAwarePromise((resolve, reject) => {
for (let i = 0; i < promises.length; i++) {
promises[i].then(
(v) => {
if (finished) {
return;
}
finished = true;
resolve(v);
},
(err) => {
errors.push(err);
count--;
if (count === 0) {
finished = true;
reject(new AggregateError(errors, 'All promises were rejected'));
}
},
);
}
});
}
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> {
return ZoneAwarePromise.allWithCallback(values);
}
static allSettled<R>(values: any): Promise<R> {
const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
return P.allWithCallback(values, {
thenCallback: (value: any) => ({status: 'fulfilled', value}),
errorCallback: (err: any) => ({status: 'rejected', reason: err}),
});
}
static allWithCallback<R>(
values: any,
callback?: {
thenCallback: (value: any) => any;
errorCallback: (err: any) => 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;
try {
value.then(
(value: any) => {
resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
unresolvedCount--;
if (unresolvedCount === 0) {
resolve!(resolvedValues);
}
},
(err: any) => {
if (!callback) {
reject!(err);
} else {
resolvedValues[curValueIndex] = callback.errorCallback(err);
unresolvedCount--;
if (unresolvedCount === 0) {
resolve!(resolvedValues);
}
}
},
);
} catch (thenErr) {
reject!(thenErr);
}
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 {
const onceWrapper = once();
executor &&
executor(
onceWrapper(makeResolver(promise, RESOLVED)),
onceWrapper(makeResolver(promise, REJECTED)),
);
} catch (error) {
resolvePromise(promise, false, error);
}
}
get [Symbol.toStringTag]() {
return 'Promise' as any;
}
get [Symbol.species]() {
return ZoneAwarePromise;
}
then<TResult1 = R, TResult2 = never>(
onFulfilled?: ((value: R) => TResult1 | PromiseLike<TResult1>) | undefined | null,
onRejected?: ((reason: any) => TResult2 | PromiseLike<TResult2>) | undefined | null,
): Promise<TResult1 | TResult2> {
// We must read `Symbol.species` safely because `this` may be anything. For instance, `this`
// may be an object without a prototype (created through `Object.create(null)`); thus
// `this.constructor` will be undefined. One of the use cases is SystemJS creating
// prototype-less objects (modules) via `Object.create(null)`. The SystemJS creates an empty
// object and copies promise properties into that object (within the `getOrCreateLoad`
// function). The zone.js then checks if the resolved value has the `then` method and
// invokes it with the `value` context. Otherwise, this will throw an error: `TypeError:
// Cannot read properties of undefined (reading 'Symbol(Symbol.species)')`.
let C = (this.constructor as any)?.[Symbol.species];
if (!C || typeof C !== 'function') {
C = this.constructor || ZoneAwarePromise;
}
const chainPromise: Promise<TResult1 | TResult2> = new (C as typeof ZoneAwarePromise)(noop);
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> {
// See comment on the call to `then` about why thee `Symbol.species` is safely accessed.
let C = (this.constructor as any)?.[Symbol.species];
if (!C || typeof C !== 'function') {
C = ZoneAwarePromise;
}
const chainPromise: Promise<R | never> = new (C as typeof ZoneAwarePromise)(noop);
(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; | {
"end_byte": 20992,
"start_byte": 11977,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/promise.ts"
} |
angular/packages/zone.js/lib/common/promise.ts_20997_22881 | ZoneAwarePromise['race'] = ZoneAwarePromise.race;
ZoneAwarePromise['all'] = ZoneAwarePromise.all;
const NativePromise = (global[symbolPromise] = global['Promise']);
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 (self: any, args: any[]) {
let resultPromise = fn.apply(self, args);
if (resultPromise instanceof ZoneAwarePromise) {
return resultPromise;
}
let ctor = resultPromise.constructor;
if (!ctor[symbolThenPatched]) {
patchThen(ctor);
}
return resultPromise;
};
}
if (NativePromise) {
patchThen(NativePromise);
patchMethod(global, 'fetch', (delegate) => zoneify(delegate));
}
// 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;
});
} | {
"end_byte": 22881,
"start_byte": 20997,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/promise.ts"
} |
angular/packages/zone.js/lib/common/fetch.ts_0_4647 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
import {ZoneType} from '../zone-impl';
export function patchFetch(Zone: ZoneType): void {
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 OriginalResponse = global.Response;
const placeholder = function () {};
const createFetchTask = (
source: string,
data: TaskData | undefined,
originalImpl: any,
self: any,
args: any[],
ac?: AbortController,
) =>
new Promise((resolve, reject) => {
const task = Zone.current.scheduleMacroTask(
source,
placeholder,
data,
() => {
// The promise object returned by the original implementation passed into the
// function. This might be a `fetch` promise, `Response.prototype.json` promise,
// etc.
let implPromise;
let zone = Zone.current;
try {
(zone as any)[fetchTaskScheduling] = true;
implPromise = originalImpl.apply(self, args);
} catch (error) {
reject(error);
return;
} finally {
(zone as any)[fetchTaskScheduling] = false;
}
if (!(implPromise instanceof ZoneAwarePromise)) {
let ctor = implPromise.constructor;
if (!ctor[symbolThenPatched]) {
api.patchThen(ctor);
}
}
implPromise.then(
(resource: any) => {
if (task.state !== 'notScheduled') {
task.invoke();
}
resolve(resource);
},
(error: any) => {
if (task.state !== 'notScheduled') {
task.invoke();
}
reject(error);
},
);
},
() => {
ac?.abort();
},
);
});
global['fetch'] = function () {
const args = Array.prototype.slice.call(arguments);
const options = args.length > 1 ? args[1] : {};
const signal: AbortSignal | undefined = options?.signal;
const ac = new AbortController();
const fetchSignal = ac.signal;
options.signal = fetchSignal;
args[1] = options;
let onAbort: () => void;
if (signal) {
const nativeAddEventListener =
signal[Zone.__symbol__('addEventListener') as 'addEventListener'] ||
signal.addEventListener;
onAbort = () => ac!.abort();
nativeAddEventListener.call(signal, 'abort', onAbort, {once: true});
}
return createFetchTask(
'fetch',
{fetchArgs: args} as FetchTaskData,
fetch,
this,
args,
ac,
).finally(() => {
// We need to be good citizens and remove the `abort` listener once
// the fetch is settled. The `abort` listener may not be called at all,
// which means the event listener closure would retain a reference to
// the `ac` object even if it goes out of scope. Since browser's garbage
// collectors work differently, some may not be smart enough to collect a signal.
signal?.removeEventListener('abort', onAbort);
});
};
if (OriginalResponse?.prototype) {
// https://fetch.spec.whatwg.org/#body-mixin
['arrayBuffer', 'blob', 'formData', 'json', 'text']
// Safely check whether the method exists on the `Response` prototype before patching.
.filter((method) => typeof OriginalResponse.prototype[method] === 'function')
.forEach((method) => {
api.patchMethod(
OriginalResponse.prototype,
method,
(delegate: Function) => (self, args) =>
createFetchTask(`Response.${method}`, undefined, delegate, self, args, undefined),
);
});
}
});
}
| {
"end_byte": 4647,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/common/fetch.ts"
} |
angular/packages/zone.js/lib/extra/socket-io.ts_0_1113 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchSocketIo(Zone: ZoneType): void {
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, api, [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;
};
});
}
| {
"end_byte": 1113,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/socket-io.ts"
} |
angular/packages/zone.js/lib/extra/rollup-jsonp.ts_0_259 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchJsonp} from './jsonp';
patchJsonp(Zone);
| {
"end_byte": 259,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/rollup-jsonp.ts"
} |
angular/packages/zone.js/lib/extra/bluebird.ts_0_3427 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchBluebird(Zone: ZoneType): void {
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);
},
);
});
if (typeof window !== 'undefined') {
window.addEventListener('unhandledrejection', function (event: any) {
const error = event.detail && event.detail.reason;
if (error && error.isHandledByZone) {
event.preventDefault();
if (typeof event.stopImmediatePropagation === 'function') {
event.stopImmediatePropagation();
}
}
});
} else if (typeof process !== 'undefined') {
process.on('unhandledRejection', (reason: any, p: any) => {
if (reason && reason.isHandledByZone) {
const listeners = process.listeners('unhandledRejection');
if (listeners) {
// remove unhandledRejection listeners so the callback
// will not be triggered.
process.removeAllListeners('unhandledRejection');
process.nextTick(() => {
listeners.forEach((listener) => process.on('unhandledRejection', listener));
});
}
}
});
}
Bluebird.onPossiblyUnhandledRejection(function (e: any, promise: any) {
try {
Zone.current.runGuarded(() => {
e.isHandledByZone = true;
throw e;
});
} catch (err: any) {
err.isHandledByZone = false;
api.onUnhandledError(err);
}
});
// override global promise
global.Promise = Bluebird;
};
});
}
| {
"end_byte": 3427,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/bluebird.ts"
} |
angular/packages/zone.js/lib/extra/electron.ts_0_1802 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchElectron(Zone: ZoneType): void {
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));
});
}
let {desktopCapturer, shell, CallbacksRegistry, ipcRenderer} = require('electron');
if (!CallbacksRegistry) {
try {
// Try to load CallbacksRegistry class from @electron/remote src
// since from electron 14+, the CallbacksRegistry is moved to @electron/remote
// package and not exported to outside, so this is a hack to patch CallbacksRegistry.
CallbacksRegistry =
require('@electron/remote/dist/src/renderer/callbacks-registry').CallbacksRegistry;
} catch (err) {}
}
// 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) {
if (ipcRenderer) {
patchArguments(ipcRenderer, 'on', 'ipcRenderer.on');
}
return;
}
patchArguments(CallbacksRegistry.prototype, 'add', 'CallbackRegistry.add');
});
}
| {
"end_byte": 1802,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/electron.ts"
} |
angular/packages/zone.js/lib/extra/rollup-socket-io.ts_0_269 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchSocketIo} from './socket-io';
patchSocketIo(Zone);
| {
"end_byte": 269,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/rollup-socket-io.ts"
} |
angular/packages/zone.js/lib/extra/jsonp.ts_0_3111 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchJsonp(Zone: ZoneType): void {
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 (this: unknown) {
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,
);
},
);
};
});
}
| {
"end_byte": 3111,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/jsonp.ts"
} |
angular/packages/zone.js/lib/extra/rollup-cordova.ts_0_265 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchCordova} from './cordova';
patchCordova(Zone);
| {
"end_byte": 265,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/rollup-cordova.ts"
} |
angular/packages/zone.js/lib/extra/cordova.ts_0_1778 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchCordova(Zone: ZoneType): void {
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];
},
});
});
});
}
});
}
| {
"end_byte": 1778,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/cordova.ts"
} |
angular/packages/zone.js/lib/extra/rollup-bluebird.ts_0_268 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchBluebird} from './bluebird';
patchBluebird(Zone);
| {
"end_byte": 268,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/rollup-bluebird.ts"
} |
angular/packages/zone.js/lib/extra/rollup-electron.ts_0_268 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchElectron} from './electron';
patchElectron(Zone);
| {
"end_byte": 268,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/extra/rollup-electron.ts"
} |
angular/packages/zone.js/lib/rxjs/rxjs-fake-async.ts_0_882 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {asapScheduler, asyncScheduler, Scheduler} from 'rxjs';
import {ZoneType} from '../zone-impl';
export function patchRxJsFakeAsync(Zone: ZoneType): void {
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);
});
});
}
| {
"end_byte": 882,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/rxjs/rxjs-fake-async.ts"
} |
angular/packages/zone.js/lib/rxjs/rxjs.ts_0_8261 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {Observable, Subscriber, Subscription} from 'rxjs';
import {ZoneType} from '../zone-impl';
type ZoneSubscriberContext = {
_zone: Zone;
} & Subscriber<any>;
export function patchRxJs(Zone: ZoneType): void {
(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;
if (!subscribe) {
(this as any)._zoneSubscribe = subscribe;
} else {
(this as any)._zoneSubscribe = function (this: ZoneSubscriberContext) {
if (this._zone && this._zone !== Zone.current) {
const tearDown = this._zone.run(subscribe, this, arguments as any);
if (typeof tearDown === 'function') {
const zone = this._zone;
return function (this: ZoneSubscriberContext) {
if (zone !== Zone.current) {
return zone.run(tearDown, this, arguments as any);
}
return tearDown.apply(this, arguments);
};
} else {
return tearDown;
}
} else {
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 || (this as any)._zoneUnsubscribeCleared) {
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;
if (!unsubscribe) {
(this as any)._zoneUnsubscribe = unsubscribe;
// In some operator such as `retryWhen`, the _unsubscribe
// method will be set to null, so we need to set another flag
// to tell that we should return null instead of finding
// in the prototype chain.
(this as any)._zoneUnsubscribeCleared = true;
} else {
(this as any)._zoneUnsubscribeCleared = false;
(this as any)._zoneUnsubscribe = function () {
if (this._zone && this._zone !== Zone.current) {
return this._zone.run(unsubscribe, this, arguments);
} else {
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 (this: ZoneSubscriberContext) {
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 as any, nextSource);
} else {
return next.apply(this, arguments as any);
}
};
Subscriber.prototype.error = function (this: ZoneSubscriberContext) {
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 as any, errorSource);
} else {
return error.apply(this, arguments as any);
}
};
Subscriber.prototype.complete = function (this: ZoneSubscriberContext) {
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 as any, completeSource);
} else {
return complete.call(this);
}
};
};
patchObservable();
patchSubscription();
patchSubscriber();
});
}
| {
"end_byte": 8261,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/rxjs/rxjs.ts"
} |
angular/packages/zone.js/lib/rxjs/rollup-rxjs.ts_0_256 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchRxJs} from './rxjs';
patchRxJs(Zone);
| {
"end_byte": 256,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/rxjs/rollup-rxjs.ts"
} |
angular/packages/zone.js/lib/node/rollup-test-main.ts_0_301 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import './rollup-main';
// load test related files into bundle
import '../testing/zone-testing';
| {
"end_byte": 301,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/node/rollup-test-main.ts"
} |
angular/packages/zone.js/lib/node/main.ts_0_592 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchPromise} from '../common/promise';
import {patchToString} from '../common/to-string';
import {loadZone} from '../zone';
import {ZoneType} from '../zone-impl';
import {patchNode} from './node';
export function rollupMain(): ZoneType {
const Zone = loadZone();
patchNode(Zone); // Node needs to come first.
patchPromise(Zone);
patchToString(Zone);
return Zone;
}
| {
"end_byte": 592,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/node/main.ts"
} |
angular/packages/zone.js/lib/node/node.ts_0_6030 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {findEventTasks} from '../common/events';
import {patchQueueMicrotask} from '../common/queue-microtask';
import {patchTimer} from '../common/timers';
import {ArraySlice, isMix, patchMacroTask, patchMicroTask} from '../common/utils';
import {ZoneType} from '../zone-impl';
import {patchEvents} from './events';
import {patchFs} from './fs';
import {patchNodeUtil} from './node_util';
const set = 'set';
const clear = 'clear';
export function patchNode(Zone: ZoneType): void {
patchNodeUtil(Zone);
patchEvents(Zone);
patchFs(Zone);
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);
}
};
}
});
});
Zone.__load_patch('queueMicrotask', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
patchQueueMicrotask(global, api);
});
}
| {
"end_byte": 6030,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/node/node.ts"
} |
angular/packages/zone.js/lib/node/node_util.ts_0_735 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {
bindArguments,
patchMacroTask,
patchMethod,
patchOnProperties,
setShouldCopySymbolProperties,
} from '../common/utils';
import {ZoneType} from '../zone-impl';
export function patchNodeUtil(Zone: ZoneType): void {
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);
});
}
| {
"end_byte": 735,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/node/node_util.ts"
} |
angular/packages/zone.js/lib/node/fs.ts_0_2225 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchMacroTask} from '../common/utils';
import {ZoneType} from '../zone-impl';
export function patchFs(Zone: ZoneType): void {
Zone.__load_patch('fs', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
let fs: any;
try {
fs = require('fs');
} catch (err) {}
if (!fs) return;
// 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',
'lutimes',
'link',
'lstat',
'mkdir',
'mkdtemp',
'open',
'opendir',
'read',
'readdir',
'readFile',
'readlink',
'realpath',
'rename',
'rmdir',
'stat',
'symlink',
'truncate',
'unlink',
'utimes',
'write',
'writeFile',
'writev',
];
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,
};
});
});
const realpathOriginalDelegate = fs.realpath?.[api.symbol('OriginalDelegate')];
// This is the only specific method that should be additionally patched because the previous
// `patchMacroTask` has overridden the `realpath` function and its `native` property.
if (realpathOriginalDelegate?.native) {
fs.realpath.native = realpathOriginalDelegate.native;
patchMacroTask(fs.realpath, 'native', (self, args) => ({
args,
target: self,
cbIdx: args.length > 0 ? args.length - 1 : -1,
name: 'fs.realpath.native',
}));
}
});
}
| {
"end_byte": 2225,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/node/fs.ts"
} |
angular/packages/zone.js/lib/node/rollup-main.ts_0_254 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {rollupMain} from './main';
rollupMain();
| {
"end_byte": 254,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/node/rollup-main.ts"
} |
angular/packages/zone.js/lib/node/events.ts_0_2065 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchEventTarget} from '../common/events';
import {ZoneType} from '../zone-impl';
export function patchEvents(Zone: ZoneType): void {
Zone.__load_patch('EventEmitter', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
// 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 EE_OFF = 'off';
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;
}
if (!eventName) {
return '';
}
return eventName.toString().replace('(', '_').replace(')', '_');
};
function patchEventEmitterMethods(obj: any) {
const result = patchEventTarget(global, api, [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];
obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
}
}
// EventEmitter
let events;
try {
events = require('events');
} catch (err) {}
if (events && events.EventEmitter) {
patchEventEmitterMethods(events.EventEmitter.prototype);
}
});
}
| {
"end_byte": 2065,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/node/events.ts"
} |
angular/packages/zone.js/lib/jasmine/rollup-jasmine.ts_0_265 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchJasmine} from './jasmine';
patchJasmine(Zone);
| {
"end_byte": 265,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/jasmine/rollup-jasmine.ts"
} |
angular/packages/zone.js/lib/jasmine/jasmine.ts_0_316 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/// <reference types="jasmine"/>
import {ZoneType} from '../zone-impl';
('use strict');
declare let jest: any; | {
"end_byte": 316,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/jasmine/jasmine.ts"
} |
angular/packages/zone.js/lib/jasmine/jasmine.ts_318_9403 | export function patchJasmine(Zone: ZoneType): void {
Zone.__load_patch('jasmine', (global: any, Zone: ZoneType, api: _ZonePrivate) => {
const __extends = function (d: any, b: any) {
for (const p in b) if (b.hasOwnProperty(p)) d[p] = b[p];
function __(this: Object) {
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 jest !== 'undefined') {
// return if jasmine is a light implementation inside jest
// in this case, we are running inside jest not jasmine
return;
}
if (typeof jasmine == 'undefined' || (jasmine as any)['__zone_patch__']) {
return;
}
(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;
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 isNode = typeof process !== 'undefined' && !!process.on;
// Note: Jasmine checks internally if `process` and `process.on` is defined.
// Otherwise, it installs the browser rejection handler through the
// `global.addEventListener`. This code may be run in the browser environment where
// `process` is not defined, and this will lead to a runtime exception since Webpack 5
// removed automatic Node.js polyfills. Note, that events are named differently, it's
// `unhandledRejection` in Node.js and `unhandledrejection` in the browser.
const originalHandlers: any[] = isNode
? process.listeners('unhandledRejection')
: global.eventListeners('unhandledrejection');
const result = originalInstall.apply(this, arguments);
isNode
? process.removeAllListeners('unhandledRejection')
: global.removeAllListeners('unhandledrejection');
if (originalHandlers) {
originalHandlers.forEach((handler) => {
if (isNode) {
process.on('unhandledRejection', handler);
} else {
global.addEventListener('unhandledrejection', handler);
}
});
}
return result;
};
}
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(description, 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.setFakeBaseSystemTime.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;
};
}
// monkey patch createSpyObj to make properties enumerable to true
if (!(jasmine as any)[Zone.__symbol__('createSpyObj')]) {
const originalCreateSpyObj = jasmine.createSpyObj;
(jasmine as any)[Zone.__symbol__('createSpyObj')] = originalCreateSpyObj;
jasmine.createSpyObj = function () {
const args: any = Array.prototype.slice.call(arguments);
const propertyNames = args.length >= 3 ? args[2] : null;
let spyObj: any;
if (propertyNames) {
const defineProperty = Object.defineProperty;
Object.defineProperty = function <T>(obj: T, p: PropertyKey, attributes: any) {
return defineProperty.call(this, obj, p, {
...attributes,
configurable: true,
enumerable: true,
}) as T;
};
try {
spyObj = originalCreateSpyObj.apply(this, args);
} finally {
Object.defineProperty = defineProperty;
}
} else {
spyObj = originalCreateSpyObj.apply(this, args);
}
return spyObj;
};
}
/**
* Gets a function wrapping the body of a Jasmine `describe` block to execute in a
* synchronous-only zone.
*/ | {
"end_byte": 9403,
"start_byte": 318,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/jasmine/jasmine.ts"
} |
angular/packages/zone.js/lib/jasmine/jasmine.ts_9408_16727 | function wrapDescribeInZone(description: string, describeBody: Function): Function {
return function (this: unknown) {
// 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`.
const syncZone = ambientZone.fork(new SyncTestZoneSpec(`jasmine.describe#${description}`));
return syncZone.run(describeBody, this, arguments as any as any[]);
};
}
function runInTestZone(
testBody: Function,
applyThis: any,
queueRunner: QueueRunner,
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 (this: QueueRunnerUserContext, done: Function) {
return runInTestZone(testBody, this, this.queueRunner!, done);
}
: function (this: QueueRunnerUserContext) {
return runInTestZone(testBody, this, this.queueRunner!);
})
);
}
interface QueueRunner {
execute(): void;
testProxyZoneSpec: ZoneSpec | null;
testProxyZone: Zone | null;
}
interface QueueRunnerAttrs {
queueableFns: {fn: Function}[];
clearStack: (fn: any) => void;
catchException: () => boolean;
fail: () => void;
onComplete: () => void;
onException: (error: any) => void;
userContext: QueueRunnerUserContext;
timeout: {setTimeout: Function; clearTimeout: Function};
}
type QueueRunnerUserContext = {queueRunner?: QueueRunner};
const QueueRunner = (jasmine as any).QueueRunner as {
new (attrs: QueueRunnerAttrs): QueueRunner;
};
(jasmine as any).QueueRunner = (function (_super) {
__extends(ZoneQueueRunner, _super);
function ZoneQueueRunner(this: QueueRunner, attrs: QueueRunnerAttrs) {
if (attrs.onComplete) {
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 (this: undefined | QueueRunner, 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);
});
} | {
"end_byte": 16727,
"start_byte": 9408,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/jasmine/jasmine.ts"
} |
angular/packages/zone.js/lib/zone-spec/long-stack-trace.ts_0_6562 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {globalThis}
*/
import {ZoneType} from '../zone-impl';
export function patchLongStackTrace(Zone: ZoneType): void {
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 as Error;
}
}
// 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);
}
// 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
function stackTracesEnabled(): boolean {
// Cast through any since this property only exists on Error in the nodejs
// typings.
return (Error as any).stackTraceLimit > 0;
}
type LongStackTraceZoneSpec = ZoneSpec & {longStackTraceLimit: number};
(Zone as any)['longStackTraceZoneSpec'] = <LongStackTraceZoneSpec>{
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 (stackTracesEnabled()) {
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 (stackTracesEnabled()) {
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 (!stackTracesEnabled()) {
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();
}
| {
"end_byte": 6562,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/long-stack-trace.ts"
} |
angular/packages/zone.js/lib/zone-spec/rollup-long-stack-trace.ts_0_288 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchLongStackTrace} from './long-stack-trace';
patchLongStackTrace(Zone);
| {
"end_byte": 288,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/rollup-long-stack-trace.ts"
} |
angular/packages/zone.js/lib/zone-spec/task-tracking.ts_0_2758 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
/**
* 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.
*/
export 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' || task.data?.isPeriodic)
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 function patchTaskTracking(Zone: ZoneType): void {
// Export the class so that new instances can be created with proper
// constructor params.
(Zone as any)['TaskTrackingZoneSpec'] = TaskTrackingZoneSpec;
}
| {
"end_byte": 2758,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/task-tracking.ts"
} |
angular/packages/zone.js/lib/zone-spec/rollup-sync-test.ts_0_269 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchSyncTest} from './sync-test';
patchSyncTest(Zone);
| {
"end_byte": 269,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/rollup-sync-test.ts"
} |
angular/packages/zone.js/lib/zone-spec/rollup-wtf.ts_0_253 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchWtf} from './wtf';
patchWtf(Zone);
| {
"end_byte": 253,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/rollup-wtf.ts"
} |
angular/packages/zone.js/lib/zone-spec/async-test.ts_0_7821 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {__symbol__, ZoneType} from '../zone-impl';
const __global: any =
(typeof window !== 'undefined' && window) || (typeof self !== 'undefined' && self) || global;
class AsyncTestZoneSpec implements ZoneSpec {
// Needs to be a getter and not a plain property in order run this just-in-time. Otherwise
// `__symbol__` would be evaluated during top-level execution prior to the Zone prefix being
// changed for tests.
static get symbolParentUnresolved(): string {
return __symbol__('parentUnresolved');
}
_pendingMicroTasks: boolean = false;
_pendingMacroTasks: boolean = false;
_alreadyErrored: boolean = false;
_isSync: boolean = false;
_existingFinishTimer: ReturnType<typeof setTimeout> | null = null;
entryFunction: Function | null = null;
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[__symbol__('supportWaitUnResolvedChainedPromise')] === true;
}
isUnresolvedChainedPromisePending() {
return this.unresolvedChainedPromiseCount > 0;
}
_finishCallbackIfDone() {
// NOTE: Technically the `onHasTask` could fire together with the initial synchronous
// completion in `onInvoke`. `onHasTask` might call this method when it captured e.g.
// microtasks in the proxy zone that now complete as part of this async zone run.
// Consider the following scenario:
// 1. A test `beforeEach` schedules a microtask in the ProxyZone.
// 2. An actual empty `it` spec executes in the AsyncTestZone` (using e.g. `waitForAsync`).
// 3. The `onInvoke` invokes `_finishCallbackIfDone` because the spec runs synchronously.
// 4. We wait the scheduled timeout (see below) to account for unhandled promises.
// 5. The microtask from (1) finishes and `onHasTask` is invoked.
// --> We register a second `_finishCallbackIfDone` even though we have scheduled a timeout.
// If the finish timeout from below is already scheduled, terminate the existing scheduled
// finish invocation, avoiding calling `jasmine` `done` multiple times. *Note* that we would
// want to schedule a new finish callback in case the task state changes again.
if (this._existingFinishTimer !== null) {
clearTimeout(this._existingFinishTimer);
this._existingFinishTimer = null;
}
if (
!(
this._pendingMicroTasks ||
this._pendingMacroTasks ||
(this.supportWaitUnresolvedChainedPromise && this.isUnresolvedChainedPromisePending())
)
) {
// We wait until the next tick because we would like to catch unhandled promises which could
// cause test logic to be executed. In such cases we cannot finish with tasks pending then.
this.runZone.run(() => {
this._existingFinishTimer = 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 {
if (!this.entryFunction) {
this.entryFunction = delegate;
}
try {
this._isSync = true;
return parentZoneDelegate.invoke(targetZone, delegate, applyThis, applyArgs, source);
} finally {
// We need to check the delegate is the same as entryFunction or not.
// Consider the following case.
//
// asyncTestZone.run(() => { // Here the delegate will be the entryFunction
// Zone.current.run(() => { // Here the delegate will not be the entryFunction
// });
// });
//
// We only want to check whether there are async tasks scheduled
// for the entry function.
if (this._isSync && this.entryFunction === delegate) {
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);
// We should only trigger finishCallback when the target zone is the AsyncTestZone
// Consider the following cases.
//
// const childZone = asyncTestZone.fork({
// name: 'child',
// onHasTask: ...
// });
//
// So we have nested zones declared the onHasTask hook, in this case,
// the onHasTask will be triggered twice, and cause the finishCallbackIfDone()
// is also be invoked twice. So we need to only trigger the finishCallbackIfDone()
// when the current zone is the same as the target zone.
if (current !== target) {
return;
}
if (hasTaskState.change == 'microTask') {
this._pendingMicroTasks = hasTaskState.microTask;
this._finishCallbackIfDone();
} else if (hasTaskState.change == 'macroTask') {
this._pendingMacroTasks = hasTaskState.macroTask;
this._finishCallbackIfDone();
}
}
} | {
"end_byte": 7821,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/async-test.ts"
} |
angular/packages/zone.js/lib/zone-spec/async-test.ts_7823_12325 | export function patchAsyncTest(Zone: ZoneType): void {
// Export the class so that new instances can be created with proper
// constructor params.
(Zone as any)['AsyncTestZoneSpec'] = AsyncTestZoneSpec;
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 (this: unknown, 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(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 (this: unknown) {
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/plugins/async-test',
);
}
const ProxyZoneSpec = (Zone as any)['ProxyZoneSpec'] as {
get(): {setDelegate(spec: ZoneSpec): void; getDelegate(): ZoneSpec};
assertPresent: () => void;
};
if (!ProxyZoneSpec) {
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/plugins/proxy',
);
}
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
// still 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);
}
});
} | {
"end_byte": 12325,
"start_byte": 7823,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/async-test.ts"
} |
angular/packages/zone.js/lib/zone-spec/proxy.ts_0_7291 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export 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 a new delegateSpec was set, check if we need to trigger hasTask
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 = '--Pending 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 function patchProxyZoneSpec(Zone: ZoneType): void {
// Export the class so that new instances can be created with proper
// constructor params.
(Zone as any)['ProxyZoneSpec'] = ProxyZoneSpec;
}
| {
"end_byte": 7291,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/proxy.ts"
} |
angular/packages/zone.js/lib/zone-spec/rollup-proxy.ts_0_275 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchProxyZoneSpec} from './proxy';
patchProxyZoneSpec(Zone);
| {
"end_byte": 275,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/rollup-proxy.ts"
} |
angular/packages/zone.js/lib/zone-spec/rollup-task-tracking.ts_0_281 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {patchTaskTracking} from './task-tracking';
patchTaskTracking(Zone);
| {
"end_byte": 281,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/rollup-task-tracking.ts"
} |
angular/packages/zone.js/lib/zone-spec/fake-async-test.ts_0_2001 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
const global: any =
(typeof window === 'object' && window) || (typeof self === 'object' && self) || globalThis.global;
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;
// Since when we compile this file to `es2015`, and if we define
// this `FakeDate` as `class FakeDate`, and then set `FakeDate.prototype`
// there will be an error which is `Cannot assign to read only property 'prototype'`
// so we need to use function implementation here.
function FakeDate() {
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);
}
}
FakeDate.now = function (this: unknown) {
const fakeAsyncTestZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncTestZoneSpec) {
return fakeAsyncTestZoneSpec.getFakeSystemTime();
}
return OriginalDate.now.apply(this, arguments);
};
FakeDate.UTC = OriginalDate.UTC;
FakeDate.parse = OriginalDate.parse;
// keep a reference for zone patched timer function
let patchedTimers:
| {
setTimeout: typeof setTimeout;
setInterval: typeof setInterval;
clearTimeout: typeof clearTimeout;
clearInterval: typeof clearInterval;
nativeSetTimeout: typeof setTimeout;
nativeClearTimeout: typeof clearTimeout;
}
| undefined;
const timeoutCallback = function () {}; | {
"end_byte": 2001,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/fake-async-test.ts"
} |
angular/packages/zone.js/lib/zone-spec/fake-async-test.ts_2003_9289 | class Scheduler {
// Next scheduler id.
public static nextNodeJSId: number = 1;
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 _currentTickTime: number = 0;
// Current fake system base time in millis.
private _currentFakeBaseSystemTime: number = OriginalDate.now();
// track requeuePeriodicTimer
private _currentTickRequeuePeriodicEntries: any[] = [];
constructor() {}
static getNextId() {
const id = patchedTimers!.nativeSetTimeout.call(global, timeoutCallback, 0);
patchedTimers!.nativeClearTimeout.call(global, id);
if (typeof id === 'number') {
return id;
}
// in NodeJS, we just use a number for fakeAsync, since it will not
// conflict with native TimeoutId
return Scheduler.nextNodeJSId++;
}
getCurrentTickTime() {
return this._currentTickTime;
}
getFakeSystemTime() {
return this._currentFakeBaseSystemTime + this._currentTickTime;
}
setFakeBaseSystemTime(fakeBaseSystemTime: number) {
this._currentFakeBaseSystemTime = fakeBaseSystemTime;
}
getRealSystemTime() {
return OriginalDate.now();
}
scheduleFunction(
cb: Function,
delay: number,
options?: {
args?: any[];
isPeriodic?: boolean;
isRequestAnimationFrame?: boolean;
id?: number;
isRequeuePeriodic?: boolean;
},
): number {
options = {
...{
args: [],
isPeriodic: false,
isRequestAnimationFrame: false,
id: -1,
isRequeuePeriodic: false,
},
...options,
};
let currentId = options.id! < 0 ? Scheduler.nextId : options.id!;
Scheduler.nextId = Scheduler.getNextId();
let endTime = this._currentTickTime + delay;
// Insert so that scheduler queue remains sorted by end time.
let newEntry: ScheduledFunction = {
endTime: endTime,
id: currentId,
func: cb,
args: options.args!,
delay: delay,
isPeriodic: options.isPeriodic!,
isRequestAnimationFrame: options.isRequestAnimationFrame!,
};
if (options.isRequeuePeriodic!) {
this._currentTickRequeuePeriodicEntries.push(newEntry);
}
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;
}
}
}
removeAll(): void {
this._schedulerQueue = [];
}
getTimerCount(): number {
return this._schedulerQueue.length;
}
tickToNext(
step: number = 1,
doTick?: (elapsed: number) => void,
tickOptions?: {
processNewMacroTasksSynchronously: boolean;
},
) {
if (this._schedulerQueue.length < step) {
return;
}
// Find the last task currently queued in the scheduler queue and tick
// till that time.
const startTime = this._currentTickTime;
const targetTask = this._schedulerQueue[step - 1];
this.tick(targetTask.endTime - startTime, doTick, tickOptions);
}
tick(
millis: number = 0,
doTick?: (elapsed: number) => void,
tickOptions?: {
processNewMacroTasksSynchronously: boolean;
},
): void {
let finalTime = this._currentTickTime + millis;
let lastCurrentTime = 0;
tickOptions = Object.assign({processNewMacroTasksSynchronously: true}, tickOptions);
// we need to copy the schedulerQueue so nested timeout
// will not be wrongly called in the current tick
// https://github.com/angular/angular/issues/33799
const schedulerQueue = tickOptions.processNewMacroTasksSynchronously
? this._schedulerQueue
: this._schedulerQueue.slice();
if (schedulerQueue.length === 0 && doTick) {
doTick(millis);
return;
}
while (schedulerQueue.length > 0) {
// clear requeueEntries before each loop
this._currentTickRequeuePeriodicEntries = [];
let current = 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 = schedulerQueue.shift()!;
if (!tickOptions.processNewMacroTasksSynchronously) {
const idx = this._schedulerQueue.indexOf(current);
if (idx >= 0) {
this._schedulerQueue.splice(idx, 1);
}
}
lastCurrentTime = this._currentTickTime;
this._currentTickTime = current.endTime;
if (doTick) {
doTick(this._currentTickTime - lastCurrentTime);
}
let retval = current.func.apply(
global,
current.isRequestAnimationFrame ? [this._currentTickTime] : current.args,
);
if (!retval) {
// Uncaught exception in the current scheduled function. Stop processing the queue.
break;
}
// check is there any requeue periodic entry is added in
// current loop, if there is, we need to add to current loop
if (!tickOptions.processNewMacroTasksSynchronously) {
this._currentTickRequeuePeriodicEntries.forEach((newEntry) => {
let i = 0;
for (; i < schedulerQueue.length; i++) {
const currentEntry = schedulerQueue[i];
if (newEntry.endTime < currentEntry.endTime) {
break;
}
}
schedulerQueue.splice(i, 0, newEntry);
});
}
}
}
lastCurrentTime = this._currentTickTime;
this._currentTickTime = finalTime;
if (doTick) {
doTick(this._currentTickTime - lastCurrentTime);
}
}
flushOnlyPendingTimers(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._currentTickTime;
const lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
this.tick(lastTask.endTime - startTime, doTick, {processNewMacroTasksSynchronously: false});
return this._currentTickTime - startTime;
}
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._currentTickTime;
const lastTask = this._schedulerQueue[this._schedulerQueue.length - 1];
this.tick(lastTask.endTime - startTime, doTick);
return this._currentTickTime - startTime;
} | {
"end_byte": 9289,
"start_byte": 2003,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/fake-async-test.ts"
} |
angular/packages/zone.js/lib/zone-spec/fake-async-test.ts_9293_10598 | private flushNonPeriodic(limit: number, doTick?: (elapsed: number) => void): number {
const startTime = this._currentTickTime;
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._currentTickTime;
this._currentTickTime = current.endTime;
if (doTick) {
// Update any secondary schedulers like Jasmine mock Date.
doTick(this._currentTickTime - 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._currentTickTime - startTime;
}
} | {
"end_byte": 10598,
"start_byte": 9293,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/fake-async-test.ts"
} |
angular/packages/zone.js/lib/zone-spec/fake-async-test.ts_10600_18437 | 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,
isPeriodic: true,
id,
isRequeuePeriodic: true,
});
}
};
}
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, isRequestAnimationFrame: !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, isPeriodic: 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;
}
getCurrentTickTime() {
return this._scheduler.getCurrentTickTime();
}
getFakeSystemTime() {
return this._scheduler.getFakeSystemTime();
}
setFakeBaseSystemTime(realTime: number) {
this._scheduler.setFakeBaseSystemTime(realTime);
}
getRealSystemTime() {
return this._scheduler.getRealSystemTime();
}
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 (!patchedTimers) {
throw new Error('Expected timers to have been patched.');
}
if (global.setTimeout !== patchedTimers.setTimeout) {
global.setTimeout = patchedTimers.setTimeout;
global.clearTimeout = patchedTimers.clearTimeout;
}
if (global.setInterval !== patchedTimers.setInterval) {
global.setInterval = patchedTimers.setInterval;
global.clearInterval = patchedTimers.clearInterval;
}
}
lockDatePatch() {
this.patchDateLocked = true;
FakeAsyncTestZoneSpec.patchDate();
}
unlockDatePatch() {
this.patchDateLocked = false;
FakeAsyncTestZoneSpec.resetDate();
}
tickToNext(
steps: number = 1,
doTick?: (elapsed: number) => void,
tickOptions: {
processNewMacroTasksSynchronously: boolean;
} = {processNewMacroTasksSynchronously: true},
): void {
if (steps <= 0) {
return;
}
FakeAsyncTestZoneSpec.assertInZone();
this.flushMicrotasks();
this._scheduler.tickToNext(steps, doTick, tickOptions);
if (this._lastError !== null) {
this._resetLastErrorAndThrow();
}
}
tick(
millis: number = 0,
doTick?: (elapsed: number) => void,
tickOptions: {
processNewMacroTasksSynchronously: boolean;
} = {processNewMacroTasksSynchronously: true},
): void {
FakeAsyncTestZoneSpec.assertInZone();
this.flushMicrotasks();
this._scheduler.tick(millis, doTick, tickOptions);
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;
} | {
"end_byte": 18437,
"start_byte": 10600,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/fake-async-test.ts"
} |
angular/packages/zone.js/lib/zone-spec/fake-async-test.ts_18441_26009 | flushOnlyPendingTimers(doTick?: (elapsed: number) => void): number {
FakeAsyncTestZoneSpec.assertInZone();
this.flushMicrotasks();
const elapsed = this._scheduler.flushOnlyPendingTimers(doTick);
if (this._lastError !== null) {
this._resetLastErrorAndThrow();
}
return elapsed;
}
removeAllTimers() {
FakeAsyncTestZoneSpec.assertInZone();
this._scheduler.removeAll();
this.pendingPeriodicTimers = [];
this.pendingTimers = [];
}
getTimerCount() {
return this._scheduler.getTimerCount() + this._microtasks.length;
}
// 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.
}
}
let _fakeAsyncTestZoneSpec: FakeAsyncTestZoneSpec | null = null;
type ProxyZoneSpecType = {
setDelegate(delegateSpec: ZoneSpec): void;
getDelegate(): ZoneSpec;
resetDelegate(): void;
};
function getProxyZoneSpec(): {get(): ProxyZoneSpecType; assertPresent: () => ProxyZoneSpecType} {
return Zone && (Zone as any)['ProxyZoneSpec'];
}
/**
* Clears out the shared fake async zone for a test.
* To be called in a global `beforeEach`.
*
* @experimental
*/
export 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.
getProxyZoneSpec() && getProxyZoneSpec().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.
*
* When flush is `false`, 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
* @param options
* flush: when true, will drain the macrotask queue after the test function completes.
* @returns The function wrapped to be executed in the fakeAsync zone
*
* @experimental
*/ | {
"end_byte": 26009,
"start_byte": 18441,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/fake-async-test.ts"
} |
angular/packages/zone.js/lib/zone-spec/fake-async-test.ts_26010_30773 | export function fakeAsync(fn: Function, options: {flush?: boolean} = {}): (...args: any[]) => any {
const {flush = true} = options;
// Not using an arrow function to preserve context passed from call site
const fakeAsyncFn: any = function (this: unknown, ...args: any[]) {
const ProxyZoneSpec = getProxyZoneSpec();
if (!ProxyZoneSpec) {
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/plugins/proxy',
);
}
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) {
const FakeAsyncTestZoneSpec = Zone && (Zone as any)['FakeAsyncTestZoneSpec'];
if (proxyZoneSpec.getDelegate() instanceof FakeAsyncTestZoneSpec) {
throw new Error('fakeAsync() calls can not be nested');
}
_fakeAsyncTestZoneSpec = new FakeAsyncTestZoneSpec() as FakeAsyncTestZoneSpec;
}
let res: any;
const lastProxyZoneSpec = proxyZoneSpec.getDelegate();
proxyZoneSpec.setDelegate(_fakeAsyncTestZoneSpec);
_fakeAsyncTestZoneSpec.lockDatePatch();
try {
res = fn.apply(this, args);
if (flush) {
_fakeAsyncTestZoneSpec.flush(20, true);
} else {
flushMicrotasks();
}
} finally {
proxyZoneSpec.setDelegate(lastProxyZoneSpec);
}
if (!flush) {
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();
}
};
(fakeAsyncFn as any).isFakeAsync = true;
return fakeAsyncFn;
}
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
*/
export function tick(millis: number = 0, ignoreNestedTimeout = false): void {
_getFakeAsyncZoneSpec().tick(millis, null, ignoreNestedTimeout);
}
/**
* 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
*/
export function flush(maxTurns?: number): number {
return _getFakeAsyncZoneSpec().flush(maxTurns);
}
/**
* Discard all remaining periodic tasks.
*
* @experimental
*/
export function discardPeriodicTasks(): void {
const zoneSpec = _getFakeAsyncZoneSpec();
const pendingTimers = zoneSpec.pendingPeriodicTimers;
zoneSpec.pendingPeriodicTimers.length = 0;
}
/**
* Flush any pending microtasks.
*
* @experimental
*/
export function flushMicrotasks(): void {
_getFakeAsyncZoneSpec().flushMicrotasks();
}
export function patchFakeAsyncTest(Zone: ZoneType): void {
// Export the class so that new instances can be created with proper
// constructor params.
(Zone as any)['FakeAsyncTestZoneSpec'] = FakeAsyncTestZoneSpec;
Zone.__load_patch(
'fakeasync',
(global: any, Zone: ZoneType, api: _ZonePrivate) => {
(Zone as any)[api.symbol('fakeAsyncTest')] = {
resetFakeAsyncZone,
flushMicrotasks,
discardPeriodicTasks,
tick,
flush,
fakeAsync,
};
},
true,
);
patchedTimers = {
setTimeout: global.setTimeout,
setInterval: global.setInterval,
clearTimeout: global.clearTimeout,
clearInterval: global.clearInterval,
nativeSetTimeout: global[Zone.__symbol__('setTimeout')],
nativeClearTimeout: global[Zone.__symbol__('clearTimeout')],
};
Scheduler.nextId = Scheduler.getNextId();
} | {
"end_byte": 30773,
"start_byte": 26010,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/fake-async-test.ts"
} |
angular/packages/zone.js/lib/zone-spec/wtf.ts_0_5843 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
/**
* @fileoverview
* @suppress {missingRequire}
*/
import {ZoneType} from '../zone-impl';
const _global: any =
(typeof window === 'object' && window) || (typeof self === 'object' && self) || global;
export function patchWtf(Zone: ZoneType): void {
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)) {
// explicit : any due to https://github.com/microsoft/TypeScript/issues/33191
let value: any = 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();
}
| {
"end_byte": 5843,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/wtf.ts"
} |
angular/packages/zone.js/lib/zone-spec/sync-test.ts_0_1086 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
export function patchSyncTest(Zone: ZoneType): void {
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 (${this.name}).`);
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;
}
| {
"end_byte": 1086,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/zone-spec/sync-test.ts"
} |
angular/packages/zone.js/lib/jest/jest.ts_0_5962 | /**
* @license
* Copyright Google LLC 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.dev/license
*/
import {ZoneType} from '../zone-impl';
('use strict');
declare let jest: any;
export function patchJest(Zone: ZoneType): void {
Zone.__load_patch('jest', (context: any, Zone: ZoneType, api: _ZonePrivate) => {
if (typeof jest === 'undefined' || jest['__zone_patch__']) {
return;
}
// From jest 29 and jest-preset-angular v13, the module transform logic
// changed, and now jest-preset-angular use the use the tsconfig target
// other than the hardcoded one, https://github.com/thymikee/jest-preset-angular/issues/2010
// But jest-angular-preset doesn't introduce the @babel/plugin-transform-async-to-generator
// which is needed by angular since `async/await` still need to be transformed
// to promise for ES2017+ target.
// So for now, we disable to output the uncaught error console log for a temp solution,
// until jest-preset-angular find a proper solution.
(Zone as any)[api.symbol('ignoreConsoleErrorUncaughtError')] = true;
jest['__zone_patch__'] = true;
const ProxyZoneSpec = (Zone as any)['ProxyZoneSpec'];
const SyncTestZoneSpec = (Zone as any)['SyncTestZoneSpec'];
if (!ProxyZoneSpec) {
throw new Error('Missing ProxyZoneSpec');
}
const rootZone = Zone.current;
const syncZone = rootZone.fork(new SyncTestZoneSpec('jest.describe'));
const proxyZoneSpec = new ProxyZoneSpec();
const proxyZone = rootZone.fork(proxyZoneSpec);
function wrapDescribeFactoryInZone(originalJestFn: Function) {
return function (this: unknown, ...tableArgs: any[]) {
const originalDescribeFn = originalJestFn.apply(this, tableArgs);
return function (this: unknown, ...args: any[]) {
args[1] = wrapDescribeInZone(args[1]);
return originalDescribeFn.apply(this, args);
};
};
}
function wrapTestFactoryInZone(originalJestFn: Function) {
return function (this: unknown, ...tableArgs: any[]) {
return function (this: unknown, ...args: any[]) {
args[1] = wrapTestInZone(args[1]);
return originalJestFn.apply(this, tableArgs).apply(this, args);
};
};
}
/**
* Gets a function wrapping the body of a jest `describe` block to execute in a
* synchronous-only zone.
*/
function wrapDescribeInZone(describeBody: Function): Function {
return function (this: unknown, ...args: any[]) {
return syncZone.run(describeBody, this, args);
};
}
/**
* Gets a function wrapping the body of a jest `it/beforeEach/afterEach` block to
* execute in a ProxyZone zone.
* This will run in the `proxyZone`.
*/
function wrapTestInZone(testBody: Function, isTestFunc = false): Function {
if (typeof testBody !== 'function') {
return testBody;
}
const wrappedFunc = function () {
if (
(Zone as any)[api.symbol('useFakeTimersCalled')] === true &&
testBody &&
!(testBody as any).isFakeAsync
) {
// jest.useFakeTimers is called, run into fakeAsyncTest automatically.
const fakeAsyncModule = (Zone as any)[Zone.__symbol__('fakeAsyncTest')];
if (fakeAsyncModule && typeof fakeAsyncModule.fakeAsync === 'function') {
testBody = fakeAsyncModule.fakeAsync(testBody);
}
}
proxyZoneSpec.isTestFunc = isTestFunc;
return proxyZone.run(testBody, null, arguments as any);
};
// Update the length of wrappedFunc to be the same as the length of the testBody
// So jest core can handle whether the test function has `done()` or not correctly
Object.defineProperty(wrappedFunc, 'length', {
configurable: true,
writable: true,
enumerable: false,
});
wrappedFunc.length = testBody.length;
return wrappedFunc;
}
['describe', 'xdescribe', 'fdescribe'].forEach((methodName) => {
let originalJestFn: Function = context[methodName];
if (context[Zone.__symbol__(methodName)]) {
return;
}
context[Zone.__symbol__(methodName)] = originalJestFn;
context[methodName] = function (this: unknown, ...args: any[]) {
args[1] = wrapDescribeInZone(args[1]);
return originalJestFn.apply(this, args);
};
context[methodName].each = wrapDescribeFactoryInZone((originalJestFn as any).each);
});
context.describe.only = context.fdescribe;
context.describe.skip = context.xdescribe;
['it', 'xit', 'fit', 'test', 'xtest'].forEach((methodName) => {
let originalJestFn: Function = context[methodName];
if (context[Zone.__symbol__(methodName)]) {
return;
}
context[Zone.__symbol__(methodName)] = originalJestFn;
context[methodName] = function (this: unknown, ...args: any[]) {
args[1] = wrapTestInZone(args[1], true);
return originalJestFn.apply(this, args);
};
context[methodName].each = wrapTestFactoryInZone((originalJestFn as any).each);
context[methodName].todo = (originalJestFn as any).todo;
context[methodName].failing = (originalJestFn as any).failing;
});
context.it.only = context.fit;
context.it.skip = context.xit;
context.test.only = context.fit;
context.test.skip = context.xit;
['beforeEach', 'afterEach', 'beforeAll', 'afterAll'].forEach((methodName) => {
let originalJestFn: Function = context[methodName];
if (context[Zone.__symbol__(methodName)]) {
return;
}
context[Zone.__symbol__(methodName)] = originalJestFn;
context[methodName] = function (this: unknown, ...args: any[]) {
args[0] = wrapTestInZone(args[0]);
return originalJestFn.apply(this, args);
};
}); | {
"end_byte": 5962,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/jest/jest.ts"
} |
angular/packages/zone.js/lib/jest/jest.ts_5968_12050 | (Zone as any).patchJestObject = function patchJestObject(Timer: any, isModern = false) {
// check whether currently the test is inside fakeAsync()
function isPatchingFakeTimer() {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
return !!fakeAsyncZoneSpec;
}
// check whether the current function is inside `test/it` or other methods
// such as `describe/beforeEach`
function isInTestFunc() {
const proxyZoneSpec = Zone.current.get('ProxyZoneSpec');
return proxyZoneSpec && proxyZoneSpec.isTestFunc;
}
if (Timer[api.symbol('fakeTimers')]) {
return;
}
Timer[api.symbol('fakeTimers')] = true;
// patch jest fakeTimer internal method to make sure no console.warn print out
api.patchMethod(Timer, '_checkFakeTimers', (delegate) => {
return function (self: any, args: any[]) {
if (isPatchingFakeTimer()) {
return true;
} else {
return delegate.apply(self, args);
}
};
});
// patch useFakeTimers(), set useFakeTimersCalled flag, and make test auto run into fakeAsync
api.patchMethod(Timer, 'useFakeTimers', (delegate) => {
return function (self: any, args: any[]) {
(Zone as any)[api.symbol('useFakeTimersCalled')] = true;
if (isModern || isInTestFunc()) {
return delegate.apply(self, args);
}
return self;
};
});
// patch useRealTimers(), unset useFakeTimers flag
api.patchMethod(Timer, 'useRealTimers', (delegate) => {
return function (self: any, args: any[]) {
(Zone as any)[api.symbol('useFakeTimersCalled')] = false;
if (isModern || isInTestFunc()) {
return delegate.apply(self, args);
}
return self;
};
});
// patch setSystemTime(), call setCurrentRealTime() in the fakeAsyncTest
api.patchMethod(Timer, 'setSystemTime', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
fakeAsyncZoneSpec.setFakeBaseSystemTime(args[0]);
} else {
return delegate.apply(self, args);
}
};
});
// patch getSystemTime(), call getCurrentRealTime() in the fakeAsyncTest
api.patchMethod(Timer, 'getRealSystemTime', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec && isPatchingFakeTimer()) {
return fakeAsyncZoneSpec.getRealSystemTime();
} else {
return delegate.apply(self, args);
}
};
});
// patch runAllTicks(), run all microTasks inside fakeAsync
api.patchMethod(Timer, 'runAllTicks', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.flushMicrotasks();
} else {
return delegate.apply(self, args);
}
};
});
// patch runAllTimers(), run all macroTasks inside fakeAsync
api.patchMethod(Timer, 'runAllTimers', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.flush(100, true);
} else {
return delegate.apply(self, args);
}
};
});
// patch advanceTimersByTime(), call tick() in the fakeAsyncTest
api.patchMethod(Timer, 'advanceTimersByTime', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.tick(args[0]);
} else {
return delegate.apply(self, args);
}
};
});
// patch runOnlyPendingTimers(), call flushOnlyPendingTimers() in the fakeAsyncTest
api.patchMethod(Timer, 'runOnlyPendingTimers', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.flushOnlyPendingTimers();
} else {
return delegate.apply(self, args);
}
};
});
// patch advanceTimersToNextTimer(), call tickToNext() in the fakeAsyncTest
api.patchMethod(Timer, 'advanceTimersToNextTimer', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.tickToNext(args[0]);
} else {
return delegate.apply(self, args);
}
};
});
// patch clearAllTimers(), call removeAllTimers() in the fakeAsyncTest
api.patchMethod(Timer, 'clearAllTimers', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
fakeAsyncZoneSpec.removeAllTimers();
} else {
return delegate.apply(self, args);
}
};
});
// patch getTimerCount(), call getTimerCount() in the fakeAsyncTest
api.patchMethod(Timer, 'getTimerCount', (delegate) => {
return function (self: any, args: any[]) {
const fakeAsyncZoneSpec = Zone.current.get('FakeAsyncTestZoneSpec');
if (fakeAsyncZoneSpec) {
return fakeAsyncZoneSpec.getTimerCount();
} else {
return delegate.apply(self, args);
}
};
});
};
});
} | {
"end_byte": 12050,
"start_byte": 5968,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/lib/jest/jest.ts"
} |
angular/packages/zone.js/doc/error.puml_0_474 | @startuml
scheduling --> unknown: zoneSpec.onScheduleTask\nor task.scheduleFn\nthrow error
running --> scheduled: error in \ntask.callback\nand task is\nperiodical\ntask
running --> notScheduled: error in\ntask.callback\nand\ntask is not\nperiodical
running: zoneSpec.onHandleError
running --> throw: error in\n task.callback\n and \nzoneSpec.onHandleError\n return true
canceling --> unknown: zoneSpec.onCancelTask\n or task.cancelFn\n throw error
unknown --> throw
@enduml | {
"end_byte": 474,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/doc/error.puml"
} |
angular/packages/zone.js/doc/override-task.puml_0_525 | @startuml
[*] --> notScheduled: initialize
notScheduled --> scheduling: scheduleTask
scheduling: zoneSpec.onScheduleTask
scheduling: zoneSpec.onHasTask
scheduling --> scheduled: override with\n anotherZone
scheduled --> running: timeout callback\nreadystatechange\ncallback
running: anotherZoneSpec:onInvokeTask
scheduled --> canceling: clearTimeout\n/abort request
canceling: anotherZoneSpec.onCancelTask
canceling --> notScheduled
canceling: zneSpec.onHasTask
running --> notScheduled
running: zoneSpec.onHasTask
@enduml | {
"end_byte": 525,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/doc/override-task.puml"
} |
angular/packages/zone.js/doc/microtask.puml_0_333 | @startuml
[*] --> notScheduled: initialize
notScheduled --> scheduling: promise.then/\nprocess.nextTick\nand so on
scheduling: zoneSpec.onScheduleTask
scheduling: zoneSpec.onHasTask
scheduling --> scheduled
scheduled --> running: callback
running: zoneSpec:onInvokeTask
running --> notScheduled
running: zoneSpec.onHasTask
@enduml | {
"end_byte": 333,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/doc/microtask.puml"
} |
angular/packages/zone.js/doc/eventtask.puml_0_514 | @startuml
[*] --> notScheduled: initialize
notScheduled --> scheduling: addEventListener
scheduling: zoneSpec.onScheduleTask
scheduling: zoneSpec.onHasTask
scheduling --> scheduled
scheduled --> running: event\n triggered
running: zoneSpec:onInvokeTask
scheduled --> canceling: removeEventListener
canceling: zoneSpec.onCancelTask
canceling --> notScheduled
canceling: zoneSpec.onHasTask
running --> scheduled: callback\n finished
running: zoneSpec.onHasTask
running --> canceling: removeEventListener
@enduml | {
"end_byte": 514,
"start_byte": 0,
"url": "https://github.com/angular/angular/blob/main/packages/zone.js/doc/eventtask.puml"
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.