source: trip-planner-front/node_modules/zone.js/fesm2015/zone-mix.js@ b738035

Last change on this file since b738035 was 6a3a178, checked in by Ema <ema_spirova@…>, 3 years ago

initial commit

  • Property mode set to 100644
File size: 135.5 KB
RevLine 
[6a3a178]1'use strict';
2/**
3 * @license Angular v12.0.0-next.0
4 * (c) 2010-2020 Google LLC. https://angular.io/
5 * License: MIT
6 */
7/**
8 * @license
9 * Copyright Google LLC All Rights Reserved.
10 *
11 * Use of this source code is governed by an MIT-style license that can be
12 * found in the LICENSE file at https://angular.io/license
13 */
14const Zone$1 = (function (global) {
15 const performance = global['performance'];
16 function mark(name) {
17 performance && performance['mark'] && performance['mark'](name);
18 }
19 function performanceMeasure(name, label) {
20 performance && performance['measure'] && performance['measure'](name, label);
21 }
22 mark('Zone');
23 // Initialize before it's accessed below.
24 // __Zone_symbol_prefix global can be used to override the default zone
25 // symbol prefix with a custom one if needed.
26 const symbolPrefix = global['__Zone_symbol_prefix'] || '__zone_symbol__';
27 function __symbol__(name) {
28 return symbolPrefix + name;
29 }
30 const checkDuplicate = global[__symbol__('forceDuplicateZoneCheck')] === true;
31 if (global['Zone']) {
32 // if global['Zone'] already exists (maybe zone.js was already loaded or
33 // some other lib also registered a global object named Zone), we may need
34 // to throw an error, but sometimes user may not want this error.
35 // For example,
36 // we have two web pages, page1 includes zone.js, page2 doesn't.
37 // and the 1st time user load page1 and page2, everything work fine,
38 // but when user load page2 again, error occurs because global['Zone'] already exists.
39 // so we add a flag to let user choose whether to throw this error or not.
40 // By default, if existing Zone is from zone.js, we will not throw the error.
41 if (checkDuplicate || typeof global['Zone'].__symbol__ !== 'function') {
42 throw new Error('Zone already loaded.');
43 }
44 else {
45 return global['Zone'];
46 }
47 }
48 class Zone {
49 constructor(parent, zoneSpec) {
50 this._parent = parent;
51 this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>';
52 this._properties = zoneSpec && zoneSpec.properties || {};
53 this._zoneDelegate =
54 new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec);
55 }
56 static assertZonePatched() {
57 if (global['Promise'] !== patches['ZoneAwarePromise']) {
58 throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' +
59 'has been overwritten.\n' +
60 'Most likely cause is that a Promise polyfill has been loaded ' +
61 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' +
62 'If you must load one, do so before loading zone.js.)');
63 }
64 }
65 static get root() {
66 let zone = Zone.current;
67 while (zone.parent) {
68 zone = zone.parent;
69 }
70 return zone;
71 }
72 static get current() {
73 return _currentZoneFrame.zone;
74 }
75 static get currentTask() {
76 return _currentTask;
77 }
78 // tslint:disable-next-line:require-internal-with-underscore
79 static __load_patch(name, fn, ignoreDuplicate = false) {
80 if (patches.hasOwnProperty(name)) {
81 // `checkDuplicate` option is defined from global variable
82 // so it works for all modules.
83 // `ignoreDuplicate` can work for the specified module
84 if (!ignoreDuplicate && checkDuplicate) {
85 throw Error('Already loaded patch: ' + name);
86 }
87 }
88 else if (!global['__Zone_disable_' + name]) {
89 const perfName = 'Zone:' + name;
90 mark(perfName);
91 patches[name] = fn(global, Zone, _api);
92 performanceMeasure(perfName, perfName);
93 }
94 }
95 get parent() {
96 return this._parent;
97 }
98 get name() {
99 return this._name;
100 }
101 get(key) {
102 const zone = this.getZoneWith(key);
103 if (zone)
104 return zone._properties[key];
105 }
106 getZoneWith(key) {
107 let current = this;
108 while (current) {
109 if (current._properties.hasOwnProperty(key)) {
110 return current;
111 }
112 current = current._parent;
113 }
114 return null;
115 }
116 fork(zoneSpec) {
117 if (!zoneSpec)
118 throw new Error('ZoneSpec required!');
119 return this._zoneDelegate.fork(this, zoneSpec);
120 }
121 wrap(callback, source) {
122 if (typeof callback !== 'function') {
123 throw new Error('Expecting function got: ' + callback);
124 }
125 const _callback = this._zoneDelegate.intercept(this, callback, source);
126 const zone = this;
127 return function () {
128 return zone.runGuarded(_callback, this, arguments, source);
129 };
130 }
131 run(callback, applyThis, applyArgs, source) {
132 _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
133 try {
134 return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
135 }
136 finally {
137 _currentZoneFrame = _currentZoneFrame.parent;
138 }
139 }
140 runGuarded(callback, applyThis = null, applyArgs, source) {
141 _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
142 try {
143 try {
144 return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source);
145 }
146 catch (error) {
147 if (this._zoneDelegate.handleError(this, error)) {
148 throw error;
149 }
150 }
151 }
152 finally {
153 _currentZoneFrame = _currentZoneFrame.parent;
154 }
155 }
156 runTask(task, applyThis, applyArgs) {
157 if (task.zone != this) {
158 throw new Error('A task can only be run in the zone of creation! (Creation: ' +
159 (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
160 }
161 // https://github.com/angular/zone.js/issues/778, sometimes eventTask
162 // will run in notScheduled(canceled) state, we should not try to
163 // run such kind of task but just return
164 if (task.state === notScheduled && (task.type === eventTask || task.type === macroTask)) {
165 return;
166 }
167 const reEntryGuard = task.state != running;
168 reEntryGuard && task._transitionTo(running, scheduled);
169 task.runCount++;
170 const previousTask = _currentTask;
171 _currentTask = task;
172 _currentZoneFrame = { parent: _currentZoneFrame, zone: this };
173 try {
174 if (task.type == macroTask && task.data && !task.data.isPeriodic) {
175 task.cancelFn = undefined;
176 }
177 try {
178 return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs);
179 }
180 catch (error) {
181 if (this._zoneDelegate.handleError(this, error)) {
182 throw error;
183 }
184 }
185 }
186 finally {
187 // if the task's state is notScheduled or unknown, then it has already been cancelled
188 // we should not reset the state to scheduled
189 if (task.state !== notScheduled && task.state !== unknown) {
190 if (task.type == eventTask || (task.data && task.data.isPeriodic)) {
191 reEntryGuard && task._transitionTo(scheduled, running);
192 }
193 else {
194 task.runCount = 0;
195 this._updateTaskCount(task, -1);
196 reEntryGuard &&
197 task._transitionTo(notScheduled, running, notScheduled);
198 }
199 }
200 _currentZoneFrame = _currentZoneFrame.parent;
201 _currentTask = previousTask;
202 }
203 }
204 scheduleTask(task) {
205 if (task.zone && task.zone !== this) {
206 // check if the task was rescheduled, the newZone
207 // should not be the children of the original zone
208 let newZone = this;
209 while (newZone) {
210 if (newZone === task.zone) {
211 throw Error(`can not reschedule task to ${this.name} which is descendants of the original zone ${task.zone.name}`);
212 }
213 newZone = newZone.parent;
214 }
215 }
216 task._transitionTo(scheduling, notScheduled);
217 const zoneDelegates = [];
218 task._zoneDelegates = zoneDelegates;
219 task._zone = this;
220 try {
221 task = this._zoneDelegate.scheduleTask(this, task);
222 }
223 catch (err) {
224 // should set task's state to unknown when scheduleTask throw error
225 // because the err may from reschedule, so the fromState maybe notScheduled
226 task._transitionTo(unknown, scheduling, notScheduled);
227 // TODO: @JiaLiPassion, should we check the result from handleError?
228 this._zoneDelegate.handleError(this, err);
229 throw err;
230 }
231 if (task._zoneDelegates === zoneDelegates) {
232 // we have to check because internally the delegate can reschedule the task.
233 this._updateTaskCount(task, 1);
234 }
235 if (task.state == scheduling) {
236 task._transitionTo(scheduled, scheduling);
237 }
238 return task;
239 }
240 scheduleMicroTask(source, callback, data, customSchedule) {
241 return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, undefined));
242 }
243 scheduleMacroTask(source, callback, data, customSchedule, customCancel) {
244 return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel));
245 }
246 scheduleEventTask(source, callback, data, customSchedule, customCancel) {
247 return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel));
248 }
249 cancelTask(task) {
250 if (task.zone != this)
251 throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' +
252 (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')');
253 task._transitionTo(canceling, scheduled, running);
254 try {
255 this._zoneDelegate.cancelTask(this, task);
256 }
257 catch (err) {
258 // if error occurs when cancelTask, transit the state to unknown
259 task._transitionTo(unknown, canceling);
260 this._zoneDelegate.handleError(this, err);
261 throw err;
262 }
263 this._updateTaskCount(task, -1);
264 task._transitionTo(notScheduled, canceling);
265 task.runCount = 0;
266 return task;
267 }
268 _updateTaskCount(task, count) {
269 const zoneDelegates = task._zoneDelegates;
270 if (count == -1) {
271 task._zoneDelegates = null;
272 }
273 for (let i = 0; i < zoneDelegates.length; i++) {
274 zoneDelegates[i]._updateTaskCount(task.type, count);
275 }
276 }
277 }
278 // tslint:disable-next-line:require-internal-with-underscore
279 Zone.__symbol__ = __symbol__;
280 const DELEGATE_ZS = {
281 name: '',
282 onHasTask: (delegate, _, target, hasTaskState) => delegate.hasTask(target, hasTaskState),
283 onScheduleTask: (delegate, _, target, task) => delegate.scheduleTask(target, task),
284 onInvokeTask: (delegate, _, target, task, applyThis, applyArgs) => delegate.invokeTask(target, task, applyThis, applyArgs),
285 onCancelTask: (delegate, _, target, task) => delegate.cancelTask(target, task)
286 };
287 class ZoneDelegate {
288 constructor(zone, parentDelegate, zoneSpec) {
289 this._taskCounts = { 'microTask': 0, 'macroTask': 0, 'eventTask': 0 };
290 this.zone = zone;
291 this._parentDelegate = parentDelegate;
292 this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS);
293 this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt);
294 this._forkCurrZone =
295 zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate._forkCurrZone);
296 this._interceptZS =
297 zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS);
298 this._interceptDlgt =
299 zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt);
300 this._interceptCurrZone =
301 zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate._interceptCurrZone);
302 this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS);
303 this._invokeDlgt =
304 zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt);
305 this._invokeCurrZone =
306 zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate._invokeCurrZone);
307 this._handleErrorZS =
308 zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS);
309 this._handleErrorDlgt =
310 zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt);
311 this._handleErrorCurrZone =
312 zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate._handleErrorCurrZone);
313 this._scheduleTaskZS =
314 zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS);
315 this._scheduleTaskDlgt = zoneSpec &&
316 (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt);
317 this._scheduleTaskCurrZone =
318 zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate._scheduleTaskCurrZone);
319 this._invokeTaskZS =
320 zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS);
321 this._invokeTaskDlgt =
322 zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt);
323 this._invokeTaskCurrZone =
324 zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate._invokeTaskCurrZone);
325 this._cancelTaskZS =
326 zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS);
327 this._cancelTaskDlgt =
328 zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt);
329 this._cancelTaskCurrZone =
330 zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate._cancelTaskCurrZone);
331 this._hasTaskZS = null;
332 this._hasTaskDlgt = null;
333 this._hasTaskDlgtOwner = null;
334 this._hasTaskCurrZone = null;
335 const zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask;
336 const parentHasTask = parentDelegate && parentDelegate._hasTaskZS;
337 if (zoneSpecHasTask || parentHasTask) {
338 // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such
339 // a case all task related interceptors must go through this ZD. We can't short circuit it.
340 this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS;
341 this._hasTaskDlgt = parentDelegate;
342 this._hasTaskDlgtOwner = this;
343 this._hasTaskCurrZone = zone;
344 if (!zoneSpec.onScheduleTask) {
345 this._scheduleTaskZS = DELEGATE_ZS;
346 this._scheduleTaskDlgt = parentDelegate;
347 this._scheduleTaskCurrZone = this.zone;
348 }
349 if (!zoneSpec.onInvokeTask) {
350 this._invokeTaskZS = DELEGATE_ZS;
351 this._invokeTaskDlgt = parentDelegate;
352 this._invokeTaskCurrZone = this.zone;
353 }
354 if (!zoneSpec.onCancelTask) {
355 this._cancelTaskZS = DELEGATE_ZS;
356 this._cancelTaskDlgt = parentDelegate;
357 this._cancelTaskCurrZone = this.zone;
358 }
359 }
360 }
361 fork(targetZone, zoneSpec) {
362 return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) :
363 new Zone(targetZone, zoneSpec);
364 }
365 intercept(targetZone, callback, source) {
366 return this._interceptZS ?
367 this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) :
368 callback;
369 }
370 invoke(targetZone, callback, applyThis, applyArgs, source) {
371 return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) :
372 callback.apply(applyThis, applyArgs);
373 }
374 handleError(targetZone, error) {
375 return this._handleErrorZS ?
376 this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) :
377 true;
378 }
379 scheduleTask(targetZone, task) {
380 let returnTask = task;
381 if (this._scheduleTaskZS) {
382 if (this._hasTaskZS) {
383 returnTask._zoneDelegates.push(this._hasTaskDlgtOwner);
384 }
385 // clang-format off
386 returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task);
387 // clang-format on
388 if (!returnTask)
389 returnTask = task;
390 }
391 else {
392 if (task.scheduleFn) {
393 task.scheduleFn(task);
394 }
395 else if (task.type == microTask) {
396 scheduleMicroTask(task);
397 }
398 else {
399 throw new Error('Task is missing scheduleFn.');
400 }
401 }
402 return returnTask;
403 }
404 invokeTask(targetZone, task, applyThis, applyArgs) {
405 return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) :
406 task.callback.apply(applyThis, applyArgs);
407 }
408 cancelTask(targetZone, task) {
409 let value;
410 if (this._cancelTaskZS) {
411 value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task);
412 }
413 else {
414 if (!task.cancelFn) {
415 throw Error('Task is not cancelable');
416 }
417 value = task.cancelFn(task);
418 }
419 return value;
420 }
421 hasTask(targetZone, isEmpty) {
422 // hasTask should not throw error so other ZoneDelegate
423 // can still trigger hasTask callback
424 try {
425 this._hasTaskZS &&
426 this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty);
427 }
428 catch (err) {
429 this.handleError(targetZone, err);
430 }
431 }
432 // tslint:disable-next-line:require-internal-with-underscore
433 _updateTaskCount(type, count) {
434 const counts = this._taskCounts;
435 const prev = counts[type];
436 const next = counts[type] = prev + count;
437 if (next < 0) {
438 throw new Error('More tasks executed then were scheduled.');
439 }
440 if (prev == 0 || next == 0) {
441 const isEmpty = {
442 microTask: counts['microTask'] > 0,
443 macroTask: counts['macroTask'] > 0,
444 eventTask: counts['eventTask'] > 0,
445 change: type
446 };
447 this.hasTask(this.zone, isEmpty);
448 }
449 }
450 }
451 class ZoneTask {
452 constructor(type, source, callback, options, scheduleFn, cancelFn) {
453 // tslint:disable-next-line:require-internal-with-underscore
454 this._zone = null;
455 this.runCount = 0;
456 // tslint:disable-next-line:require-internal-with-underscore
457 this._zoneDelegates = null;
458 // tslint:disable-next-line:require-internal-with-underscore
459 this._state = 'notScheduled';
460 this.type = type;
461 this.source = source;
462 this.data = options;
463 this.scheduleFn = scheduleFn;
464 this.cancelFn = cancelFn;
465 if (!callback) {
466 throw new Error('callback is not defined');
467 }
468 this.callback = callback;
469 const self = this;
470 // TODO: @JiaLiPassion options should have interface
471 if (type === eventTask && options && options.useG) {
472 this.invoke = ZoneTask.invokeTask;
473 }
474 else {
475 this.invoke = function () {
476 return ZoneTask.invokeTask.call(global, self, this, arguments);
477 };
478 }
479 }
480 static invokeTask(task, target, args) {
481 if (!task) {
482 task = this;
483 }
484 _numberOfNestedTaskFrames++;
485 try {
486 task.runCount++;
487 return task.zone.runTask(task, target, args);
488 }
489 finally {
490 if (_numberOfNestedTaskFrames == 1) {
491 drainMicroTaskQueue();
492 }
493 _numberOfNestedTaskFrames--;
494 }
495 }
496 get zone() {
497 return this._zone;
498 }
499 get state() {
500 return this._state;
501 }
502 cancelScheduleRequest() {
503 this._transitionTo(notScheduled, scheduling);
504 }
505 // tslint:disable-next-line:require-internal-with-underscore
506 _transitionTo(toState, fromState1, fromState2) {
507 if (this._state === fromState1 || this._state === fromState2) {
508 this._state = toState;
509 if (toState == notScheduled) {
510 this._zoneDelegates = null;
511 }
512 }
513 else {
514 throw new Error(`${this.type} '${this.source}': can not transition to '${toState}', expecting state '${fromState1}'${fromState2 ? ' or \'' + fromState2 + '\'' : ''}, was '${this._state}'.`);
515 }
516 }
517 toString() {
518 if (this.data && typeof this.data.handleId !== 'undefined') {
519 return this.data.handleId.toString();
520 }
521 else {
522 return Object.prototype.toString.call(this);
523 }
524 }
525 // add toJSON method to prevent cyclic error when
526 // call JSON.stringify(zoneTask)
527 toJSON() {
528 return {
529 type: this.type,
530 state: this.state,
531 source: this.source,
532 zone: this.zone.name,
533 runCount: this.runCount
534 };
535 }
536 }
537 //////////////////////////////////////////////////////
538 //////////////////////////////////////////////////////
539 /// MICROTASK QUEUE
540 //////////////////////////////////////////////////////
541 //////////////////////////////////////////////////////
542 const symbolSetTimeout = __symbol__('setTimeout');
543 const symbolPromise = __symbol__('Promise');
544 const symbolThen = __symbol__('then');
545 let _microTaskQueue = [];
546 let _isDrainingMicrotaskQueue = false;
547 let nativeMicroTaskQueuePromise;
548 function scheduleMicroTask(task) {
549 // if we are not running in any task, and there has not been anything scheduled
550 // we must bootstrap the initial task creation by manually scheduling the drain
551 if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) {
552 // We are not running in Task, so we need to kickstart the microtask queue.
553 if (!nativeMicroTaskQueuePromise) {
554 if (global[symbolPromise]) {
555 nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0);
556 }
557 }
558 if (nativeMicroTaskQueuePromise) {
559 let nativeThen = nativeMicroTaskQueuePromise[symbolThen];
560 if (!nativeThen) {
561 // native Promise is not patchable, we need to use `then` directly
562 // issue 1078
563 nativeThen = nativeMicroTaskQueuePromise['then'];
564 }
565 nativeThen.call(nativeMicroTaskQueuePromise, drainMicroTaskQueue);
566 }
567 else {
568 global[symbolSetTimeout](drainMicroTaskQueue, 0);
569 }
570 }
571 task && _microTaskQueue.push(task);
572 }
573 function drainMicroTaskQueue() {
574 if (!_isDrainingMicrotaskQueue) {
575 _isDrainingMicrotaskQueue = true;
576 while (_microTaskQueue.length) {
577 const queue = _microTaskQueue;
578 _microTaskQueue = [];
579 for (let i = 0; i < queue.length; i++) {
580 const task = queue[i];
581 try {
582 task.zone.runTask(task, null, null);
583 }
584 catch (error) {
585 _api.onUnhandledError(error);
586 }
587 }
588 }
589 _api.microtaskDrainDone();
590 _isDrainingMicrotaskQueue = false;
591 }
592 }
593 //////////////////////////////////////////////////////
594 //////////////////////////////////////////////////////
595 /// BOOTSTRAP
596 //////////////////////////////////////////////////////
597 //////////////////////////////////////////////////////
598 const NO_ZONE = { name: 'NO ZONE' };
599 const notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown';
600 const microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask';
601 const patches = {};
602 const _api = {
603 symbol: __symbol__,
604 currentZoneFrame: () => _currentZoneFrame,
605 onUnhandledError: noop,
606 microtaskDrainDone: noop,
607 scheduleMicroTask: scheduleMicroTask,
608 showUncaughtError: () => !Zone[__symbol__('ignoreConsoleErrorUncaughtError')],
609 patchEventTarget: () => [],
610 patchOnProperties: noop,
611 patchMethod: () => noop,
612 bindArguments: () => [],
613 patchThen: () => noop,
614 patchMacroTask: () => noop,
615 patchEventPrototype: () => noop,
616 isIEOrEdge: () => false,
617 getGlobalObjects: () => undefined,
618 ObjectDefineProperty: () => noop,
619 ObjectGetOwnPropertyDescriptor: () => undefined,
620 ObjectCreate: () => undefined,
621 ArraySlice: () => [],
622 patchClass: () => noop,
623 wrapWithCurrentZone: () => noop,
624 filterProperties: () => [],
625 attachOriginToPatched: () => noop,
626 _redefineProperty: () => noop,
627 patchCallbacks: () => noop
628 };
629 let _currentZoneFrame = { parent: null, zone: new Zone(null, null) };
630 let _currentTask = null;
631 let _numberOfNestedTaskFrames = 0;
632 function noop() { }
633 performanceMeasure('Zone', 'Zone');
634 return global['Zone'] = Zone;
635})(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global);
636
637/**
638 * @license
639 * Copyright Google LLC All Rights Reserved.
640 *
641 * Use of this source code is governed by an MIT-style license that can be
642 * found in the LICENSE file at https://angular.io/license
643 */
644/**
645 * Suppress closure compiler errors about unknown 'Zone' variable
646 * @fileoverview
647 * @suppress {undefinedVars,globalThis,missingRequire}
648 */
649/// <reference types="node"/>
650// issue #989, to reduce bundle size, use short name
651/** Object.getOwnPropertyDescriptor */
652const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
653/** Object.defineProperty */
654const ObjectDefineProperty = Object.defineProperty;
655/** Object.getPrototypeOf */
656const ObjectGetPrototypeOf = Object.getPrototypeOf;
657/** Object.create */
658const ObjectCreate = Object.create;
659/** Array.prototype.slice */
660const ArraySlice = Array.prototype.slice;
661/** addEventListener string const */
662const ADD_EVENT_LISTENER_STR = 'addEventListener';
663/** removeEventListener string const */
664const REMOVE_EVENT_LISTENER_STR = 'removeEventListener';
665/** zoneSymbol addEventListener */
666const ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR);
667/** zoneSymbol removeEventListener */
668const ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR);
669/** true string const */
670const TRUE_STR = 'true';
671/** false string const */
672const FALSE_STR = 'false';
673/** Zone symbol prefix string const. */
674const ZONE_SYMBOL_PREFIX = Zone.__symbol__('');
675function wrapWithCurrentZone(callback, source) {
676 return Zone.current.wrap(callback, source);
677}
678function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) {
679 return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel);
680}
681const zoneSymbol = Zone.__symbol__;
682const isWindowExists = typeof window !== 'undefined';
683const internalWindow = isWindowExists ? window : undefined;
684const _global = isWindowExists && internalWindow || typeof self === 'object' && self || global;
685const REMOVE_ATTRIBUTE = 'removeAttribute';
686const NULL_ON_PROP_VALUE = [null];
687function bindArguments(args, source) {
688 for (let i = args.length - 1; i >= 0; i--) {
689 if (typeof args[i] === 'function') {
690 args[i] = wrapWithCurrentZone(args[i], source + '_' + i);
691 }
692 }
693 return args;
694}
695function patchPrototype(prototype, fnNames) {
696 const source = prototype.constructor['name'];
697 for (let i = 0; i < fnNames.length; i++) {
698 const name = fnNames[i];
699 const delegate = prototype[name];
700 if (delegate) {
701 const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name);
702 if (!isPropertyWritable(prototypeDesc)) {
703 continue;
704 }
705 prototype[name] = ((delegate) => {
706 const patched = function () {
707 return delegate.apply(this, bindArguments(arguments, source + '.' + name));
708 };
709 attachOriginToPatched(patched, delegate);
710 return patched;
711 })(delegate);
712 }
713 }
714}
715function isPropertyWritable(propertyDesc) {
716 if (!propertyDesc) {
717 return true;
718 }
719 if (propertyDesc.writable === false) {
720 return false;
721 }
722 return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined');
723}
724const isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope);
725// Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
726// this code.
727const isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' &&
728 {}.toString.call(_global.process) === '[object process]');
729const isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']);
730// we are in electron of nw, so we are both browser and nodejs
731// Make sure to access `process` through `_global` so that WebPack does not accidentally browserify
732// this code.
733const isMix = typeof _global.process !== 'undefined' &&
734 {}.toString.call(_global.process) === '[object process]' && !isWebWorker &&
735 !!(isWindowExists && internalWindow['HTMLElement']);
736const zoneSymbolEventNames = {};
737const wrapFn = function (event) {
738 // https://github.com/angular/zone.js/issues/911, in IE, sometimes
739 // event will be undefined, so we need to use window.event
740 event = event || _global.event;
741 if (!event) {
742 return;
743 }
744 let eventNameSymbol = zoneSymbolEventNames[event.type];
745 if (!eventNameSymbol) {
746 eventNameSymbol = zoneSymbolEventNames[event.type] = zoneSymbol('ON_PROPERTY' + event.type);
747 }
748 const target = this || event.target || _global;
749 const listener = target[eventNameSymbol];
750 let result;
751 if (isBrowser && target === internalWindow && event.type === 'error') {
752 // window.onerror have different signiture
753 // https://developer.mozilla.org/en-US/docs/Web/API/GlobalEventHandlers/onerror#window.onerror
754 // and onerror callback will prevent default when callback return true
755 const errorEvent = event;
756 result = listener &&
757 listener.call(this, errorEvent.message, errorEvent.filename, errorEvent.lineno, errorEvent.colno, errorEvent.error);
758 if (result === true) {
759 event.preventDefault();
760 }
761 }
762 else {
763 result = listener && listener.apply(this, arguments);
764 if (result != undefined && !result) {
765 event.preventDefault();
766 }
767 }
768 return result;
769};
770function patchProperty(obj, prop, prototype) {
771 let desc = ObjectGetOwnPropertyDescriptor(obj, prop);
772 if (!desc && prototype) {
773 // when patch window object, use prototype to check prop exist or not
774 const prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop);
775 if (prototypeDesc) {
776 desc = { enumerable: true, configurable: true };
777 }
778 }
779 // if the descriptor not exists or is not configurable
780 // just return
781 if (!desc || !desc.configurable) {
782 return;
783 }
784 const onPropPatchedSymbol = zoneSymbol('on' + prop + 'patched');
785 if (obj.hasOwnProperty(onPropPatchedSymbol) && obj[onPropPatchedSymbol]) {
786 return;
787 }
788 // A property descriptor cannot have getter/setter and be writable
789 // deleting the writable and value properties avoids this error:
790 //
791 // TypeError: property descriptors must not specify a value or be writable when a
792 // getter or setter has been specified
793 delete desc.writable;
794 delete desc.value;
795 const originalDescGet = desc.get;
796 const originalDescSet = desc.set;
797 // substr(2) cuz 'onclick' -> 'click', etc
798 const eventName = prop.substr(2);
799 let eventNameSymbol = zoneSymbolEventNames[eventName];
800 if (!eventNameSymbol) {
801 eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName);
802 }
803 desc.set = function (newValue) {
804 // in some of windows's onproperty callback, this is undefined
805 // so we need to check it
806 let target = this;
807 if (!target && obj === _global) {
808 target = _global;
809 }
810 if (!target) {
811 return;
812 }
813 let previousValue = target[eventNameSymbol];
814 if (previousValue) {
815 target.removeEventListener(eventName, wrapFn);
816 }
817 // issue #978, when onload handler was added before loading zone.js
818 // we should remove it with originalDescSet
819 if (originalDescSet) {
820 originalDescSet.apply(target, NULL_ON_PROP_VALUE);
821 }
822 if (typeof newValue === 'function') {
823 target[eventNameSymbol] = newValue;
824 target.addEventListener(eventName, wrapFn, false);
825 }
826 else {
827 target[eventNameSymbol] = null;
828 }
829 };
830 // The getter would return undefined for unassigned properties but the default value of an
831 // unassigned property is null
832 desc.get = function () {
833 // in some of windows's onproperty callback, this is undefined
834 // so we need to check it
835 let target = this;
836 if (!target && obj === _global) {
837 target = _global;
838 }
839 if (!target) {
840 return null;
841 }
842 const listener = target[eventNameSymbol];
843 if (listener) {
844 return listener;
845 }
846 else if (originalDescGet) {
847 // result will be null when use inline event attribute,
848 // such as <button onclick="func();">OK</button>
849 // because the onclick function is internal raw uncompiled handler
850 // the onclick will be evaluated when first time event was triggered or
851 // the property is accessed, https://github.com/angular/zone.js/issues/525
852 // so we should use original native get to retrieve the handler
853 let value = originalDescGet && originalDescGet.call(this);
854 if (value) {
855 desc.set.call(this, value);
856 if (typeof target[REMOVE_ATTRIBUTE] === 'function') {
857 target.removeAttribute(prop);
858 }
859 return value;
860 }
861 }
862 return null;
863 };
864 ObjectDefineProperty(obj, prop, desc);
865 obj[onPropPatchedSymbol] = true;
866}
867function patchOnProperties(obj, properties, prototype) {
868 if (properties) {
869 for (let i = 0; i < properties.length; i++) {
870 patchProperty(obj, 'on' + properties[i], prototype);
871 }
872 }
873 else {
874 const onProperties = [];
875 for (const prop in obj) {
876 if (prop.substr(0, 2) == 'on') {
877 onProperties.push(prop);
878 }
879 }
880 for (let j = 0; j < onProperties.length; j++) {
881 patchProperty(obj, onProperties[j], prototype);
882 }
883 }
884}
885const originalInstanceKey = zoneSymbol('originalInstance');
886// wrap some native API on `window`
887function patchClass(className) {
888 const OriginalClass = _global[className];
889 if (!OriginalClass)
890 return;
891 // keep original class in global
892 _global[zoneSymbol(className)] = OriginalClass;
893 _global[className] = function () {
894 const a = bindArguments(arguments, className);
895 switch (a.length) {
896 case 0:
897 this[originalInstanceKey] = new OriginalClass();
898 break;
899 case 1:
900 this[originalInstanceKey] = new OriginalClass(a[0]);
901 break;
902 case 2:
903 this[originalInstanceKey] = new OriginalClass(a[0], a[1]);
904 break;
905 case 3:
906 this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]);
907 break;
908 case 4:
909 this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]);
910 break;
911 default:
912 throw new Error('Arg list too long.');
913 }
914 };
915 // attach original delegate to patched function
916 attachOriginToPatched(_global[className], OriginalClass);
917 const instance = new OriginalClass(function () { });
918 let prop;
919 for (prop in instance) {
920 // https://bugs.webkit.org/show_bug.cgi?id=44721
921 if (className === 'XMLHttpRequest' && prop === 'responseBlob')
922 continue;
923 (function (prop) {
924 if (typeof instance[prop] === 'function') {
925 _global[className].prototype[prop] = function () {
926 return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments);
927 };
928 }
929 else {
930 ObjectDefineProperty(_global[className].prototype, prop, {
931 set: function (fn) {
932 if (typeof fn === 'function') {
933 this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop);
934 // keep callback in wrapped function so we can
935 // use it in Function.prototype.toString to return
936 // the native one.
937 attachOriginToPatched(this[originalInstanceKey][prop], fn);
938 }
939 else {
940 this[originalInstanceKey][prop] = fn;
941 }
942 },
943 get: function () {
944 return this[originalInstanceKey][prop];
945 }
946 });
947 }
948 }(prop));
949 }
950 for (prop in OriginalClass) {
951 if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) {
952 _global[className][prop] = OriginalClass[prop];
953 }
954 }
955}
956function copySymbolProperties(src, dest) {
957 if (typeof Object.getOwnPropertySymbols !== 'function') {
958 return;
959 }
960 const symbols = Object.getOwnPropertySymbols(src);
961 symbols.forEach((symbol) => {
962 const desc = Object.getOwnPropertyDescriptor(src, symbol);
963 Object.defineProperty(dest, symbol, {
964 get: function () {
965 return src[symbol];
966 },
967 set: function (value) {
968 if (desc && (!desc.writable || typeof desc.set !== 'function')) {
969 // if src[symbol] is not writable or not have a setter, just return
970 return;
971 }
972 src[symbol] = value;
973 },
974 enumerable: desc ? desc.enumerable : true,
975 configurable: desc ? desc.configurable : true
976 });
977 });
978}
979let shouldCopySymbolProperties = false;
980function setShouldCopySymbolProperties(flag) {
981 shouldCopySymbolProperties = flag;
982}
983function patchMethod(target, name, patchFn) {
984 let proto = target;
985 while (proto && !proto.hasOwnProperty(name)) {
986 proto = ObjectGetPrototypeOf(proto);
987 }
988 if (!proto && target[name]) {
989 // somehow we did not find it, but we can see it. This happens on IE for Window properties.
990 proto = target;
991 }
992 const delegateName = zoneSymbol(name);
993 let delegate = null;
994 if (proto && (!(delegate = proto[delegateName]) || !proto.hasOwnProperty(delegateName))) {
995 delegate = proto[delegateName] = proto[name];
996 // check whether proto[name] is writable
997 // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob
998 const desc = proto && ObjectGetOwnPropertyDescriptor(proto, name);
999 if (isPropertyWritable(desc)) {
1000 const patchDelegate = patchFn(delegate, delegateName, name);
1001 proto[name] = function () {
1002 return patchDelegate(this, arguments);
1003 };
1004 attachOriginToPatched(proto[name], delegate);
1005 if (shouldCopySymbolProperties) {
1006 copySymbolProperties(delegate, proto[name]);
1007 }
1008 }
1009 }
1010 return delegate;
1011}
1012// TODO: @JiaLiPassion, support cancel task later if necessary
1013function patchMacroTask(obj, funcName, metaCreator) {
1014 let setNative = null;
1015 function scheduleTask(task) {
1016 const data = task.data;
1017 data.args[data.cbIdx] = function () {
1018 task.invoke.apply(this, arguments);
1019 };
1020 setNative.apply(data.target, data.args);
1021 return task;
1022 }
1023 setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
1024 const meta = metaCreator(self, args);
1025 if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
1026 return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask);
1027 }
1028 else {
1029 // cause an error by calling it directly.
1030 return delegate.apply(self, args);
1031 }
1032 });
1033}
1034function patchMicroTask(obj, funcName, metaCreator) {
1035 let setNative = null;
1036 function scheduleTask(task) {
1037 const data = task.data;
1038 data.args[data.cbIdx] = function () {
1039 task.invoke.apply(this, arguments);
1040 };
1041 setNative.apply(data.target, data.args);
1042 return task;
1043 }
1044 setNative = patchMethod(obj, funcName, (delegate) => function (self, args) {
1045 const meta = metaCreator(self, args);
1046 if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') {
1047 return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask);
1048 }
1049 else {
1050 // cause an error by calling it directly.
1051 return delegate.apply(self, args);
1052 }
1053 });
1054}
1055function attachOriginToPatched(patched, original) {
1056 patched[zoneSymbol('OriginalDelegate')] = original;
1057}
1058let isDetectedIEOrEdge = false;
1059let ieOrEdge = false;
1060function isIE() {
1061 try {
1062 const ua = internalWindow.navigator.userAgent;
1063 if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1) {
1064 return true;
1065 }
1066 }
1067 catch (error) {
1068 }
1069 return false;
1070}
1071function isIEOrEdge() {
1072 if (isDetectedIEOrEdge) {
1073 return ieOrEdge;
1074 }
1075 isDetectedIEOrEdge = true;
1076 try {
1077 const ua = internalWindow.navigator.userAgent;
1078 if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) {
1079 ieOrEdge = true;
1080 }
1081 }
1082 catch (error) {
1083 }
1084 return ieOrEdge;
1085}
1086
1087/**
1088 * @license
1089 * Copyright Google LLC All Rights Reserved.
1090 *
1091 * Use of this source code is governed by an MIT-style license that can be
1092 * found in the LICENSE file at https://angular.io/license
1093 */
1094Zone.__load_patch('ZoneAwarePromise', (global, Zone, api) => {
1095 const ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor;
1096 const ObjectDefineProperty = Object.defineProperty;
1097 function readableObjectToString(obj) {
1098 if (obj && obj.toString === Object.prototype.toString) {
1099 const className = obj.constructor && obj.constructor.name;
1100 return (className ? className : '') + ': ' + JSON.stringify(obj);
1101 }
1102 return obj ? obj.toString() : Object.prototype.toString.call(obj);
1103 }
1104 const __symbol__ = api.symbol;
1105 const _uncaughtPromiseErrors = [];
1106 const isDisableWrappingUncaughtPromiseRejection = global[__symbol__('DISABLE_WRAPPING_UNCAUGHT_PROMISE_REJECTION')] === true;
1107 const symbolPromise = __symbol__('Promise');
1108 const symbolThen = __symbol__('then');
1109 const creationTrace = '__creationTrace__';
1110 api.onUnhandledError = (e) => {
1111 if (api.showUncaughtError()) {
1112 const rejection = e && e.rejection;
1113 if (rejection) {
1114 console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined);
1115 }
1116 else {
1117 console.error(e);
1118 }
1119 }
1120 };
1121 api.microtaskDrainDone = () => {
1122 while (_uncaughtPromiseErrors.length) {
1123 const uncaughtPromiseError = _uncaughtPromiseErrors.shift();
1124 try {
1125 uncaughtPromiseError.zone.runGuarded(() => {
1126 if (uncaughtPromiseError.throwOriginal) {
1127 throw uncaughtPromiseError.rejection;
1128 }
1129 throw uncaughtPromiseError;
1130 });
1131 }
1132 catch (error) {
1133 handleUnhandledRejection(error);
1134 }
1135 }
1136 };
1137 const UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler');
1138 function handleUnhandledRejection(e) {
1139 api.onUnhandledError(e);
1140 try {
1141 const handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL];
1142 if (typeof handler === 'function') {
1143 handler.call(this, e);
1144 }
1145 }
1146 catch (err) {
1147 }
1148 }
1149 function isThenable(value) {
1150 return value && value.then;
1151 }
1152 function forwardResolution(value) {
1153 return value;
1154 }
1155 function forwardRejection(rejection) {
1156 return ZoneAwarePromise.reject(rejection);
1157 }
1158 const symbolState = __symbol__('state');
1159 const symbolValue = __symbol__('value');
1160 const symbolFinally = __symbol__('finally');
1161 const symbolParentPromiseValue = __symbol__('parentPromiseValue');
1162 const symbolParentPromiseState = __symbol__('parentPromiseState');
1163 const source = 'Promise.then';
1164 const UNRESOLVED = null;
1165 const RESOLVED = true;
1166 const REJECTED = false;
1167 const REJECTED_NO_CATCH = 0;
1168 function makeResolver(promise, state) {
1169 return (v) => {
1170 try {
1171 resolvePromise(promise, state, v);
1172 }
1173 catch (err) {
1174 resolvePromise(promise, false, err);
1175 }
1176 // Do not return value or you will break the Promise spec.
1177 };
1178 }
1179 const once = function () {
1180 let wasCalled = false;
1181 return function wrapper(wrappedFunction) {
1182 return function () {
1183 if (wasCalled) {
1184 return;
1185 }
1186 wasCalled = true;
1187 wrappedFunction.apply(null, arguments);
1188 };
1189 };
1190 };
1191 const TYPE_ERROR = 'Promise resolved with itself';
1192 const CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace');
1193 // Promise Resolution
1194 function resolvePromise(promise, state, value) {
1195 const onceWrapper = once();
1196 if (promise === value) {
1197 throw new TypeError(TYPE_ERROR);
1198 }
1199 if (promise[symbolState] === UNRESOLVED) {
1200 // should only get value.then once based on promise spec.
1201 let then = null;
1202 try {
1203 if (typeof value === 'object' || typeof value === 'function') {
1204 then = value && value.then;
1205 }
1206 }
1207 catch (err) {
1208 onceWrapper(() => {
1209 resolvePromise(promise, false, err);
1210 })();
1211 return promise;
1212 }
1213 // if (value instanceof ZoneAwarePromise) {
1214 if (state !== REJECTED && value instanceof ZoneAwarePromise &&
1215 value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) &&
1216 value[symbolState] !== UNRESOLVED) {
1217 clearRejectedNoCatch(value);
1218 resolvePromise(promise, value[symbolState], value[symbolValue]);
1219 }
1220 else if (state !== REJECTED && typeof then === 'function') {
1221 try {
1222 then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false)));
1223 }
1224 catch (err) {
1225 onceWrapper(() => {
1226 resolvePromise(promise, false, err);
1227 })();
1228 }
1229 }
1230 else {
1231 promise[symbolState] = state;
1232 const queue = promise[symbolValue];
1233 promise[symbolValue] = value;
1234 if (promise[symbolFinally] === symbolFinally) {
1235 // the promise is generated by Promise.prototype.finally
1236 if (state === RESOLVED) {
1237 // the state is resolved, should ignore the value
1238 // and use parent promise value
1239 promise[symbolState] = promise[symbolParentPromiseState];
1240 promise[symbolValue] = promise[symbolParentPromiseValue];
1241 }
1242 }
1243 // record task information in value when error occurs, so we can
1244 // do some additional work such as render longStackTrace
1245 if (state === REJECTED && value instanceof Error) {
1246 // check if longStackTraceZone is here
1247 const trace = Zone.currentTask && Zone.currentTask.data &&
1248 Zone.currentTask.data[creationTrace];
1249 if (trace) {
1250 // only keep the long stack trace into error when in longStackTraceZone
1251 ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace });
1252 }
1253 }
1254 for (let i = 0; i < queue.length;) {
1255 scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]);
1256 }
1257 if (queue.length == 0 && state == REJECTED) {
1258 promise[symbolState] = REJECTED_NO_CATCH;
1259 let uncaughtPromiseError = value;
1260 try {
1261 // Here we throws a new Error to print more readable error log
1262 // and if the value is not an error, zone.js builds an `Error`
1263 // Object here to attach the stack information.
1264 throw new Error('Uncaught (in promise): ' + readableObjectToString(value) +
1265 (value && value.stack ? '\n' + value.stack : ''));
1266 }
1267 catch (err) {
1268 uncaughtPromiseError = err;
1269 }
1270 if (isDisableWrappingUncaughtPromiseRejection) {
1271 // If disable wrapping uncaught promise reject
1272 // use the value instead of wrapping it.
1273 uncaughtPromiseError.throwOriginal = true;
1274 }
1275 uncaughtPromiseError.rejection = value;
1276 uncaughtPromiseError.promise = promise;
1277 uncaughtPromiseError.zone = Zone.current;
1278 uncaughtPromiseError.task = Zone.currentTask;
1279 _uncaughtPromiseErrors.push(uncaughtPromiseError);
1280 api.scheduleMicroTask(); // to make sure that it is running
1281 }
1282 }
1283 }
1284 // Resolving an already resolved promise is a noop.
1285 return promise;
1286 }
1287 const REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler');
1288 function clearRejectedNoCatch(promise) {
1289 if (promise[symbolState] === REJECTED_NO_CATCH) {
1290 // if the promise is rejected no catch status
1291 // and queue.length > 0, means there is a error handler
1292 // here to handle the rejected promise, we should trigger
1293 // windows.rejectionhandled eventHandler or nodejs rejectionHandled
1294 // eventHandler
1295 try {
1296 const handler = Zone[REJECTION_HANDLED_HANDLER];
1297 if (handler && typeof handler === 'function') {
1298 handler.call(this, { rejection: promise[symbolValue], promise: promise });
1299 }
1300 }
1301 catch (err) {
1302 }
1303 promise[symbolState] = REJECTED;
1304 for (let i = 0; i < _uncaughtPromiseErrors.length; i++) {
1305 if (promise === _uncaughtPromiseErrors[i].promise) {
1306 _uncaughtPromiseErrors.splice(i, 1);
1307 }
1308 }
1309 }
1310 }
1311 function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) {
1312 clearRejectedNoCatch(promise);
1313 const promiseState = promise[symbolState];
1314 const delegate = promiseState ?
1315 (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution :
1316 (typeof onRejected === 'function') ? onRejected : forwardRejection;
1317 zone.scheduleMicroTask(source, () => {
1318 try {
1319 const parentPromiseValue = promise[symbolValue];
1320 const isFinallyPromise = !!chainPromise && symbolFinally === chainPromise[symbolFinally];
1321 if (isFinallyPromise) {
1322 // if the promise is generated from finally call, keep parent promise's state and value
1323 chainPromise[symbolParentPromiseValue] = parentPromiseValue;
1324 chainPromise[symbolParentPromiseState] = promiseState;
1325 }
1326 // should not pass value to finally callback
1327 const value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ?
1328 [] :
1329 [parentPromiseValue]);
1330 resolvePromise(chainPromise, true, value);
1331 }
1332 catch (error) {
1333 // if error occurs, should always return this error
1334 resolvePromise(chainPromise, false, error);
1335 }
1336 }, chainPromise);
1337 }
1338 const ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }';
1339 const noop = function () { };
1340 class ZoneAwarePromise {
1341 static toString() {
1342 return ZONE_AWARE_PROMISE_TO_STRING;
1343 }
1344 static resolve(value) {
1345 return resolvePromise(new this(null), RESOLVED, value);
1346 }
1347 static reject(error) {
1348 return resolvePromise(new this(null), REJECTED, error);
1349 }
1350 static race(values) {
1351 let resolve;
1352 let reject;
1353 let promise = new this((res, rej) => {
1354 resolve = res;
1355 reject = rej;
1356 });
1357 function onResolve(value) {
1358 resolve(value);
1359 }
1360 function onReject(error) {
1361 reject(error);
1362 }
1363 for (let value of values) {
1364 if (!isThenable(value)) {
1365 value = this.resolve(value);
1366 }
1367 value.then(onResolve, onReject);
1368 }
1369 return promise;
1370 }
1371 static all(values) {
1372 return ZoneAwarePromise.allWithCallback(values);
1373 }
1374 static allSettled(values) {
1375 const P = this && this.prototype instanceof ZoneAwarePromise ? this : ZoneAwarePromise;
1376 return P.allWithCallback(values, {
1377 thenCallback: (value) => ({ status: 'fulfilled', value }),
1378 errorCallback: (err) => ({ status: 'rejected', reason: err })
1379 });
1380 }
1381 static allWithCallback(values, callback) {
1382 let resolve;
1383 let reject;
1384 let promise = new this((res, rej) => {
1385 resolve = res;
1386 reject = rej;
1387 });
1388 // Start at 2 to prevent prematurely resolving if .then is called immediately.
1389 let unresolvedCount = 2;
1390 let valueIndex = 0;
1391 const resolvedValues = [];
1392 for (let value of values) {
1393 if (!isThenable(value)) {
1394 value = this.resolve(value);
1395 }
1396 const curValueIndex = valueIndex;
1397 try {
1398 value.then((value) => {
1399 resolvedValues[curValueIndex] = callback ? callback.thenCallback(value) : value;
1400 unresolvedCount--;
1401 if (unresolvedCount === 0) {
1402 resolve(resolvedValues);
1403 }
1404 }, (err) => {
1405 if (!callback) {
1406 reject(err);
1407 }
1408 else {
1409 resolvedValues[curValueIndex] = callback.errorCallback(err);
1410 unresolvedCount--;
1411 if (unresolvedCount === 0) {
1412 resolve(resolvedValues);
1413 }
1414 }
1415 });
1416 }
1417 catch (thenErr) {
1418 reject(thenErr);
1419 }
1420 unresolvedCount++;
1421 valueIndex++;
1422 }
1423 // Make the unresolvedCount zero-based again.
1424 unresolvedCount -= 2;
1425 if (unresolvedCount === 0) {
1426 resolve(resolvedValues);
1427 }
1428 return promise;
1429 }
1430 constructor(executor) {
1431 const promise = this;
1432 if (!(promise instanceof ZoneAwarePromise)) {
1433 throw new Error('Must be an instanceof Promise.');
1434 }
1435 promise[symbolState] = UNRESOLVED;
1436 promise[symbolValue] = []; // queue;
1437 try {
1438 executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED));
1439 }
1440 catch (error) {
1441 resolvePromise(promise, false, error);
1442 }
1443 }
1444 get [Symbol.toStringTag]() {
1445 return 'Promise';
1446 }
1447 get [Symbol.species]() {
1448 return ZoneAwarePromise;
1449 }
1450 then(onFulfilled, onRejected) {
1451 let C = this.constructor[Symbol.species];
1452 if (!C || typeof C !== 'function') {
1453 C = this.constructor || ZoneAwarePromise;
1454 }
1455 const chainPromise = new C(noop);
1456 const zone = Zone.current;
1457 if (this[symbolState] == UNRESOLVED) {
1458 this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected);
1459 }
1460 else {
1461 scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected);
1462 }
1463 return chainPromise;
1464 }
1465 catch(onRejected) {
1466 return this.then(null, onRejected);
1467 }
1468 finally(onFinally) {
1469 let C = this.constructor[Symbol.species];
1470 if (!C || typeof C !== 'function') {
1471 C = ZoneAwarePromise;
1472 }
1473 const chainPromise = new C(noop);
1474 chainPromise[symbolFinally] = symbolFinally;
1475 const zone = Zone.current;
1476 if (this[symbolState] == UNRESOLVED) {
1477 this[symbolValue].push(zone, chainPromise, onFinally, onFinally);
1478 }
1479 else {
1480 scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally);
1481 }
1482 return chainPromise;
1483 }
1484 }
1485 // Protect against aggressive optimizers dropping seemingly unused properties.
1486 // E.g. Closure Compiler in advanced mode.
1487 ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve;
1488 ZoneAwarePromise['reject'] = ZoneAwarePromise.reject;
1489 ZoneAwarePromise['race'] = ZoneAwarePromise.race;
1490 ZoneAwarePromise['all'] = ZoneAwarePromise.all;
1491 const NativePromise = global[symbolPromise] = global['Promise'];
1492 global['Promise'] = ZoneAwarePromise;
1493 const symbolThenPatched = __symbol__('thenPatched');
1494 function patchThen(Ctor) {
1495 const proto = Ctor.prototype;
1496 const prop = ObjectGetOwnPropertyDescriptor(proto, 'then');
1497 if (prop && (prop.writable === false || !prop.configurable)) {
1498 // check Ctor.prototype.then propertyDescriptor is writable or not
1499 // in meteor env, writable is false, we should ignore such case
1500 return;
1501 }
1502 const originalThen = proto.then;
1503 // Keep a reference to the original method.
1504 proto[symbolThen] = originalThen;
1505 Ctor.prototype.then = function (onResolve, onReject) {
1506 const wrapped = new ZoneAwarePromise((resolve, reject) => {
1507 originalThen.call(this, resolve, reject);
1508 });
1509 return wrapped.then(onResolve, onReject);
1510 };
1511 Ctor[symbolThenPatched] = true;
1512 }
1513 api.patchThen = patchThen;
1514 function zoneify(fn) {
1515 return function (self, args) {
1516 let resultPromise = fn.apply(self, args);
1517 if (resultPromise instanceof ZoneAwarePromise) {
1518 return resultPromise;
1519 }
1520 let ctor = resultPromise.constructor;
1521 if (!ctor[symbolThenPatched]) {
1522 patchThen(ctor);
1523 }
1524 return resultPromise;
1525 };
1526 }
1527 if (NativePromise) {
1528 patchThen(NativePromise);
1529 patchMethod(global, 'fetch', delegate => zoneify(delegate));
1530 }
1531 // This is not part of public API, but it is useful for tests, so we expose it.
1532 Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors;
1533 return ZoneAwarePromise;
1534});
1535
1536/**
1537 * @license
1538 * Copyright Google LLC All Rights Reserved.
1539 *
1540 * Use of this source code is governed by an MIT-style license that can be
1541 * found in the LICENSE file at https://angular.io/license
1542 */
1543// override Function.prototype.toString to make zone.js patched function
1544// look like native function
1545Zone.__load_patch('toString', (global) => {
1546 // patch Func.prototype.toString to let them look like native
1547 const originalFunctionToString = Function.prototype.toString;
1548 const ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate');
1549 const PROMISE_SYMBOL = zoneSymbol('Promise');
1550 const ERROR_SYMBOL = zoneSymbol('Error');
1551 const newFunctionToString = function toString() {
1552 if (typeof this === 'function') {
1553 const originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL];
1554 if (originalDelegate) {
1555 if (typeof originalDelegate === 'function') {
1556 return originalFunctionToString.call(originalDelegate);
1557 }
1558 else {
1559 return Object.prototype.toString.call(originalDelegate);
1560 }
1561 }
1562 if (this === Promise) {
1563 const nativePromise = global[PROMISE_SYMBOL];
1564 if (nativePromise) {
1565 return originalFunctionToString.call(nativePromise);
1566 }
1567 }
1568 if (this === Error) {
1569 const nativeError = global[ERROR_SYMBOL];
1570 if (nativeError) {
1571 return originalFunctionToString.call(nativeError);
1572 }
1573 }
1574 }
1575 return originalFunctionToString.call(this);
1576 };
1577 newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString;
1578 Function.prototype.toString = newFunctionToString;
1579 // patch Object.prototype.toString to let them look like native
1580 const originalObjectToString = Object.prototype.toString;
1581 const PROMISE_OBJECT_TO_STRING = '[object Promise]';
1582 Object.prototype.toString = function () {
1583 if (typeof Promise === 'function' && this instanceof Promise) {
1584 return PROMISE_OBJECT_TO_STRING;
1585 }
1586 return originalObjectToString.call(this);
1587 };
1588});
1589
1590/**
1591 * @license
1592 * Copyright Google LLC All Rights Reserved.
1593 *
1594 * Use of this source code is governed by an MIT-style license that can be
1595 * found in the LICENSE file at https://angular.io/license
1596 */
1597let passiveSupported = false;
1598if (typeof window !== 'undefined') {
1599 try {
1600 const options = Object.defineProperty({}, 'passive', {
1601 get: function () {
1602 passiveSupported = true;
1603 }
1604 });
1605 window.addEventListener('test', options, options);
1606 window.removeEventListener('test', options, options);
1607 }
1608 catch (err) {
1609 passiveSupported = false;
1610 }
1611}
1612// an identifier to tell ZoneTask do not create a new invoke closure
1613const OPTIMIZED_ZONE_EVENT_TASK_DATA = {
1614 useG: true
1615};
1616const zoneSymbolEventNames$1 = {};
1617const globalSources = {};
1618const EVENT_NAME_SYMBOL_REGX = new RegExp('^' + ZONE_SYMBOL_PREFIX + '(\\w+)(true|false)$');
1619const IMMEDIATE_PROPAGATION_SYMBOL = zoneSymbol('propagationStopped');
1620function prepareEventNames(eventName, eventNameToString) {
1621 const falseEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + FALSE_STR;
1622 const trueEventName = (eventNameToString ? eventNameToString(eventName) : eventName) + TRUE_STR;
1623 const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
1624 const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
1625 zoneSymbolEventNames$1[eventName] = {};
1626 zoneSymbolEventNames$1[eventName][FALSE_STR] = symbol;
1627 zoneSymbolEventNames$1[eventName][TRUE_STR] = symbolCapture;
1628}
1629function patchEventTarget(_global, apis, patchOptions) {
1630 const ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR;
1631 const REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR;
1632 const LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners';
1633 const REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners';
1634 const zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER);
1635 const ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':';
1636 const PREPEND_EVENT_LISTENER = 'prependListener';
1637 const PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':';
1638 const invokeTask = function (task, target, event) {
1639 // for better performance, check isRemoved which is set
1640 // by removeEventListener
1641 if (task.isRemoved) {
1642 return;
1643 }
1644 const delegate = task.callback;
1645 if (typeof delegate === 'object' && delegate.handleEvent) {
1646 // create the bind version of handleEvent when invoke
1647 task.callback = (event) => delegate.handleEvent(event);
1648 task.originalDelegate = delegate;
1649 }
1650 // invoke static task.invoke
1651 task.invoke(task, target, [event]);
1652 const options = task.options;
1653 if (options && typeof options === 'object' && options.once) {
1654 // if options.once is true, after invoke once remove listener here
1655 // only browser need to do this, nodejs eventEmitter will cal removeListener
1656 // inside EventEmitter.once
1657 const delegate = task.originalDelegate ? task.originalDelegate : task.callback;
1658 target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate, options);
1659 }
1660 };
1661 // global shared zoneAwareCallback to handle all event callback with capture = false
1662 const globalZoneAwareCallback = function (event) {
1663 // https://github.com/angular/zone.js/issues/911, in IE, sometimes
1664 // event will be undefined, so we need to use window.event
1665 event = event || _global.event;
1666 if (!event) {
1667 return;
1668 }
1669 // event.target is needed for Samsung TV and SourceBuffer
1670 // || global is needed https://github.com/angular/zone.js/issues/190
1671 const target = this || event.target || _global;
1672 const tasks = target[zoneSymbolEventNames$1[event.type][FALSE_STR]];
1673 if (tasks) {
1674 // invoke all tasks which attached to current target with given event.type and capture = false
1675 // for performance concern, if task.length === 1, just invoke
1676 if (tasks.length === 1) {
1677 invokeTask(tasks[0], target, event);
1678 }
1679 else {
1680 // https://github.com/angular/zone.js/issues/836
1681 // copy the tasks array before invoke, to avoid
1682 // the callback will remove itself or other listener
1683 const copyTasks = tasks.slice();
1684 for (let i = 0; i < copyTasks.length; i++) {
1685 if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
1686 break;
1687 }
1688 invokeTask(copyTasks[i], target, event);
1689 }
1690 }
1691 }
1692 };
1693 // global shared zoneAwareCallback to handle all event callback with capture = true
1694 const globalZoneAwareCaptureCallback = function (event) {
1695 // https://github.com/angular/zone.js/issues/911, in IE, sometimes
1696 // event will be undefined, so we need to use window.event
1697 event = event || _global.event;
1698 if (!event) {
1699 return;
1700 }
1701 // event.target is needed for Samsung TV and SourceBuffer
1702 // || global is needed https://github.com/angular/zone.js/issues/190
1703 const target = this || event.target || _global;
1704 const tasks = target[zoneSymbolEventNames$1[event.type][TRUE_STR]];
1705 if (tasks) {
1706 // invoke all tasks which attached to current target with given event.type and capture = false
1707 // for performance concern, if task.length === 1, just invoke
1708 if (tasks.length === 1) {
1709 invokeTask(tasks[0], target, event);
1710 }
1711 else {
1712 // https://github.com/angular/zone.js/issues/836
1713 // copy the tasks array before invoke, to avoid
1714 // the callback will remove itself or other listener
1715 const copyTasks = tasks.slice();
1716 for (let i = 0; i < copyTasks.length; i++) {
1717 if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) {
1718 break;
1719 }
1720 invokeTask(copyTasks[i], target, event);
1721 }
1722 }
1723 }
1724 };
1725 function patchEventTargetMethods(obj, patchOptions) {
1726 if (!obj) {
1727 return false;
1728 }
1729 let useGlobalCallback = true;
1730 if (patchOptions && patchOptions.useG !== undefined) {
1731 useGlobalCallback = patchOptions.useG;
1732 }
1733 const validateHandler = patchOptions && patchOptions.vh;
1734 let checkDuplicate = true;
1735 if (patchOptions && patchOptions.chkDup !== undefined) {
1736 checkDuplicate = patchOptions.chkDup;
1737 }
1738 let returnTarget = false;
1739 if (patchOptions && patchOptions.rt !== undefined) {
1740 returnTarget = patchOptions.rt;
1741 }
1742 let proto = obj;
1743 while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) {
1744 proto = ObjectGetPrototypeOf(proto);
1745 }
1746 if (!proto && obj[ADD_EVENT_LISTENER]) {
1747 // somehow we did not find it, but we can see it. This happens on IE for Window properties.
1748 proto = obj;
1749 }
1750 if (!proto) {
1751 return false;
1752 }
1753 if (proto[zoneSymbolAddEventListener]) {
1754 return false;
1755 }
1756 const eventNameToString = patchOptions && patchOptions.eventNameToString;
1757 // a shared global taskData to pass data for scheduleEventTask
1758 // so we do not need to create a new object just for pass some data
1759 const taskData = {};
1760 const nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER];
1761 const nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] =
1762 proto[REMOVE_EVENT_LISTENER];
1763 const nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] =
1764 proto[LISTENERS_EVENT_LISTENER];
1765 const nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] =
1766 proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER];
1767 let nativePrependEventListener;
1768 if (patchOptions && patchOptions.prepend) {
1769 nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] =
1770 proto[patchOptions.prepend];
1771 }
1772 /**
1773 * This util function will build an option object with passive option
1774 * to handle all possible input from the user.
1775 */
1776 function buildEventListenerOptions(options, passive) {
1777 if (!passiveSupported && typeof options === 'object' && options) {
1778 // doesn't support passive but user want to pass an object as options.
1779 // this will not work on some old browser, so we just pass a boolean
1780 // as useCapture parameter
1781 return !!options.capture;
1782 }
1783 if (!passiveSupported || !passive) {
1784 return options;
1785 }
1786 if (typeof options === 'boolean') {
1787 return { capture: options, passive: true };
1788 }
1789 if (!options) {
1790 return { passive: true };
1791 }
1792 if (typeof options === 'object' && options.passive !== false) {
1793 return Object.assign(Object.assign({}, options), { passive: true });
1794 }
1795 return options;
1796 }
1797 const customScheduleGlobal = function (task) {
1798 // if there is already a task for the eventName + capture,
1799 // just return, because we use the shared globalZoneAwareCallback here.
1800 if (taskData.isExisting) {
1801 return;
1802 }
1803 return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options);
1804 };
1805 const customCancelGlobal = function (task) {
1806 // if task is not marked as isRemoved, this call is directly
1807 // from Zone.prototype.cancelTask, we should remove the task
1808 // from tasksList of target first
1809 if (!task.isRemoved) {
1810 const symbolEventNames = zoneSymbolEventNames$1[task.eventName];
1811 let symbolEventName;
1812 if (symbolEventNames) {
1813 symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR];
1814 }
1815 const existingTasks = symbolEventName && task.target[symbolEventName];
1816 if (existingTasks) {
1817 for (let i = 0; i < existingTasks.length; i++) {
1818 const existingTask = existingTasks[i];
1819 if (existingTask === task) {
1820 existingTasks.splice(i, 1);
1821 // set isRemoved to data for faster invokeTask check
1822 task.isRemoved = true;
1823 if (existingTasks.length === 0) {
1824 // all tasks for the eventName + capture have gone,
1825 // remove globalZoneAwareCallback and remove the task cache from target
1826 task.allRemoved = true;
1827 task.target[symbolEventName] = null;
1828 }
1829 break;
1830 }
1831 }
1832 }
1833 }
1834 // if all tasks for the eventName + capture have gone,
1835 // we will really remove the global event callback,
1836 // if not, return
1837 if (!task.allRemoved) {
1838 return;
1839 }
1840 return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options);
1841 };
1842 const customScheduleNonGlobal = function (task) {
1843 return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
1844 };
1845 const customSchedulePrepend = function (task) {
1846 return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options);
1847 };
1848 const customCancelNonGlobal = function (task) {
1849 return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options);
1850 };
1851 const customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal;
1852 const customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal;
1853 const compareTaskCallbackVsDelegate = function (task, delegate) {
1854 const typeOfDelegate = typeof delegate;
1855 return (typeOfDelegate === 'function' && task.callback === delegate) ||
1856 (typeOfDelegate === 'object' && task.originalDelegate === delegate);
1857 };
1858 const compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate;
1859 const unpatchedEvents = Zone[zoneSymbol('UNPATCHED_EVENTS')];
1860 const passiveEvents = _global[zoneSymbol('PASSIVE_EVENTS')];
1861 const makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget = false, prepend = false) {
1862 return function () {
1863 const target = this || _global;
1864 let eventName = arguments[0];
1865 if (patchOptions && patchOptions.transferEventName) {
1866 eventName = patchOptions.transferEventName(eventName);
1867 }
1868 let delegate = arguments[1];
1869 if (!delegate) {
1870 return nativeListener.apply(this, arguments);
1871 }
1872 if (isNode && eventName === 'uncaughtException') {
1873 // don't patch uncaughtException of nodejs to prevent endless loop
1874 return nativeListener.apply(this, arguments);
1875 }
1876 // don't create the bind delegate function for handleEvent
1877 // case here to improve addEventListener performance
1878 // we will create the bind delegate when invoke
1879 let isHandleEvent = false;
1880 if (typeof delegate !== 'function') {
1881 if (!delegate.handleEvent) {
1882 return nativeListener.apply(this, arguments);
1883 }
1884 isHandleEvent = true;
1885 }
1886 if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) {
1887 return;
1888 }
1889 const passive = passiveSupported && !!passiveEvents && passiveEvents.indexOf(eventName) !== -1;
1890 const options = buildEventListenerOptions(arguments[2], passive);
1891 if (unpatchedEvents) {
1892 // check upatched list
1893 for (let i = 0; i < unpatchedEvents.length; i++) {
1894 if (eventName === unpatchedEvents[i]) {
1895 if (passive) {
1896 return nativeListener.call(target, eventName, delegate, options);
1897 }
1898 else {
1899 return nativeListener.apply(this, arguments);
1900 }
1901 }
1902 }
1903 }
1904 const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
1905 const once = options && typeof options === 'object' ? options.once : false;
1906 const zone = Zone.current;
1907 let symbolEventNames = zoneSymbolEventNames$1[eventName];
1908 if (!symbolEventNames) {
1909 prepareEventNames(eventName, eventNameToString);
1910 symbolEventNames = zoneSymbolEventNames$1[eventName];
1911 }
1912 const symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
1913 let existingTasks = target[symbolEventName];
1914 let isExisting = false;
1915 if (existingTasks) {
1916 // already have task registered
1917 isExisting = true;
1918 if (checkDuplicate) {
1919 for (let i = 0; i < existingTasks.length; i++) {
1920 if (compare(existingTasks[i], delegate)) {
1921 // same callback, same capture, same event name, just return
1922 return;
1923 }
1924 }
1925 }
1926 }
1927 else {
1928 existingTasks = target[symbolEventName] = [];
1929 }
1930 let source;
1931 const constructorName = target.constructor['name'];
1932 const targetSource = globalSources[constructorName];
1933 if (targetSource) {
1934 source = targetSource[eventName];
1935 }
1936 if (!source) {
1937 source = constructorName + addSource +
1938 (eventNameToString ? eventNameToString(eventName) : eventName);
1939 }
1940 // do not create a new object as task.data to pass those things
1941 // just use the global shared one
1942 taskData.options = options;
1943 if (once) {
1944 // if addEventListener with once options, we don't pass it to
1945 // native addEventListener, instead we keep the once setting
1946 // and handle ourselves.
1947 taskData.options.once = false;
1948 }
1949 taskData.target = target;
1950 taskData.capture = capture;
1951 taskData.eventName = eventName;
1952 taskData.isExisting = isExisting;
1953 const data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : undefined;
1954 // keep taskData into data to allow onScheduleEventTask to access the task information
1955 if (data) {
1956 data.taskData = taskData;
1957 }
1958 const task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn);
1959 // should clear taskData.target to avoid memory leak
1960 // issue, https://github.com/angular/angular/issues/20442
1961 taskData.target = null;
1962 // need to clear up taskData because it is a global object
1963 if (data) {
1964 data.taskData = null;
1965 }
1966 // have to save those information to task in case
1967 // application may call task.zone.cancelTask() directly
1968 if (once) {
1969 options.once = true;
1970 }
1971 if (!(!passiveSupported && typeof task.options === 'boolean')) {
1972 // if not support passive, and we pass an option object
1973 // to addEventListener, we should save the options to task
1974 task.options = options;
1975 }
1976 task.target = target;
1977 task.capture = capture;
1978 task.eventName = eventName;
1979 if (isHandleEvent) {
1980 // save original delegate for compare to check duplicate
1981 task.originalDelegate = delegate;
1982 }
1983 if (!prepend) {
1984 existingTasks.push(task);
1985 }
1986 else {
1987 existingTasks.unshift(task);
1988 }
1989 if (returnTarget) {
1990 return target;
1991 }
1992 };
1993 };
1994 proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget);
1995 if (nativePrependEventListener) {
1996 proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true);
1997 }
1998 proto[REMOVE_EVENT_LISTENER] = function () {
1999 const target = this || _global;
2000 let eventName = arguments[0];
2001 if (patchOptions && patchOptions.transferEventName) {
2002 eventName = patchOptions.transferEventName(eventName);
2003 }
2004 const options = arguments[2];
2005 const capture = !options ? false : typeof options === 'boolean' ? true : options.capture;
2006 const delegate = arguments[1];
2007 if (!delegate) {
2008 return nativeRemoveEventListener.apply(this, arguments);
2009 }
2010 if (validateHandler &&
2011 !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) {
2012 return;
2013 }
2014 const symbolEventNames = zoneSymbolEventNames$1[eventName];
2015 let symbolEventName;
2016 if (symbolEventNames) {
2017 symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR];
2018 }
2019 const existingTasks = symbolEventName && target[symbolEventName];
2020 if (existingTasks) {
2021 for (let i = 0; i < existingTasks.length; i++) {
2022 const existingTask = existingTasks[i];
2023 if (compare(existingTask, delegate)) {
2024 existingTasks.splice(i, 1);
2025 // set isRemoved to data for faster invokeTask check
2026 existingTask.isRemoved = true;
2027 if (existingTasks.length === 0) {
2028 // all tasks for the eventName + capture have gone,
2029 // remove globalZoneAwareCallback and remove the task cache from target
2030 existingTask.allRemoved = true;
2031 target[symbolEventName] = null;
2032 // in the target, we have an event listener which is added by on_property
2033 // such as target.onclick = function() {}, so we need to clear this internal
2034 // property too if all delegates all removed
2035 if (typeof eventName === 'string') {
2036 const onPropertySymbol = ZONE_SYMBOL_PREFIX + 'ON_PROPERTY' + eventName;
2037 target[onPropertySymbol] = null;
2038 }
2039 }
2040 existingTask.zone.cancelTask(existingTask);
2041 if (returnTarget) {
2042 return target;
2043 }
2044 return;
2045 }
2046 }
2047 }
2048 // issue 930, didn't find the event name or callback
2049 // from zone kept existingTasks, the callback maybe
2050 // added outside of zone, we need to call native removeEventListener
2051 // to try to remove it.
2052 return nativeRemoveEventListener.apply(this, arguments);
2053 };
2054 proto[LISTENERS_EVENT_LISTENER] = function () {
2055 const target = this || _global;
2056 let eventName = arguments[0];
2057 if (patchOptions && patchOptions.transferEventName) {
2058 eventName = patchOptions.transferEventName(eventName);
2059 }
2060 const listeners = [];
2061 const tasks = findEventTasks(target, eventNameToString ? eventNameToString(eventName) : eventName);
2062 for (let i = 0; i < tasks.length; i++) {
2063 const task = tasks[i];
2064 let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
2065 listeners.push(delegate);
2066 }
2067 return listeners;
2068 };
2069 proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () {
2070 const target = this || _global;
2071 let eventName = arguments[0];
2072 if (!eventName) {
2073 const keys = Object.keys(target);
2074 for (let i = 0; i < keys.length; i++) {
2075 const prop = keys[i];
2076 const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
2077 let evtName = match && match[1];
2078 // in nodejs EventEmitter, removeListener event is
2079 // used for monitoring the removeListener call,
2080 // so just keep removeListener eventListener until
2081 // all other eventListeners are removed
2082 if (evtName && evtName !== 'removeListener') {
2083 this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName);
2084 }
2085 }
2086 // remove removeListener listener finally
2087 this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener');
2088 }
2089 else {
2090 if (patchOptions && patchOptions.transferEventName) {
2091 eventName = patchOptions.transferEventName(eventName);
2092 }
2093 const symbolEventNames = zoneSymbolEventNames$1[eventName];
2094 if (symbolEventNames) {
2095 const symbolEventName = symbolEventNames[FALSE_STR];
2096 const symbolCaptureEventName = symbolEventNames[TRUE_STR];
2097 const tasks = target[symbolEventName];
2098 const captureTasks = target[symbolCaptureEventName];
2099 if (tasks) {
2100 const removeTasks = tasks.slice();
2101 for (let i = 0; i < removeTasks.length; i++) {
2102 const task = removeTasks[i];
2103 let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
2104 this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
2105 }
2106 }
2107 if (captureTasks) {
2108 const removeTasks = captureTasks.slice();
2109 for (let i = 0; i < removeTasks.length; i++) {
2110 const task = removeTasks[i];
2111 let delegate = task.originalDelegate ? task.originalDelegate : task.callback;
2112 this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options);
2113 }
2114 }
2115 }
2116 }
2117 if (returnTarget) {
2118 return this;
2119 }
2120 };
2121 // for native toString patch
2122 attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener);
2123 attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener);
2124 if (nativeRemoveAllListeners) {
2125 attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners);
2126 }
2127 if (nativeListeners) {
2128 attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners);
2129 }
2130 return true;
2131 }
2132 let results = [];
2133 for (let i = 0; i < apis.length; i++) {
2134 results[i] = patchEventTargetMethods(apis[i], patchOptions);
2135 }
2136 return results;
2137}
2138function findEventTasks(target, eventName) {
2139 if (!eventName) {
2140 const foundTasks = [];
2141 for (let prop in target) {
2142 const match = EVENT_NAME_SYMBOL_REGX.exec(prop);
2143 let evtName = match && match[1];
2144 if (evtName && (!eventName || evtName === eventName)) {
2145 const tasks = target[prop];
2146 if (tasks) {
2147 for (let i = 0; i < tasks.length; i++) {
2148 foundTasks.push(tasks[i]);
2149 }
2150 }
2151 }
2152 }
2153 return foundTasks;
2154 }
2155 let symbolEventName = zoneSymbolEventNames$1[eventName];
2156 if (!symbolEventName) {
2157 prepareEventNames(eventName);
2158 symbolEventName = zoneSymbolEventNames$1[eventName];
2159 }
2160 const captureFalseTasks = target[symbolEventName[FALSE_STR]];
2161 const captureTrueTasks = target[symbolEventName[TRUE_STR]];
2162 if (!captureFalseTasks) {
2163 return captureTrueTasks ? captureTrueTasks.slice() : [];
2164 }
2165 else {
2166 return captureTrueTasks ? captureFalseTasks.concat(captureTrueTasks) :
2167 captureFalseTasks.slice();
2168 }
2169}
2170function patchEventPrototype(global, api) {
2171 const Event = global['Event'];
2172 if (Event && Event.prototype) {
2173 api.patchMethod(Event.prototype, 'stopImmediatePropagation', (delegate) => function (self, args) {
2174 self[IMMEDIATE_PROPAGATION_SYMBOL] = true;
2175 // we need to call the native stopImmediatePropagation
2176 // in case in some hybrid application, some part of
2177 // application will be controlled by zone, some are not
2178 delegate && delegate.apply(self, args);
2179 });
2180 }
2181}
2182
2183/**
2184 * @license
2185 * Copyright Google LLC All Rights Reserved.
2186 *
2187 * Use of this source code is governed by an MIT-style license that can be
2188 * found in the LICENSE file at https://angular.io/license
2189 */
2190function patchCallbacks(api, target, targetName, method, callbacks) {
2191 const symbol = Zone.__symbol__(method);
2192 if (target[symbol]) {
2193 return;
2194 }
2195 const nativeDelegate = target[symbol] = target[method];
2196 target[method] = function (name, opts, options) {
2197 if (opts && opts.prototype) {
2198 callbacks.forEach(function (callback) {
2199 const source = `${targetName}.${method}::` + callback;
2200 const prototype = opts.prototype;
2201 if (prototype.hasOwnProperty(callback)) {
2202 const descriptor = api.ObjectGetOwnPropertyDescriptor(prototype, callback);
2203 if (descriptor && descriptor.value) {
2204 descriptor.value = api.wrapWithCurrentZone(descriptor.value, source);
2205 api._redefineProperty(opts.prototype, callback, descriptor);
2206 }
2207 else if (prototype[callback]) {
2208 prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
2209 }
2210 }
2211 else if (prototype[callback]) {
2212 prototype[callback] = api.wrapWithCurrentZone(prototype[callback], source);
2213 }
2214 });
2215 }
2216 return nativeDelegate.call(target, name, opts, options);
2217 };
2218 api.attachOriginToPatched(target[method], nativeDelegate);
2219}
2220
2221/**
2222 * @license
2223 * Copyright Google LLC All Rights Reserved.
2224 *
2225 * Use of this source code is governed by an MIT-style license that can be
2226 * found in the LICENSE file at https://angular.io/license
2227 */
2228const globalEventHandlersEventNames = [
2229 'abort',
2230 'animationcancel',
2231 'animationend',
2232 'animationiteration',
2233 'auxclick',
2234 'beforeinput',
2235 'blur',
2236 'cancel',
2237 'canplay',
2238 'canplaythrough',
2239 'change',
2240 'compositionstart',
2241 'compositionupdate',
2242 'compositionend',
2243 'cuechange',
2244 'click',
2245 'close',
2246 'contextmenu',
2247 'curechange',
2248 'dblclick',
2249 'drag',
2250 'dragend',
2251 'dragenter',
2252 'dragexit',
2253 'dragleave',
2254 'dragover',
2255 'drop',
2256 'durationchange',
2257 'emptied',
2258 'ended',
2259 'error',
2260 'focus',
2261 'focusin',
2262 'focusout',
2263 'gotpointercapture',
2264 'input',
2265 'invalid',
2266 'keydown',
2267 'keypress',
2268 'keyup',
2269 'load',
2270 'loadstart',
2271 'loadeddata',
2272 'loadedmetadata',
2273 'lostpointercapture',
2274 'mousedown',
2275 'mouseenter',
2276 'mouseleave',
2277 'mousemove',
2278 'mouseout',
2279 'mouseover',
2280 'mouseup',
2281 'mousewheel',
2282 'orientationchange',
2283 'pause',
2284 'play',
2285 'playing',
2286 'pointercancel',
2287 'pointerdown',
2288 'pointerenter',
2289 'pointerleave',
2290 'pointerlockchange',
2291 'mozpointerlockchange',
2292 'webkitpointerlockerchange',
2293 'pointerlockerror',
2294 'mozpointerlockerror',
2295 'webkitpointerlockerror',
2296 'pointermove',
2297 'pointout',
2298 'pointerover',
2299 'pointerup',
2300 'progress',
2301 'ratechange',
2302 'reset',
2303 'resize',
2304 'scroll',
2305 'seeked',
2306 'seeking',
2307 'select',
2308 'selectionchange',
2309 'selectstart',
2310 'show',
2311 'sort',
2312 'stalled',
2313 'submit',
2314 'suspend',
2315 'timeupdate',
2316 'volumechange',
2317 'touchcancel',
2318 'touchmove',
2319 'touchstart',
2320 'touchend',
2321 'transitioncancel',
2322 'transitionend',
2323 'waiting',
2324 'wheel'
2325];
2326const documentEventNames = [
2327 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'freeze', 'fullscreenchange',
2328 'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror',
2329 'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange',
2330 'visibilitychange', 'resume'
2331];
2332const windowEventNames = [
2333 'absolutedeviceorientation',
2334 'afterinput',
2335 'afterprint',
2336 'appinstalled',
2337 'beforeinstallprompt',
2338 'beforeprint',
2339 'beforeunload',
2340 'devicelight',
2341 'devicemotion',
2342 'deviceorientation',
2343 'deviceorientationabsolute',
2344 'deviceproximity',
2345 'hashchange',
2346 'languagechange',
2347 'message',
2348 'mozbeforepaint',
2349 'offline',
2350 'online',
2351 'paint',
2352 'pageshow',
2353 'pagehide',
2354 'popstate',
2355 'rejectionhandled',
2356 'storage',
2357 'unhandledrejection',
2358 'unload',
2359 'userproximity',
2360 'vrdisplayconnected',
2361 'vrdisplaydisconnected',
2362 'vrdisplaypresentchange'
2363];
2364const htmlElementEventNames = [
2365 'beforecopy', 'beforecut', 'beforepaste', 'copy', 'cut', 'paste', 'dragstart', 'loadend',
2366 'animationstart', 'search', 'transitionrun', 'transitionstart', 'webkitanimationend',
2367 'webkitanimationiteration', 'webkitanimationstart', 'webkittransitionend'
2368];
2369const mediaElementEventNames = ['encrypted', 'waitingforkey', 'msneedkey', 'mozinterruptbegin', 'mozinterruptend'];
2370const ieElementEventNames = [
2371 'activate',
2372 'afterupdate',
2373 'ariarequest',
2374 'beforeactivate',
2375 'beforedeactivate',
2376 'beforeeditfocus',
2377 'beforeupdate',
2378 'cellchange',
2379 'controlselect',
2380 'dataavailable',
2381 'datasetchanged',
2382 'datasetcomplete',
2383 'errorupdate',
2384 'filterchange',
2385 'layoutcomplete',
2386 'losecapture',
2387 'move',
2388 'moveend',
2389 'movestart',
2390 'propertychange',
2391 'resizeend',
2392 'resizestart',
2393 'rowenter',
2394 'rowexit',
2395 'rowsdelete',
2396 'rowsinserted',
2397 'command',
2398 'compassneedscalibration',
2399 'deactivate',
2400 'help',
2401 'mscontentzoom',
2402 'msmanipulationstatechanged',
2403 'msgesturechange',
2404 'msgesturedoubletap',
2405 'msgestureend',
2406 'msgesturehold',
2407 'msgesturestart',
2408 'msgesturetap',
2409 'msgotpointercapture',
2410 'msinertiastart',
2411 'mslostpointercapture',
2412 'mspointercancel',
2413 'mspointerdown',
2414 'mspointerenter',
2415 'mspointerhover',
2416 'mspointerleave',
2417 'mspointermove',
2418 'mspointerout',
2419 'mspointerover',
2420 'mspointerup',
2421 'pointerout',
2422 'mssitemodejumplistitemremoved',
2423 'msthumbnailclick',
2424 'stop',
2425 'storagecommit'
2426];
2427const webglEventNames = ['webglcontextrestored', 'webglcontextlost', 'webglcontextcreationerror'];
2428const formEventNames = ['autocomplete', 'autocompleteerror'];
2429const detailEventNames = ['toggle'];
2430const frameEventNames = ['load'];
2431const frameSetEventNames = ['blur', 'error', 'focus', 'load', 'resize', 'scroll', 'messageerror'];
2432const marqueeEventNames = ['bounce', 'finish', 'start'];
2433const XMLHttpRequestEventNames = [
2434 'loadstart', 'progress', 'abort', 'error', 'load', 'progress', 'timeout', 'loadend',
2435 'readystatechange'
2436];
2437const IDBIndexEventNames = ['upgradeneeded', 'complete', 'abort', 'success', 'error', 'blocked', 'versionchange', 'close'];
2438const websocketEventNames = ['close', 'error', 'open', 'message'];
2439const workerEventNames = ['error', 'message'];
2440const eventNames = globalEventHandlersEventNames.concat(webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames, htmlElementEventNames, ieElementEventNames);
2441function filterProperties(target, onProperties, ignoreProperties) {
2442 if (!ignoreProperties || ignoreProperties.length === 0) {
2443 return onProperties;
2444 }
2445 const tip = ignoreProperties.filter(ip => ip.target === target);
2446 if (!tip || tip.length === 0) {
2447 return onProperties;
2448 }
2449 const targetIgnoreProperties = tip[0].ignoreProperties;
2450 return onProperties.filter(op => targetIgnoreProperties.indexOf(op) === -1);
2451}
2452function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) {
2453 // check whether target is available, sometimes target will be undefined
2454 // because different browser or some 3rd party plugin.
2455 if (!target) {
2456 return;
2457 }
2458 const filteredProperties = filterProperties(target, onProperties, ignoreProperties);
2459 patchOnProperties(target, filteredProperties, prototype);
2460}
2461function propertyDescriptorPatch(api, _global) {
2462 if (isNode && !isMix) {
2463 return;
2464 }
2465 if (Zone[api.symbol('patchEvents')]) {
2466 // events are already been patched by legacy patch.
2467 return;
2468 }
2469 const supportsWebSocket = typeof WebSocket !== 'undefined';
2470 const ignoreProperties = _global['__Zone_ignore_on_properties'];
2471 // for browsers that we can patch the descriptor: Chrome & Firefox
2472 if (isBrowser) {
2473 const internalWindow = window;
2474 const ignoreErrorProperties = isIE() ? [{ target: internalWindow, ignoreProperties: ['error'] }] : [];
2475 // in IE/Edge, onProp not exist in window object, but in WindowPrototype
2476 // so we need to pass WindowPrototype to check onProp exist or not
2477 patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties ? ignoreProperties.concat(ignoreErrorProperties) : ignoreProperties, ObjectGetPrototypeOf(internalWindow));
2478 patchFilteredProperties(Document.prototype, eventNames, ignoreProperties);
2479 if (typeof internalWindow['SVGElement'] !== 'undefined') {
2480 patchFilteredProperties(internalWindow['SVGElement'].prototype, eventNames, ignoreProperties);
2481 }
2482 patchFilteredProperties(Element.prototype, eventNames, ignoreProperties);
2483 patchFilteredProperties(HTMLElement.prototype, eventNames, ignoreProperties);
2484 patchFilteredProperties(HTMLMediaElement.prototype, mediaElementEventNames, ignoreProperties);
2485 patchFilteredProperties(HTMLFrameSetElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
2486 patchFilteredProperties(HTMLBodyElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties);
2487 patchFilteredProperties(HTMLFrameElement.prototype, frameEventNames, ignoreProperties);
2488 patchFilteredProperties(HTMLIFrameElement.prototype, frameEventNames, ignoreProperties);
2489 const HTMLMarqueeElement = internalWindow['HTMLMarqueeElement'];
2490 if (HTMLMarqueeElement) {
2491 patchFilteredProperties(HTMLMarqueeElement.prototype, marqueeEventNames, ignoreProperties);
2492 }
2493 const Worker = internalWindow['Worker'];
2494 if (Worker) {
2495 patchFilteredProperties(Worker.prototype, workerEventNames, ignoreProperties);
2496 }
2497 }
2498 const XMLHttpRequest = _global['XMLHttpRequest'];
2499 if (XMLHttpRequest) {
2500 // XMLHttpRequest is not available in ServiceWorker, so we need to check here
2501 patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties);
2502 }
2503 const XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget'];
2504 if (XMLHttpRequestEventTarget) {
2505 patchFilteredProperties(XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames, ignoreProperties);
2506 }
2507 if (typeof IDBIndex !== 'undefined') {
2508 patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties);
2509 patchFilteredProperties(IDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
2510 patchFilteredProperties(IDBOpenDBRequest.prototype, IDBIndexEventNames, ignoreProperties);
2511 patchFilteredProperties(IDBDatabase.prototype, IDBIndexEventNames, ignoreProperties);
2512 patchFilteredProperties(IDBTransaction.prototype, IDBIndexEventNames, ignoreProperties);
2513 patchFilteredProperties(IDBCursor.prototype, IDBIndexEventNames, ignoreProperties);
2514 }
2515 if (supportsWebSocket) {
2516 patchFilteredProperties(WebSocket.prototype, websocketEventNames, ignoreProperties);
2517 }
2518}
2519
2520/**
2521 * @license
2522 * Copyright Google LLC All Rights Reserved.
2523 *
2524 * Use of this source code is governed by an MIT-style license that can be
2525 * found in the LICENSE file at https://angular.io/license
2526 */
2527Zone.__load_patch('util', (global, Zone, api) => {
2528 api.patchOnProperties = patchOnProperties;
2529 api.patchMethod = patchMethod;
2530 api.bindArguments = bindArguments;
2531 api.patchMacroTask = patchMacroTask;
2532 // In earlier version of zone.js (<0.9.0), we use env name `__zone_symbol__BLACK_LISTED_EVENTS` to
2533 // define which events will not be patched by `Zone.js`.
2534 // In newer version (>=0.9.0), we change the env name to `__zone_symbol__UNPATCHED_EVENTS` to keep
2535 // the name consistent with angular repo.
2536 // The `__zone_symbol__BLACK_LISTED_EVENTS` is deprecated, but it is still be supported for
2537 // backwards compatibility.
2538 const SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS');
2539 const SYMBOL_UNPATCHED_EVENTS = Zone.__symbol__('UNPATCHED_EVENTS');
2540 if (global[SYMBOL_UNPATCHED_EVENTS]) {
2541 global[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_UNPATCHED_EVENTS];
2542 }
2543 if (global[SYMBOL_BLACK_LISTED_EVENTS]) {
2544 Zone[SYMBOL_BLACK_LISTED_EVENTS] = Zone[SYMBOL_UNPATCHED_EVENTS] =
2545 global[SYMBOL_BLACK_LISTED_EVENTS];
2546 }
2547 api.patchEventPrototype = patchEventPrototype;
2548 api.patchEventTarget = patchEventTarget;
2549 api.isIEOrEdge = isIEOrEdge;
2550 api.ObjectDefineProperty = ObjectDefineProperty;
2551 api.ObjectGetOwnPropertyDescriptor = ObjectGetOwnPropertyDescriptor;
2552 api.ObjectCreate = ObjectCreate;
2553 api.ArraySlice = ArraySlice;
2554 api.patchClass = patchClass;
2555 api.wrapWithCurrentZone = wrapWithCurrentZone;
2556 api.filterProperties = filterProperties;
2557 api.attachOriginToPatched = attachOriginToPatched;
2558 api._redefineProperty = Object.defineProperty;
2559 api.patchCallbacks = patchCallbacks;
2560 api.getGlobalObjects = () => ({
2561 globalSources,
2562 zoneSymbolEventNames: zoneSymbolEventNames$1,
2563 eventNames,
2564 isBrowser,
2565 isMix,
2566 isNode,
2567 TRUE_STR,
2568 FALSE_STR,
2569 ZONE_SYMBOL_PREFIX,
2570 ADD_EVENT_LISTENER_STR,
2571 REMOVE_EVENT_LISTENER_STR
2572 });
2573});
2574
2575/**
2576 * @license
2577 * Copyright Google LLC All Rights Reserved.
2578 *
2579 * Use of this source code is governed by an MIT-style license that can be
2580 * found in the LICENSE file at https://angular.io/license
2581 */
2582const taskSymbol = zoneSymbol('zoneTask');
2583function patchTimer(window, setName, cancelName, nameSuffix) {
2584 let setNative = null;
2585 let clearNative = null;
2586 setName += nameSuffix;
2587 cancelName += nameSuffix;
2588 const tasksByHandleId = {};
2589 function scheduleTask(task) {
2590 const data = task.data;
2591 data.args[0] = function () {
2592 return task.invoke.apply(this, arguments);
2593 };
2594 data.handleId = setNative.apply(window, data.args);
2595 return task;
2596 }
2597 function clearTask(task) {
2598 return clearNative.call(window, task.data.handleId);
2599 }
2600 setNative =
2601 patchMethod(window, setName, (delegate) => function (self, args) {
2602 if (typeof args[0] === 'function') {
2603 const options = {
2604 isPeriodic: nameSuffix === 'Interval',
2605 delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 :
2606 undefined,
2607 args: args
2608 };
2609 const callback = args[0];
2610 args[0] = function timer() {
2611 try {
2612 return callback.apply(this, arguments);
2613 }
2614 finally {
2615 // issue-934, task will be cancelled
2616 // even it is a periodic task such as
2617 // setInterval
2618 // https://github.com/angular/angular/issues/40387
2619 // Cleanup tasksByHandleId should be handled before scheduleTask
2620 // Since some zoneSpec may intercept and doesn't trigger
2621 // scheduleFn(scheduleTask) provided here.
2622 if (!(options.isPeriodic)) {
2623 if (typeof options.handleId === 'number') {
2624 // in non-nodejs env, we remove timerId
2625 // from local cache
2626 delete tasksByHandleId[options.handleId];
2627 }
2628 else if (options.handleId) {
2629 // Node returns complex objects as handleIds
2630 // we remove task reference from timer object
2631 options.handleId[taskSymbol] = null;
2632 }
2633 }
2634 }
2635 };
2636 const task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask);
2637 if (!task) {
2638 return task;
2639 }
2640 // Node.js must additionally support the ref and unref functions.
2641 const handle = task.data.handleId;
2642 if (typeof handle === 'number') {
2643 // for non nodejs env, we save handleId: task
2644 // mapping in local cache for clearTimeout
2645 tasksByHandleId[handle] = task;
2646 }
2647 else if (handle) {
2648 // for nodejs env, we save task
2649 // reference in timerId Object for clearTimeout
2650 handle[taskSymbol] = task;
2651 }
2652 // check whether handle is null, because some polyfill or browser
2653 // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame
2654 if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' &&
2655 typeof handle.unref === 'function') {
2656 task.ref = handle.ref.bind(handle);
2657 task.unref = handle.unref.bind(handle);
2658 }
2659 if (typeof handle === 'number' || handle) {
2660 return handle;
2661 }
2662 return task;
2663 }
2664 else {
2665 // cause an error by calling it directly.
2666 return delegate.apply(window, args);
2667 }
2668 });
2669 clearNative =
2670 patchMethod(window, cancelName, (delegate) => function (self, args) {
2671 const id = args[0];
2672 let task;
2673 if (typeof id === 'number') {
2674 // non nodejs env.
2675 task = tasksByHandleId[id];
2676 }
2677 else {
2678 // nodejs env.
2679 task = id && id[taskSymbol];
2680 // other environments.
2681 if (!task) {
2682 task = id;
2683 }
2684 }
2685 if (task && typeof task.type === 'string') {
2686 if (task.state !== 'notScheduled' &&
2687 (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) {
2688 if (typeof id === 'number') {
2689 delete tasksByHandleId[id];
2690 }
2691 else if (id) {
2692 id[taskSymbol] = null;
2693 }
2694 // Do not cancel already canceled functions
2695 task.zone.cancelTask(task);
2696 }
2697 }
2698 else {
2699 // cause an error by calling it directly.
2700 delegate.apply(window, args);
2701 }
2702 });
2703}
2704
2705/**
2706 * @license
2707 * Copyright Google LLC All Rights Reserved.
2708 *
2709 * Use of this source code is governed by an MIT-style license that can be
2710 * found in the LICENSE file at https://angular.io/license
2711 */
2712function patchCustomElements(_global, api) {
2713 const { isBrowser, isMix } = api.getGlobalObjects();
2714 if ((!isBrowser && !isMix) || !_global['customElements'] || !('customElements' in _global)) {
2715 return;
2716 }
2717 const callbacks = ['connectedCallback', 'disconnectedCallback', 'adoptedCallback', 'attributeChangedCallback'];
2718 api.patchCallbacks(api, _global.customElements, 'customElements', 'define', callbacks);
2719}
2720
2721/**
2722 * @license
2723 * Copyright Google LLC All Rights Reserved.
2724 *
2725 * Use of this source code is governed by an MIT-style license that can be
2726 * found in the LICENSE file at https://angular.io/license
2727 */
2728function eventTargetPatch(_global, api) {
2729 if (Zone[api.symbol('patchEventTarget')]) {
2730 // EventTarget is already patched.
2731 return;
2732 }
2733 const { eventNames, zoneSymbolEventNames, TRUE_STR, FALSE_STR, ZONE_SYMBOL_PREFIX } = api.getGlobalObjects();
2734 // predefine all __zone_symbol__ + eventName + true/false string
2735 for (let i = 0; i < eventNames.length; i++) {
2736 const eventName = eventNames[i];
2737 const falseEventName = eventName + FALSE_STR;
2738 const trueEventName = eventName + TRUE_STR;
2739 const symbol = ZONE_SYMBOL_PREFIX + falseEventName;
2740 const symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName;
2741 zoneSymbolEventNames[eventName] = {};
2742 zoneSymbolEventNames[eventName][FALSE_STR] = symbol;
2743 zoneSymbolEventNames[eventName][TRUE_STR] = symbolCapture;
2744 }
2745 const EVENT_TARGET = _global['EventTarget'];
2746 if (!EVENT_TARGET || !EVENT_TARGET.prototype) {
2747 return;
2748 }
2749 api.patchEventTarget(_global, [EVENT_TARGET && EVENT_TARGET.prototype]);
2750 return true;
2751}
2752function patchEvent(global, api) {
2753 api.patchEventPrototype(global, api);
2754}
2755
2756/**
2757 * @license
2758 * Copyright Google LLC All Rights Reserved.
2759 *
2760 * Use of this source code is governed by an MIT-style license that can be
2761 * found in the LICENSE file at https://angular.io/license
2762 */
2763Zone.__load_patch('legacy', (global) => {
2764 const legacyPatch = global[Zone.__symbol__('legacyPatch')];
2765 if (legacyPatch) {
2766 legacyPatch();
2767 }
2768});
2769Zone.__load_patch('queueMicrotask', (global, Zone, api) => {
2770 api.patchMethod(global, 'queueMicrotask', delegate => {
2771 return function (self, args) {
2772 Zone.current.scheduleMicroTask('queueMicrotask', args[0]);
2773 };
2774 });
2775});
2776Zone.__load_patch('timers', (global) => {
2777 const set = 'set';
2778 const clear = 'clear';
2779 patchTimer(global, set, clear, 'Timeout');
2780 patchTimer(global, set, clear, 'Interval');
2781 patchTimer(global, set, clear, 'Immediate');
2782});
2783Zone.__load_patch('requestAnimationFrame', (global) => {
2784 patchTimer(global, 'request', 'cancel', 'AnimationFrame');
2785 patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame');
2786 patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame');
2787});
2788Zone.__load_patch('blocking', (global, Zone) => {
2789 const blockingMethods = ['alert', 'prompt', 'confirm'];
2790 for (let i = 0; i < blockingMethods.length; i++) {
2791 const name = blockingMethods[i];
2792 patchMethod(global, name, (delegate, symbol, name) => {
2793 return function (s, args) {
2794 return Zone.current.run(delegate, global, args, name);
2795 };
2796 });
2797 }
2798});
2799Zone.__load_patch('EventTarget', (global, Zone, api) => {
2800 patchEvent(global, api);
2801 eventTargetPatch(global, api);
2802 // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener
2803 const XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget'];
2804 if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) {
2805 api.patchEventTarget(global, [XMLHttpRequestEventTarget.prototype]);
2806 }
2807});
2808Zone.__load_patch('MutationObserver', (global, Zone, api) => {
2809 patchClass('MutationObserver');
2810 patchClass('WebKitMutationObserver');
2811});
2812Zone.__load_patch('IntersectionObserver', (global, Zone, api) => {
2813 patchClass('IntersectionObserver');
2814});
2815Zone.__load_patch('FileReader', (global, Zone, api) => {
2816 patchClass('FileReader');
2817});
2818Zone.__load_patch('on_property', (global, Zone, api) => {
2819 propertyDescriptorPatch(api, global);
2820});
2821Zone.__load_patch('customElements', (global, Zone, api) => {
2822 patchCustomElements(global, api);
2823});
2824Zone.__load_patch('XHR', (global, Zone) => {
2825 // Treat XMLHttpRequest as a macrotask.
2826 patchXHR(global);
2827 const XHR_TASK = zoneSymbol('xhrTask');
2828 const XHR_SYNC = zoneSymbol('xhrSync');
2829 const XHR_LISTENER = zoneSymbol('xhrListener');
2830 const XHR_SCHEDULED = zoneSymbol('xhrScheduled');
2831 const XHR_URL = zoneSymbol('xhrURL');
2832 const XHR_ERROR_BEFORE_SCHEDULED = zoneSymbol('xhrErrorBeforeScheduled');
2833 function patchXHR(window) {
2834 const XMLHttpRequest = window['XMLHttpRequest'];
2835 if (!XMLHttpRequest) {
2836 // XMLHttpRequest is not available in service worker
2837 return;
2838 }
2839 const XMLHttpRequestPrototype = XMLHttpRequest.prototype;
2840 function findPendingTask(target) {
2841 return target[XHR_TASK];
2842 }
2843 let oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
2844 let oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
2845 if (!oriAddListener) {
2846 const XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget'];
2847 if (XMLHttpRequestEventTarget) {
2848 const XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype;
2849 oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER];
2850 oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
2851 }
2852 }
2853 const READY_STATE_CHANGE = 'readystatechange';
2854 const SCHEDULED = 'scheduled';
2855 function scheduleTask(task) {
2856 const data = task.data;
2857 const target = data.target;
2858 target[XHR_SCHEDULED] = false;
2859 target[XHR_ERROR_BEFORE_SCHEDULED] = false;
2860 // remove existing event listener
2861 const listener = target[XHR_LISTENER];
2862 if (!oriAddListener) {
2863 oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER];
2864 oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER];
2865 }
2866 if (listener) {
2867 oriRemoveListener.call(target, READY_STATE_CHANGE, listener);
2868 }
2869 const newListener = target[XHR_LISTENER] = () => {
2870 if (target.readyState === target.DONE) {
2871 // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with
2872 // readyState=4 multiple times, so we need to check task state here
2873 if (!data.aborted && target[XHR_SCHEDULED] && task.state === SCHEDULED) {
2874 // check whether the xhr has registered onload listener
2875 // if that is the case, the task should invoke after all
2876 // onload listeners finish.
2877 // Also if the request failed without response (status = 0), the load event handler
2878 // will not be triggered, in that case, we should also invoke the placeholder callback
2879 // to close the XMLHttpRequest::send macroTask.
2880 // https://github.com/angular/angular/issues/38795
2881 const loadTasks = target[Zone.__symbol__('loadfalse')];
2882 if (target.status !== 0 && loadTasks && loadTasks.length > 0) {
2883 const oriInvoke = task.invoke;
2884 task.invoke = function () {
2885 // need to load the tasks again, because in other
2886 // load listener, they may remove themselves
2887 const loadTasks = target[Zone.__symbol__('loadfalse')];
2888 for (let i = 0; i < loadTasks.length; i++) {
2889 if (loadTasks[i] === task) {
2890 loadTasks.splice(i, 1);
2891 }
2892 }
2893 if (!data.aborted && task.state === SCHEDULED) {
2894 oriInvoke.call(task);
2895 }
2896 };
2897 loadTasks.push(task);
2898 }
2899 else {
2900 task.invoke();
2901 }
2902 }
2903 else if (!data.aborted && target[XHR_SCHEDULED] === false) {
2904 // error occurs when xhr.send()
2905 target[XHR_ERROR_BEFORE_SCHEDULED] = true;
2906 }
2907 }
2908 };
2909 oriAddListener.call(target, READY_STATE_CHANGE, newListener);
2910 const storedTask = target[XHR_TASK];
2911 if (!storedTask) {
2912 target[XHR_TASK] = task;
2913 }
2914 sendNative.apply(target, data.args);
2915 target[XHR_SCHEDULED] = true;
2916 return task;
2917 }
2918 function placeholderCallback() { }
2919 function clearTask(task) {
2920 const data = task.data;
2921 // Note - ideally, we would call data.target.removeEventListener here, but it's too late
2922 // to prevent it from firing. So instead, we store info for the event listener.
2923 data.aborted = true;
2924 return abortNative.apply(data.target, data.args);
2925 }
2926 const openNative = patchMethod(XMLHttpRequestPrototype, 'open', () => function (self, args) {
2927 self[XHR_SYNC] = args[2] == false;
2928 self[XHR_URL] = args[1];
2929 return openNative.apply(self, args);
2930 });
2931 const XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send';
2932 const fetchTaskAborting = zoneSymbol('fetchTaskAborting');
2933 const fetchTaskScheduling = zoneSymbol('fetchTaskScheduling');
2934 const sendNative = patchMethod(XMLHttpRequestPrototype, 'send', () => function (self, args) {
2935 if (Zone.current[fetchTaskScheduling] === true) {
2936 // a fetch is scheduling, so we are using xhr to polyfill fetch
2937 // and because we already schedule macroTask for fetch, we should
2938 // not schedule a macroTask for xhr again
2939 return sendNative.apply(self, args);
2940 }
2941 if (self[XHR_SYNC]) {
2942 // if the XHR is sync there is no task to schedule, just execute the code.
2943 return sendNative.apply(self, args);
2944 }
2945 else {
2946 const options = { target: self, url: self[XHR_URL], isPeriodic: false, args: args, aborted: false };
2947 const task = scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask);
2948 if (self && self[XHR_ERROR_BEFORE_SCHEDULED] === true && !options.aborted &&
2949 task.state === SCHEDULED) {
2950 // xhr request throw error when send
2951 // we should invoke task instead of leaving a scheduled
2952 // pending macroTask
2953 task.invoke();
2954 }
2955 }
2956 });
2957 const abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', () => function (self, args) {
2958 const task = findPendingTask(self);
2959 if (task && typeof task.type == 'string') {
2960 // If the XHR has already completed, do nothing.
2961 // If the XHR has already been aborted, do nothing.
2962 // Fix #569, call abort multiple times before done will cause
2963 // macroTask task count be negative number
2964 if (task.cancelFn == null || (task.data && task.data.aborted)) {
2965 return;
2966 }
2967 task.zone.cancelTask(task);
2968 }
2969 else if (Zone.current[fetchTaskAborting] === true) {
2970 // the abort is called from fetch polyfill, we need to call native abort of XHR.
2971 return abortNative.apply(self, args);
2972 }
2973 // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no
2974 // task
2975 // to cancel. Do nothing.
2976 });
2977 }
2978});
2979Zone.__load_patch('geolocation', (global) => {
2980 /// GEO_LOCATION
2981 if (global['navigator'] && global['navigator'].geolocation) {
2982 patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']);
2983 }
2984});
2985Zone.__load_patch('PromiseRejectionEvent', (global, Zone) => {
2986 // handle unhandled promise rejection
2987 function findPromiseRejectionHandler(evtName) {
2988 return function (e) {
2989 const eventTasks = findEventTasks(global, evtName);
2990 eventTasks.forEach(eventTask => {
2991 // windows has added unhandledrejection event listener
2992 // trigger the event listener
2993 const PromiseRejectionEvent = global['PromiseRejectionEvent'];
2994 if (PromiseRejectionEvent) {
2995 const evt = new PromiseRejectionEvent(evtName, { promise: e.promise, reason: e.rejection });
2996 eventTask.invoke(evt);
2997 }
2998 });
2999 };
3000 }
3001 if (global['PromiseRejectionEvent']) {
3002 Zone[zoneSymbol('unhandledPromiseRejectionHandler')] =
3003 findPromiseRejectionHandler('unhandledrejection');
3004 Zone[zoneSymbol('rejectionHandledHandler')] =
3005 findPromiseRejectionHandler('rejectionhandled');
3006 }
3007});
3008
3009/**
3010 * @license
3011 * Copyright Google LLC All Rights Reserved.
3012 *
3013 * Use of this source code is governed by an MIT-style license that can be
3014 * found in the LICENSE file at https://angular.io/license
3015 */
3016Zone.__load_patch('node_util', (global, Zone, api) => {
3017 api.patchOnProperties = patchOnProperties;
3018 api.patchMethod = patchMethod;
3019 api.bindArguments = bindArguments;
3020 api.patchMacroTask = patchMacroTask;
3021 setShouldCopySymbolProperties(true);
3022});
3023
3024/**
3025 * @license
3026 * Copyright Google LLC All Rights Reserved.
3027 *
3028 * Use of this source code is governed by an MIT-style license that can be
3029 * found in the LICENSE file at https://angular.io/license
3030 */
3031Zone.__load_patch('EventEmitter', (global) => {
3032 // For EventEmitter
3033 const EE_ADD_LISTENER = 'addListener';
3034 const EE_PREPEND_LISTENER = 'prependListener';
3035 const EE_REMOVE_LISTENER = 'removeListener';
3036 const EE_REMOVE_ALL_LISTENER = 'removeAllListeners';
3037 const EE_LISTENERS = 'listeners';
3038 const EE_ON = 'on';
3039 const EE_OFF = 'off';
3040 const compareTaskCallbackVsDelegate = function (task, delegate) {
3041 // same callback, same capture, same event name, just return
3042 return task.callback === delegate || task.callback.listener === delegate;
3043 };
3044 const eventNameToString = function (eventName) {
3045 if (typeof eventName === 'string') {
3046 return eventName;
3047 }
3048 if (!eventName) {
3049 return '';
3050 }
3051 return eventName.toString().replace('(', '_').replace(')', '_');
3052 };
3053 function patchEventEmitterMethods(obj) {
3054 const result = patchEventTarget(global, [obj], {
3055 useG: false,
3056 add: EE_ADD_LISTENER,
3057 rm: EE_REMOVE_LISTENER,
3058 prepend: EE_PREPEND_LISTENER,
3059 rmAll: EE_REMOVE_ALL_LISTENER,
3060 listeners: EE_LISTENERS,
3061 chkDup: false,
3062 rt: true,
3063 diff: compareTaskCallbackVsDelegate,
3064 eventNameToString: eventNameToString
3065 });
3066 if (result && result[0]) {
3067 obj[EE_ON] = obj[EE_ADD_LISTENER];
3068 obj[EE_OFF] = obj[EE_REMOVE_LISTENER];
3069 }
3070 }
3071 // EventEmitter
3072 let events;
3073 try {
3074 events = require('events');
3075 }
3076 catch (err) {
3077 }
3078 if (events && events.EventEmitter) {
3079 patchEventEmitterMethods(events.EventEmitter.prototype);
3080 }
3081});
3082
3083/**
3084 * @license
3085 * Copyright Google LLC All Rights Reserved.
3086 *
3087 * Use of this source code is governed by an MIT-style license that can be
3088 * found in the LICENSE file at https://angular.io/license
3089 */
3090Zone.__load_patch('fs', () => {
3091 let fs;
3092 try {
3093 fs = require('fs');
3094 }
3095 catch (err) {
3096 }
3097 // watch, watchFile, unwatchFile has been patched
3098 // because EventEmitter has been patched
3099 const TO_PATCH_MACROTASK_METHODS = [
3100 'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod',
3101 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod',
3102 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read',
3103 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat',
3104 'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile',
3105 ];
3106 if (fs) {
3107 TO_PATCH_MACROTASK_METHODS.filter(name => !!fs[name] && typeof fs[name] === 'function')
3108 .forEach(name => {
3109 patchMacroTask(fs, name, (self, args) => {
3110 return {
3111 name: 'fs.' + name,
3112 args: args,
3113 cbIdx: args.length > 0 ? args.length - 1 : -1,
3114 target: self
3115 };
3116 });
3117 });
3118 }
3119});
3120
3121/**
3122 * @license
3123 * Copyright Google LLC All Rights Reserved.
3124 *
3125 * Use of this source code is governed by an MIT-style license that can be
3126 * found in the LICENSE file at https://angular.io/license
3127 */
3128const set = 'set';
3129const clear = 'clear';
3130Zone.__load_patch('node_timers', (global, Zone) => {
3131 // Timers
3132 let globalUseTimeoutFromTimer = false;
3133 try {
3134 const timers = require('timers');
3135 let globalEqualTimersTimeout = global.setTimeout === timers.setTimeout;
3136 if (!globalEqualTimersTimeout && !isMix) {
3137 // 1. if isMix, then we are in mix environment such as Electron
3138 // we should only patch timers.setTimeout because global.setTimeout
3139 // have been patched
3140 // 2. if global.setTimeout not equal timers.setTimeout, check
3141 // whether global.setTimeout use timers.setTimeout or not
3142 const originSetTimeout = timers.setTimeout;
3143 timers.setTimeout = function () {
3144 globalUseTimeoutFromTimer = true;
3145 return originSetTimeout.apply(this, arguments);
3146 };
3147 const detectTimeout = global.setTimeout(() => { }, 100);
3148 clearTimeout(detectTimeout);
3149 timers.setTimeout = originSetTimeout;
3150 }
3151 patchTimer(timers, set, clear, 'Timeout');
3152 patchTimer(timers, set, clear, 'Interval');
3153 patchTimer(timers, set, clear, 'Immediate');
3154 }
3155 catch (error) {
3156 // timers module not exists, for example, when we using nativeScript
3157 // timers is not available
3158 }
3159 if (isMix) {
3160 // if we are in mix environment, such as Electron,
3161 // the global.setTimeout has already been patched,
3162 // so we just patch timers.setTimeout
3163 return;
3164 }
3165 if (!globalUseTimeoutFromTimer) {
3166 // 1. global setTimeout equals timers setTimeout
3167 // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout)
3168 // 3. or load timers module error happens, we should patch global setTimeout
3169 patchTimer(global, set, clear, 'Timeout');
3170 patchTimer(global, set, clear, 'Interval');
3171 patchTimer(global, set, clear, 'Immediate');
3172 }
3173 else {
3174 // global use timers setTimeout, but not equals
3175 // this happens when use nodejs v0.10.x, global setTimeout will
3176 // use a lazy load version of timers setTimeout
3177 // we should not double patch timer's setTimeout
3178 // so we only store the __symbol__ for consistency
3179 global[Zone.__symbol__('setTimeout')] = global.setTimeout;
3180 global[Zone.__symbol__('setInterval')] = global.setInterval;
3181 global[Zone.__symbol__('setImmediate')] = global.setImmediate;
3182 }
3183});
3184// patch process related methods
3185Zone.__load_patch('nextTick', () => {
3186 // patch nextTick as microTask
3187 patchMicroTask(process, 'nextTick', (self, args) => {
3188 return {
3189 name: 'process.nextTick',
3190 args: args,
3191 cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1,
3192 target: process
3193 };
3194 });
3195});
3196Zone.__load_patch('handleUnhandledPromiseRejection', (global, Zone, api) => {
3197 Zone[api.symbol('unhandledPromiseRejectionHandler')] =
3198 findProcessPromiseRejectionHandler('unhandledRejection');
3199 Zone[api.symbol('rejectionHandledHandler')] =
3200 findProcessPromiseRejectionHandler('rejectionHandled');
3201 // handle unhandled promise rejection
3202 function findProcessPromiseRejectionHandler(evtName) {
3203 return function (e) {
3204 const eventTasks = findEventTasks(process, evtName);
3205 eventTasks.forEach(eventTask => {
3206 // process has added unhandledrejection event listener
3207 // trigger the event listener
3208 if (evtName === 'unhandledRejection') {
3209 eventTask.invoke(e.rejection, e.promise);
3210 }
3211 else if (evtName === 'rejectionHandled') {
3212 eventTask.invoke(e.promise);
3213 }
3214 });
3215 };
3216 }
3217});
3218// Crypto
3219Zone.__load_patch('crypto', () => {
3220 let crypto;
3221 try {
3222 crypto = require('crypto');
3223 }
3224 catch (err) {
3225 }
3226 // use the generic patchMacroTask to patch crypto
3227 if (crypto) {
3228 const methodNames = ['randomBytes', 'pbkdf2'];
3229 methodNames.forEach(name => {
3230 patchMacroTask(crypto, name, (self, args) => {
3231 return {
3232 name: 'crypto.' + name,
3233 args: args,
3234 cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ?
3235 args.length - 1 :
3236 -1,
3237 target: crypto
3238 };
3239 });
3240 });
3241 }
3242});
3243Zone.__load_patch('console', (global, Zone) => {
3244 const consoleMethods = ['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace'];
3245 consoleMethods.forEach((m) => {
3246 const originalMethod = console[Zone.__symbol__(m)] = console[m];
3247 if (originalMethod) {
3248 console[m] = function () {
3249 const args = ArraySlice.call(arguments);
3250 if (Zone.current === Zone.root) {
3251 return originalMethod.apply(this, args);
3252 }
3253 else {
3254 return Zone.root.run(originalMethod, this, args);
3255 }
3256 };
3257 }
3258 });
3259});
Note: See TracBrowser for help on using the repository browser.