zone.umd.js 151 KB

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