zone-node.umd.js 133 KB

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