zone.umd.js 149 KB

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